Compare commits

...
Author SHA1 Message Date
9f29e5388e chore: clean up trainer and orchestrator logging (#3345)
## Summary

Log audit of the trainer and orchestrator, from a side-by-side read of a
full run's logs and the code that emitted them.

**Conventions** (applied everywhere):
- Every potentially slow action logs an active-tense info line first
(`Initializing X`, `Waiting for X`) — the last info line always names
the action that crashed or hung.
- Each one is paired with a debug completion carrying `format_time`
timing (`Initialized X in 1.2s`). All debug timings now use
`format_time`.
- Component inits log exactly `Initializing X ({config})`. Monitors log
a names-only summary plus one full-config line per monitor, from
`monitors.setup`.

**Gaps filled** (previously silent hang points): startup weight sync
(can block minutes), orchestrator teardown (info + one debug line per
stage, so a wedged component is identifiable),
`setup_torch_distributed`, device mesh init, trainer startup broadcast,
W&B finalize.

**Setup reorder** (orchestrator): local init first — sender, filesystem
weight broadcast — then the waits last before the main loop (env servers
→ inference pool → NCCL/NIXL handshake → startup sync). The NCCL/NIXL
handshake stays post-readiness (it POSTs to live engines); the
checkpoint's curricula restore follows `envs.start()` (`TrainSource`
needs loaded tasksets). One awaited metrics scrape primes the
concurrency controller so `Derived initial max inflight` logs before
`Starting orchestrator loop`.

**Renames and demotions** (highlights):
- `waiting for trainer to broadcast checkpoint N` → `Waiting for the
trainer to broadcast policy v{N}`; steps vs 0-indexed policy versions
untangled throughout.
- The inference wait is info every 30 s (`Waiting for inference server
at {url} to start up (30s elapsed)`), error at debug — was a warning
every 10 s.
- One identity line on all three processes: `Starting from scratch` /
`Resuming from step {N}`; `Broadcasting base policy weights (v{N})`.
- Launcher: `Starting {name} server`, `Starting orchestrator` (no
"process").
- Removed the per-group success debug in the train sink (flooded one
line per group); drop-path logs stay, renamed `Dropped group | ... |
reason=...`.
- Demoted to debug: ZMQ sender/receiver init/close, `Using shared W&B
mode`, `Loading model config`, executor setup, GC line. LoRA debug no
longer dumps the full model repr.
- Punctuation/tense/indexing: `Saving final checkpoint at step N`, no
trailing `.`/`!` on finish lines, 1-indexed micro steps.

## Verification

Ran alphabet-sort debug-level runs on this branch (from scratch,
`--resume.step 2`, and post-merge): clean startup → steps → drain →
teardown on both processes, all lines rendering as intended, e.g.

```
INFO  Syncing inference to the trainer's startup broadcast (v0)
DEBUG Synced inference to policy v0 in 115ms
INFO  Stopping orchestrator components
DEBUG Stopping dispatcher
SUCCESS Orchestrator finished
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Mostly logging, but orchestrator setup order, resume-step timing,
NCCL/NIXL after pool ready, and an extra metrics probe change real
startup/teardown sequencing. A hang or resume mismatch would show up at
run start.
> 
> **Overview**
> Makes trainer/orchestrator/launcher logs follow a consistent pattern:
an **info** line for each potentially slow action (`Initializing` /
`Waiting`), then a **debug** completion with `format_time`. Identity
lines are aligned (`Starting from scratch` / `Resuming from step N`),
policy versions are labeled `v{N}`, and noisy lines (ZMQ init, GC,
per-group success, full model repr) are demoted or removed.
> 
> **Orchestrator `setup` is reordered**, not just reworded: local work
(packer, micro-batch sender, filesystem broadcast) runs first; env
servers, inference readiness, NCCL/NIXL handshake, and startup weight
sync wait last. Resume step is applied before those waits. Teardown now
logs each stage. An awaited `inference_metrics.probe()` primes the
concurrency controller before the loop starts.
> 
> Inference health wait is info every 30s (errors at debug). Drop-path
logs stay as `Dropped group | … | reason=…`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f1f33c0fc2fa3a2193118991c256cee0aae232ff. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 16:59:26 -07:00
822db2902c feat: drop orchestrator-side renderer for trace-stamped mm token map (#3349)
## Summary

- Drop the orchestrator-side renderer: the orchestrator built a full
`Renderer` only to read `mm_token_type_id_map` off it and stamp
per-token modality markers in `trace_to_samples`. verifiers now stamps
the map onto the trace at turn commit and exposes the training-ready
stream as `Branch.mm_token_type_ids` (PrimeIntellect-ai/verifiers#2424)
— the orchestrator consumes that and builds no renderer at all.
- `trace_to_samples` reads `branch.mm_token_type_ids` directly; the
`mm_token_type_ids_mapping` parameter and its `TrainSink`/`Orchestrator`
plumbing are gone.
- `setup_policy_inference_pool` (now just an `InferencePool`
construction) is inlined into `Orchestrator.setup()`; its mock-based
unit test file is removed.
- Bumps `deps/verifiers` to verifiers main, which includes the merged
PrimeIntellect-ai/verifiers#2424. Rollout rendering is unchanged — it
already happens inside verifiers' renderer train client.

## Verification

Before/after 6-step multimodal RL runs (color-codeword,
`Qwen/Qwen3.5-4B`, 1 train + 1 infer GPU, batch 64, group 8):

- **Before** (main): rewards 0.17 → 0.36 across 6 steps, 0% errors, all
samples trainable, losses finite.
- **After** (this PR + vf#2424): rewards 0.13 → 0.42 across 6 steps, 0%
errors, all samples trainable, losses finite. The trainer hard-fails on
image samples missing `mm_token_type_ids` (`prepare_sample` raises), so
completing all steps proves the new path delivers them. The after-run's
orchestrator log contains no renderer initialization.
- Offline equivalence on the after-run's 833 dumped traces (2499
branches): every trace's stamped `mm_token_type_id_map` equals the
renderer map the orchestrator used to build (`{<|image_pad|>: 1,
<|video_pad|>: 2}`), and per-token ids computed the old way match
`Branch.mm_token_type_ids`' computation exactly.
- `tests/unit/orchestrator` green (the pre-existing `test_qwen3_vl_e2e`
failure needs a live vLLM and fails identically on main).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the multimodal training-sample path: missing or mismatched
`mm_token_type_ids` would fail trainer `prepare_sample`. Behavior now
depends on verifiers stamping the map correctly rather than a local
renderer.
> 
> **Overview**
> Stops building an orchestrator-side `Renderer` just to stamp
multimodal token types. Training samples now take `mm_token_type_ids`
from `branch.mm_token_type_ids` (stamped by verifiers at turn commit).
> 
> `setup_policy_inference_pool` is inlined as a direct `InferencePool`
construction. `TrainSink` / `Orchestrator` no longer plumb
`mm_token_type_ids_mapping`, and the helper’s unit tests are removed.
Rollout rendering is unchanged (still inside the renderer train client).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4e6fde2b910f91e80fd460704077f87c98329032. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 16:36:48 -07:00
Mika SenghaasandGitHub adfbc6003d feat: expose repository skills to codex (#3347)
## Summary

- Add `.agents/skills` as a symlink to the shared `skills/` directory.
- Make repository skills available through Codex default discovery.

## Verification

- Confirmed `.agents/skills` resolves to `../skills`.
- Commit hooks passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Config-only symlink for agent skill discovery; no runtime, auth, or
data-handling changes.
> 
> **Overview**
> Adds a `.agents/skills` symlink to `../skills` so Codex can discover
the repo’s shared skills via its default lookup path.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
625149a26b20bafa2d3901222d4c1b7f4bdef35b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-22 15:44:18 -07:00
94a93203cf fix: only pkill zombie torchrun/vLLM processes in CI (#3346)
## Summary
- Gate the autouse `cleanup_zombies` fixture in `tests/conftest.py` on
`USERNAME_CI`.
- The fixture pkills `-f torchrun` / `-f VLLM` host-wide at every test
module start. In CI this cleans up zombies from previous tests, but
locally it kills any concurrent training run on the box.
- `USERNAME_CI` is already set to `CI_RUNNER` by all CI pytest jobs
(`cpu_tests`, `gpu_tests`, `nightly_tests`) and already keys the `user`
fixture, so CI behavior is unchanged and no workflow changes are needed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Test-only fixture change; CI behavior is preserved. Residual risk is
local leftover processes if tests leak zombies without USERNAME_CI.
> 
> **Overview**
> Stops the autouse `cleanup_zombies` fixture from host-wide `pkill` of
`torchrun`/`VLLM` on local pytest runs, so concurrent training jobs are
no longer killed.
> 
> The kill still runs when `USERNAME_CI` is set (already used by CI
pytest jobs), so CI zombie cleanup is unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
454f89e5c269d62410f2ea007b884537dd964045. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 15:44:00 -07:00
f0d27513a4 chore: glm-4.5-air swe example to bf16 + bash harness (#3343)
## Summary

- `examples/advanced/glm-4.5-air/swe.toml`: serve inference from the
bf16 checkpoint directly — drop `quantization = "fp8"` from
`[inference.vllm]`.
- Switch the train and eval harnesses from `rlm` to `bash`. Drop the
rlm-only `summarize_at_tokens` knobs.
- Update the header comments to match.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Example-only TOML config; no training, inference, or harness code
changes.
> 
> **Overview**
> Updates the GLM-4.5-Air SWE example so inference serves the **bf16**
checkpoint directly (drops vLLM `fp8` quantization) and train/eval use
the **bash** harness instead of **rlm**, including removing
`summarize_at_tokens`. Header comments are aligned with that.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
72032855baa5712daab635147683cf9c09541bf0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 13:45:23 -07:00
684f0d0afe chore: fold source sub-configs into dotted keys (#3344)
## Summary

- Fold every `[[...source]]` entry's nested sub-configs into dotted keys
in one block (`env.taskset.id = "..."`, `env.agent.harness.id = "..."`)
instead of one full-path subsection header per nested config. Applies to
all train/eval source blocks in `configs/`, `examples/`, and `k8s/` (51
TOML files, −868/+322 lines).
- Move the top-level `[monitors.prime]` block up next to
`[monitors.wandb]` in the 4 files where it sat inside the orchestrator
section.
- Apply the same style to the TOML snippets in `docs/` and the `configs`
/ `training/start-run` skills, and document the convention in the
configs skill. Nested arrays of tables (e.g.
`[[...source.env.taskset.task.judges]]`) keep their full-path headers.

Purely cosmetic — no config semantics change. Verified by asserting
`tomllib` parses every file to an identical dict before and after, and
by diffing the resolved-config JSON from `rl --dry-run` (identical up to
the CLI-passed `output_dir`).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 13:39:56 -07:00
83 changed files with 610 additions and 1327 deletions
+1
View File
@@ -0,0 +1 @@
../skills
+6 -14
View File
@@ -34,20 +34,12 @@ max_completion_tokens = 768
[[orchestrator.train.source]]
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # Checkpoint at the end of training
+5 -11
View File
@@ -21,17 +21,11 @@ seq_len = 8192
[[orchestrator.train.source]]
name = "hendrycks-math"
[orchestrator.train.source.env.taskset]
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "math-env"
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
env.taskset.dataset_subset = "default"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.model]
seq_len = 16384
+3 -9
View File
@@ -24,15 +24,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+3 -9
View File
@@ -29,14 +29,8 @@ max_completion_tokens = 1024
[[eval.source]]
name = "reverse-text"
[eval.source.env.taskset]
id = "reverse-text"
[eval.source.env.agent.harness]
id = "null"
[eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
+3 -9
View File
@@ -42,15 +42,9 @@ max_completion_tokens = 512
[[orchestrator.train.source]]
name = "wiki-search"
[orchestrator.train.source.env.taskset]
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "wiki-search"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # Checkpoint at the end of training
+3 -9
View File
@@ -23,15 +23,9 @@ group_size = 8
[[orchestrator.train.source]]
name = "wordle"
[orchestrator.train.source.env.taskset]
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
env.taskset.id = "wordle"
env.player.harness.id = "null"
env.player.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
+9 -17
View File
@@ -27,23 +27,15 @@ max_completion_tokens = 384
[[orchestrator.train.source]]
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 2
max_turns = 2
min_names_per_turn = 1
max_names_per_turn = 3
[orchestrator.train.source.env.taskset.task]
similarity_power = 4
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 2
env.taskset.max_turns = 2
env.taskset.min_names_per_turn = 1
env.taskset.max_names_per_turn = 3
env.taskset.task.similarity_power = 4
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
@@ -30,15 +30,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
@@ -27,15 +27,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
@@ -30,15 +30,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
@@ -42,15 +42,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -61,15 +55,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -48,15 +48,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -67,15 +61,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -30,15 +30,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
@@ -27,15 +27,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
+6 -14
View File
@@ -23,20 +23,12 @@ max_inflight = 128
[[orchestrator.train.source]]
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 768
+8 -20
View File
@@ -23,17 +23,11 @@ max_inflight = 128
[[orchestrator.train.source]]
name = "hendrycks-math"
[orchestrator.train.source.env.taskset]
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "math-env"
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
env.taskset.dataset_subset = "default"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 50
@@ -41,15 +35,9 @@ interval = 50
[[orchestrator.eval.source]]
name = "aime2024"
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "aime24"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer]
+3 -9
View File
@@ -23,15 +23,9 @@ max_inflight = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 128
+3 -9
View File
@@ -24,15 +24,9 @@ max_inflight = 128
[[orchestrator.train.source]]
name = "wiki-search"
[orchestrator.train.source.env.taskset]
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "wiki-search"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
+3 -9
View File
@@ -23,15 +23,9 @@ max_inflight = 128
[[orchestrator.train.source]]
name = "wordle"
[orchestrator.train.source.env.taskset]
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
env.taskset.id = "wordle"
env.player.harness.id = "null"
env.player.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
@@ -25,16 +25,10 @@ max_completion_tokens = 64
[[orchestrator.train.source]]
name = "color-codeword"
[orchestrator.train.source.env.taskset]
id = "color-codeword"
images_per_turn = 1
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "color-codeword"
env.taskset.images_per_turn = 1
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer]
+6 -14
View File
@@ -26,20 +26,12 @@ alpha = 0.1
[[orchestrator.train.source]]
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
+6 -18
View File
@@ -23,15 +23,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -42,15 +36,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+6 -18
View File
@@ -23,15 +23,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -42,15 +36,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+12 -34
View File
@@ -33,34 +33,18 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text-grpo"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text-opd"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.source.algo]
type = "opd"
[orchestrator.train.source.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
algo.type = "opd"
algo.teacher.name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
algo.teacher.base_url = "http://localhost:8001/v1"
[orchestrator.eval]
interval = 5
@@ -71,15 +55,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+6 -18
View File
@@ -35,15 +35,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -54,15 +48,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+6 -18
View File
@@ -35,15 +35,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -54,15 +48,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 1e-4
+10 -30
View File
@@ -23,21 +23,11 @@ max_completion_tokens = 512
[[orchestrator.train.source]]
name = "kuhn-poker"
[orchestrator.train.source.env.taskset]
id = "kuhn-poker"
[orchestrator.train.source.env.player0.harness]
id = "null"
[orchestrator.train.source.env.player0.runtime]
type = "subprocess"
[orchestrator.train.source.env.player1.harness]
id = "null"
[orchestrator.train.source.env.player1.runtime]
type = "subprocess"
env.taskset.id = "kuhn-poker"
env.player0.harness.id = "null"
env.player0.runtime.type = "subprocess"
env.player1.harness.id = "null"
env.player1.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -48,21 +38,11 @@ max_completion_tokens = 512
[[orchestrator.eval.source]]
name = "kuhn-poker"
[orchestrator.eval.source.env.taskset]
id = "kuhn-poker"
[orchestrator.eval.source.env.player0.harness]
id = "null"
[orchestrator.eval.source.env.player0.runtime]
type = "subprocess"
[orchestrator.eval.source.env.player1.harness]
id = "null"
[orchestrator.eval.source.env.player1.runtime]
type = "subprocess"
env.taskset.id = "kuhn-poker"
env.player0.harness.id = "null"
env.player0.runtime.type = "subprocess"
env.player1.harness.id = "null"
env.player1.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+6 -18
View File
@@ -31,15 +31,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -50,15 +44,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+6 -18
View File
@@ -40,15 +40,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -59,15 +53,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+6 -18
View File
@@ -40,15 +40,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -59,15 +53,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 1e-4
+9 -23
View File
@@ -41,6 +41,8 @@ num_infer_replicas = 1
project = "swe-ablations"
name = "debug-concurrency"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -104,17 +106,9 @@ thinking_retention = "all"
[[orchestrator.train.source]]
name = "scaleswe"
[orchestrator.train.source.env.taskset]
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
labels = ["debug-concurrency"]
[monitors.prime]
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["debug-concurrency"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
@@ -124,18 +118,10 @@ interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
num_examples = 100
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["debug-concurrency"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["debug-concurrency"]
env.agent.timeout.rollout = 3600
# --- Inference ---
+9 -27
View File
@@ -19,27 +19,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text-a"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text-b"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 5
@@ -50,15 +38,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+1 -1
+17 -51
View File
@@ -124,31 +124,17 @@ type = "grpo"
[[orchestrator.train.source]]
name = "math" # inherits the top-level grpo
[orchestrator.train.source.env.taskset]
id = "math"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "math"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "terminal"
[orchestrator.train.source.env.taskset]
id = "terminal"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "terminal"
env.agent.harness.id = "bash"
env.agent.runtime.type = "subprocess"
# this env runs its own algorithm
[orchestrator.train.source.algo]
type = "echo"
algo.type = "echo"
```
### The Algorithm Classes
@@ -365,21 +351,11 @@ episode_agents = ["solver"]
name = "proposer-solver"
group_size = 4 # proposed problems per source task
env.n = 4 # solver attempts per proposed problem
[orchestrator.train.source.env.taskset]
id = "proposer-solver"
[orchestrator.train.source.env.proposer.harness]
id = "null"
[orchestrator.train.source.env.proposer.runtime]
type = "subprocess"
[orchestrator.train.source.env.solver.harness]
id = "null"
[orchestrator.train.source.env.solver.runtime]
type = "subprocess"
env.taskset.id = "proposer-solver"
env.proposer.harness.id = "null"
env.proposer.runtime.type = "subprocess"
env.solver.harness.id = "null"
env.solver.runtime.type = "subprocess"
```
`group_size` controls how many problems are proposed from each source task. `env.n` controls how many solvers attempt each proposed problem. If a comparison contains only one trace—for example, a solver when `env.n = 1`—its advantage is zero.
@@ -399,21 +375,11 @@ decay = 0.95
[[orchestrator.train.source]]
name = "kuhn-poker"
[orchestrator.train.source.env.taskset]
id = "kuhn-poker"
[orchestrator.train.source.env.player0.harness]
id = "null"
[orchestrator.train.source.env.player0.runtime]
type = "subprocess"
[orchestrator.train.source.env.player1.harness]
id = "null"
[orchestrator.train.source.env.player1.runtime]
type = "subprocess"
env.taskset.id = "kuhn-poker"
env.player0.harness.id = "null"
env.player0.runtime.type = "subprocess"
env.player1.harness.id = "null"
env.player1.runtime.type = "subprocess"
```
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.
+13 -33
View File
@@ -106,10 +106,8 @@ uv run rl @ rl.toml --orchestrator.train.source.0.args \
```toml
[[orchestrator.train.source]]
[orchestrator.train.source.args]
dataset_name = "openai/gsm8k"
dataset_subset = "main"
args.dataset_name = "openai/gsm8k"
args.dataset_subset = "main"
```
### Optional Sub-Configs
@@ -153,42 +151,24 @@ Training and evaluation sources are arrays of tables. Set one source per environ
[[orchestrator.train.source]]
name = "gsm8k"
ratio = 3 # 75% of batches
[orchestrator.train.source.env.taskset]
id = "gsm8k"
split = "train"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "gsm8k"
env.taskset.split = "train"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text"
ratio = 1 # default — 25% of batches
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.eval.source]]
name = "gsm8k-eval"
[orchestrator.eval.source.env.taskset]
id = "gsm8k"
split = "test"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "gsm8k"
env.taskset.split = "test"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
+3 -9
View File
@@ -187,15 +187,9 @@ num_examples = 32
[[eval.source]]
name = "reverse-text"
[eval.source.env.taskset]
id = "reverse-text"
[eval.source.env.agent.harness]
id = "null"
[eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
+22 -44
View File
@@ -25,6 +25,8 @@ num_infer_replicas = 4
project = "search-ablations"
name = "glm45air-search"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -88,8 +90,6 @@ num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.0
[monitors.prime]
# --- Train: the search envs with usable training data (rlm `search` skill, prime sandbox) ---
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
@@ -97,18 +97,12 @@ num_turns_weight = 0.0
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
[[orchestrator.train.source]]
name = "openseeker"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "openseeker"
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.runtime.labels = ["glm45air-search"]
env.taskset.id = "openseeker"
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
@@ -127,18 +121,12 @@ choices = ["A", "B"]
[[orchestrator.train.source]]
name = "redsearcher"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.runtime.labels = ["glm45air-search"]
env.taskset.id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
@@ -163,24 +151,14 @@ interval = 20
[[orchestrator.eval.source]]
name = "browsecomp"
num_examples = 500 # full set is 1266; cap eval at 500
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm45air-search"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "browsecomp"
[orchestrator.eval.source.env.taskset.task.judge]
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.agent.timeout.rollout = 3600
env.taskset.id = "browsecomp"
env.taskset.task.judge.model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.eval.source.env.taskset.task.judges]]
+13 -31
View File
@@ -1,4 +1,4 @@
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, rlm harness on a prime sandbox
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash 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.
@@ -7,9 +7,8 @@
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
#
# 1 train + 3 infer nodes. Inference serves FP8 via online per-tensor quantization of the bf16
# checkpoint; weight broadcasts re-quantize through the same path on every update. The trainer fits on one
# node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
# 1 train + 3 infer nodes. Inference serves the bf16 checkpoint as-is (no quantization). The trainer
# fits on one node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
# skip-gather / skip-optimizer checkpointing.
@@ -40,6 +39,8 @@ num_infer_replicas = 3
project = "swe-ablations"
name = "glm45air-scaleswe"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -103,39 +104,21 @@ thinking_retention = "all"
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe"]
[orchestrator.train.source.env.taskset]
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["glm45air-swe"]
[monitors.prime]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm45air-swe"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe"]
env.agent.timeout.rollout = 3600
# --- Inference ---
@@ -149,5 +132,4 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
quantization = "fp8"
enable_return_routed_experts = true
+16 -40
View File
@@ -26,6 +26,8 @@ num_infer_replicas = 4
project = "terminal-ablations"
name = "glm45air-terminal"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -89,22 +91,14 @@ num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[monitors.prime]
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
[[orchestrator.train.source]]
name = "tmax"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["glm45air-terminal"]
[orchestrator.train.source.env.taskset]
id = "tmax"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.runtime.labels = ["glm45air-terminal"]
env.taskset.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]]
@@ -128,27 +122,17 @@ interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm45air-terminal"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.agent.timeout.rollout = 3600
env.taskset.id = "swebench-verified"
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# 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"
@@ -159,19 +143,11 @@ id = "swebench-verified"
[[orchestrator.eval.source]]
name = "terminal-bench-2"
group_size = 4 # avg@4
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm45air-terminal"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "terminal-bench-2"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.agent.timeout.rollout = 3600
env.taskset.id = "terminal-bench-2"
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
+3 -9
View File
@@ -134,15 +134,9 @@ clear_thinking = false
[[orchestrator.train.source]]
name = "r2e"
[orchestrator.train.source.env.taskset]
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
[orchestrator.train.source.env.agent.runtime]
labels = ["glm5-llmd"]
env.taskset.id = "r2e-gym"
env.agent.harness.id = "rlm"
env.agent.runtime.labels = ["glm5-llmd"]
[inference]
# <0.80 because glm5 layers are too large for 0.85
+3 -9
View File
@@ -78,15 +78,9 @@ interval = 20
[[orchestrator.eval.source]]
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm5-pd-disag", "swe-bench-verified"]
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm5-pd-disag", "swe-bench-verified"]
[inference]
# we need <0.85 bc glm5 layers are too large for 0.85
+24 -68
View File
@@ -54,103 +54,59 @@ max_inflight = 4096
name = "swe"
ratio = 0.3
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
[orchestrator.train.source.env.taskset]
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
labels = ["intellect-3.1", "swe"]
env.taskset.id = "r2e-gym"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["intellect-3.1", "swe"]
[[orchestrator.train.source]]
name = "deepdive"
ratio = 0.2
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
[orchestrator.train.source.env.taskset]
id = "deepdive"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
[orchestrator.train.source.env.agent.runtime]
labels = ["intellect-3.1", "deepdive"]
env.taskset.id = "deepdive"
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.runtime.labels = ["intellect-3.1", "deepdive"]
[[orchestrator.train.source]]
name = "math"
ratio = 0.3
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
[orchestrator.train.source.env.taskset]
id = "i3_math"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "i3_math"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "logic"
ratio = 0.2
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
[orchestrator.train.source.env.taskset]
id = "i3_logic"
[orchestrator.train.source.env.taskset.filter]
max = 0.874
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "i3_logic"
env.taskset.filter.max = 0.874
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "code"
ratio = 0.2
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
[orchestrator.train.source.env.taskset]
id = "i3_code"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "i3_code"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["intellect-3.1", "swe-bench-verified"]
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["intellect-3.1", "swe-bench-verified"]
[[orchestrator.eval.source]]
name = "aime2025"
[orchestrator.eval.source.env.taskset]
id = "aime25"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference.vllm]
tensor_parallel_size = 8
+6 -18
View File
@@ -53,30 +53,18 @@ max_inflight = 4096
[[orchestrator.train.source]]
name = "swe"
[orchestrator.train.source.env.taskset]
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
labels = ["minimax-swe", "swe"]
env.taskset.id = "r2e-gym"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["minimax-swe", "swe"]
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["minimax-swe", "swe-bench-verified"]
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["minimax-swe", "swe-bench-verified"]
[inference.vllm]
tensor_parallel_size = 8
+11 -25
View File
@@ -22,6 +22,8 @@ num_infer_replicas = 4
project = "nemotron-3-super"
name = "nemotron-3-super-swe"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -85,37 +87,21 @@ truncate_history_thinking = false
[[orchestrator.train.source]]
name = "scaleswe"
[orchestrator.train.source.env.taskset]
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["nemotron-3-super-swe"]
[monitors.prime]
env.taskset.id = "scaleswe"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.runtime.labels = ["nemotron-3-super-swe"]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
labels = ["nemotron-3-super-swe"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
env.taskset.id = "swebench-verified"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.runtime.labels = ["nemotron-3-super-swe"]
env.agent.timeout.rollout = 3600
[inference]
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
+6 -18
View File
@@ -52,30 +52,18 @@ max_completion_tokens = 32768
[[orchestrator.train.source]]
name = "math"
[orchestrator.train.source.env.taskset]
id = "i3_math"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "i3_math"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
name = "aime2025"
[orchestrator.eval.source.env.taskset]
id = "aime25"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference.vllm]
tensor_parallel_size = 8
+6 -18
View File
@@ -50,30 +50,18 @@ initial_inflight = 1024
[[orchestrator.train.source]]
name = "swe"
[orchestrator.train.source.env.taskset]
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
labels = ["qwen30b-swe", "swe"]
env.taskset.id = "r2e-gym"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["qwen30b-swe", "swe"]
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["qwen30b-swe", "swe-bench-verified"]
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["qwen30b-swe", "swe-bench-verified"]
[inference.vllm]
tensor_parallel_size = 8
+5 -13
View File
@@ -36,19 +36,11 @@ group_size = 16
max_off_policy_steps = 32
[[orchestrator.train.source]]
[orchestrator.train.source.env.taskset]
id = "general-agent"
min_tier = 1
[orchestrator.train.source.env.taskset.task.tools]
colocated = true
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "modal"
env.taskset.id = "general-agent"
env.taskset.min_tier = 1
env.taskset.task.tools.colocated = true
env.agent.harness.id = "null"
env.agent.runtime.type = "modal"
[inference]
+6 -14
View File
@@ -33,19 +33,11 @@ max_completion_tokens = 768
[[orchestrator.train.source]]
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference] # Default inference config
+8 -20
View File
@@ -18,17 +18,11 @@ seq_len = 8192
[[orchestrator.train.source]]
name = "hendrycks-math"
[orchestrator.train.source.env.taskset]
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "math-env"
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
env.taskset.dataset_subset = "default"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 50
@@ -36,15 +30,9 @@ interval = 50
[[orchestrator.eval.source]]
name = "aime2024"
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "aime24"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.model]
seq_len = 16384
+3 -9
View File
@@ -17,15 +17,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+3 -9
View File
@@ -22,15 +22,9 @@ max_completion_tokens = 1024
[[eval.source]]
name = "reverse-text"
[eval.source.env.taskset]
id = "reverse-text"
[eval.source.env.agent.harness]
id = "null"
[eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
+3 -9
View File
@@ -45,15 +45,9 @@ max_completion_tokens = 512
[[orchestrator.train.source]]
name = "wiki-search"
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
[orchestrator.train.source.env.taskset]
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "wiki-search"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # Checkpoint at the end of training
+3 -9
View File
@@ -20,15 +20,9 @@ group_size = 16
[[orchestrator.train.source]]
name = "wordle"
[orchestrator.train.source.env.taskset]
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
env.taskset.id = "wordle"
env.player.harness.id = "null"
env.player.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
+6 -18
View File
@@ -21,24 +21,12 @@ max_inflight = 32
[[eval.source]]
name = "swebench-verified"
[eval.source.env.taskset]
id = "swebench-verified"
[eval.source.env.agent.harness]
id = "bash"
[eval.source.env.agent.timeout]
rollout = 3600
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
[[eval.source]]
name = "terminal-bench-2"
[eval.source.env.taskset]
id = "terminal-bench-2"
[eval.source.env.agent.harness]
id = "bash"
[eval.source.env.agent.timeout]
rollout = 3600
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
+3 -9
View File
@@ -15,15 +15,9 @@ max_completion_tokens = 128
[[train.source]]
name = "reverse-text"
[train.source.env.taskset]
id = "reverse-text"
[train.source.env.agent.harness]
id = "null"
[train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[renderer]
name = "prime-qwen3"
+10 -20
View File
@@ -34,7 +34,9 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
## Special syntax
**No inline tables** — checked-in configs use `[section]` headers, never `key = { ... }`. Expand `env.taskset = { id = "..." }` to a full-path header (`[orchestrator.train.source.env.taskset]` — subtable headers after a `[[...]]` entry attach to that entry).
**No inline tables** — checked-in configs use `[section]` headers or dotted keys, never `key = { ... }`.
**Sources are one block** — inside a `[[...source]]` entry, write nested sub-configs as dotted keys in the same block (`env.taskset.id = "..."`, `env.agent.harness.id = "..."`), not one subsection header per nested config. Nested arrays of tables (e.g. `[[orchestrator.train.source.env.taskset.task.judges]]`) keep full-path headers — they attach to the preceding `[[...source]]` entry.
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
@@ -45,28 +47,16 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
```toml
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.eval.source]]
name = "reverse-text-eval"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
split = "test"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.taskset.split = "test"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text` or `--orchestrator.eval.source.0.env.taskset.id reverse-text`.
+3 -9
View File
@@ -114,15 +114,9 @@ max_inflight = 128
[[eval.source]]
num_examples = 32 # always cap eval size for smokes
group_size = 4
[eval.source.env.taskset]
id = "aime25"
[eval.source.env.agent.harness]
id = "null"
[eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/envs/eval/{name}.log`.
+2 -2
View File
@@ -252,7 +252,7 @@ def rl_local(config: RLConfig):
for split, source, address in env_servers(config):
name = source.resolved_name
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
logger.info(f"Starting {split} env server {name} at {address}")
logger.info(f"Starting {name} server")
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
env_server_log.parent.mkdir(parents=True, exist_ok=True)
@@ -282,7 +282,7 @@ def rl_local(config: RLConfig):
monitor_threads.append(monitor_thread)
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()]
logger.info("Starting orchestrator process")
logger.info("Starting orchestrator")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
with open(log_dir / "orchestrator.log", "w") as log_file:
orchestrator_process = Popen(
+2 -2
View File
@@ -446,7 +446,7 @@ def sft_local(config: SFTConfig):
# deterministic address, polling until the server is up.
for source, address in eval_env_servers(config):
name = source.resolved_name
logger.info(f"Starting eval env server {name} at {address}")
logger.info(f"Starting {name} server")
start_process(
f"env/eval/{name}",
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
@@ -455,7 +455,7 @@ def sft_local(config: SFTConfig):
)
if config.eval is not None:
logger.info("Starting evals process")
logger.info("Starting evals")
start_process(
"evals",
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
+13 -5
View File
@@ -9,6 +9,7 @@ down training.
from __future__ import annotations
import os
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, overload
@@ -18,7 +19,7 @@ from prime_rl.monitors.file import FileMonitor
from prime_rl.monitors.prime import PrimeMonitor
from prime_rl.monitors.wandb import WandbMonitor
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
if TYPE_CHECKING:
import verifiers.v1 as vf
@@ -60,12 +61,13 @@ async def setup(
if rank != 0:
return
monitors: list[tuple[Monitor, dict[str, Any]]] = []
monitors: list[tuple[str, Monitor, dict[str, Any]]] = []
if prime is not None:
monitors.append((PrimeMonitor(prime), dict(config=run_config)))
monitors.append(("prime", PrimeMonitor(prime), dict(config=run_config)))
if wandb is not None:
monitors.append(
(
"wandb",
WandbMonitor(wandb),
dict(
output_dir=output_dir,
@@ -77,11 +79,17 @@ async def setup(
)
)
if file is not None:
monitors.append((FileMonitor(file), dict(output_dir=output_dir)))
monitors.append(("file", FileMonitor(file), dict(output_dir=output_dir)))
if not monitors:
return
for monitor, init_kwargs in monitors:
get_logger().info(f"Initializing monitors ({', '.join(name for name, _, _ in monitors)})")
t0 = time.perf_counter()
for name, monitor, init_kwargs in monitors:
get_logger().info(f"Initializing {name} monitor ({monitor.config})")
await monitor.init(**init_kwargs)
MONITORS.append(monitor)
get_logger().debug(f"Initialized monitors in {format_time(time.perf_counter() - t0)}")
def get(monitor_cls: type[Monitor]) -> Monitor | None:
+1 -1
View File
@@ -28,7 +28,7 @@ class FileMonitor(Monitor):
self.path.parent.mkdir(parents=True, exist_ok=True)
# Line-buffered append so a concurrently-running dashboard can tail the file.
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
self.logger.info(f"Logging metrics to {self.path} and episodes to {output_dir / 'rollouts'}")
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
sanitized, dropped = sanitize(metrics)
+5 -2
View File
@@ -16,6 +16,7 @@ from prime_rl.configs.monitors import WandbMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.monitors.wandb.overview import ensure_overview_view
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import format_time
if TYPE_CHECKING:
import verifiers.v1 as vf
@@ -63,7 +64,7 @@ class WandbMonitor(Monitor):
x_primary=primary,
x_update_finish_state=finisher,
)
self.logger.info(f"Using shared W&B mode ({label=}, {primary=}, {finisher=})")
self.logger.debug(f"Using shared W&B mode ({label=}, {primary=}, {finisher=})")
is_online = True
else:
run_id = None
@@ -130,7 +131,7 @@ class WandbMonitor(Monitor):
except Exception as e:
self.logger.warning(f"Failed to create W&B overview view - {e}")
self.logger.info(f"Logging metrics to W&B run {self.wandb.id} ({self.wandb.url})")
self.logger.info(f"Logging metrics to W&B ({self.wandb.url})")
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
wandb.log({**metrics, "step": step})
@@ -140,6 +141,8 @@ class WandbMonitor(Monitor):
async def finalize(self) -> None:
self.logger.info(f"Finalizing W&B run {self.wandb.id}")
t0 = time.perf_counter()
# Explicit finish: in (experimental) shared mode the SDK's atexit finish does
# not land the run state - without this, even clean runs decay to "crashed".
await asyncio.to_thread(wandb.finish, exit_code=0)
self.logger.debug(f"Finalized W&B run in {format_time(time.perf_counter() - t0)}")
+1 -1
View File
@@ -678,7 +678,7 @@ class Dispatcher:
env_name = group.env_name if group is not None else claimed[-1][1].env_name
self.metrics.record_cancellation(kind=kind, env_name=env_name, n=cancelled)
get_logger().debug(
f"drop {kind} | group={str(group_id)[:8]} env={env_name} reason={reason} | "
f"Dropped {kind} group | group={str(group_id)[:8]} env={env_name} reason={reason} | "
f"cancelled={cancelled} (inflight={inflight_cancelled} unscheduled={unscheduled_cancelled})"
)
await self.out_q.put(
+5 -2
View File
@@ -20,6 +20,7 @@ keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
from __future__ import annotations
import asyncio
import time
from collections.abc import Iterator, Sequence
from itertools import islice
from typing import Generic, TypeVar
@@ -30,7 +31,7 @@ from verifiers.v1.serve import EnvClient
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
from prime_rl.orchestrator.generation_source import GenerationSource
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
# Max wait for the env server to answer health. Generous because the launcher spawns
# servers concurrently with the orchestrator, and a server imports its env package
@@ -68,6 +69,7 @@ class Env:
async def start(self) -> None:
"""Connect to the env server and load the taskset client-side."""
get_logger().debug(f"Connecting {self.name} to env server {self.address}")
t0 = time.perf_counter()
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.
@@ -82,7 +84,7 @@ class Env:
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}")
get_logger().info(f"Env {self.name} ready in {format_time(time.perf_counter() - t0)} (num_tasks={num_tasks})")
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
sampling = {**self.sampling_args}
@@ -196,6 +198,7 @@ class TrainEnvs(Envs[TrainEnv]):
self._envs: dict[str, TrainEnv] = {}
for config in configs:
assert config.algo is not None, "TrainSourceConfig.algo must be resolved before env construction"
get_logger().info(f"Initializing {config.algo.type} algorithm for {config.resolved_name}")
env = TrainEnv(
config,
addresses[("train", config.resolved_name)],
+108 -89
View File
@@ -31,12 +31,10 @@ from modelexpress.client import MxClient
from verifiers.v1.runtimes import set_base_sandbox_labels
if TYPE_CHECKING:
from renderers.base import Renderer
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.orchestrator.ckpt import CheckpointManager
from prime_rl.transports.rollouts.base import MicroBatchSender
from prime_rl.utils.client import InferencePool
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
from prime_rl import monitors
from prime_rl.configs.orchestrator import OrchestratorConfig
@@ -71,7 +69,6 @@ from prime_rl.orchestrator.utils import (
get_weight_dir,
intercept_vf_logging,
set_default_executor,
setup_policy_inference_pool,
trim_process_memory,
)
from prime_rl.orchestrator.watcher import WeightWatcher
@@ -79,7 +76,7 @@ from prime_rl.trainer.model import setup_tokenizer
from prime_rl.transports.rollouts import setup_micro_batch_sender
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
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.client import InferencePool, init_nccl_broadcast, init_nixl_broadcast
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.utils import (
@@ -137,8 +134,6 @@ class Orchestrator:
periodic_logger: PeriodicLogger
# Set by ``setup()`` only when relevant config is present
renderer: Renderer | None
mm_token_type_ids_mapping: dict[int, int] | None
heart: Heartbeat | None
inference_metrics: InferenceMetricsCollector | None
eval_envs: EvalEnvs | None
@@ -154,8 +149,7 @@ class Orchestrator:
# Route the in-process v1 library logging through our handler. The
# env server runs in a child process, so its logging is separate.
intercept_vf_logging(logger="verifiers.v1", level="WARN")
algorithms = sorted({env.algo.type for env in config.train.source if env.algo is not None})
get_logger().info(f"Starting orchestrator (algorithm: {', '.join(algorithms)})")
get_logger().info("Starting orchestrator")
self.progress = Progress()
self.ckpt_manager = setup_ckpt_manager(config.output_dir, config.ckpt)
@@ -178,8 +172,6 @@ class Orchestrator:
# Optional attributes — ``setup()`` populates them when the relevant
# config is present
self.renderer = None
self.mm_token_type_ids_mapping = None
self.heart = None
self.inference_metrics = None
self.eval_envs = None
@@ -199,24 +191,22 @@ class Orchestrator:
set_default_executor()
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
t0 = time.perf_counter()
self.tokenizer = setup_tokenizer(config.tokenizer)
get_logger().debug(f"Initialized tokenizer in {format_time(time.perf_counter() - t0)}")
# The one model prime-rl hosts: the live policy. Frozen model
# references are external endpoints — each env's Algorithm builds its
# own pools in ``setup()`` below.
get_logger().info(
f"Initializing policy inference pool (base_url={config.model.client.base_url}, model={config.model.name})"
get_logger().info(f"Initializing policy inference pool ({config.model})")
self.policy_inference = InferencePool(
config.model.client,
model_name=config.model.name,
train_client_type="renderer",
eval_client_type="openai_chat_completions",
renderer_config=config.renderer,
)
self.renderer, self.policy_inference = await setup_policy_inference_pool(
config=config, tokenizer=self.tokenizer
)
self.mm_token_type_ids_mapping = (
getattr(self.renderer, "mm_token_type_id_map", None) if self.renderer is not None else None
)
if self.mm_token_type_ids_mapping == {}:
self.mm_token_type_ids_mapping = None
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
wandb=config.monitors.wandb,
prime=config.monitors.prime,
@@ -237,25 +227,14 @@ class Orchestrator:
if config.heartbeat is not None:
self.heart = Heartbeat(config.heartbeat.url)
get_logger().info("Loading training environments")
self.train_envs = TrainEnvs(
config.train.source,
config.env_addresses,
policy_pool=self.policy_inference,
renderer_config=config.renderer,
)
get_logger().debug(
f"Loaded {len(self.train_envs)} training environment(s) ({', '.join(self.train_envs.names)})"
)
await self.train_envs.start()
get_logger().success("Train environment(s) ready")
if config.eval is not None:
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.eval.source, config.env_addresses)
get_logger().debug(f"Loaded {len(self.eval_envs)} eval environment(s) ({', '.join(self.eval_envs.names)})")
await self.eval_envs.start()
get_logger().success("Eval environment(s) ready")
if config.resume is not None:
if config.resume.dir is not None:
@@ -267,10 +246,52 @@ class Orchestrator:
# Resume below may bump ``policy.version`` and the LoRA model name
self.policy.model_name = self.policy_inference.model_name
self.lora_name = config.model.lora.name if config.model.lora else None
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
# trainer even when ``ckpt.skip_progress`` leaves the counter unrestored. The curricula
# themselves are restored below, once the envs are loaded.
if self.resume_step is not None:
self.progress.step = self.resume_step + 1
get_logger().info(f"Resuming from step {self.resume_step}")
else:
get_logger().info("Starting from scratch")
# Transports are local setup — initialize them before the env and inference waits.
self.packer = BatchPacker(config)
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
self.sender = setup_micro_batch_sender(
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
)
if config.weight_broadcast.type == "filesystem":
# Nothing to set up client-side — the watcher polls the broadcast dir.
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
# Wait phase: envs, then inference, then the trainer's startup broadcast —
# the last things before the main loop starts.
get_logger().info(f"Loading train environments ({', '.join(self.train_envs.names)})")
t0 = time.perf_counter()
await self.train_envs.start()
get_logger().success(f"Train environments ready in {format_time(time.perf_counter() - t0)}")
if self.eval_envs is not None:
get_logger().info(f"Loading eval environments ({', '.join(self.eval_envs.names)})")
t0 = time.perf_counter()
await self.eval_envs.start()
get_logger().success(f"Eval environments ready in {format_time(time.perf_counter() - t0)}")
self.train_source = TrainSource(self.train_envs)
if self.resume_step is not None:
resume = self.config.resume
resume_path = resume.dir / "orchestrator" if resume is not None and resume.dir is not None else None
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step, path=resume_path)
self.progress.step = self.resume_step + 1
get_logger().info("Waiting for policy inference pool to be ready")
t0 = time.perf_counter()
await self.policy_inference.wait_for_ready(config.model.name)
get_logger().success("Policy inference pool ready")
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
# Build + ready pools for each env's frozen generation source and the
# algorithm's frozen reference model
await asyncio.gather(
@@ -278,61 +299,46 @@ class Orchestrator:
*(env.algorithm.setup() for env in self.train_envs),
)
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
if config.weight_broadcast.type == "nccl":
await init_nccl_broadcast(
self.policy_inference.admin_clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
inference_world_size=config.weight_broadcast.inference_world_size,
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
)
elif config.weight_broadcast.type == "nixl":
await init_nixl_broadcast(
self.policy_inference.admin_clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
config.weight_broadcast.inference_world_size,
config.weight_broadcast.session_id,
)
self.model_express = ModelExpressSession(
client=MxClient(server_url=f"{config.weight_broadcast.host}:{config.weight_broadcast.port}"),
role="orchestrator",
rank=0,
session_id=config.weight_broadcast.session_id,
worker_id="orchestrator",
)
self.model_express.publish()
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.lora_name = config.model.lora.name if config.model.lora else None
self.train_source = TrainSource(self.train_envs)
if self.resume_step is not None:
resume = self.config.resume
resume_path = resume.dir / "orchestrator" if resume is not None and resume.dir is not None else None
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step, path=resume_path)
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
self.progress.step = self.resume_step + 1
get_logger().info(f"Resuming orchestrator from checkpoint step {self.resume_step}")
else:
get_logger().info("Training from scratch")
self.packer = BatchPacker(config)
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
self.sender = setup_micro_batch_sender(
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
)
# The in-memory broadcast transports rendezvous with live inference
# engines, so their setup must follow pool readiness.
if config.weight_broadcast.type in ("nccl", "nixl"):
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
if config.weight_broadcast.type == "nccl":
await init_nccl_broadcast(
self.policy_inference.admin_clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
inference_world_size=config.weight_broadcast.inference_world_size,
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
)
else:
await init_nixl_broadcast(
self.policy_inference.admin_clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
config.weight_broadcast.inference_world_size,
config.weight_broadcast.session_id,
)
self.model_express = ModelExpressSession(
client=MxClient(server_url=f"{config.weight_broadcast.host}:{config.weight_broadcast.port}"),
role="orchestrator",
rank=0,
session_id=config.weight_broadcast.session_id,
worker_id="orchestrator",
)
self.model_express.publish()
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
get_logger().debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
# Sync inference to the incoming policy before the first step, rendezvousing
# with the trainer's startup broadcast (v{resume_step} on resume, v0 from
# scratch).
sync_version = self.resume_step if self.resume_step is not None else 0
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
t0 = time.perf_counter()
if config.weight_broadcast.type == "nixl":
weights_path = None
else:
@@ -362,6 +368,7 @@ class Orchestrator:
self.policy_inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
self.policy.version = sync_version
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
self.eval_source: EvalSource | None = (
EvalSource(
@@ -408,11 +415,13 @@ class Orchestrator:
log_to_wandb=wandb_enabled and config.collect_inference_metrics,
)
await self.inference_metrics.start()
# One awaited scrape so the concurrency controller derives (and logs) its
# initial limit before the loop-start line; failures are tolerated.
await self.inference_metrics.probe()
self.train_sink = TrainSink(
config,
tokenizer=self.tokenizer,
train_envs=self.train_envs,
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
progress=self.progress,
batch_size=config.batch_size,
token_batch_size=config.token_batch_size,
@@ -511,13 +520,13 @@ class Orchestrator:
# first ship).
if self.config.ckpt is not None and self.progress.step > 1:
self.progress.step -= 1
get_logger().info("Writing final checkpoint")
get_logger().info(f"Saving final checkpoint at step {self.progress.step}")
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
await self.stop()
if clean_exit:
get_logger().success("Orchestrator finished.")
get_logger().success("Orchestrator finished")
else:
get_logger().warning("Orchestrator cleanup complete (forced).")
get_logger().warning("Orchestrator cleanup complete (forced)")
trim_process_memory()
async def wait_for_final_broadcast(self) -> None:
@@ -980,13 +989,14 @@ class Orchestrator:
if lead > TARGET_LAG:
if was_set:
get_logger().info(
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
f"Pausing dispatcher until the trainer publishes policy v{self.progress.step - 1 - TARGET_LAG} "
f"(currently v{self.policy.version})"
)
self.gate_closed_at = time.perf_counter()
gate.clear()
else:
if not was_set:
get_logger().info("Resuming dispatcher")
get_logger().info(f"Resuming dispatcher (policy v{self.policy.version})")
if self.gate_closed_at is not None:
self.wait_for_policy_time += time.perf_counter() - self.gate_closed_at
self.gate_closed_at = None
@@ -1012,10 +1022,13 @@ class Orchestrator:
training artifacts are already persisted before this is reached."""
async def teardown() -> None:
get_logger().debug("Closing micro batch sender")
self.sender.close()
if self.dispatcher is not None:
get_logger().debug("Stopping dispatcher")
await self.dispatcher.stop()
if self.watcher is not None:
get_logger().debug("Stopping weight watcher")
await self.watcher.stop()
if self.periodic_logger is not None:
await self.periodic_logger.stop()
@@ -1026,14 +1039,19 @@ class Orchestrator:
await safe_cancel(task)
self.component_tasks.clear()
if self.inference_metrics is not None:
get_logger().debug("Stopping inference metrics collector")
await self.inference_metrics.stop()
if getattr(self, "policy_inference", None) is not None:
get_logger().debug("Stopping policy inference pool")
await self.policy_inference.stop()
if self.train_envs is not None:
get_logger().debug("Stopping generation source and algorithm pools")
for env in self.train_envs:
for pool in (*env.generation_source.connected_pools, *env.algorithm.connected_pools):
await pool.stop()
get_logger().info("Stopping orchestrator components")
t0 = time.perf_counter()
task = asyncio.create_task(teardown())
_, pending = await asyncio.wait({task}, timeout=SHUTDOWN_TIMEOUT_S)
if pending:
@@ -1043,6 +1061,7 @@ class Orchestrator:
)
os._exit(0)
await task
get_logger().debug(f"Stopped orchestrator components in {format_time(time.perf_counter() - t0)}")
@clean_exit
+5 -19
View File
@@ -70,7 +70,6 @@ class TrainSink:
*,
tokenizer,
train_envs: TrainEnvs,
mm_token_type_ids_mapping: dict[int, int] | None,
progress: Progress,
batch_size: int | None,
token_batch_size: int | None,
@@ -82,7 +81,6 @@ class TrainSink:
self.config = config
self.tokenizer = tokenizer
self.train_envs = train_envs
self.mm_token_type_ids_mapping = mm_token_type_ids_mapping
self.progress = progress
self.batch_size = batch_size
self.token_batch_size = token_batch_size
@@ -232,8 +230,8 @@ class TrainSink:
self.pending_episodes.extend(group, admitted=False, cancelled=True)
self._record_zero_output(group, [], n_owed)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | dropped: cancelled (stale)"
f"Dropped group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reason=cancelled (stale)"
)
return
@@ -246,20 +244,15 @@ class TrainSink:
self._record_zero_output(group, survivors, n_owed)
reason = "no trainable survivors" if not survivors else "rejected by curriculum"
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | dropped: {reason}"
f"Dropped group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reason={reason}"
)
return
samples_by_trace: dict[str, list[TrainingSample]] = {}
temperature = env.sampling_args["temperature"]
for trace in survivors:
samples = await asyncio.to_thread(
trace_to_samples,
trace,
env_name=env_name,
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
)
samples = await asyncio.to_thread(trace_to_samples, trace, env_name=env_name)
for sample in samples:
sample.temperatures = [temperature] * len(sample.token_ids)
stamp_loss_routing(sample, env.algorithm.action_loss_type)
@@ -292,13 +285,6 @@ class TrainSink:
self.zero_output_units = 0
self.reported_zero_output_windows = 0
rewards = [trace.reward for trace in survivors if trace.id in samples_by_trace]
avg_reward = sum(rewards) / len(rewards)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reward={avg_reward:.4f}"
)
def _trace(self, trace_id: str) -> vf.Trace:
episode = self.episode_by_trace[trace_id]
return next(trace for trace in episode.traces if trace.id == trace_id)
+5 -13
View File
@@ -108,12 +108,7 @@ def _loss_weights(branch: vf.Branch, name: str, trained_nodes: set[int]) -> list
return weights if any(weights) else None
def trace_to_samples(
trace: vf.Trace,
*,
env_name: str = "",
mm_token_type_ids_mapping: dict[int, int] | None = None,
) -> list[TrainingSample]:
def trace_to_samples(trace: vf.Trace, *, env_name: str = "") -> list[TrainingSample]:
"""Convert a v1 `Trace` into `TrainingSample`s — one per branch.
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
@@ -121,21 +116,18 @@ def trace_to_samples(
the trainable (model-sampled) tokens, the context tokens between completions stay masked
out. Errored traces are dropped upstream (`TrainSink.process_episode`), so no error
handling happens here. A branch carrying images also gets `mm_kwargs` (the concatenated
pixel tensors) and `mm_token_type_ids` (the renderer's `mm_token_type_id_map` applied to
the branch tokens). Branches with no sampled tokens (e.g. an openai client carrying none)
yield nothing.
pixel tensors) and `mm_token_type_ids` (`branch.mm_token_type_ids`, computed from the
trace's renderer-stamped `mm_token_type_id_map`). Branches with no sampled tokens
(e.g. an openai client carrying none) yield nothing.
"""
samples: list[TrainingSample] = []
trained_loss_nodes: dict[str, set[int]] = {"rl": set(), "ce": set(), "ref_kl": set()}
for branch, mask in iter_trainable_branches(trace):
token_ids = branch.token_ids
mm_kwargs: dict[str, EncodedTensor] | None = None
mm_token_type_ids: list[int] | None = None
mmd = branch.multi_modal_data
if mmd is not None:
mm_kwargs = _encode_mm_kwargs(mmd.mm_items)
mapping = mm_token_type_ids_mapping or {}
mm_token_type_ids = [mapping.get(t, 0) for t in token_ids]
samples.append(
TrainingSample(
token_ids=token_ids,
@@ -145,7 +137,7 @@ def trace_to_samples(
env_name=env_name,
ref_logprobs=branch.reference_logprobs,
mm_kwargs=mm_kwargs,
mm_token_type_ids=mm_token_type_ids,
mm_token_type_ids=branch.mm_token_type_ids,
routed_experts=_encode_routed_experts(branch.routed_experts, len(token_ids)),
rl_weights=_loss_weights(branch, "rl", trained_loss_nodes["rl"]),
ce_weights=_loss_weights(branch, "ce", trained_loss_nodes["ce"]),
+1 -33
View File
@@ -10,8 +10,6 @@ from typing import Any
import verifiers.v1 as vf
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import InterceptHandler, get_logger, setup_logger
from prime_rl.utils.utils import (
get_broadcast_dir,
@@ -70,36 +68,6 @@ def episode_staleness(episode: vf.Episode[Any, Any, Any], training_step: int) ->
return total, in_flight, in_queue
async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
"""Build the live policy inference pool + matching renderer. Returns
``(renderer, inference_pool)``.
Training is renderer-only: the renderer object is the canonical
messages → token ids path (sft backfill, opsd scoring prefixes, echo role
attribution) and is always built. The renderer-client sampling path is
wired onto the pool; when no train env samples from the live policy the
renderer is still kept for client-side tokenization and the pool's evals
use plain chat-completions."""
from renderers.base import create_renderer
client_config = config.model.client
model_name = config.model.name
renderer = create_renderer(tokenizer, config.renderer)
get_logger().info(f"Initialized {type(renderer).__name__} for {model_name}")
if config.any_policy_sourced:
get_logger().info("Using direct renderer rollout client")
else:
get_logger().info("No policy-sourced train env — renderer kept for client-side tokenization only")
inference_pool = InferencePool(
client_config,
model_name=model_name,
train_client_type="renderer",
eval_client_type="openai_chat_completions",
renderer_config=config.renderer,
)
return renderer, inference_pool
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
"""Intercepts verifiers logging and routes through prime-rl logger with optional prefix."""
vf_logger = logging.getLogger(logger)
@@ -120,7 +88,7 @@ def setup_env_server_logging(log_level: str, json_logging: bool = False) -> None
def set_default_executor(max_workers: int = 64) -> None:
"""Scale the default asyncio thread pool so asyncio.to_thread has enough capacity."""
get_logger().info(f"Setting default executor to ThreadPoolExecutor(max_workers={max_workers})")
get_logger().debug(f"Setting default executor to ThreadPoolExecutor(max_workers={max_workers})")
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=max_workers))
+5 -6
View File
@@ -103,10 +103,7 @@ class WeightWatcher:
weights_path = get_step_path(broadcast_dir, next_step)
stable_marker = weights_path / "STABLE"
if not stable_marker.exists():
get_logger().info(
f"Orchestrator paused: waiting for trainer to broadcast checkpoint {next_step}. "
"Training is progressing normally."
)
get_logger().info(f"Waiting for the trainer to broadcast policy v{next_step}")
await wait_for_path(stable_marker)
self.last_wait_for_ckpt_time = time.perf_counter() - t0
@@ -135,12 +132,14 @@ class WeightWatcher:
f"Observer {type(observer).__name__}.on_version_pending({next_step}) raised: {exc!r}"
)
get_logger().debug(f"Updating weights to step {next_step}")
get_logger().debug(f"Updating inference weights to policy v{next_step}")
t1 = time.perf_counter()
await self.inference.update_weights(weights_path, lora_name=self.lora_name, step=next_step)
self.last_update_weights_time = time.perf_counter() - t1
self.update_count += 1
get_logger().debug(f"Updated weights to step {next_step} in {format_time(self.last_update_weights_time)}")
get_logger().debug(
f"Updated inference weights to policy v{next_step} in {format_time(self.last_update_weights_time)}"
)
if self.lora_name is not None:
self.inference.update_model_name(self.lora_name)
+3 -3
View File
@@ -21,7 +21,7 @@ from prime_rl.configs.shared import ResumeConfig
from prime_rl.configs.trainer import CheckpointConfig
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path
@@ -194,7 +194,7 @@ class CheckpointManager:
# Save sharded state
dcp_save(state_dict, checkpoint_id=path)
self.logger.debug(f"Training checkpoint saved in {time.perf_counter() - start_time:.2f} seconds")
self.logger.debug(f"Saved training checkpoint in {format_time(time.perf_counter() - start_time)}")
def load_from_path(
self,
@@ -232,7 +232,7 @@ class CheckpointManager:
)
dataloader.load_state_dict(torch.load(dataloader_path, weights_only=False))
self.logger.debug(f"Training checkpoint loaded in {time.perf_counter() - start_time:.2f} seconds")
self.logger.debug(f"Loaded training checkpoint in {format_time(time.perf_counter() - start_time)}")
def load(
self,
+1 -1
View File
@@ -241,7 +241,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
)
raise RuntimeError("Cannot apply LoRA to FSDP-wrapped model. Apply LoRA before setup_fsdp().")
logger.debug(f"Applying LoRA to model: {model} for {config.target_modules}")
logger.debug(f"Applying LoRA to {type(model).__name__} (target_modules={config.target_modules})")
target_modules = _find_target_modules(model, config.target_modules)
logger.debug(
f"Found {len(target_modules)} target modules for LoRA: {target_modules[:10]} ... {target_modules[-10:]}"
+3 -3
View File
@@ -595,7 +595,7 @@ def get_model(
config: ModelConfig, device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.bfloat16
) -> nn.Module:
logger = get_logger()
logger.info(
logger.debug(
f"Loading model config (name={config.name}, attn={config.attn}, trust_remote_code={config.trust_remote_code})"
)
@@ -778,7 +778,7 @@ def get_model(
trust_remote_code=config.trust_remote_code,
**dtype_kwarg,
)
logger.debug(f"Loaded model {config.name} in {time.perf_counter() - load_model_start_time:.2f} seconds")
logger.debug(f"Loaded model {config.name} in {format_time(time.perf_counter() - load_model_start_time)}")
assert model.lm_head.weight.dtype == dtype, (
f"LM head dtype wasnt loaded correctly {model.lm_head.weight.dtype} != {dtype}"
@@ -1057,7 +1057,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
generator = torch.Generator(device="cuda").manual_seed(seed_tensor.item())
for module in lora_modules:
module._init_lora_parameters(generator)
logger.debug(f"Loaded weights using HF DCP in {time.perf_counter() - load_dcp_start_time:.2f} seconds")
logger.debug(f"Loaded weights using HF DCP in {format_time(time.perf_counter() - load_dcp_start_time)}")
def can_reinit_empty_buffers(model: nn.Module):
+6 -1
View File
@@ -17,6 +17,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import time
from dataclasses import dataclass
from functools import cached_property
@@ -25,7 +26,7 @@ from torch._utils import _get_available_device_type
from torch.distributed.device_mesh import DeviceMesh, init_device_mesh
from prime_rl.configs.trainer import ModelConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
device_type = _get_available_device_type() or "cuda"
@@ -105,7 +106,9 @@ class ParallelDims:
names.append(name)
self.logger.info(f"Building {len(dims)}-D device mesh with {names}, {dims}")
t0 = time.perf_counter()
mesh = init_device_mesh(device_type, dims, mesh_dim_names=names)
self.logger.debug(f"Built device mesh in {format_time(time.perf_counter() - t0)}")
# Create all the submesh here to ensure all required process groups are
# initialized:
@@ -163,7 +166,9 @@ class ParallelDims:
names.append(name)
self.logger.info(f"Building {len(dims)}-D device mesh with {names}, {dims}")
t0 = time.perf_counter()
mesh = init_device_mesh(device_type, dims, mesh_dim_names=names)
self.logger.debug(f"Built device mesh in {format_time(time.perf_counter() - t0)}")
# Create all the submesh here to ensure all required process groups are
# initialized:
+28 -17
View File
@@ -79,10 +79,9 @@ def train(config: TrainerConfig):
config.log.level,
json_logging=config.log.json_logging,
)
logger.info(f"Starting RL trainer in {world} in {config.output_dir}")
logger.info(f"Starting RL trainer in {world} (output_dir={config.output_dir})")
# Setup the monitors
logger.info(f"Initializing monitors ({config.monitors})")
asyncio.run(
monitors.setup(
wandb=config.monitors.wandb, file=config.monitors.file, output_dir=config.output_dir, run_config=config
@@ -140,19 +139,21 @@ def train(config: TrainerConfig):
# Initialize the model and tokenizer
logger.info(f"Initializing model ({config.model})")
t0 = time.perf_counter()
loading_from_ckpt_later = checkpoint_step is not None
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
logger.debug(f"Initialized model in {format_time(time.perf_counter() - t0)}")
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
raise ValueError("Packed multimodal training requires model support")
# Set up the loss function for the RL loss type (ce / ref_kl are fixed)
logger.info(f"Setting up loss function ({config.loss})")
logger.info(f"Initializing loss function ({config.loss})")
rl_loss_fn = setup_rl_loss_fn(config.loss)
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
t0 = time.perf_counter()
optimizer, gradient_manager = setup_optimizer(
config.optim,
list(model.named_parameters()),
@@ -164,9 +165,10 @@ def train(config: TrainerConfig):
get_full_offload_dtype_policy(model, config.model) if config.model.full_offload is not None else None
),
)
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
logger.debug(f"Initialized optimizer in {format_time(time.perf_counter() - t0)}")
logger.info(f"Using `{config.scheduler.type}` scheduler ({config.scheduler})")
logger.info(f"Initializing scheduler ({config.scheduler})")
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
# Set up weight broadcast (skip when using fake data since there's no inference server)
if config.data.fake:
@@ -174,12 +176,14 @@ def train(config: TrainerConfig):
logger.info("Skipping weight broadcast setup (fake data mode)")
else:
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
weight_broadcast = setup_weight_broadcast(
config.output_dir,
config.weight_broadcast,
parallel_dims,
config.model.lora,
)
logger.debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
if parallel_dims.cp_enabled:
cp_group = parallel_dims.world_mesh["cp"].get_group()
@@ -228,14 +232,16 @@ def train(config: TrainerConfig):
)
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
progress.step += 1
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
logger.info(
f"Starting from step {progress.step} (total_tokens={progress.total_tokens}, total_samples={progress.total_samples})"
)
logger.info(
f"Resuming from step {checkpoint_step} "
f"(total_tokens={progress.total_tokens}, total_samples={progress.total_samples})"
)
else:
logger.info("Starting from scratch")
# Set up the data loader (Optionally, use a fake data loader for debugging)
logger.info(f"Initializing data loader ({config.data})")
t0 = time.perf_counter()
if config.data.fake:
dataloader = FakeDataLoader(config.data.fake, config.model.seq_len, parallel_dims.get_mesh("dp").size())
else:
@@ -245,6 +251,7 @@ def train(config: TrainerConfig):
parallel_dims.get_mesh("dp").size(),
config.rollout_transport,
)
logger.debug(f"Initialized data loader in {format_time(time.perf_counter() - t0)}")
token_exporter = setup_token_exporter(config, parallel_dims, world, logger)
@@ -273,22 +280,26 @@ def train(config: TrainerConfig):
# and so a broken broadcast path fails at startup instead of after the first
# optimizer step.
if progress.step == start_step and weight_broadcast is not None:
logger.info(f"Broadcasting startup policy weights (v{progress.step - 1}) to inference engines")
logger.info(f"Broadcasting base policy weights (v{progress.step - 1}) to inference engines")
t0 = time.perf_counter()
weight_broadcast.broadcast_weights(model, step=progress.step - 1)
logger.debug(
f"Broadcast base policy weights (v{progress.step - 1}) in {format_time(time.perf_counter() - t0)}"
)
# Wait for the batch to be available
logger.debug("Waiting for training batch to arrive")
wait_for_batch_start_time = time.perf_counter()
dataloader.wait_for_batch()
wait_for_batch_time = time.perf_counter() - wait_for_batch_start_time
logger.debug(f"Waited for batch to arrive for {wait_for_batch_time:.2f} seconds")
logger.debug(f"Waited for batch for {format_time(wait_for_batch_time)}")
# Load the training batch
logger.debug("Loading batch")
load_data_start_time = time.perf_counter()
micro_batches = dataloader.get_batch()
load_data_time = time.perf_counter() - load_data_start_time
logger.debug(f"Loaded batch in {load_data_time:.2f} seconds")
logger.debug(f"Loaded batch in {format_time(load_data_time)}")
batch_size = len(micro_batches)
memory_profiler = None
@@ -539,7 +550,7 @@ def train(config: TrainerConfig):
tensors[key].append(loss_tensor.detach().to("cpu"))
# Debug log with *local, micro step* stats
micro_step_message = f"Micro Step {micro_step}/{len(micro_batches)} | Loss {tensors['loss'][-1].mean().item():.4f} | Entropy {tensors['entropy/all'][-1].mean().item():.4f}"
micro_step_message = f"Micro Step {micro_step + 1}/{len(micro_batches)} | Loss {tensors['loss'][-1].mean().item():.4f} | Entropy {tensors['entropy/all'][-1].mean().item():.4f}"
if has_mismatch_tokens:
micro_step_message += f" | Mismatch KL {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
if "max_vio" in tensors:
@@ -726,7 +737,7 @@ def train(config: TrainerConfig):
# Write final checkpoint
if config.ckpt is not None:
logger.info("Writing final checkpoint")
logger.info(f"Saving final checkpoint at step {progress.step}")
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
ckpt_manager.maybe_clean()
@@ -734,7 +745,7 @@ def train(config: TrainerConfig):
gradient_manager.close()
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
logger.success("RL trainer finished!")
logger.success("RL trainer finished")
# Stop metrics/health server if configured
if metrics_server is not None:
+11 -10
View File
@@ -72,10 +72,9 @@ def train(config: SFTConfig):
config.log.level,
json_logging=config.log.json_logging,
)
logger.info(f"Starting SFT trainer in {world}")
logger.info(f"Starting SFT trainer in {world} (output_dir={config.run_dir})")
# Setup the monitors
logger.info(f"Initializing monitors ({config.monitors})")
asyncio.run(
monitors.setup(
wandb=config.monitors.wandb,
@@ -184,7 +183,7 @@ def train(config: SFTConfig):
renderer = create_renderer(tokenizer, config.renderer)
if processor is not None and hasattr(renderer, "_processor"):
renderer._processor = processor
logger.info(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
logger.debug(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
@@ -208,7 +207,7 @@ def train(config: SFTConfig):
if config.max_steps is not None and (config.ckpt and config.ckpt.skip_scheduler and checkpoint_step is not None)
else config.max_steps
)
logger.info(f"Setting up {config.scheduler.type} scheduler with {scheduler_steps} steps ({config.scheduler})")
logger.info(f"Initializing scheduler with {scheduler_steps} steps ({config.scheduler})")
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
# Set up the dataset and dataloader
@@ -237,16 +236,18 @@ def train(config: SFTConfig):
dataloader=dataloader if not skip.skip_dataloader else None,
path=resume_dir / "trainer" if resume_dir is not None else None,
)
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
if not skip.skip_progress:
progress.step += 1
# This redundant setup is necessary because loading the optimizer's state has side effects on the scheduler state dict
if skip.skip_scheduler:
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
logger.info(
f"Starting from step {progress.step} (total_tokens={progress.total_tokens}, total_samples={progress.total_samples}, dataset_state={get_dataset_state(dataloader)})"
)
logger.info(
f"Resuming from step {checkpoint_step} (total_tokens={progress.total_tokens}, "
f"total_samples={progress.total_samples}, dataset_state={get_dataset_state(dataloader)})"
)
else:
logger.info("Starting from scratch")
# Create the iterator only after a potential resume: iter() forks workers with a
# copy of the dataset's *current* state, so a later load_state_dict never reaches
@@ -705,7 +706,7 @@ def train(config: SFTConfig):
# Write final checkpoint
if config.ckpt is not None:
logger.info("Writing final checkpoint")
logger.info(f"Saving final checkpoint at step {progress.step}")
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
ckpt_manager.maybe_clean()
@@ -720,7 +721,7 @@ def train(config: SFTConfig):
gradient_manager.close()
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
logger.success("SFT trainer finished!")
logger.success("SFT trainer finished")
def main():
+5 -2
View File
@@ -17,7 +17,7 @@ from torchtitan.distributed.utils import clip_grad_norm_ as torch_clip_grad_norm
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_ckpt_dir
from prime_rl.utils.utils import get_step_path
@@ -52,7 +52,7 @@ class GarbageCollection:
def _collect(self, generation: int = 1):
begin = time.monotonic()
gc.collect(generation)
get_logger().info(f"[GC] collection took {time.monotonic() - begin:.2f}s")
get_logger().debug(f"Collected garbage in {format_time(time.monotonic() - begin)}")
def prepare_gradient_offload(
@@ -172,6 +172,8 @@ def setup_full_cpu_optimizer_offload(config: "OptimizerInBackwardOffloadConfig")
def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: bool = False):
get_logger().info(f"Initializing torch distributed (timeout={int(timeout.total_seconds())}s)")
t0 = time.perf_counter()
device_id = get_world().local_rank
torch.cuda.set_device(device_id)
# Use Gloo backend for CPU and NCCL for GPU when CPU offloading is enabled
@@ -189,6 +191,7 @@ def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: b
dist.distributed_c10d.default_pg_timeout = timeout
dist.init_process_group(backend=backend, timeout=timeout, device_id=device_id)
get_logger().debug(f"Initialized torch distributed in {format_time(time.perf_counter() - t0)}")
def print_sample(input_ids: list[int], loss_mask: list[bool], tokenizer: PreTrainedTokenizer):
+8 -8
View File
@@ -35,9 +35,9 @@ class ZMQMicroBatchSender(MicroBatchSender):
self._ready = False
self.logger.info(
f"ZMQ micro batch sender initialized: endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm}"
self.logger.debug(
f"Initialized ZMQ micro batch sender (endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm})"
)
self._topic_prefix = b"data_rank|"
@@ -84,7 +84,7 @@ class ZMQMicroBatchSender(MicroBatchSender):
self.socket.close(linger=0)
self.ready_socket.close(linger=0)
finally:
self.logger.info("ZMQ micro batch sender closed")
self.logger.debug("Closed ZMQ micro batch sender")
class ZMQMicroBatchReceiver(MicroBatchReceiver):
@@ -111,9 +111,9 @@ class ZMQMicroBatchReceiver(MicroBatchReceiver):
# Announce readiness after connect+subscribe are set
self.ready_socket.send(str(data_rank).encode("utf-8"))
self.logger.info(
f"ZMQ micro batch receiver initialized: endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm}"
self.logger.debug(
f"Initialized ZMQ micro batch receiver (endpoint=tcp://{transport.host}:{transport.port} "
f"ready_endpoint=tcp://{transport.host}:{transport.port + 1} hwm={transport.hwm})"
)
self._current_step = current_step
@@ -138,4 +138,4 @@ class ZMQMicroBatchReceiver(MicroBatchReceiver):
self.socket.close(linger=0)
self.ready_socket.close(linger=0)
finally:
self.logger.info("ZMQ micro batch receiver closed")
self.logger.debug("Closed ZMQ micro batch receiver")
@@ -11,6 +11,7 @@ from prime_rl.trainer.lora import get_lora_state, save_lora_config
from prime_rl.trainer.utils import maybe_clean
from prime_rl.trainer.world import get_world
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.utils.logger import format_time
from prime_rl.utils.utils import get_all_ckpt_steps, get_broadcast_dir, get_step_path
from prime_rl.utils.weights import (
convert_state_dict_to_hf,
@@ -28,11 +29,11 @@ class FileSystemWeightBroadcast(WeightBroadcast):
):
super().__init__(output_dir, lora_config)
self.world = get_world()
self.logger.debug("Filesystem broadcast initialized")
self.logger.debug("Initialized filesystem weight broadcast")
def broadcast_weights(self, model: nn.Module, step: int) -> None:
"""Broadcast weights by saving a HF-compatible checkpoint to shared filesystem and notifies the orchestrator."""
self.logger.debug("Starting broadcasting weights to inference engine via shared filesystem")
self.logger.debug(f"Broadcasting policy weights (v{step}) via the shared filesystem")
start_time = time.perf_counter()
adapter_only = self.lora_config is not None
@@ -67,7 +68,7 @@ class FileSystemWeightBroadcast(WeightBroadcast):
if self.world.is_master:
self._notify_orchestrator(save_dir)
self.logger.debug(f"Weights broadcasted in {time.perf_counter() - start_time:.2f}s")
self.logger.debug(f"Broadcast policy weights (v{step}) in {format_time(time.perf_counter() - start_time)}")
def _notify_orchestrator(self, save_dir: Path):
"""Notify the orchestrator that the weights have been broadcast by writing a 'STABLE' file to a shared filesystem."""
+5 -5
View File
@@ -17,7 +17,7 @@ from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.utils import get_world
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.utils.client import NCCL_READY_MARKER
from prime_rl.utils.logger import get_logger
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
from prime_rl.utils.pathing import sync_wait_for_path
from prime_rl.utils.utils import get_broadcast_dir, get_step_path
@@ -132,9 +132,9 @@ class NCCLWeightBroadcastSender:
host=host, port=port, rank=rank, world_size=world_size, store_timeout=timeout
)
self.communicator = PyNcclCommunicator(pg, device=device)
self.logger.debug("NCCL broadcast initialized on master rank")
self.logger.debug("Initialized NCCL broadcast on master rank")
else:
self.logger.debug("NCCL broadcast initialized on non-master rank (no communicator)")
self.logger.debug("Initialized NCCL broadcast on non-master rank (no communicator)")
@torch.no_grad()
def broadcast_weights(self, model: nn.Module, step: int) -> None:
@@ -194,7 +194,7 @@ class NCCLWeightBroadcast(WeightBroadcast):
@torch.no_grad()
def broadcast_weights(self, model: nn.Module, step: int) -> None:
"""Broadcast the state dict of a model into the inference pool using NCCL and notifies the orchestrator."""
self.logger.debug("Starting broadcasting weights to inference engine via NCCL")
self.logger.debug(f"Broadcasting policy weights (v{step}) via NCCL")
start_time = time.perf_counter()
# Only the master touches the filesystem to notify the orchestrator, but all
# ranks must wait for the inference pool before entering the broadcast path:
@@ -209,7 +209,7 @@ class NCCLWeightBroadcast(WeightBroadcast):
if self.world.world_size > 1:
dist.barrier()
self.nccl_broadcast_sender.broadcast_weights(model, step)
self.logger.debug(f"Weights broadcasted in {time.perf_counter() - start_time:.2f}s")
self.logger.debug(f"Broadcast policy weights (v{step}) in {format_time(time.perf_counter() - start_time)}")
def _notify_orchestrator(self, save_dir: Path) -> None:
"""Create the STABLE marker the orchestrator's weight watcher polls for."""
+6 -5
View File
@@ -172,13 +172,13 @@ async def maybe_check_has_model(
async def check_health(
admin_clients: list[AsyncClient], interval: int = 1, log_interval: int = 10, timeout: int = 1800
admin_clients: list[AsyncClient], interval: int = 1, log_interval: int = 30, timeout: int = 1800
) -> None:
logger = get_logger()
async def _check_health(admin_client: AsyncClient) -> None:
wait_time = 0
logger.debug("Starting pinging /health to check health")
logger.debug("Pinging /health until the inference server is ready")
while wait_time < timeout:
try:
response = await admin_client.get("/health")
@@ -190,9 +190,10 @@ async def check_health(
return
except Exception as e:
if wait_time % log_interval == 0 and wait_time > 0:
logger.warning(
f"Inference server was not reached after {wait_time} seconds (Error: {e}) on {admin_client.base_url}"
logger.info(
f"Waiting for inference server at {admin_client.base_url} to start up ({wait_time}s elapsed)"
)
logger.debug(f"Inference server at {admin_client.base_url} not reachable: {e!r}")
await asyncio.sleep(interval)
wait_time += interval
msg = f"Inference server is not ready after {wait_time} (>{timeout}) seconds. Aborting..."
@@ -253,7 +254,7 @@ async def _admin_post(client: AsyncClient, path: str, *, timeout_s: float = ADMI
async def _pause_engines(admin_clients: list[AsyncClient], *, step: int) -> None:
"""Pause all inference engines, waiting for in-flight requests to drain."""
logger = get_logger()
logger.info(f"Updating policy in-flight to v{step}")
logger.debug(f"Pausing inference engines to update weights to policy v{step}")
await asyncio.gather(
*[_admin_post(client, "/pause", params={"mode": "keep", "clear_cache": "false"}) for client in admin_clients]
)
+5 -3
View File
@@ -38,9 +38,11 @@ def setup_world():
@pytest.fixture(autouse=True, scope="module")
def cleanup_zombies():
"""Auto-fixture to cleanup zombies between module tests. Used in CI to avoid zombie processes from previous tests."""
subprocess.run(["pkill", "-f", "torchrun"])
subprocess.run(["pkill", "-f", "VLLM"])
"""Auto-fixture to cleanup zombies between module tests. Only runs in CI (USERNAME_CI is set)
to avoid killing training runs on local machines."""
if os.environ.get("USERNAME_CI"):
subprocess.run(["pkill", "-f", "torchrun"])
subprocess.run(["pkill", "-f", "VLLM"])
yield
@@ -1,94 +0,0 @@
import asyncio
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from renderers import Qwen3VLRendererConfig
from prime_rl.orchestrator.utils import setup_policy_inference_pool
def test_setup_policy_inference_pool_uses_renderer_when_enabled():
async def run() -> None:
tokenizer = object()
renderer_settings = Qwen3VLRendererConfig()
config = SimpleNamespace(
model=SimpleNamespace(
client=SimpleNamespace(base_url="http://localhost:8000/v1"),
name="policy-model",
),
renderer=renderer_settings,
any_policy_sourced=True,
)
renderer = object()
inference_pool = object()
with (
patch("renderers.base.create_renderer", return_value=renderer) as create_renderer_mock,
patch(
"prime_rl.orchestrator.utils.InferencePool",
new=MagicMock(return_value=inference_pool),
) as setup_pool_mock,
):
returned_renderer, returned_pool = await setup_policy_inference_pool(
config=config,
tokenizer=tokenizer,
)
assert returned_renderer is renderer
assert returned_pool is inference_pool
create_renderer_mock.assert_called_once_with(tokenizer, renderer_settings)
setup_pool_mock.assert_called_once_with(
config.model.client,
model_name="policy-model",
train_client_type="renderer",
eval_client_type="openai_chat_completions",
renderer_config=renderer_settings,
)
asyncio.run(run())
def test_setup_policy_inference_pool_keeps_renderer_without_policy_sampling():
"""Frozen-sourced runs (e.g. sft) have no train env sampling from the live
policy, but training is renderer-only: the renderer is still built and the
pool is wired with the renderer train client. ``any_policy_sourced`` only
flips the log line, not the pool setup."""
async def run() -> None:
tokenizer = object()
renderer_settings = Qwen3VLRendererConfig()
config = SimpleNamespace(
model=SimpleNamespace(
client=SimpleNamespace(base_url="http://localhost:8000/v1"),
name="policy-model",
),
renderer=renderer_settings,
any_policy_sourced=False,
)
renderer = object()
inference_pool = object()
with (
patch("renderers.base.create_renderer", return_value=renderer) as create_renderer_mock,
patch(
"prime_rl.orchestrator.utils.InferencePool",
new=MagicMock(return_value=inference_pool),
) as setup_pool_mock,
):
returned_renderer, returned_pool = await setup_policy_inference_pool(
config=config,
tokenizer=tokenizer,
)
assert returned_renderer is renderer
assert returned_pool is inference_pool
create_renderer_mock.assert_called_once_with(tokenizer, renderer_settings)
setup_pool_mock.assert_called_once_with(
config.model.client,
model_name="policy-model",
train_client_type="renderer",
eval_client_type="openai_chat_completions",
renderer_config=renderer_settings,
)
asyncio.run(run())