87afa63d1938c464b361765115e7e4aecceb713a
2836
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
87afa63d19 |
Track renderers trinity-dsv41 branch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
699342d3dc |
Merge upstream/main into trinity-dsv41; port V4.1 engram onto shared n-gram module
Merges upstream/main ( |
||
|
|
282af8058a |
Bump renderers: trinity-dsv41 with upstream main
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
eed0e44ce0 |
feat: scope dashboard token usage to episode, trace and branch (#4417)
## Summary - The trace sidebar shows **input / output / total tokens** from the trace's own `num_input_tokens` / `num_output_tokens` / `num_total_tokens`, so input + output = total. Before, it summed provider usage over every call: "input tokens" counted the re-sent context once per turn, and "total input" and "total tokens" built on that. - The sidebar groups its rows by scope: - **episode** (only when the episode has more than one trace): trace count and the episode's input / output / total. - **trace**: messages, turns, tool calls, branches, input / output / total and cost. - **branch N** (only for a multi-branch trace with one branch selected): messages, turns, tool calls and the branch's input / output / total. - Messages, turns and tool calls used to be per selected branch without saying so. They now sit in the section for their scope. - Timeline tooltips and the semantic inspector show the same input / output / total rows. - **Trace lanes** read the trace's fields. - **Branch and context lanes** count each fed-in token once (`new_input_tokens`, the same rule as verifiers' `min_new_input_tokens`). - **A single model call** shows its whole prompt (cached part included) as input. - The sidebar, timeline tooltips and semantic inspector no longer show "total input", "cached input", "reasoning tokens", "max context length", "cumulative processed" or "uncached input". Cached input added up the cached prompt of every call, so it counted the shared context again on each turn. The other rows read as parts of the total. Timeline lanes no longer carry `total_input_tokens`, `cached_tokens` or `reasoning_tokens`. - Counts the record already carries are read from it instead of recounted: the sidebar's trace turns and branches (`num_turns`, `num_branches`), its episode tokens (`Episode.num_*_tokens`), the live table's turns, branches and cost, the index row's turns and cost (`Episode.num_turns`, `Episode.usage.cost`), and the timeline trace lane's cost (`Trace.usage.cost`). The live table counted model calls as turns; it now reports sampled turns, like the finished table. - The trace toggle lists traces in the order their agents started, and an episode opens on the earliest one. An agentic judge used to come before the solver it graded. Trace indices stay as stored, so links and citations still resolve. ## Verification Ran a one-episode agentic-judge eval on SWE-bench Verified with the bash harness. Solver compaction was set at 12K tokens, so the solver trace split into 5 branches. Then opened it in a dashboard served from this branch (Playwright, no page errors). - **Live:** the solver trace carries the `num_*` fields while it runs. The trace section and the branch section updated as the trace grew. - **Finished:** the dashboard matches verifiers' `Episode` / `Trace` / `Branch` models on every number: | scope | input | output | total | |---|---|---|---| | episode | 42,707 | 28,557 | 71,264 | | solver trace | 37,259 | 26,608 | 63,867 | | solver branches 0–4 | 5,533 / 6,387 / 7,806 / 8,528 / 9,005 | 6,157 / 7,197 / 5,486 / 5,103 / 2,665 | 11,690 / 13,584 / 13,292 / 13,631 / 11,670 | | judge trace | 5,448 | 1,949 | 7,397 | - The old sidebar would have shown about 622K "total tokens" for the same solver trace, because it counted the re-sent context on every turn. - A branch's total here is input + output. On a compacted branch this exceeds verifiers' `Branch.num_total_tokens` (final sequence length). On the summary call, the server's chat template dropped the earlier turns' reasoning from the prompt, so those tokens were counted when generated but are no longer in the final sequence. - `tests/unit/test_dashboard_timeline.py`: the two semantic-context totals changed from 260 → 140 and 310 → 190. In those fixtures, the second call's prompt is shorter than the first call's final sequence, so it adds no new input. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes how token totals and costs are computed across the dashboard and live/index summaries; wrong field usage would misreport usage but does not affect training or auth. > > **Overview** > Dashboard token and activity numbers now align with persisted **episode / trace / branch** scopes instead of re-summing per-call provider usage (which inflated totals when context was resent each turn). > > The sidebar groups **episode**, **trace**, and selected **branch** rows and reads `num_*_tokens` (plus `branchTokens` / server `new_input_tokens` for branch paths). Timeline and semantic views drop cached/reasoning/max-context breakdowns; per-call tooltips treat **input** as full prompt (cached included). Monitors (**index**, **live**) stop recomputing turns, branches, and cost from calls and use record fields instead. Trace tabs and default selection follow **agent start order** via `traceOrder`. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 59aadfaa0a65b69346ae0082c114601584f82813. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
e18b36f059 |
refactor: rename env servers to env worker pools (#4381)
The environment hosting entrypoint launches a broker and a pool of episode workers. Calling that unit an "env server" obscures the source → pool replica → broker/workers hierarchy. This follow-up to #4375 names those roles consistently. - Rename the command to `uv run env-worker-pool`, its schema to `EnvWorkerPoolConfig` in `prime_rl.configs.env_worker_pool`, and the orchestrator field to `env_worker_pool_replicas`. - Rename `EnvServerPool` to `EnvWorkerPool`, `EnvServer` to `EnvWorker` in `prime_rl.env.worker`, and `serve_env` to `run_env_worker_pool`. Process titles distinguish `PRL::EnvBroker` and `PRL::EnvWorker`. - Update the RL/eval launchers, the shared SFT/pretrain launcher, SLURM templates, config helpers, CI paths, dashboard text, docs, and the affected skills. Document per-source configuration, pool replicas, and worker concurrency. - Anchor the root virtualenv ignore rule so it does not hide `src/prime_rl/env/` on case-insensitive filesystems. `[serve]`, the wire protocol, pool sizing/dispatch behavior, and run artifact paths are unchanged. This is a naming change; direct worker-to-sink data delivery remains separate work. ## Breaking names | Before | After | | --- | --- | | `env-server` | `env-worker-pool` | | `prime_rl.configs.env_server.EnvServerConfig` | `prime_rl.configs.env_worker_pool.EnvWorkerPoolConfig` | | `OrchestratorConfig.env_server_replicas` | `OrchestratorConfig.env_worker_pool_replicas` | | `prime_rl.env.pool.EnvServerPool` | `prime_rl.env.pool.EnvWorkerPool` | | `prime_rl.env.server.EnvServer` | `prime_rl.env.worker.EnvWorker` | | `prime_rl.env.serve_env` | `prime_rl.env.run_env_worker_pool` | | `EnvClient.wait_for_server_startup` | `EnvClient.wait_for_pool_startup` | ## Validation - 447 focused CPU tests passed (env, configs, supported orchestrator/eval/transport tests, dashboard artifacts and pathing); four cases deselected. Tests requiring unavailable `torch`, `vllm`, and TextArena dependencies were excluded. - Temporary smoke script exercised static pools with 1/2 workers and elastic pools capped at 1/unbounded: address discovery, task/error round-trip through the broker and worker, process titles, graceful shutdown, and IPC cleanup all passed. The smoke env deliberately raises an episode error; it does not call inference. - Both wheels build; wheel contents and the renamed console entrypoint verified. Entrypoint help, touched TOML parsing, Ruff, and `pre-commit run --all-files` pass. - The deep-backlog ZMQ test timed out after 18 seconds on both unchanged base `c0ad9e9f4` and this branch, so it was deselected. No GPU training run. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Breaking renames span the CLI, Python imports, and orchestrator config fields; behavior is unchanged but existing scripts and TOML must be updated. > > **Overview** > Renames the environment-hosting stack so **source → broker → workers** is explicit: the CLI becomes **`uv run env-worker-pool`**, config schema **`EnvWorkerPoolConfig`** (`prime_rl.configs.env_worker_pool`), and orchestrator **`env_worker_pool_replicas`** replace the old `env-server` / `EnvServerConfig` / `env_server_replicas` names. > > Runtime symbols align with that model—**`EnvWorkerPool`**, **`EnvWorker`**, **`run_env_worker_pool`**, broker/worker process titles (**`PRL::EnvBroker`** / **`PRL::EnvWorker`**), and **`EnvClient.wait_for_pool_startup`**. RL/SFT/eval launchers, SLURM templates, pathing helpers, CI filters, dashboard copy, docs, and skills are updated to match; **`[serve]`**, the ZMQ wire protocol, and artifact paths stay the same. > > **.gitignore** anchors **`/ENV/`** so a root `ENV` venv directory is not confused with **`src/prime_rl/env/`** on case-insensitive filesystems. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 47c74d92f30d54524ad2e0c79ae1dae0e42def31. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> |
||
|
|
94171d1aa0 |
feat: more extensive env logs (#4383)
## Summary - Bump `deps/verifiers` to the merged PrimeIntellect-ai/verifiers#3061. Lines are scoped `[<episode>/<trace> <agent>]`, lifecycle lines are timed, and INFO keeps to episode start/finish plus one `Finished rollout` per agent run. - Env servers colorize their console sink only on a terminal. The launcher redirects an env server's stdout into `logs/.../envs/<split>/<name>.log`, so the colorized format used to land raw ANSI codes in that file. Without a terminal, the console sink now uses the plain layout the file sink already used (`setup_logger(colorize=...)`). - Env server, pool and client log lines follow the verifiers style: an active sentence, then `key=value` fields, then error details after ` - `. For example, `EnvServerPool up (address=..., workers=1/inf, pool=ElasticPoolConfig(...))` is now `Started env server pool address=... pool=elastic workers=1 max_workers=inf multiplex=128`. - Remove `log.vf_level`. Env servers and the in-process verifiers loggers follow `log.level`, so `--log.level debug` turns on debug output everywhere. Before, env servers used `vf_level` and the orchestrator and eval runner capped verifiers at WARN. - `InterceptHandler` records the real call site. Its frame walk started at `emit()`, which is not in stdlib logging, so it stopped at once. At DEBUG, every verifiers line then reported `logging/__init__.py::1762` as its call site. ## Breaking - `log.vf_level` and `$PRIME_VF_LOG_LEVEL` are removed. Set `log.level` (or `$PRIME_LOG_LEVEL`) instead; it now also sets the verifiers and env-server level. A config that still sets `vf_level` fails validation. ## Verification - `pytest tests/unit/{env,utils,eval,orchestrator,monitors}` and `test_configs.py`: all pass, except tests that need GPU extras (`prime_kernels`, `fla`, `vllm`) this venv lacks. - `uv run eval` on gsm8k, terminal-bench-2 `fix-git`, proposer-solver and a forced retry, at INFO and at DEBUG (`--log.level debug`). The env-server logs contain no ANSI codes, and DEBUG lines name their real call sites (`[rollout.py::276]`, `[prime.py::270]`, ...). - `uv run eval gsm8k -n 1 -r 1 --log.level debug`: the env-server log has the verifiers DEBUG lines (`Starting rollout`, `Served turn`, ...). - `uv run eval gsm8k -n 2 -r 1` after the env-server log rewrite. The env-server log reads: ``` INFO Started env server pool address=tcp://127.0.0.1:40267 pool=elastic workers=1 max_workers=inf multiplex=128 INFO Started env server taskset=gsm8k address=ipc:///tmp/prl-env-pool-wh3dujah/0 INFO Stopped env server taskset=gsm8k address=ipc:///tmp/prl-env-pool-wh3dujah/0 INFO Stopped env server pool address=tcp://127.0.0.1:40267 ``` 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Removes a config field (`log.vf_level`) and changes default verifiers verbosity in orchestrator/eval (was capped at WARN, now follows `log.level`), which can increase log volume at INFO/DEBUG. > > **Overview** > **Unifies logging verbosity** by removing **`log.vf_level`** (and **`$PRIME_VF_LOG_LEVEL`**). Orchestrator, eval, env servers, and in-process **`verifiers`** now all follow **`log.level`** / **`$PRIME_LOG_LEVEL`**; configs that still set `vf_level` fail validation. **Docs** in `training.md` reflect the single knob and point env log verbosity at `orchestrator.log.level`. > > **Env-server observability** is tightened: lifecycle and error lines use a consistent *sentence + `key=value`* style across pool, server, client, and delta paths. When stdout is redirected to run logs (non-TTY), **`setup_logger`** writes the **plain** console format so **`logs/.../envs/*.log`** no longer contain raw ANSI. **`InterceptHandler`** walks frames correctly so verifiers **DEBUG** lines show the real call site, not `logging/__init__.py`. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9d379337fda67529fd4848b68513254aae37d600. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
f2351023f4 |
feat: tolerate changed task sources on resume (#4370)
## Summary - An RL run can now resume with a different set of train and eval sources. You can add a source, remove one, or change one (its taskset, ratio, sampler or gates). Before, a resume with changed train sources failed to load the orchestrator checkpoint. - A resume re-runs the train groups that were drawn before the checkpoint but not yet trained. Before, those tasks were silently skipped. - Fix: live config values (`ratio`, `sampling`, `interval`) now carry over to the same source on resume. Before, they could move to another source. Scope: the RL orchestrator only. SFT online evals and `uv run eval --resume` keep no per-source state and do not change. ## Motivation A long RL run often changes its data mix between restarts: a new env, a dropped env, or a taskset with more tasks. Today a restart like that has three problems: 1. **The checkpoint does not load.** `TrainSource` and `Curriculum` raise when the envs or admission gates differ from the checkpoint. The only way out is to start the curricula from scratch. 2. **The sampler position becomes wrong.** `StandardSampler` saves a cursor into the taskset. When the taskset gains or loses tasks, the cursor points at different tasks. 3. **Drawn tasks get lost.** The orchestrator samples ahead of the trainer. Groups that were drawn but not trained at the checkpoint are gone after the resume, and the resumed run draws past them. A fourth problem is in the config merge. `merge_resumed_config` matched source lists by position. When you moved or replaced a source, it took another source's live values. When the number of sources changed, every source lost its live values. This PR is also the base for rollout checkpointing (#4296), which continues the open groups from the checkpoint instead of re-running them. ## What happens on resume | Change between checkpoint and resume | Result | |---|---| | Add a train source | It starts with a fresh curriculum. | | Remove a train source | Its curriculum state and its open groups are dropped (with a log line). | | A taskset gains tasks | The new tasks start at the lowest surviving sampling count, so they join the current pass. They are not sampled first to catch up. | | Rows are added, removed or moved anywhere in a taskset | The other tasks keep their state: the default `Task.key` no longer includes the row index (PrimeIntellect-ai/verifiers#3101, from #4413). A change to a task's other data, including a config-level `system_prompt`, makes it a new task. | | A taskset loses tasks | Their counts (`StandardSampler`), rewards (`DifficultyPoolSampler`) and open groups are dropped. A task added back at a later resume starts as a new task. | | Change `ratio`, `sampling` or `interval` | The launch value wins. A value the launch config did not change keeps its live value. | | Change the sampler type | The sampler starts fresh, with a warning. | | Add or remove an admission gate | A new gate starts fresh; a removed gate's state is dropped. | | Rename a source | Counts as removing one source and adding another. Naming an unnamed source with its old resolved name (its env id) keeps its state. | | Add an eval source | It first runs at the next step that is a multiple of its interval. Eval sources keep no checkpointed state. | | Streaming (unbounded) taskset | It resumes at the same offset into the stream: it reads and discards that many tasks. This resumes at the same task only if the stream yields the same tasks in the same order. Its open groups are dropped, because a stream cannot find a task by key. | ## Changes **Sampling counts instead of a cursor** (`curriculum/samplers/standard.py`) - `StandardSampler` checkpoints `{task_key: sampling_count}` for a finite taskset. It yields a least-sampled task, with ties broken by source order. For an unchanged taskset, this is the same order as the old cycle. - On load, it reconciles the counts with the current taskset, as in the table above. - One pass scans the taskset once. With 100k tasks, 1M samples take 0.28 s and a load takes 0.08 s. - A streaming taskset keeps the cursor, as an offset into the stream. **State restored by name** (`train_source.py`, `curriculum/base.py`, `samplers/pool.py`) - `TrainSource` restores each curriculum by source name. - `Curriculum` records its sampler type, and restores gates by name. - `DifficultyPoolSampler` drops the rewards of removed tasks. **Open groups re-run** (`train_source.py`, `train_sink.py`) - `TrainSource` gives each draw a group id. The group stays open until its samples ship or it finalizes without training: rejected by the curriculum, no trainable samples left, all queued traces stale, or pruned. A group cancelled at shutdown stays open. - The checkpoint saves the open groups as (source, task key). A resume re-runs them whole, in draw order, before it draws new tasks. Their sampling counts do not go up a second time. - `TrainSink` owns every close through one callback (`on_groups_closed`): groups that end without shipping, and the groups of a shipped batch (`TrainSink.shipped`, called after the trainer received it). - A re-run group goes through the curriculum again, with its new rollouts. Today's sampler and gate tolerate this (`DifficultyPoolSampler` overwrites the task's reward, `AdvRangeGate` keeps no state); the `observe` and `admit` docstrings state it for new ones. **Config merge by source name** (`configs/diff.py`) - `merge_resumed_config` matches sources by resolved name: `name`, else the env id. This is the same key `TrainSource` uses. **Task keys** (#4413): pins verifiers main (`57314c0ec`), whose default `Task.key` excludes the generated row index. The curriculum tests reload tasksets through `Taskset`, so inserted, removed and reordered rows get new indices, as in a real reload. **Docs**: `docs/training.md` (Resuming a Run: what a resume restores, and changing sources on resume). ## Compatibility - **Checkpoints from main load.** A cursor converts to counts. The conversion assumes the taskset is unchanged since the checkpoint, and a log line says so. A missing sampler type is inferred. Such a checkpoint has no open groups, so nothing re-runs. - **Main cannot load a checkpoint from this PR.** Main rejects the new fields (`sampler_type`, `open_groups`). This matters only if you roll back to main after resuming on this PR. ## Verification **Resume e2e** (reverse-text, Qwen3-0.6B, one node on SLURM, about 7 minutes per attempt). Three sources took disjoint 10-task slices of reverse-text, so each task was drawn several times and the counts mean something. 1. Run A trained steps 1–4 on `rt-a` and `rt-b` (ratio 1:1), with a checkpoint every 2 steps. 2. The restart resumed step 4 in the same run dir and trained steps 5–8. It removed `rt-b`, added `rt-c`, and changed `rt-a` (ratio 1 → 2, taskset 10 → 15 tasks). | Check | Result | |---|---| | Restart loads and trains | Steps 5–8 trained 128 of 128 samples each; checkpoints at steps 6 and 8. | | Removed `rt-b` | Its curriculum and its 5 open groups were dropped. No `rt-b` group was dispatched after the restart. | | Added `rt-c` | Fresh curriculum; at step 8 all 10 tasks had count 1. | | `rt-a`'s open group | The 1 open group re-ran first, on the same task. | | `rt-a`'s new tasks | The 5 new tasks started at count 1, the lowest surviving count. At step 8, all 15 tasks were at count 3 or 4. | | `rt-a`'s ratio | The resolved config held `ratio = 2.0`. New draws were 30 `rt-a` to 10 `rt-c`, within the noise of a 2:1 coin over 40 draws. | The restart logged: ``` Resuming curriculum state for env rt-a Reconciled sampling counts with the taskset: 5 new task(s) start at count 1, 0 removed task(s) dropped Env rt-c is not in the checkpoint, so its curriculum starts fresh Dropped the checkpointed curriculum state of env rt-b, which is no longer configured Dropped 5 open group(s) of env rt-b, which is no longer configured Re-running 1 open group(s) from the checkpoint ``` The e2e did not cover a taskset that loses tasks, a changed sampler type, or changed gates. Unit tests cover those. **Unit tests** - `tests/unit/orchestrator/test_curriculum.py`: static order equals the old cycle. It also covers resumes with added and removed tasks, an added and a removed env, a changed sampler type, a changed gate set, and a cursor checkpoint from main. - `test_curriculum.py` and `test_train_sink.py`: open groups re-run in order without recounting. A rejected group closes, a group closes when its batch ships (`TrainSink.shipped`) and not when the batch is taken, and a group cancelled at shutdown stays open. Removed envs and tasks are dropped. The rng restore check draws before the checkpoint, so it can fail. - `tests/unit/test_config_diff.py` and `test_config_update.py`: the source merge by name (reordered, replaced, removed, updated and added, and named with its old resolved name), and an eval source list changed on resume. - `pytest tests/unit/orchestrator tests/unit/env tests/unit/test_configs.py tests/unit/test_config_diff.py`: 475 passed, before the latest review round. The latest round is verified by CI. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Touches orchestrator resume, curriculum sampling, and live-config merge—logic mistakes could mis-schedule tasks or lose training batches, though extensive tests mitigate obvious regressions. > > **Overview** > **Resuming mixed RL sources now tracks unfinished groups instead of skipping them.** `TrainSource` issues per-draw `TaskRequest.group_id`s, snapshots `(env, task key)` for anything still open when a checkpoint saves, and replays those draws (with sampler state untouched) before taking fresh tasks while streaming envs drop in-flight work they cannot key. `TrainSink` closes groups whenever admission fails, batches ship after `sender.send`, pruned traces clear, or staleness drops everything, but shutdown cancellations stay open for another try, and the orchestrator wires those closes back to `TrainSource` so resume bookkeeping matches lived rollouts. **Curriculum state survives reshuffles instead of hard failing merges.** `merge_resumed_config` now aligns `train.source` lists by resolved env names, newly added sources inherit launch fields, and eval source edits get regression coverage via `EvalSource`. `Curriculum` checkpoints sampler types, reloads gates by name, warns when the sampler class changes, and both `StandardSampler` and `DifficultyPoolSampler` reconcile per-task counts/rewards with edited tasksets (legacy cursor checkpoints convert with an explicit log). **Docs/tests call out the new behavior**, so reviewers can expect checkpoint compatibility notes and expanded unit suites around samplers, train-source reopen ordering, train-sink closures, and source-list merges. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 6503dc5ed8ac24a15fb237c495fd426c01c63849. 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 Opus 5.5 <noreply@anthropic.com> Co-authored-by: Konstantin Dunas <git@hallerite.com> |
||
|
|
f7a365fe2c |
feat: read derived trace values from the record (#4415)
## Summary - Bump `deps/verifiers` to PrimeIntellect-ai/verifiers#3102. That PR serializes derived trace and episode values as computed fields: `reward`, `usage`, `is_truncated`, `num_turns`, `num_branches`, `last_reply`, `has_error`, `is_format_violation`, span `duration` and policy `drift`. - Stream the new trace fields to live watchers (`SCALAR_FIELDS` in `env/delta.py`). - The episode index (`monitors/file/traces/index.py`) reads `reward`, `is_truncated`, `num_turns`, `num_branches` and `usage.cost` from the record, and timing from span `duration`. The copied `TRUNCATING_STOPS` rule and the node and call walks are gone. The index record now leaves out model calls. - The dashboard timeline (`server.py`) and trace viewer (`app.js`) read `reward`, `is_truncated` and `usage` from the trace instead of recomputing them. The viewer still walks calls for max context length. - `uv.lock`: `prime-sandboxes` 0.5.5 → 0.5.7. The bump pulls in that floor from verifiers. ## Breaking - Trace records written before this bump have none of these fields. In the dashboard's trace viewer, such a trace shows no reward, `is_truncated` reads false, and the usage totals and finished timing phases are empty. Episode index rows that were already written keep their values. ## Verification - `pytest tests/unit`: dashboard, monitors, env delta and eval tests pass. This includes the guard test that every serialized `Trace` field is streamed. The only failures come from modules missing in the slim test venv (`torch` and env tasksets). - `test_episode_summary_excludes_copied_assistant_context_from_turns` now builds a real `WireEpisode` and summarizes its record. - I have not checked the trace viewer in a browser. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Backward-incompatible dashboard/index behavior for legacy traces missing new serialized fields; bumps a core dependency version. > > **Overview** > **Serialized trace fields are now the source of truth** for rewards, usage, truncation, and counts across the file monitor index, live deltas, and dashboard (API + UI). > > The episode **index builder** stops walking `nodes`/`calls`; it reads `reward`, `usage.cost`, `is_truncated`, `num_turns`, and `num_branches` from each trace, derives timing only from `duration`, and simplifies truncation detection. **`SCALAR_FIELDS`** in `env/delta.py` now includes these fields so live streams stay in sync. > > The **dashboard** timeline exposes `trace.reward` directly, the trace viewer shows **aggregated `usage`** and `is_truncated` from the record, **truncation-rate tiles** rely on `series.truncated` only, and timing rendering is adjusted for open spans. **Tests** build a real `WireEpisode` via `index_record`. **`uv.lock`** bumps **`prime-sandboxes` to 0.5.7** (floor aligned with verifiers). > > **Breaking:** Older traces without these serialized fields may show empty reward/usage and false truncation in the viewer; existing index rows are unaffected. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 418d5b0572ebebb154c6d530acd70182fa8e5d2d. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
c82ef25941 |
feat: bump vllm-router to v0.2.4 (#4411)
## Summary - Bump `vllm-router` from v0.2.3 to [v0.2.4](https://github.com/PrimeIntellect-ai/router/releases/tag/v0.2.4) (x86_64 and aarch64 wheels). - Relock `uv.lock`. Only the `vllm-router` entries change. The release adds these router changes: - Remove the DP rank from proxied GET worker URLs (router#65). - Pass `video_url` and audio content parts through in chat messages (router#67). - Keep SLL sessions alive while a request is in flight (router#68). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Behavior changes live in the disaggregated inference router (proxy URLs and chat forwarding), so disagg deployments should smoke-test routing and multimodal requests after upgrade. > > **Overview** > Pins **`vllm-router`** from **0.2.3** to **0.2.4** for both **x86_64** and **aarch64** wheels in `pyproject.toml`, and refreshes **`uv.lock`** (URLs, version pins, and wheel hashes only). > > Installs via the existing **`disagg`** extra; no changes in this repo’s application code. The upstream release adjusts proxied worker GET URLs (drops DP rank), forwards **`video_url`** and audio parts in chat payloads, and keeps SLL sessions open for in-flight requests. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit e75143a2329f0db54d803a44ba1e717d78ed742e. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
9df62e5ffe |
fix(inference): configurable Mooncake KV lease, 60 s by default (#4410)
## Summary The Mooncake master was started with `-default_kv_lease_ttl=3600000` (1 h). A lease protects a KV object from eviction, so with a 1 h lease the store can't evict anything for the first hour. On a long run the pool fills up, every new put fails, and the store stops caching. The lease is now a `kv_cache_offload` field: `lease_ttl_s`, default 60 s. 60 s is long enough for the P/D handoff, where the old 5 s lease let objects expire before decode read them. It is short enough that the pool can keep recycling space. Under P/D the larger of the two roles' values applies, since one master serves both. ## Evidence 2×8 H200 nodes, 8 TP1 engines with small GPU KV, shared Mooncake store over RDMA, kv-stress agentic workload: | | 1 h lease (main) | 30 s lease | |---|---|---| | Store state | 200 GiB pool full in ~6 min; 8.4M allocation failures (`NO_AVAILABLE_HANDLE`) | ~780 of 859 GB used, 5.4M evictions, 0 allocation failures | | Mooncake hit rate, concurrency ≥ 64 | 0.00 | 0.90 | | Generated tok/s at concurrency 256 | 521 | 755 (+45%) | The 30 s run also used 400 GiB per node instead of 200, so the pool size isn't held constant. The 1 h run's 8.4M failed puts show the lease blocking eviction regardless of pool size. Template rendering was checked for the default (60000 ms), an override (30000 ms), and P/D with different per-role values (the larger is used). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes Mooncake eviction timing for distributed KV offload; mis-tuned values can break P/D handoff or cache recycling, but defaults are evidence-backed and the field is explicit. > > **Overview** > Replaces the hard-coded **1 hour** Mooncake master `-default_kv_lease_ttl` with a tunable **`lease_ttl_s`** on Mooncake KV offload config (**60 s** default). The SLURM `_mooncake_store` template converts that to milliseconds and passes it to `mooncake_master`; under disaggregated P/D it uses the **maximum** `lease_ttl_s` across prefill/decode offload configs because one master serves both. > > This addresses pools that could not evict entries while leases were long, leading to full stores, failed puts, and effectively **zero** prefix-cache hits under stress—while keeping TTL long enough for prefill→decode reuse. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 7a2c2b2fe20e79d28d8aea8782e724b60ff2a4dc. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
d8219c2957 |
feat: post eval regression results to Slack (#4409)
## Summary - Each eval job of the regression workflow posts one Slack message for its config when it ends. The message has the verdict, the model, the gated metrics against the baseline, and a link to the workflow run. - The post goes to the `SLACK_WEBHOOK_URL` repo secret. The step skips when the secret is not set. - Only nightly (`schedule`) and manual (`workflow_dispatch`) runs with one repeat post. PR runs and multi-repeat baseline runs do not. - The post happens in the eval job, not in the summary job. GSM8K reports after about 12 min and does not wait for the 4 h Terminal-Bench-2.1 job. The stuck Parallel / Invariance GPU job also no longer delays the results. - An eval that crashes, times out, or is cancelled posts "no repeat finished". A job that hits `timeout-minutes` ends as cancelled, so the step runs on `always()`. - The comment on the eval job timeout says that agent evals cap their rollout time in the config. It said they have no rollout timeout. - `eval.py summarize --slack <path>` writes the webhook payload. The comparison logic moves into `gate()`, which the Markdown table and the Slack message share. The Markdown summary output is unchanged. - `docs/development.md` mentions the Slack post. Example message (from the last Terminal-Bench-2.1 PR run): ``` ✅ Eval regression: Terminal-Bench-2.1: no regression internal/deepseek-v4.1-flash-1017-ci · 82 tasks × 1 rollouts · workflow run ✅ Accuracy: 59.76% vs 65.85% ± 2.86% (Δ −6.10%, tolerance ±9.40%) ✅ Time to finish (s): 14453 vs 14475 ± 11 (Δ −22, tolerance ±3619) ✅ Error rate: 4.88% vs 1.95% ± 0.67% (Δ +2.93%, tolerance ±10.00%) ✅ Truncation rate: 0.00% vs 0.00% ± 0.00% (Δ +0.00%, tolerance ±1.00%) ``` ## Verification - I rendered the payload locally from the saved Terminal-Bench-2.1 PR result, a GSM8K baseline repeat, and an empty result set. - The Markdown summary of the new `eval.py` is byte-identical to the one on `main`. - The commit has `[skip ci]`, so this PR does not start the 4 h Terminal-Bench-2.1 eval. A manual dispatch of GSM8K only on this branch tests the Slack post. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Changes are CI notifications and reporting refactor only; no runtime training/inference paths, with webhook posting gated and non-blocking (`|| true` on summarize). > > **Overview** > Nightly and manual regression **eval** jobs now **post one Slack message per config** as soon as that matrix job finishes, instead of waiting on the aggregate summary job. Posts use the `SLACK_WEBHOOK_URL` secret (skipped if unset), run on **`always()`** so timeouts/cancellations still notify, and are limited to **non-PR runs with a single repeat** (baseline multi-repeat runs still report only in the GitHub summary). > > **`eval.py`** gains shared **`gate()`** logic for baseline comparison, a **`slack()`** webhook payload builder, and **`summarize --slack <path>`**; Markdown gating output is intended to stay the same. **`docs/development.md`** documents the Slack behavior, and the eval job timeout comment now notes that agent eval configs cap rollout time per config. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 2b54672427872d136f30620afee1fb1b3ebf2931. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
030d245f00 |
fix(orchestrator): keep router session releases working after a burst (#4408)
This PR gives the orchestrator's router-session releases their own HTTP client and caps how many run at once. Before, a burst of releases could leave the shared client permanently unable to send any request, so releases silently stopped for the rest of the run. From then on the router treated every finished rollout as still running, and placed new rollouts on inference replicas based on that wrong picture of their load. **Background.** With the `sticky_least_loaded` router policy, each rollout is a session pinned to one inference replica so later turns reuse its prefix cache. The router places each new session on the replica holding the fewest sessions. When an episode ends, the orchestrator calls `/finish_session` so the router stops counting it. If a release never arrives, the router keeps counting the session until its time to live (TTL) expires, 2 h by default. **Bug 1: a burst loses most of its releases.** All releases shared one httpx client with 4 connections, a 10 s wait per attempt for a free connection, and errors logged at DEBUG. When many episodes end at once (for example, a sandbox outage failing thousands of episodes), thousands of releases queue for those 4 connections: ``` episodes ending at once shared httpx pool (4 connections) router release ─┐ release ─┼─► wait up to 10 s ─► [ conn ][ conn ][ conn ][ conn ] ─► /finish_session release ─┘ for a connection ... (thousands) ``` Most time out waiting, which loses those releases. On its own this is temporary: once the burst drains, releases work again. **Bug 2: those timeouts permanently break the client.** httpcore 1.0.9 (the latest release) has a race in exactly that timeout. It is reported upstream in encode/httpcore#1099 (open, unmerged), where a comment reproduces this pool-timeout case on the same versions; the pydantic fork fixed it in pydantic/httpx2#983. ``` time queued request R pool (4 slots) ───────────────────────────────────────────────────────────────────────────────── 0 s joins the queue, 10 s timer starts slots 1-4 busy ... 10 s (still asleep) request in slot 1 finishes; pool creates connection C (CONNECTING) and hands it to R 10 s timer fires before R wakes up: R raises PoolTimeout and leaves (C is never used) C stays in slot 1: never opened, so never "closed", "idle" or "expired", so never cleaned up ``` The pool opens a new connection instead of reusing the one that just finished because the old client kept at most 1 idle connection, and httpcore 1.0.9 counts every connection, busy or idle, against that limit. So with 4 connections open, each one is closed the moment it frees up. Thousands of requests time out at nearly the same moment, so this fires reliably and each occurrence costs one slot for good: ``` slot 1 busy ──► dead C ──────────────────────────────────────────────► slot 2 busy ─────────► dead C ───────────────────────────────────────► slot 3 busy ───────────────► dead C ─────────────────────────────────► slot 4 busy ─────────────────────► dead C ───────────────────────────► └─ from here on, every release waits 10 s for a slot and fails with PoolTimeout ``` A fresh client works immediately, which is how the reproducer confirms the pool, not the router, is at fault. **Consequence.** The router keeps treating finished sessions as active until its TTL removes them. It sends each new session to the replica with the fewest sessions, so a replica holding many finished ones looks busier than it is and receives less new work, while a replica holding few receives more. The session counts look even across replicas, but the actual work is not. If the table reaches `VLLM_ROUTER_SLL_MAX_SESSIONS` (100,000 by default), new sessions are no longer pinned to one replica and lose their prefix cache on every turn (we have not hit this; the largest table we have seen peaked at about a third of the limit). Training data and rewards are unaffected; this is purely a routing-efficiency problem, and it was invisible because nothing was logged above DEBUG. **The fix.** A release now needs one of 32 tickets (a semaphore) before it sends anything, and the release client has exactly 32 connections. Releases that find no free ticket wait in `clients.py`, not inside httpx, so httpx's pool wait and its race never come into play: ``` thousands of releases arrive at once (one per finished session) │ ▼ ┌─ waiting for a ticket ───────────┐ │ (semaphore in clients.py) │──► waited 30 s, still no ticket? │ R R R R R R ... │ give up: never sent, counted as failed, └───────────────┬──────────────────┘ router removes the session after its TTL │ takes 1 of 32 tickets ▼ ┌─ httpx client, 32 connections ───┐ │ a ticket holder always finds an │──► POST /finish_session ──► router │ idle connection, so it never │ │ waits inside httpx │ └───────────────┬──────────────────┘ │ request done (success or error) ▼ ticket returned; the next release in line goes ``` - Releases use a dedicated client with one connection per ticket, so requests never wait inside httpx's pool. - A `PoolTimeout` can then only mean a leaked connection, so the release path replaces the client and the next releases go out on a fresh one. - Failures log a WARNING each time their total doubles, so a burst logs a handful of lines, and `sessions/released` / `sessions/release_failed` report cumulative counts. | Reproducer (httpx 0.28.1, httpcore 1.0.9) | Before | After | |---|---|---| | Burst of 6,000 releases, 10 ms server | 21 delivered (0.35%) | all delivered | | Single releases after each burst of 4,000 against a 2 s server | 0/3, every burst | 3/3, every burst | | Pool state after those bursts | 4 connections stuck `CONNECTING` | 32 `IDLE` | Trade-offs a reviewer should know: - If the router answers releases slowly (for example, under heavy load), a release that waits more than 30 s for a ticket is dropped, so an episode never waits longer than that to finish. - Replacing a broken client fails up to 31 releases already in flight on it; those sessions wait for the router TTL. - Two other call sites keep the original 4-connection client unchanged: weight-update admin calls (`AdminPlane`) and the Dynamo frontend's startup checks. Each sends only a few requests at a time, so none ever waits for a connection. ## Verification Commit bbd2d3baa adds `tools/repro_session_release_pool_leak.py` and the next commit removes it, so it stays in this PR's history without landing on `main`. It copies the old and new release paths, runs them against a local `/finish_session` server through the dispatcher's cancellation pattern, and prints delivery, follow-up releases and pool state per burst. It runs anywhere, without the repo's dependencies: ``` git show bbd2d3baa:tools/repro_session_release_pool_leak.py > /tmp/repro.py uv run --no-project --with httpx==0.28.1 --with httpcore==1.0.9 --with anyio==4.13.0 \ --with tenacity==9.1.4 --with starlette --with uvicorn python /tmp/repro.py old # or: new ``` `--server-delay 0.01 --episodes 3000 --bursts 1` gives the first table row; `new --undersized-pool` gives the pool 4 connections for 32 tickets, so its connections leak and the client replacement path recovers it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
f1bc12fd37 |
feat: replace a retried agent run's trace in the live stream (#4376)
## Summary - Bump `deps/verifiers` to the merged PrimeIntellect-ai/verifiers#3057. A retried agent run keeps its trace id and counts `attempt`, and a retried episode keeps its id. - `DeltaStreamer` stores the attempt on each trace cursor. When a trace's attempt changes under a known id, it sends a `discard` for that id and then reopens the trace from scratch. `EpisodeAssembly`, the orchestrator's live view and the file monitor already apply discard-then-open as a replace, so they don't change. - `attempt` joins `HEADER_FIELDS`, so the assembled trace carries it. ## Verification - `tests/unit/env/test_env_delta.py::test_retried_agent_run_replaces_its_trace` (new): the client ends with one trace, `attempt == 2`, holding only the retry's nodes. - `pytest tests/unit/{env,orchestrator,monitors,eval}`: 203 passed. `test_batch.py` and `test_prefill_logprobs.py` need the GPU extras (`fla`, `vllm`), which this box's venv doesn't install. - End to end, via `vf-run` and prime-rl `uv run eval`: gsm8k (null harness, subprocess) and terminal-bench-2 `fix-git` (bash harness, prime sandbox). Every run succeeds, and the log ids match the stored trace ids with `attempt: 1`. - Forced retry (bogus model, one agent retry plus one episode retry, so 4 attempts), via both entrypoints: the agent retry reuses the trace id, and the episode retry keeps the episode id and starts a new agent run. The stored episode and trace both have `attempt: 2` and carry all errors. Through prime-rl, no stale live trace files remain. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes live episode delta semantics for retried agent runs; correctness depends on clients already treating discard-then-open as replace, but the behavior is localized to streaming assembly. > > **Overview** > When an agent run is retried but keeps the same trace id, the live stream now treats it as a **replace** instead of appending onto the abandoned attempt. > > **`DeltaStreamer`** tracks **`attempt`** on each **`TraceCursor`**. If a live trace’s **`attempt`** differs from what was already sent for that id, it emits a **`discard`** delta, clears the cursor, and **`open`**s the trace again from scratch (same path as when a trace disappears from the live set). **`attempt`** is included in **`HEADER_FIELDS`**, so assembled traces carry which retry they represent. > > A new unit test asserts that after a retry with **`attempt: 2`**, the client ends with one trace whose nodes are only from the retry (not the first attempt’s turns). > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 362d57e790471ceba33d31041ee068f6fb3d4bf6. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
b9b7d1dd9e |
feat: add PI-TerminalBench2.1 to the eval regression suite (#4155)
## Summary
- Add `tests/regression/configs/eval/pi-terminalbench2-1.toml`:
PI-TerminalBench2.1 (82 reviewed Terminal-Bench 2 tasks), one rollout
each, `internal/deepseek-v4.1-flash-1017-ci` (a dedicated CI deployment
with a 1k concurrency cap), bash harness in prime sandboxes.
- Every task is in flight at once. `env.taskset.ignore_timeouts = true`
drops the tasks' own agent and verifier timeouts. One 4 h agent budget
(`env.agent.timeout.rollout = 14400`) replaces them, so the eval ends in
about 4 h, inside the 6 h job limit.
- A rollout that runs out of time gets reward 0
(`env.agent.scoring.skip_on_timeout = true`) and does not count as an
error.
- Rollouts are not retried, so the gate sees the raw error rate. A retry
would also start a new 4 h budget late in the run.
- Run every config in `tests/regression/configs/eval/` in the `eval`
suite of `regression.yml`, not only gsm8k:
- `Eval / Plan` builds one job per config and repeat, named from a
display-name map in the plan step: `Eval / GSM8K`, `Eval /
Terminal-Bench-2.1`, or `Eval / GSM8K (2)` with several repeats. A
config missing from the map shows its file name.
- The new dispatch input `eval_config` runs one config, e.g. `-f
eval_config=pi-terminalbench2-1`.
- The new dispatch input `eval_max_parallel` caps how many eval jobs run
at once, e.g. `-f eval_max_parallel=2` for a baseline.
- `Eval / Summary` compares each config against its own baseline in
`tests/regression/baselines/eval/` and fails if any config regresses or
has no finished run.
- With `eval_set_baseline`, the bot PR refreshes the baselines of every
config that ran.
- The eval job timeout goes from 60 to 360 min, the GitHub-hosted
maximum.
- Cache `~/.cache/harbor` on the `prime-envs` commit. Harbor tasksets
download their task files from `prime-tasks` on each run otherwise.
- `eval.py summarize` takes `--name` for the heading of each config's
block.
- A baseline file can set a minimum tolerance per metric under
`"tolerance"`. `eval.py baseline` keeps it when it rewrites the file.
- Update the `regression.yml` row in `docs/development.md`.
- Add the PI-TerminalBench2.1 baseline in
`tests/regression/baselines/eval/pi-terminalbench2-1.json` and
`tests/regression/reports/eval/pi-terminalbench2-1.md`: accuracy 65.85%
± 2.86% (std), errors 1.95%, time to finish 4.0 h. It allows 10% errors
(`"tolerance": {"error_rate": 0.1}`): errors are rare sandbox and
harness failures, and five repeats under-sample their spread.
- The 5 repeats ([run
41763261279](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/41763261279))
ran without the cap and hit the 6 h job limit with 1–2 tasks still
running. I scored them as if the cap had applied: rollouts over 4 h or
unfinished get reward 0, and retried rollouts count as errors at their
first failure.
## Verification
- The PR run on d995db6e0
([41870729344](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/41870729344)):
GSM8K passed. TB2 scored 59.8% (baseline 65.9%, tolerance ±9.4%), and 4
tasks hit the 4 h cap with reward 0. Its 4 errors (4.9%: 2 sandboxes
terminated, 1 background job lost, 1 harness exit 137) failed the old
±2.2% error tolerance. `eval.py summarize` on that result with the 10%
tolerance passes, and GSM8K still gates at its 1% floor.
- `uv run eval @ tests/regression/configs/eval/pi-terminalbench2-1.toml
--dry-run` resolves `rollout = 14400` and `skip_on_timeout = true` in
the env config.
- The summary loop renders and gates correctly against the gsm8k result
of an earlier CI run. I tested both artifact download layouts (one
artifact, several). A config with no results fails with "No repeat
finished".
- On the shared `-ht` endpoint, the slowest TB2 rollouts took 4–5 h, and
4 of 5 repeats hit the 6 h job limit. One clean repeat scored 69.5% with
1.2% errors. The `-ci` endpoint decodes at about 68 tok/s per request at
128 concurrent requests, against about 17–20 on `-ht`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes regression CI orchestration and gating for long, API-dependent
evals; misconfiguration could block merges or miss regressions, but no
production runtime or auth paths are touched.
>
> **Overview**
> Adds **PI-TerminalBench2.1** to nightly eval regression (82 tasks, 4h
rollout cap, prime sandboxes) with baseline/report, and **generalizes**
`regression.yml` so every `tests/regression/configs/eval/*.toml`
runs—not only gsm8k.
>
> The eval suite now plans a **matrix of config × repeat** jobs (display
names like Terminal-Bench-2.1), with dispatch inputs **`eval_config`**
(single config) and **`eval_max_parallel`** (throttle parallelism). Eval
jobs get a **6h timeout**, **Harbor task caching** keyed on
`prime-envs`, and per-config artifacts under `results/$CONFIG/`. **Eval
/ Summary** compares each config to its own baseline and fails if any
regresses; baseline PRs refresh all configs that ran.
>
> **`eval.py`** gains `--name` for multi-config summaries,
**per-baseline minimum tolerances** (e.g. 10% floor on error rate for
TB2), and preserves existing `tolerance` when regenerating baselines.
Docs table updated for the new workflow behavior.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
60b69cd72b3d3d2f359ba8361abfa81b7295d8d2. 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 Opus 5.5 <noreply@anthropic.com>
|
||
|
|
3c96816de9 |
feat: release recursive harness sub-agent sessions with their rollout (#4400)
## Why The env server's rollouts reach inference through a session-affinity router (vllm-router `sticky_least_loaded`), routed by `X-Session-ID`. Until now that was the trace id for every call, so a recursive harness pinned its whole tree to one data-parallel rank. nano-rlm runs up to four agents of a tree at once, each growing toward its compaction threshold. In RL runs serving DeepSeek-V4-Flash, single trees held up to ~1M tokens of live context on one rank, and a rank that collected a few of them re-prefilled evicted prefixes. Under expert parallelism that stalled every rank of its node. verifiers#3075 (with PrimeIntellect-ai/nano-rlm#252) routes each sub-agent as a session of its own, `<trace id>:<agent session>`. The orchestrator releases a rollout's router sessions with `finish_sessions` when its episode ends, but it only knew the trace ids. ## What - `deps/verifiers` moves to `308619da`, the merge of verifiers#3075. Beyond that PR, the bump brings in verifiers#3062 (CI endpoint) and verifiers#3070 (custom-env format violations stay at zero reward). There are no dependency changes, so the lock is unchanged. - The dispatcher collects each streamed call's routing session (`routing_session_id(trace, call.acp.agent_session_id)`) and releases it with the trace's own when the episode ends, so sub-agent sessions do not linger in the router until expiry and count toward its per-replica load. Rollouts without sub-agents release exactly the trace id, as before. Ran `ruff check` / `ruff format --check` (0.13.0) on the change and checked against the verifiers branch that a dumped `ModelCall` carries `acp.agent_session_id` and maps to `<trace>:<agent>`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes which session IDs are released to the inference router at episode teardown; incorrect ids could leave sessions pinned or release the wrong affinity, but the logic is additive and falls back to trace-only when ACP is absent. > > **Overview** > Rollouts that use a **recursive harness** now tear down every inference router session they opened, not just the top-level trace id. > > While streaming env deltas, the dispatcher still records `delta["trace"]`, and also collects **`routing_session_id(trace, agent_session_id)`** from each call that carries **ACP** metadata. Those ids are passed to **`finish_sessions`** when the episode finishes (same path as before), so sub-agent sessions (`<trace>:<agent>`) do not stick around on the sticky router and inflate per-replica load. Rollouts without sub-agents behave unchanged—only the trace id is released. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 19ab0dc1c2fe5a7437f390db6f3d1b4ae9cbbc4d. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
ad909f6482 |
fix: loosen monitor load test lag limits for CI runners (#4392)
## Summary - Raise `P99_LAG_S` from 25 ms to 50 ms in `tests/unit/monitors/test_monitor_load.py`. - Raise `MAX_LAG_S` from 100 ms to 250 ms. - Explain the headroom in the comment above the limits. ## Verification Before: the test failed 5 times on `ubuntu-latest` after the current monitor code landed. All failures were `count=1000` cases, with no code change involved: | Run | Branch | Assertion | Observed | Old limit | |---|---|---|---|---| | 41769341552 | main | prime p99 lag | 33.5 ms | 25 ms | | 41696122236 | chore/bump-verifiers-renderers | prime p99 lag | 30.1 ms | 25 ms | | 41730705371 | fix/mega-moe-nccl-min | file max lag | 102 ms | 100 ms | | 41552563666 | feat/episode-json | file max lag | 100 ms | 100 ms | | 41555224772 | feat/episode-json | wandb max lag | 124 ms | 100 ms | On a 30-core dev box, the same cases stay at p99 ≤ 9 ms and max ≤ 14 ms. A simulated regression still fails under the new limits. I moved the file monitor's episode write onto the event loop (`write()` instead of `await asyncio.to_thread(write)`). Even on the dev box, this gave p99 lag of about 100 ms, max of about 200 ms, and p50 of about 13 ms. Both the 100- and 1000-episode cases failed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Test-only threshold and comment changes; no production monitor or orchestrator behavior is modified. > > **Overview** > **Relaxes event-loop responsiveness thresholds** in the slow monitor load test (`test_monitor_load.py`) so it stops failing on shared GitHub runners while still guarding against real stalls. > > `P99_LAG_S` goes from **25 ms → 50 ms** and `MAX_LAG_S` from **100 ms → 250 ms**. The comment above those constants now documents why: CI alone can hit ~35 ms p99 and ~125 ms single stalls, and serializing large episodes on the loop can push p99 toward ~100 ms even on fast hardware. > > The assertions in `_assert_responsive` are unchanged—they still fail if monitors block the asyncio loop beyond these limits (a deliberate regression, e.g. blocking writes on the loop, still fails under the new caps). > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 932594fbd2cb137b9681c0c340b3dd38cba096bd. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
6284ad6d25 |
feat(pretrain): minimal pretraining entrypoint (token shards, from-scratch init) (#4377)
Adds `uv run pretrain`, which trains a model from scratch on tokenized
shards written by datatrove. SFT and pretraining become two entrypoints
over one trainer, with shared launch, data and config code.
## Structure
- `entrypoints/launcher.py`: the launch logic (local, SLURM single and
multi node), moved out of `entrypoints/sft.py`, as `launch(config,
entrypoint)`. `sft.py` and `pretrain.py` are thin wrappers. The SLURM
templates take the entrypoint name, so a pretrain job runs `uv run
pretrain`/`prime_rl.trainer.pretrain.train` in the job. The resolved
config is `<entrypoint>.json`.
- `trainer/train.py`: the shared trainer loop (moved from
`trainer/sft/train.py`). `trainer/sft/train.py` and
`trainer/pretrain/train.py` are thin mains that pass their config class.
- `trainer/data.py`: the shared data machinery only
(`StatefulIterableDataset`, `CatDataset`, `setup_dataloader`, dataset
state/progress). `setup_sft_dataset` lives in `trainer/sft/data.py`,
`setup_token_dataset` in `trainer/pretrain/data.py`.
## Config shape
- `configs/supervised.py`: `SupervisedTrainerConfig(BaseTrainerConfig)`
holds what SFT and pretraining share (data/val base, deployment, SLURM,
online evals, resume, monitors). `SFTConfig` and `PretrainConfig` are
siblings and do not import each other.
- `PretrainConfig`: `data: DatatroveDataConfig` (`type = "datatrove"`;
`paths` required, `seed`, `document_masking`), optional `val:
PretrainValConfig` (held-out shard folders, `num_samples`). Defaults are
SFT's except `optim.lr = 1e-3` and a 10-step linear warmup, then
constant. The weights are initialized with the model's own init whenever
the run does not resume; there is no user flag for this.
## Usage
Tokenize with datatrove (a separate install) and set `eos_token` (for
Qwen, `<|endoftext|>`). Then:
```toml
[model]
name = "Qwen/Qwen3-0.6B" # only the architecture is read
[data]
paths = ["data/fineweb-edu"]
seq_len = 2048
```
`uv run pretrain @ pretrain.toml`. Details are in the Pretraining
section of `docs/training.md`.
## Data
`trainer/pretrain/data.py` reads all shard files as one token pool and
cuts it into `seq_len` windows. The order and offset are new each epoch
and seeded, and resume is exact, also onto another number of GPUs.
Attention and positions restart at every document. Empty documents are
dropped. Validation stops every rank at the same window. The trainer
warns at startup if the shards look like they have no document
separator.
## Tests
- Unit: window coverage, shuffled order, and window boundaries that move
between epochs; document masking; resume from 2 ranks onto 1 equals an
uninterrupted run; validation limits; config round-trip (`uv run sft`
rejects datatrove data); from-scratch init without a padding row (GPU).
- Integration: `configs/ci/integration/pretrain/{start,resume}.toml` +
`tests/integration/test_pretrain.py` (Qwen3-0.6B config from scratch, 2
GPUs, validation every 10 steps). The first resumed loss must continue
the start run's last loss. Added to the GPU workflow.
- Checked on 2 H100s: pretrain integration 6/6. `test_reverse_text_sft`
gives the same losses and grad norms as `main` (its `test_dashboard`
fails on that cluster on `main` too: playwright cannot install).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Introduces a new training entrypoint with from-scratch weight
initialization and non-trivial dataloader checkpoint semantics; changes
are mostly additive but touch shared supervised launch/training paths
used by SFT.
>
> **Overview**
> Adds **`uv run pretrain`**, a first-class path to train dense models
**from scratch** on datatrove **`*.ds` token shards** (next-token loss,
optional held-out validation), with **`model.name` supplying
architecture only** unless resuming from checkpoint.
>
> **Refactor for sharing with SFT:** launcher logic moves to
**`entrypoints/launcher.py`** (`launch(config, entrypoint)`); the
trainer loop consolidates in **`trainer/train.py`**; shared
packing/dataloader code moves to **`trainer/data.py`**; common config
base is **`SupervisedTrainerConfig`** in **`configs/supervised.py`**,
with sibling **`PretrainConfig`** (`DatatroveDataConfig`, higher default
LR, 10-step warmup) and slimmed **`SFTConfig`**.
>
> **Pretrain-specific behavior:** **`trainer/pretrain/data.py`** treats
shard folders as one token pool, shuffles windows per epoch with a
deterministic permutation (exact resume across GPU counts), optional
document-boundary masking, and startup warnings when shards lack
separators. **`setup_model`** gains **`init_from_scratch`** (custom init
+ clearing embedding **`padding_idx`**). SLURM templates, dashboard
resolved-config detection, checkpoint export, **`run_owner`**, Prime
monitors, docs, CI TOMLs, GPU workflow matrix, and integration/unit
tests follow the new entrypoint.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
665c1c55b12bd4bd7f10dffd3a04e18d323288ac. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
|
||
|
|
35fcb52c94 |
fix: run the GSM8K eval regression on the CI endpoint (#4385)
## Summary - Run the nightly GSM8K eval regression on `internal/deepseek-v4.1-flash-1017-ci`, a dedicated CI deployment of DeepSeek V4.1 Flash with a 1k concurrency cap. It was on `internal/glm-5.3-high-throughput`, which backs up under load: on 2026-10-22, provider errors on that endpoint caused a false regression (accuracy −1.44%, error rate 1.21%). - Drop the pinned 256 in-flight episodes for the eval default of 128, so a 5-repeat baseline (5 × 128) stays under the endpoint's cap. - Refresh `tests/regression/baselines/eval/gsm8k.json` and `tests/regression/reports/eval/gsm8k.md` from 5 repeats on the new endpoint ([run 41725025527](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/41725025527)): accuracy 96.95% ± 0.29% (std), 0% errors, 0% truncation, 701 s mean time to finish. The old GLM baseline was 97.65% ± 0.18%. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Changes only affect regression eval config and stored baseline/report data, not production training or inference logic. > > **Overview** > Switches the nightly **GSM8K eval regression** from `internal/glm-5.3-high-throughput` to **`internal/deepseek-v4.1-flash-1017-ci`**, a CI-scoped inference deployment meant to avoid load-related provider failures that had triggered false regressions on GLM. > > In `tests/regression/configs/eval/gsm8k.toml`, the model name is updated and the fixed **`[concurrency]` block (256 in-flight)** is removed so the suite uses the eval default concurrency and stays within the CI endpoint cap during 5-repeat baselines. > > **Refreshed regression artifacts** from [Actions run 41725025527](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/41725025527): `tests/regression/baselines/eval/gsm8k.json` and `tests/regression/reports/eval/gsm8k.md` now reflect ~**96.95%** mean accuracy (vs ~97.65% on GLM), **0%** error/truncation rates, and roughly **half** the prior wall/eval time and output-token length. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f46f648630d8e5ab3bc316cdcc383b49e9ca31db. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
e935afc007 | feat: checkpoint action on the control API (#4379) | ||
|
|
8ce72b9911 |
feat: bump verifiers to 0.4.1 and renderers to 0.2.0 (#4384)
## Summary - Move `deps/verifiers` to `v0.4.1` and raise the pin to `verifiers[harbor]>=0.4.1` (also in `prime-rl-configs`). - Move `deps/renderers` to `renderers-v0.2.0` and raise the pin to `renderers[multimodal]>=0.2.0`. verifiers 0.4.1 requires it. - Move `deps/prime-envs` to prime-envs main (797040d29), which requires stable verifiers 0.4.1 (PrimeIntellect-ai/prime-envs#1060). - Relock `uv.lock`. Companion: PrimeIntellect-ai/prime-envs-private#383 (merged). ## Verification - `pytest tests/unit -m 'not gpu'`: 1098 passed. 6 failed in `qwen3_8_flash_next`, because `indexed_attention` does not support this box's sm_120 GPU. The bump does not touch that code. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Wide dependency upgrade on verifiers/renderers and many RL environments affects training and eval resolution, though the diff is pins and lockfile only with no local code changes. > > **Overview** > This PR **raises dependency pins** so the repo tracks stable **verifiers 0.4.1** and **renderers[multimodal] 0.2.0** (the latter required by verifiers 0.4.1). The main `pyproject.toml` moves from `verifiers[harbor]>=0.4.0` and `renderers[multimodal]>=0.1.12`; `prime-rl-configs` moves from a dev `verifiers>=0.3.2.dev158` pin to `>=0.4.1`. > > **`uv.lock` is regenerated** to match: dev-style `verifiers` specifiers across editable benchmark/env packages are normalized to `>=0.4.1`, and the editable `verifiers` package now pins `renderers[multimodal]>=0.2.0`. The lock also picks up **prime-envs** changes—new workspace members such as **`group-wise-judge`**, **`pi-automationbench`** (via git **`automation-bench`**), and **`terminal-bench-science`**, plus minor version bumps on several existing PI/SWE/search env packages (e.g. **`enterprise-ops-gym` 0.4.0**, **`pi-officeqa-pro-v2`**, **`swe-atlas-*` 0.3.0**). > > There are **no application source edits** in this diff; impact is install/resolve behavior and whatever API or behavior changed in the bumped libraries and env packages. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 926d820fb4b3768ebad0bb0d8c713f781423e04f. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
3bd59c1a43 |
fix(grpo): exclude discarded branches from length penalties (#4380)
GRPO length penalties now count only trainable branches for both the ordinary linear penalty and the subagent-weighted variant. Discarded compaction attempts no longer change output-token, input-token, or turn penalties; shared prefixes count once. Raw usage metrics still record all model calls. Whole-trace admission continues to exclude non-training agents, including agentic judges. Terminal format-violation attempts made trainable by [Verifiers #3059](https://github.com/PrimeIntellect-ai/verifiers/pull/3059) remain eligible for the penalty. Validation: 58 focused advantage and algorithm tests passed on CPU, including discarded compaction, shared-prefix, serialization, and subagent-weighting coverage. Ruff passed. |
||
|
|
c0ad9e9f4b |
feat: move the env server from verifiers into prime_rl.env (#4375)
## Summary - Move the ZMQ env server, client and worker pool from `verifiers.v1.serve` into a new `prime_rl.env` package (`server`, `client`, `pool`, `delta`, `encoding`, `types`). prime-rl is the only consumer. verifiers keeps in-process abstractions only. The wire protocol, delta streaming, and pool scaling logic are unchanged. - Move the `[serve]` config block (`ServeConfig`, `StaticPoolConfig`, `ElasticPoolConfig`) into `prime_rl.configs.env_server`. The fields and defaults do not change. `serve.pool.max_workers` now must be at least 1 when set. - Point the env-server entrypoint, the orchestrator (`EnvClient`), the live-trace file monitor (`EpisodeAssembly`) and the payload hook at `prime_rl.env`. - Log through the prime-rl logger (`get_logger()`) in the env server modules, in the prime-rl log style. - Simplify for the one caller (`entrypoints/env_server.py`): - `serve_env` takes the pool config directly (no `pool_serve_kwargs`) and only plain config data. - Every env server is an `EnvServerPool` broker over worker processes, including a one-worker pool. Pool workers start through `serve_worker`. - `log_setup` becomes `worker_setup`, since it also installs the episode hook and sandbox labels. - Remove unused address defaults, re-exports, `env_config_data`, `EnvServer.run_server` and `_context`. - Move the serve unit tests from verifiers to `tests/unit/env/`. - Add `msgpack` as a direct dependency, because verifiers drops it. - Remove the `env/` virtualenv rule from `.gitignore`. It hid `src/prime_rl/env/`. - Bump `deps/verifiers` to the merge of PrimeIntellect-ai/verifiers#3054, which removes `verifiers.v1.serve`. The new verifiers floors raise `prime-sandboxes` to 0.5.5 and `prime-tunnel` to 0.1.17 in the lock. - Update the process tree in the monitor-run skill: every env server is a broker over spawned worker processes. ## Breaking - `serve.pool.max_workers = 0` (elastic pool) is now rejected. Migrate: set `max_workers = 1`. - A pool capped at one worker (`num_workers = 1` or `max_workers = 1`) no longer runs the env server in-process. It runs a broker over one worker process, like every other pool. No config change is needed. ## Verification - `tests/unit/env`, `test_configs`, `test_dashboard_artifacts`, `tests/unit/{orchestrator,eval,transports}`: 523 passed against the verifiers branch with `verifiers.v1.serve` deleted. Excluded: `test_episode_records` and `test_modelexpress_boundary`, which fail at import in the stale local venv (`prime_runs`, `modelexpress_rl`) and do not touch this change. - E2E with `deps/verifiers` checked out at verifiers#3054 (no `verifiers.v1.serve`): - `uv run rl @ examples/basic/reverse-text/rl.toml` (20 steps): train reward 0.16 → 0.86, online eval reward 0.84 at step 20, 0% errors, no tracebacks. - `uv run eval @ examples/basic/reverse-text/eval.toml` (single-turn, Qwen3-0.6B, 20 × 3 rollouts): finished with 0% errors. `EnvServerPool` and per-worker `EnvServer` lines appear in the prime-rl log format. - Smoke: `env-server` with `reverse-text` for static pools of 1 and 2 workers and elastic pools capped at 1 and unbounded. Each published its address, answered `EnvClient` health, and shut down cleanly with its IPC directory removed. - The RL e2e was rerun after the pool-only change with the same result (train 0.18 → 0.85, eval 0.83, 0% errors). - After the submodule bump: `tests/unit/env` and `tests/unit/orchestrator` pass (160 tests). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes the core rollout transport and multiprocess env-server topology every train/eval run depends on, though the wire protocol and streaming semantics are intended to stay the same and are covered by new unit tests. > > **Overview** > **In-process verifiers serving is replaced by a first-party `prime_rl.env` stack** that owns the ZMQ wire protocol, msgpack encoding, incremental trace deltas, async client, worker `EnvServer`, and an `EnvServerPool` ROUTER broker with static or elastic scaling. The orchestrator, env-server entrypoint, live-trace monitor, and training payload hook now import from `prime_rl.env` instead of `verifiers.v1.serve`. > > **Configuration moves to `prime_rl.configs.env_server`**: discriminated `ServeConfig` with `StaticPoolConfig` / `ElasticPoolConfig` (CLI `--serve.pool.type`), plus `max_concurrent` and address binding. **`serve_env` is simplified** — it always runs through the pool broker (including a one-worker cap), takes the pool object and JSON `model_dump` env config directly, and uses **`worker_setup`** (logging, hooks, sandbox labels) in the broker and every spawned worker. > > **Dependency and hygiene**: **`msgpack` is a direct prime-rl dependency** (dropped from verifiers). Unit tests live under `tests/unit/env/`. **`.gitignore` no longer ignores `env/`**, which was hiding `src/prime_rl/env/`. > > **Behavioral breaks**: elastic **`serve.pool.max_workers` must be ≥ 1** when set (0 is rejected). A pool capped at one worker is **no longer in-process** — it is always broker + one worker process like larger pools. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d3173c61a9781367b8c674601e51d51d9fd79b60. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
08746ba7e6 |
Merge trinity into DeepSeek-V4.1 model branch (PrimeIntellect-ai/prime-rl#4057)
- Renderers: PrimeIntellect-ai/renderers#192 (V4.1 renderer) merged with the trinity Hermes parser, on dphn/renderers trinity-dsv41. - LoRA warm start: trainer-only now; upstream's startup broadcast ships the loaded adapter as policy v0, so the orchestrator hook is dropped. Parameter names follow upstream's single-slot LoRA layers. - Adapter reload timeouts moved to orchestrator/clients.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d07cd84335 |
feat: encode episodes for the file and prime monitors one node at a time (#4366)
## Summary Companion to PrimeIntellect-ai/verifiers#3042 and PrimeIntellect-ai/prime#1140 (released in `prime-runs` 0.1.6). The file monitor and the Prime monitor encode each episode in short steps, so a large episode no longer stalls the orchestrator's event loop for as long as encoding it takes. - **Pins.** - The verifiers submodule moves to verifiers main, which includes verifiers#3042: `to_json` encodes one node at a time and releases the GIL every millisecond, and `record_run` records the run on every trace. - `prime-runs` 0.1.6, already on main, contains prime#1140: the SDK uploads `episode.to_json()` as it is when the episode and its traces name the upload's run. The dispatcher's `record_run` makes that true for RL episodes. - Verifiers main also includes PrimeIntellect-ai/verifiers#3046, which removes `vf-eval`'s platform push and verifiers' `prime-runs` dependency. In `uv.lock` (uv 0.12.0), only the verifiers metadata changes. - **The file monitor writes `episode.to_json()`.** - The stream line is byte for byte what `orjson.dumps(episode.to_record())` gave before. - The index row comes from `index_record(episode)`. It dumps everything but the nodes' payloads, one trace at a time, and gives the same row. - `ChunkedJsonl.append` takes a line in parts, so the newline is written without copying a long line. - **The load test's lag limits drop** from p99 100 ms and max 250 ms to 25 ms and 100 ms, so a regression shows. Across runs at production sizes, the highest values were a p99 of 12.5 ms and a max of 22 ms. - **A hosted orchestrator stamps the platform's run id.** A hosted launch sets only `$RUN_ID`, not `$PRL_RUN_ID`, so the orchestrator stamped episodes with a random id, and the SDK re-stamped every upload. It now falls back to `$RUN_ID`, the Prime run id. ## Verification **Headline: event-loop lag at 1,000 production-sized episodes (~8 GB of JSON)**, monitor load test, dev box: | | Main (before) | This PR | |---|---|---| | prime: lag p99 / max | 14 / 17 ms | **3.1 / 3.5 ms** | | file: lag p99 / max | 47 / 93 ms | **4.8 / 15 ms** | | file: `log()` max | 177 ms | 195 ms | - **A second run:** inside the full unit suite, with more load on the box, it measured prime 11 / 18 ms, file 5.2 / 22 ms, and file `log()` max 224 ms. - **Why the GIL release matters:** encoding node by node without it left the file monitor at 15–18 / 31–66 ms, varying from run to run. A busy encoder thread keeps the GIL until CPython's 5 ms switch interval forces a handoff, and the event loop waits that out several times per wakeup. **The stall no longer grows with the episode.** One thread encodes episodes of 10 to 10,000 turns (1,000 tokens per turn) while a 5 ms ticker on the event loop records the worst stall. Medians of 5 runs, under the orchestrator's GC policy: | Turns | Episode | Encode CPU, before / after | Worst stall, before | Worst stall, after | |---|---|---|---|---| | 10 | 0.2 MB | 0.4 / 0.5 ms | 5.5 ms | 5.2 ms | | 100 | 2.2 MB | 4.0 / 4.5 ms | 8.0 ms | 1.6 ms | | 1,000 | 22 MB | 50 / 51 ms | 40 ms | 3.1 ms | | 3,000 | 65 MB | 152 / 167 ms | 100 ms | 5.2 ms | | 10,000 | 217 MB | 508 / 571 ms | 326 ms | 15 ms | - **Before:** the stall grows linearly with the episode. - **After:** it stays around 2–5 ms up to 3,000 turns, about the GIL switch interval. The 10-turn case is that interval alone, since each episode encodes in under a millisecond. - **The rest at 10,000 turns:** the trace header's pydantic dump, which holds every model call (one per turn). Alone it stalls 4.4 / 8.4 / 15 ms at 1,000 / 3,000 / 10,000 turns. Agentic episodes in production have a few hundred turns, so this part stays small. Encoding the calls one at a time, like the nodes, would remove it. - **CPU:** encoding costs up to ~12% more, from the extra calls and GIL releases. **Encoding:** `test_received_episode_encodes_as_its_record_did` sends a two-trace episode over the real delta wire into a `WireEpisode`. Then: - the file monitor's stream line equals `orjson.dumps(to_record())`, byte for byte; - its index row equals the row from the full record; - after `record_run`, the SDK takes the episode's own `to_json()`, which carries the same record as the old stamped line. **Tests:** `pytest tests/unit -m "not gpu"`: 1,077 passed, 7 failed. The same 7 fail on main on this dev box: an attention kernel without sm_120 support, and no ninja for the CPU Adam extension. **CI:** on the CI runner, the file monitor at 1,000 production-sized episodes measured event-loop lag p99 6.0 ms and max 12 ms, against 63 / 152 ms on main. Its slowest `log()` was 382 ms, under the 1 s limit. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes affect how every episode is persisted and indexed and how run identity is chosen on hosted launches; behavior is contract-tested but touches high-volume I/O on the training path. > > **Overview** > Large episodes no longer block the orchestrator event loop during trace logging. The **file monitor** writes stream lines with **`episode.to_json()`** (incremental, GIL-friendly encoding from verifiers) instead of a single **`orjson.dumps(to_record())`**, and builds index rows via new **`index_record()`** so summarization skips heavy node payloads without materializing the full record first. **`ChunkedJsonl.append`** accepts **byte parts** so the newline is appended without copying megabyte-scale lines. > > The orchestrator **`run_id`** now falls back to **`$RUN_ID`** when **`$PRL_RUN_ID`** is unset, so hosted runs align with the platform id and Prime uploads are not re-stamped with a random id. > > Monitor load tests use **stricter event-loop lag thresholds** to catch regressions. A new unit test asserts on-disk bytes and SDK upload JSON still match the legacy **`to_record()`** encoding. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f83e84906e5c9919df17e1ce7554580644ff00e7. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
7e16629f81 |
feat: non-blocking, concurrent prime uploads (#4363)
## Summary Prime uploads keep up with the orchestrator, and logging to Prime never blocks it. Companion to PrimeIntellect-ai/prime#1136. - **SDK pin.** `prime-runs[train]>=0.1.6`, which pulls `prime-traces` 0.0.12 from PyPI. These releases contain PrimeIntellect-ai/prime#1136: gzip level 1, up to 8 upload requests in flight, an upload queue bounded by records whose `submit` never blocks, and lazily built upload records. - `uv.lock` is written with uv 0.12.0 (lockfile revision 3); only the two SDK packages change. - **No thread hop for Prime.** `PrimeMonitor` calls `run.log_metrics` and `run.log_episodes` directly on the event loop, not through `asyncio.to_thread`. A queue put that never blocks needs no thread, and each hop had to win the GIL back from the uploader thread. - **A production-sized load test.** `tests/unit/monitors/test_monitor_load.py`: - **Episode sizes:** episodes draw their size from a lognormal fitted to a production RL run (median 6.4 MB, p90 17 MB; it also matches the mean of 8.5 MB and the p99 of 35 MB), capped at 60 MB. 1,000 episodes is ~8 GB of JSON, close to one production step of 1,024 samples. - **Memory:** episodes share 24 traces at log-spaced sizes, so the test's own memory stays small. - **Fake endpoint:** the fake Traces endpoint gzips at the SDK's level and counts lines under a lock, because the client now sends several requests at once. - **File monitor check:** it streams every trace chunk, since 8 GB spans two 5 GiB chunks. - **No expected failure:** the prime monitor at 1,000 episodes is no longer marked as one. - **A separate `log()` limit of 1 s.** A `log()` call may await the monitor's own work: the file monitor awaits its write, which encodes the episode on a worker thread, while the event loop keeps serving other tasks. The lag limits still cover the loop. - **The p99 lag limit rises from 50 to 100 ms.** At production sizes the file monitor encodes each episode in one call, which stalls the event loop with a p99 of ~60 ms on CI. Main's code shows the same stall with this test. #4366 makes the encoder work in short steps and tightens the limits to 25 ms p99 and 100 ms max. ## Verification **Headline: Prime monitor, 1,000 production-sized episodes (~8 GB of JSON), main against this branch.** Main ran this branch's test, with the fake endpoint gzipping at main's level 9. | | main | This branch | |---|---|---| | Episodes delivered | 725 of 1,000 | **1,000 of 1,000** | | Lost to a full upload queue | 27 | 0 | | Lost when the 60 s drain ran out | 248 | 0 | | Slowest `log()` | up to 5 s (blocked on the full queue) | **0.6 ms** | | Event-loop lag p99 / max | not reached (failed on delivery) | 14 / 17 ms | | Test time | 217 s | 28 s | **Scale: 10,000 episodes of 2.2 MB (~22 GB)**, from a local copy of the test with the count raised: | Setup | Result | |---|---| | No network time | 0 dropped; `log()` max 1.4 ms; event-loop lag p99 14 ms, max 21 ms; 570 MB peak RSS | | 100 ms + 100 MB/s per request, 1 request in flight | 2,595 delivered within the 60 s drain | | Same, 4 in flight | 9,822 delivered | | Same, 8 in flight (the default) | **10,000 delivered**; event-loop lag p99 12 ms; 860 MB peak RSS | The upload rate is ~180 episodes/s (~400 MB/s of JSON). Encoding the records is the limit. **Full load-test grid at production sizes, this branch (dev box):** 9 passed. | 1,000 episodes | Event-loop lag p99 / max | `log()` max | |---|---|---| | prime | 14 / 17 ms | 0.6 ms | | file | 47 / 93 ms | 177 ms | | wandb | 0.9 / 0.9 ms | 0.6 ms | **CI:** on the CI runner, the file monitor at 1,000 episodes measured event-loop lag p99 60 ms and max 157 ms, within this PR's limits (100 / 250 ms), and `log()` up to 299 ms (limit 1 s). With #4366 the same case measures p99 6 ms and max 12 ms. Other checks: - `pytest tests/unit/train/sft/test_prime_monitor.py tests/unit/utils/test_links.py tests/unit/orchestrator/test_episode_records.py tests/unit/train/rl -m "not gpu"`: 29 passed. - `uvx uv@0.12.0 lock --check` passes. ## Merge order 1. ~~PrimeIntellect-ai/prime#1136~~ and ~~PrimeIntellect-ai/prime#1140~~: merged and released as `prime-runs` 0.1.6 and `prime-traces` 0.0.12. 2. **#4363 (this PR)**: ready to merge. It does not need PrimeIntellect-ai/verifiers#3042. 3. PrimeIntellect-ai/verifiers#3042 4. #4366 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes the hot path for RL training telemetry (episode/metrics enqueue) and bumps external SDK versions; misbehavior could drop or delay uploads under load, though load tests now enforce delivery and loop responsiveness. > > **Overview** > **Prime logging no longer blocks the orchestrator event loop** by pinning `prime-runs[train]>=0.1.6` (and `prime-traces` 0.0.12 in the lockfile), which uses a non-blocking upload queue, concurrent uploads, and lighter gzip. > > **`PrimeMonitor`** now calls `run.log_metrics` and `run.log_episodes` directly instead of `asyncio.to_thread`, matching SDK behavior where enqueue never blocks. > > The **monitor load test** is reworked to use **production-like episode sizes** (lognormal ~6.4 MB median), shared trace templates for memory, a thread-safe fake Traces API, and multi-chunk file delivery checks. The **Prime monitor at 1,000 episodes is no longer expected to fail**; responsiveness asserts split event-loop lag (p99 100 ms) from per-`log()` duration (max 1 s). > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 11ae62999764db49fb8233bece63fdb81b69bce6. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
9eae92253e |
feat: install the prime CLI as a uv tool instead of a dependency (#4371)
## Summary - Remove `prime` (the Prime CLI) from prime-rl's runtime dependencies. No prime-rl code imports `prime_cli`. The CLI only tied prime-rl's lock to the CLI's releases, and gave `prime-sandboxes` a second path into the lock next to `verifiers`. - `Dockerfile.cuda`: install the CLI as a uv tool in its own venv (`/opt/uv-tools`, executable in `/usr/local/bin`), pinned by `ARG PRIME_CLI_VERSION=0.19.2`. The platform keeps running `uv run --no-sync prime env install '<id>'` unchanged. Since prime CLI 0.8.0, `prime env install` installs into `$UV_PROJECT_ENVIRONMENT`, `$VIRTUAL_ENV`, or the `.venv` next to the nearest `pyproject.toml`, so Hub envs still land in `/app/.venv`. - `scripts/install.sh`: run `uv tool install prime` for local use. The docs already tell users to install the CLI this way. - `uv.lock` drops `prime`, `prime-evals` and `gitignore-parser`. `pyproject.toml` drops their now-unused `exclude-newer-package` entries. Source overlays on older images keep working: the entrypoint syncs with `--inexact`, so the CLI already in those images' `/app/.venv` stays in place. ## Breaking - `uv sync` no longer installs the `prime` command into the project venv, so `uv run prime …` in a prime-rl checkout fails until the CLI is installed. Migration: run `uv tool install prime`, then call `prime …` directly. ## Verification - Local check, `prime==0.19.2` installed with `uv tool install` and absent from the target project venv: `uv run --no-sync prime env install primeintellect/gsm8k` installed `gsm8k` into the project `.venv` and not into the tool venv. A plain `prime env install` from the project root did the same. - Hosted e2e: pending (reverse-text from the Hub with `prime train`, on an image built from this branch). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Packaging and install-path changes only; runtime training code is untouched, with a documented migration for local CLI usage. > > **Overview** > **Removes the `prime` CLI from prime-rl’s Python dependencies and lockfile**, so CLI releases no longer force lock updates and transitive packages like `prime-evals` and `gitignore-parser` drop out of `uv.lock`. > > **Docker and local setup now install the CLI separately** via `uv tool install`: the CUDA image pins `PRIME_CLI_VERSION=0.19.2` into `/opt/uv-tools` with `prime` on `PATH`, and `scripts/install.sh` runs the same after `uv sync`. Hub env installs (`prime env install` / `uv run --no-sync prime env install`) are unchanged in intent—the CLI still targets the project `.venv`, not the tool venv. > > **Breaking for devs:** `uv sync` no longer puts `prime` in the project venv, so **`uv run prime …` fails until you run `uv tool install prime`** and invoke `prime` directly. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 82cac44caaa77bd77c1b2796186e74264068b873. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
5e5e9c7782 |
fix: bump prime to 0.19.2 (prime-sandboxes 0.5.4) (#4369)
## Summary - Raise the `prime` floor from `>=0.18.0` to `>=0.19.2` and relock (`uv.lock`: `prime` 0.18.0 → 0.19.2, `prime-sandboxes` 0.5.3 → 0.5.4). No other lock changes. ### CLI/SDK changes pulled in - **feat(sandboxes): volume size at create + grow** (PrimeIntellect-ai/prime#1132, released in PrimeIntellect-ai/prime#1144). `prime sandbox volumes create --size-gb N`, `prime sandbox volumes grow NAME --size-gb N`, and SDK `volumes.create(size_gb=)` / `volumes.grow()`. Additive only. - `prime` 0.19.0–0.19.1 (localhost forwards, pause/resume, 24h live-process fix) are already covered by `prime-sandboxes` 0.5.3 from #4368, which merged before this branch was cut — no overlap with it. Companion: PrimeIntellect-ai/verifiers#3045 (prime-sandboxes 0.5.4). ## Verification - `uv lock --check` passes (uv 0.12.3 and 0.13.6); `uv sync --all-extras --all-packages --locked` succeeds (resolves `prime` 0.19.2 + `prime-sandboxes` 0.5.4). - Standalone venv with 0.5.4: `Volume.size_gb` present; `Volumes.grow(name, size_gb)` exists. - `pytest tests/unit --ignore=tests/unit/train -m "not gpu"` (macOS): 737 passed, 1 skipped, 1 xfailed, 7 failed. The 7 failures (inference/orchestrator/transports) reproduce identically on `origin/main` in the same env — pre-existing, unrelated. 5 modules skipped at collection (missing linux-only `vllm`/`fla`/`prime_kernels`; CI runs on ubuntu). |
||
|
|
2de09158ed |
fix: bump prime-sandboxes to 0.5.3 and verifiers (#4368)
## Summary - Bump `prime-sandboxes` 0.5.1 → 0.5.3 so live sandbox processes are no longer capped at 24h (via PrimeIntellect-ai/verifiers#3043). - Bump `deps/verifiers` `60290d4` → `bccc2c5` (verifiers main, with PrimeIntellect-ai/verifiers#3043 merged). - Require `prime-runs[train]>=0.1.5` from PyPI. This drops the `prime-runs` git source and the `prime-traces` git override, both pinned to `adf8d25c`. The new verifiers requires `prime-runs>=0.1.5` (PrimeIntellect-ai/verifiers#3001), and the old git pin no longer resolves. 0.1.5 contains `adf8d25c`, so it includes PrimeIntellect-ai/prime#1109. `uv.lock`: `prime-runs` 0.1.4 (git) → 0.1.5, `prime-traces` 0.0.10 (git) → 0.0.11. ### Why On Prime, the SDK sent a fixed 24h deadline on every live process stream, and the sandbox ended the process when it expired. A long agent segment then lost its ACP process. The trace stopped as `harness_error` (`EOFError: ACP process closed its stdout`) instead of `agent_timeout`, so `agent_timeout` undercounted real 24h cap hits. ### prime-sandboxes changes (0.5.1 → 0.5.3) 0.5.3: - fix(sandboxes): stop capping live processes at 24h (PrimeIntellect-ai/prime#1142) 0.5.2: - feat(sandbox): add localhost forwards to the CLI and SDK (PrimeIntellect-ai/prime#1124) - feat(sandboxes): add pause and resume to the SDK and CLI (PrimeIntellect-ai/prime#1056) - fix(cli): write credential files owner-only (PrimeIntellect-ai/prime#1130); the SDK auth cache is written 0600 ### verifiers changes (`60290d4` → `bccc2c5`) Fixes and features: - fix(serve): discard kept episodes when clients disconnect (PrimeIntellect-ai/verifiers#2997) - Reuse interception tunnels for task-scoped MCP servers (PrimeIntellect-ai/verifiers#3006) - Run Prime task services as native VMs and fix Harbor setup (PrimeIntellect-ai/verifiers#2910) - Run Compose services as native Prime VMs (PrimeIntellect-ai/verifiers#2918) - Accept Harbor Compose tasks on native VMs (PrimeIntellect-ai/verifiers#2999) - Add a native Compose integration test on Prime (PrimeIntellect-ai/verifiers#3010) - fix(harbor): reject ignored verifier user overrides (PrimeIntellect-ai/verifiers#3014) - Honor configured disk size for native Compose sidecars (PrimeIntellect-ai/verifiers#3018) - Size native Compose disks per service (PrimeIntellect-ai/verifiers#3020) - fix: use apk-installed Node and npm on Alpine (PrimeIntellect-ai/verifiers#3004) - fix: retry Node downloads before extracting (PrimeIntellect-ai/verifiers#3005) - fix(CVE-2026-111497) in Brotli and Node (PrimeIntellect-ai/verifiers#2998) Dependency pins: - bump prime-sandboxes to 0.5.3 (PrimeIntellect-ai/verifiers#3043) - chore: require prime-runs 0.1.5 from PyPI (PrimeIntellect-ai/verifiers#3001) Harness versions: - Bump Codex to 0.166.0 and codex-acp to 2.5.0 (PrimeIntellect-ai/verifiers#3021) - Bump DeepSeek harness to 0.2.1-rc.5 (PrimeIntellect-ai/verifiers#3023) - Bump mini-swe-agent's LiteLLM dependency to 1.106.6 (PrimeIntellect-ai/verifiers#3031) - Bump Hermes Agent to v0.22.5 (PrimeIntellect-ai/verifiers#3024) - Bump Claude Code to 2.1.314 and claude-agent-acp to 0.99.1 (PrimeIntellect-ai/verifiers#3022) - Bump Kimi Code to 2.4.1 (PrimeIntellect-ai/verifiers#3025) - Bump OpenCode to 2.2.5 (PrimeIntellect-ai/verifiers#3026) - Bump OpenClaw to 2026.10.9 (PrimeIntellect-ai/verifiers#3027) - Bump Prime Agent to 0.10.2 (PrimeIntellect-ai/verifiers#3028) - Bump nano-rlm to e4d4407f (PrimeIntellect-ai/verifiers#3029) - Bump Terminus 2 to Harbor 0.25.0 (PrimeIntellect-ai/verifiers#3030) Dependabot lockfile bumps in verifiers (they do not change prime-rl's lock): - urllib3 2.7.0 → 2.8.0 (PrimeIntellect-ai/verifiers#2733), pyjwt 2.13.0 → 2.15.0 (PrimeIntellect-ai/verifiers#2735), opentelemetry-api 1.44.0 → 1.45.1 (PrimeIntellect-ai/verifiers#2964), authlib 1.7.2 → 1.9.1 (PrimeIntellect-ai/verifiers#2990), msgpack 1.2.1 → 1.2.3 (PrimeIntellect-ai/verifiers#2991), litellm 1.98.0 → 1.100.4 (PrimeIntellect-ai/verifiers#2992), dnspython 2.8.0 → 2.9.0 (PrimeIntellect-ai/verifiers#2993), filelock 3.32.4 → 4.2.1 (PrimeIntellect-ai/verifiers#3002), virtualenv 21.14.12 → 21.14.13 (PrimeIntellect-ai/verifiers#3008), joserfc 1.7.4 → 1.7.6 (PrimeIntellect-ai/verifiers#3017), oauthlib 3.3.1 → 4.0.0 (PrimeIntellect-ai/verifiers#3035) ## Verification - `uv sync --frozen --all-packages --all-extras` installs `prime-sandboxes` 0.5.3. `prime_sandboxes.sandbox._LIVE_PROCESS_NO_TIMEOUT_MS == 9999999999` is the default deadline for every `open_process` stream. - `uv.lock` changes only `prime-sandboxes`, `prime-runs` and `prime-traces` (plus a uv-written reorder of the `exclude-newer-package` table). - `pytest tests/unit --ignore=tests/unit/train`: 837 passed, 1 xfailed. - `tests/unit/train` (RTX PRO 6000 Blackwell, SM120): `qwen3_8_flash_next` and `test_fp8_grouped_gemm` show the same failures, and `test_fused_lm_head.py::test_inject_prime_lm_head_vanilla` kills the process, on this branch and on `main` (`823ed27`). These GPU kernel tests do not touch this diff. - verifiers#3043: the live Prime runtime tests (`tests/unit/test_runtimes.py -k prime`, including `test_exec` on a live process) pass on 0.5.3. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
ef605346cf |
feat(trainer): log EP rank imbalance for MoE (#4346)
`max_vio` measures expert-level imbalance: the busiest expert's tokens over the mean, with the top_k busiest experts dropped so that padding experts don't dominate it (#1332). With expert parallelism an MoE layer waits for the EP rank that receives the most routes, and `max_vio` tracks that poorly: hot experts that share a rank add up, hot experts on different ranks don't, and the dropped experts are often the ones that make a rank busy. This PR logs the rank-level imbalance next to `max_vio`. ## What it computes `get_global_moe_stats` already sums each micro step's per-layer expert counts over the EP group. From those counts, per micro step and layer: - **rank imbalance**: routes received by the busiest EP rank over the mean rank. EP rank r holds experts `[r*E/ep, (r+1)*E/ep)`, so the counts are viewed as `[..., ep, E/ep]` and summed. Padding routes count, since they run through the expert GEMMs like any other token. Every rank of an EP group holds the same values. A layer waits for the busiest rank of its EP group and, through its FSDP collectives, for the slowest EP group. So the logged value is the max over DP groups at each (micro step, layer), and the DP mean is logged next to it. Both ride in the existing all-reduces: the DP max is stacked into the `max_vio` MAX all-reduce and the DP mean into the `routing_confidence` SUM all-reduce. There is no new buffer, recording path or collective, and no host sync per micro step. Per-DP-group values are not logged, since that would need a gather. Logged in SFT and RL: - `ep_imbalance/rank/{mean,max}`: max over DP groups, then the mean and max over the step's layers and micro steps. - `ep_imbalance/rank_dp_mean/{mean,max}`: the same with the DP mean. - The console step line shows `EP Imbalance` (`ep_imbalance/rank/mean`). ## Measurement: SFT on DeepSeek-V4-Base The run is DeepSeek-V4-Flash-Base in bf16: 43 MoE layers (the first 3 hash-routed), 256 experts, top-6. It trains on long-context chat data packed into 524288-token rows. With cp = 8 and ep = 8, each EP group is one CP group and trains one row per micro step, 64K tokens per rank. It ran on 48 H200s (6 EP groups) with 4 micro steps per rank for 60 steps, which gives 61,920 (EP group, micro step, layer) values. | | mean | p50 | p90 | p99 | max | |---|---|---|---|---|---| | rank imbalance per EP group, micro step and layer | 1.30 | 1.27 | 1.50 | 1.72 | 3.38 | | … hash-routed layers 0-2 | 1.15 | 1.15 | 1.18 | 1.28 | 2.04 | | … learned layers 3-42 | 1.31 | 1.28 | 1.51 | 1.73 | 3.38 | | `max_vio` per layer, same counts | 2.94 | 2.87 | 4.05 | 5.36 | 22.8 | | `ep_imbalance/rank/mean` per step | 1.39 | 1.39 | 1.41 | 1.48 | 1.54 | | `ep_imbalance/rank/max` per step | 1.90 | 1.87 | 2.01 | 2.71 | 3.38 | | `ep_imbalance/rank_dp_mean/mean` per step | 1.30 | 1.30 | 1.31 | 1.32 | 1.34 | | `max_vio/mean` per step | 5.79 | 5.58 | 6.47 | 8.79 | 9.73 | - **Step time tracks the new metric more closely than `max_vio` (suggestive, not causal).** Over steps 2-60, forward plus backward time ranged from 185 to 208 s. It correlates r = 0.83 with `ep_imbalance/rank/mean` and r = 0.65 with `max_vio/mean`. On the 32 steps with more than 99.8% of tokens real (no padding spikes), the correlations are 0.73 and 0.59. - **`max_vio` and rank imbalance are loosely related.** Per (layer, micro step, EP group) r = 0.35. The learned-layer values with `max_vio` between 2 and 5 (94% of them) span 1.10 to 1.72 in rank imbalance (p1 to p99). The layer with the highest mean `max_vio` (4.5) has rank imbalance 1.23. The most imbalanced layer (1.65) has `max_vio` 3.4. - **Per layer:** the hash-routed layers sit at 1.12-1.16 and the learned layers at 1.16-1.65. In the hottest learned layers (1.45-1.65), the same rank is the busiest in 97-100% of micro steps. Most of the imbalance is static: a fixed per-layer permutation of experts over ranks, fit on steps 1-30, brings steps 31-60 from 1.30 to 1.11. - **The max over DP groups matters:** 1.39 against 1.30 for the DP mean, with only 6 groups. - **The tail comes from the run's older packing, not from the metric.** That trainer revision padded rows with token 0, and the maxima (rank imbalance 3.38, `max_vio` 22.8, and the slowest step) come from a single row that was 57% padding. At head, packs pad by repeating their own tokens (#4184), so that tail should not reproduce; the mean-level numbers (1.30 per value, 1.39 per-step DP max) are properties of the routing and carry over. The counts were recorded with this change applied to the earlier trainer revision that the run's packing needs. Every (row, layer) counts exactly row length × 6 routes, so activation-checkpoint recompute does not double count. ## Testing - A manual 4-rank gloo run of `get_global_moe_stats` at head (two EP groups of two, random counts; not committed) matches a brute-force reference for `ep_imbalance/rank` (max over DP groups) and `ep_imbalance/rank_dp_mean`, and `max_vio` and `routing_confidence` match the previous formulas. - SFT on 8 H200s with a small GLM MoE (8 experts, top-4, fake data, ep = 4, so two EP groups), on the previous revision: every key is logged, and the DP mean comes out below the DP max (1.38 vs 1.48). - The measurement above, with this change applied to an earlier trainer revision that the run's packing needed. - `ruff check`, `ruff format --check`. |
||
|
|
823ed27b1e |
feat: name the missing W&B API key in the monitor error (#4361)
## Summary - The W&B monitor without an API key fails with its own error, like the prime monitor: ``` RuntimeError: The W&B monitor found no W&B API key. Authenticate with `wandb login` (or set WANDB_API_KEY), or turn the monitor off with --no-monitors.wandb ``` Before, the error wrapped W&B's text: ``The W&B monitor could not start (No API key configured. Use `wandb login` to log in.). Authenticate with ...``. - Other W&B usage errors (for example a bad project name) keep the generic message with W&B's own text. Follows the review on #4244: a missing key fails the run with an error that tells the user, or their agent, how to fix it. ## Verification - New unit test `test_wandb_monitor_without_credentials_fails_informatively`: it runs the real `wandb.init` with no key, `HOME` and `WANDB_CONFIG_DIR` in an empty directory, and matches the new message. - `pytest tests/unit/utils/test_links.py`: 5 passed. |
||
|
|
c2704ba5ef |
feat: fail a monitor without credentials with an actionable error (#4244)
## Summary Part of the monitors stack: #4228 → #4316 → #4317 → **#4244**. Stacked on #4317. - No net change against #4317. Following review, a prime or W&B monitor without credentials still fails the launch, as it does from #4228 on. Most runs start from an agent, which can easily miss a warning. The error has the login steps and the `--no-monitors.*` flag, so the agent can act on it, and turning a monitor off stays explicit. - The earlier warn-and-continue change is reverted in 9c2e9cd73. This PR can close without merging. ## Verification - Without a Prime key, `launch_run` fails before the components start: ``` RuntimeError: The prime monitor found no Prime API key. Authenticate with `prime login` (or set PRIME_API_KEY), or turn the monitor off with --no-monitors.prime ``` - `pytest tests/unit/utils/test_links.py tests/unit/train/sft/test_prime_monitor.py`: 19 passed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes default launch behavior for observability (credentials no longer gate local runs) while keeping strict failure for attached platform runs and authenticated registration errors. > > **Overview** > **rl**, **sft**, and standalone **eval** no longer abort when Prime or W&B is enabled but no API key is present. Each monitor logs a one-line warning (with `prime login` / `wandb login` or `--no-monitors.*` guidance), runs in a **disabled** mode, and the rest of the launch continues. > > The **rl/sft launcher** (and multi-node **run_owner**) catches Prime registration’s missing-key error once, warns, sets **`PRIME_RUNS_MODE=disabled`**, and skips **`RUN_ID`** so child processes don’t repeat the warning. **PrimeMonitor** and **W&B** map their SDK’s “no API key” errors to the same disabled path; disabled monitors register **no** platform links, so the launch banner doesn’t block on them. > > **Still fails at launch:** attaching via **`RUN_ID`** without a key (empty platform page), Prime registration errors **with** a key (team/allowlist), and other W&B **`UsageError`**s (e.g. bad project). > > Docs for **training** and **eval** are updated to describe warn-and-continue instead of hard failure; unit tests cover the new paths. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9c2e9cd736a132efed040e8ffdb66806c4f4e6d0. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
8d39914cf7 |
feat: stress test the monitors with agentic episodes (#4317)
## Summary Part of the monitors stack: #4228 → #4316 → **#4317** → #4244. Stacked on #4316. - Adds `tests/unit/monitors/test_monitor_load.py`: one test, parametrized over monitor (file, prime, W&B) × episode count (10, 100, 1000). - Each episode is agentic and heavy: 100 turns, 100k tokens, numpy streams as the env-server wire delivers them (about 2 MB per upload). - Interleaved with 2000 metric rows of 200 keys. - The episodes share one trace object. Every monitor serializes each episode separately, so the load is the same at a fraction of the memory. - The test logs through `monitors.log` as the orchestrator does, under the orchestrator's `GarbageCollector` (no automatic full collections). An asyncio ticker measures how late the event loop wakes. - The test checks that everything logged arrives: - **File monitor:** every episode in the trace stream, and steps 1 to 2000 in `metrics.jsonl`. - **Prime monitor:** the real SDK run and uploader threads against fake Prime Traces and platform endpoints. The fake traces endpoint gzips like the real client. - **W&B monitor:** the real SDK in offline mode. W&B takes metrics only. - The test fails when a monitor stalls the loop: p99 lag of 50 ms or more, max lag of 250 ms or more, or one `log()` call of 250 ms or more. - `prime-1000` is an expected failure (strict). The SDK uploader gzips each episode at level 9, about 70 ms here, so 1000 episodes logged at once fill its queue. `log()` then waits for room for up to 5 s on the orchestrator's arrival path, and the SDK drops what stays queued. A TODO in the test tracks the fix; PrimeIntellect-ai/prime#1129 is the first part (gzip level 1). - The test is CPU-only, needs no network and is marked `slow`. CI's unit job runs it (it deselects only `gpu`). It takes about 110 s. ## Verification `pytest -s tests/unit/monitors/test_monitor_load.py` on the dev box, with main's `prime-traces` pin: 8 passed, 1 xfailed. | Monitor | Episodes | Loop lag p99 | Loop lag max | `log()` p99 | `log()` max | |---|---|---|---|---|---| | File | 10 / 100 / 1000 | 3.6 / 3.4 / 4.7 ms | 3.7 / 5.6 / 4.9 ms | 0.1 / 5.0 / 5.3 ms | 7.9 / 9.9 / 7.8 ms | | Prime | 10 / 100 | 5.2 / 7.9 ms | 6.0 / 10.5 ms | 0.4 / 0.4 ms | 10.1 / 15.4 ms | | Prime | 1000 | xfail: 7 of 1000 episodes dropped ("Upload queue full after 5.0s"), one `log()` call blocked 5 s | | | | | W&B (offline) | 10 / 100 / 1000 | 1.6 / 1.3 / 1.1 ms | 6.0 / 1.6 / 1.4 ms | 0.6 / 0.5 / 0.6 ms | 6.1 / 0.8 / 0.8 ms | Without the orchestrator's GC setup, a full collection pauses the loop for 220–260 ms in the 1000-episode cases. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Test-only change with no production code paths modified; it exercises existing monitor integrations under load. > > **Overview** > Adds **`tests/unit/monitors/test_monitor_load.py`**, a slow unit test that drives **file**, **Prime**, and **W&B (offline)** monitors through **`monitors.log`** the way the orchestrator does—heavy agentic episodes (up to 1000 × 100 turns / ~100k tokens) interleaved with **2000** wide metric rows, under the orchestrator **`GarbageCollector`** fixture. > > For each monitor × episode count (**10 / 100 / 1000**), it asserts **complete delivery** (trace chunks / fake Prime endpoints / W&B metric steps) and **event-loop responsiveness** (p99 lag **< 50 ms**, max lag and single **`log()`** **< 250 ms**). **Prime @ 1000 episodes** is **`xfail` (strict)** documenting **`prime_runs`** upload-queue backpressure that can block **`log()`** for seconds and drop episodes. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit bb9dbad7e881aebde4fe78a8bc4589263c8d914d. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
ba317aea09 |
feat: log rl trainer metrics to the prime run (#4316)
## Summary Part of the monitors stack: #4228 → **#4316** → #4317 → #4244. Stacked on #4228. - The RL trainer logs its per-step metrics to the run's Prime run. It builds on #4170 by @kevinjosethomas and stacks on #4228. - The trainer sets up the prime monitor from `trainer.monitors.prime` and attaches to the run that the `rl` launcher registered (`$RUN_ID`). - The orchestrator still uploads the episodes and its own metrics. - The trainer only flushes its uploads. The process that registered the run finishes it once the trainer and the orchestrator exited (#4228). - `monitors.prime` must be on or off in both components, like `monitors.wandb` and `monitors.file`. `--orchestrator.no-monitors.prime` alone is rejected, so the trainer never waits for a run the launcher did not register. - The shared `[monitors.prime]` reaches the trainer and the orchestrator, like `[monitors.wandb]` and `[monitors.file]`. `--no-monitors.prime` turns it off for both. - A trainer started without the `rl` launcher has no run to attach to. In online mode it fails with a hint, like the SFT online-eval process: launch it with `rl`, or pass `--no-monitors.prime`. - The trainer and the orchestrator keep their metric names. Both log `time/step` and `time/save_ckpt`, as they do into the shared W&B run on main. A rename is a separate change. Compared with #4170, the trainer needs no `run.json` lookup, no pending-metrics queue and no sidecar mode: it attaches through `$RUN_ID`, like every other component since #4228. ## Breaking - A standalone RL trainer (`torchrun src/prime_rl/trainer/rl/train.py ...`) needs `--no-monitors.prime`, or `PRIME_RUNS_MODE=disabled`. ## Verification - Hosted RL, reverse-text, 10 steps, from the stack head: [u68lwuthm9f7e87fxb2pnq5f](https://app.primeintellect.ai/dashboard/training/u68lwuthm9f7e87fxb2pnq5f) COMPLETED. The hosted trainer attached to the platform's run; `mismatch_kl/*`, `entropy/*`, `importance_ratio/*`, `loss/*`, `optim/*` and `perf/mfu` are on Prime at every step 1–10, next to the orchestrator's `train/*`. - `uv run rl @ examples/basic/reverse-text/rl.toml --max-steps 5 --no-monitors.wandb`, local: [ek4xpjtfdnghv2yuae0252au](https://app.primeintellect.ai/dashboard/training/ek4xpjtfdnghv2yuae0252au) COMPLETED. - `trainer.log` and `orchestrator.log` both show `(attached via $RUN_ID)`. - The Prime run has the trainer's metrics (`optim/grad_norm`, `perf/mfu`, `loss/*`) next to the orchestrator's. - Local RL, 3 steps, latest head: [vconz7g0fm720wr9mtcrqyht](https://app.primeintellect.ai/dashboard/training/vconz7g0fm720wr9mtcrqyht) COMPLETED, with the trainer's and the orchestrator's metrics at every step. - Colliding keys: in [h9ia98nk6zc9ndruvpahy4gw](https://app.primeintellect.ai/dashboard/training/h9ia98nk6zc9ndruvpahy4gw), Prime keeps the last write per key and step, so `time/step` and `time/save_ckpt` show the trainer's values. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes default monitoring behavior for standalone RL trainer launches and tightens cross-component Prime config validation; metrics upload is best-effort but misconfiguration now fails fast at startup. > > **Overview** > The RL trainer now streams **per-step metrics** (loss, MFU, `optim/grad_norm`, timing, etc.) into the same **Prime platform run** as the orchestrator, instead of Prime being orchestrator-only. > > Shared **`[monitors.prime]`** (and `--no-monitors.prime`) apply to **both** trainer and orchestrator, with validation that Prime is enabled or disabled on both—matching W&B and file monitors. The trainer **attaches via `$RUN_ID`** from the `rl` launcher and only flushes uploads; it does not register or finish the run. > > **Breaking:** a standalone `torchrun … train.py` run must pass **`--no-monitors.prime`** (or disable Prime runs in env), or online mode errors with a launch hint. Docs and the parallel-invariance regression test were updated accordingly. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit b577b5522d91179db8049d19d0631e04be8fd037. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
ccff0a56a8 |
feat: one prime monitor, sft online evals on the training run (#4228)
## Summary Part of the monitors stack: **#4228** → #4316 → #4317 → #4244. Base of the stack. - **One prime monitor.** `PrimeMonitor` and `PrimeMonitorConfig` replace the train and eval pair. `[monitors.prime]` and `--no-monitors.prime` are unchanged. - **One monitors config.** `MonitorsConfig` (`wandb`, `file`, `prime`) replaces `TrainMonitorsConfig` and `EvalMonitorsConfig`. The online-eval process takes the trainer's monitors as they are. The RL trainer gets a `monitors.prime` field, which it doesn't set up yet. - **The process that supervises the launch registers the Prime run, and every component attaches to it.** This is how a hosted launch works: the platform pre-creates the run, passes `RUN_ID` to each pod, and sets the final status from the JobSet. - Local: the `rl` or `sft` launcher. - SLURM, single node: the `rl` or `sft` launcher inside the job. The submitting process registers nothing. - SLURM, multi node: `python -m prime_rl.entrypoints.run_owner {rl,sft} <config> srun ...` wraps the job's launch step. It fails the run when the step exits non-zero, or when SLURM sends SIGTERM (cancel, time limit). - **The Prime run gets the whole launch config.** An `rl` launch registers the full RL config (trainer, inference, orchestrator, deployment), not only the orchestrator's. Multi-node SLURM jobs write the full `rl.json` and `sft.json` for the run owner. The multi-node SFT trainer runs its own `trainer.json`, as the RL components already do. - The run's id becomes the run identity: `PRL_RUN_ID`, and with it the W&B run id and the episodes' `run.id`. The launcher also exports it as `RUN_ID`, which each component's prime monitor attaches to. - A launch that fails marks the run FAILED with the failed component's error, e.g. `RuntimeError: Trainer failed with exit code -9`. The SDK leaves an attached run's failure to the process that registered it. - A component started without a launcher still registers its own run. - **SFT online evals log to the same run, like RL.** The online-eval process uploads its eval metrics and every eval episode to the sft run. Before, it opened one Prime evaluation per eval epoch. - The process that registered the run finishes it once every component exited, and fails it when a component fails. Attached components only flush, so no component can finish the run while another still logs to it. On hosted training the platform sets the final status from the JobSet. - A paused run no longer gets reported as crashed: the SDK's exit hook is dropped after the flush. - **Standalone `uv run eval`** still opens one Prime evaluation per source and epoch. - Without a Prime API key, it fails at launch with the `prime login` hint, like `rl` and `sft`. The evaluations open later, when each epoch starts. - **Fewer helpers.** - The links record is keyed by the monitor's config field (`prime`, `wandb`), and `run_links` takes the `MonitorsConfig`. - The platform record is written through `update_record`. - `register` takes the config directly and turns the SDK's missing-key error into the `prime login` hint. - **The orchestrator's monitor producer is `orchestrator`**, the name every other place uses (`orchestrator.log`, the W&B labels). ## Breaking - SFT online evals no longer create Prime evaluations. Their results are on the sft run's Prime page, and an sft run's `monitors/prime/run.json` no longer lists `evaluations`. - With the prime monitor on, `PRL_RUN_ID` (and so the W&B run id) of an `rl` or `sft` launch is the Prime run's id instead of a random uuid. - A custom multi-node SLURM template (`slurm.template_path`) must wrap its launch `srun` in `python -m prime_rl.entrypoints.run_owner {rl,sft} <config>`, as the bundled templates do. Without it, nothing registers the shared run. - A multi-node SFT job's `sft.json` is now the full config. The trainer reads `trainer.json`; a custom multi-node SFT template must pass `{{ config_path }}` (the trainer's) to the trainer and `{{ run_config_path }}` to the run owner. - The Prime run's config of an `rl` launch is the full RL config instead of the orchestrator config. - An RL config can no longer turn `monitors.wandb` or `monitors.file` on in one component only: `RLConfig` rejects it ("must match across components"). Set the shared `[monitors.<name>]` instead. - A hosted orchestrator no longer finishes its attached run; the platform marks it COMPLETED from the JobSet, as it already did. - The orchestrator's file-monitor producer is `orchestrator` instead of `orch`. Its annotation stream moves from `monitors/file/traces/annotations/orch` to `.../annotations/orchestrator`, and its `metrics.jsonl` rows carry `"producer": "orchestrator"`. ## Verification Stack head (#4244 at `450707973`), 2026-10-30: | Run | Prime | Result | |---|---|---| | Hosted RL, reverse-text, 10 steps (`prime train --pr 4244 --image-tag v0.10.1.dev143`) | [u68lwuthm9f7e87fxb2pnq5f](https://app.primeintellect.ai/dashboard/training/u68lwuthm9f7e87fxb2pnq5f) | COMPLETED by the platform; trainer and orchestrator attached via `$RUN_ID` | | Hosted SFT, fake data, online evals every 5 steps | [uvmvu17v6bks0kbip83xubnd](https://app.primeintellect.ai/dashboard/training/uvmvu17v6bks0kbip83xubnd) | COMPLETED; online evals at steps 0, 5, 10 in the same run | | Local `rl`, reverse-text, 5 steps | [g4n7oc8hqhz2pfqfi5hj9nno](https://app.primeintellect.ai/dashboard/training/g4n7oc8hqhz2pfqfi5hj9nno) | COMPLETED by the launcher; W&B run has the same id | | Local `sft`, 10 steps, evals every 5 | [dxz2k1etkdbh3go026y96td4](https://app.primeintellect.ai/dashboard/training/dxz2k1etkdbh3go026y96td4) | COMPLETED by the launcher; eval metrics at steps 0, 5, 10 | | Local `eval` | [evaluation](https://app.primeintellect.ai/dashboard/evaluations/mqbd7zx0ub6m6xnua15uerpq) | exit 0 | On hosted runs the platform stores the submitted TOML as the run's config; the full resolved config is registered for local and SLURM launches only. Run ownership: - Local RL, 3 steps: [qxnhsl4ngd9qocvlcqzbbquw](https://app.primeintellect.ai/dashboard/training/qxnhsl4ngd9qocvlcqzbbquw) COMPLETED. The orchestrator only flushed; the launcher finished the run. - `run_owner` with a step that exits 0: [sppd7r2l1kdposmws2tarp8g](https://app.primeintellect.ai/dashboard/training/sppd7r2l1kdposmws2tarp8g) COMPLETED. - SIGTERM to `run_owner` while the step runs: the step received the forwarded TERM and finished a 2 s teardown before the owner exited 143; [rfev5w1qbxnxlko6dwd22apt](https://app.primeintellect.ai/dashboard/training/rfev5w1qbxnxlko6dwd22apt) FAILED with `RuntimeError: SLURM terminated the job`. - `uv run rl @ examples/basic/reverse-text/rl.toml --max-steps 3 --no-monitors.wandb`, local: [vtcuhcp16vigkskxu02d763l](https://app.primeintellect.ai/dashboard/training/vtcuhcp16vigkskxu02d763l) COMPLETED. Its `run_config` on the platform has `trainer`, `inference`, `orchestrator` and `deployment`. - Multi-node dry runs: `rl.json` loads as a multi-node `RLConfig` and registers `trainer`, `inference`, `orchestrator`, `deployment` and `slurm`. `sft.json` loads as a multi-node `SFTConfig`, and the script's `TRAIN_CONFIG_PATH` is `trainer.json`. - Multi-node RL and SFT dry runs (`examples/advanced/qwen3-30b-a3b/math.toml`, `.../sft/h200/base.toml`) render scripts that pass `bash -n`. `run_owner` loads the configs the scripts point to. - `run_owner rl <orchestrator.json> bash -s <<'STEP_SH' ... exit 3`: the step saw `RUN_ID=PRL_RUN_ID=<id>`, the wrapper exited 3, and Prime shows run `ekc8dcf8agutxcrizts1bkbe` FAILED with `RuntimeError: The SLURM job step exited with code 3`. - SIGTERM to a running `run_owner`: exit 143, and Prime shows run `q4g9hv95qoqsl06yeacle2jd` FAILED with `RuntimeError: SLURM terminated the job`. - `test_slurm_run_owner_fails_the_run_with_its_step`: the owner registers the run (not attached), exports its id, and fails the run only when the step fails. Latest head, local reverse-text: | Run | Prime run | Status | |---|---|---| | `uv run rl @ examples/basic/reverse-text/rl.toml --max-steps 5 --no-monitors.wandb` | [kbv529xg6xoop15a0yf7ijwq](https://app.primeintellect.ai/dashboard/training/kbv529xg6xoop15a0yf7ijwq) | COMPLETED | | `uv run sft @ examples/basic/reverse-text/sft.toml --max-steps 10 --eval.interval 5 --no-ckpt` | [bwd98te1u76s82qqrloaty8i](https://app.primeintellect.ai/dashboard/training/bwd98te1u76s82qqrloaty8i) | COMPLETED; trainer and online eval attached via `$RUN_ID` | | `uv run eval @ configs/debug/eval/single-turn.toml` | [evaluation](https://app.primeintellect.ai/dashboard/evaluations/os36zxdjeqhacgls2oz5xy6j) | banner shows the evaluation link | Earlier head, with episode counts and the failure path: | Run | Prime link | Local = Prime episodes | Arrival → ingested (p50 / max) | Status | |---|---|---|---|---| | `uv run sft @ examples/basic/reverse-text/sft.toml --max-steps 10 --eval.interval 5 --no-ckpt` | [training run](https://app.primeintellect.ai/dashboard/training/neakqq9sbr4s4o0942oeb2ys) | 96 eval (3 epochs × 32) | 1.0 s / 1.9 s | COMPLETED | | `uv run rl @ examples/basic/reverse-text/rl.toml --max-steps 5 --no-monitors.wandb` | [training run](https://app.primeintellect.ai/dashboard/training/fnog09c4s2updmlso4omjoh7) | 707 train + 512 eval | 1.0 s / 1.8 s | COMPLETED | | Failure path: the RL run above, with the trainer killed (`SIGKILL`) mid-run | [training run](https://app.primeintellect.ai/dashboard/training/eb0gmivb9a0glvrfj4b4bmoc) | — | — | FAILED: `RuntimeError: Trainer failed with exit code -9` | - **SFT run:** the trainer and the online-eval process both logged `Logging metrics and episodes to Prime run neakqq9sbr4s4o0942oeb2ys (...) (attached via $RUN_ID)`. - **RL run:** the orchestrator attached through `$RUN_ID`. An episode read back from Prime Traces carries `run.id = fnog09c4s2updmlso4omjoh7`, so `PRL_RUN_ID` is the Prime id. - **Failure path:** components attach to the launcher's run, and the SDK skips a failed finish from an attached run. So the launcher marks the run failed itself, with the component's error. - **Unit tests:** `pytest tests/unit --ignore=tests/unit/train tests/unit/train/sft/test_prime_monitor.py`: 810 passed, with main merged. - **Hosted:** not run on this head. #4318, which unblocked hosted RL on main, has merged. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes run identity, Prime lifecycle ownership, and multi-node SLURM wiring; custom templates or mixed monitor settings can break tracking or fail validation. > > **Overview** > **Unifies Prime and monitor configuration** so training uses one platform run and one config shape everywhere. > > **Prime:** `PrimeTrainMonitor` / `PrimeEvalMonitor` and separate train/eval monitor config types become **`PrimeMonitor`** and shared **`MonitorsConfig`**. The **`rl`/`sft` launcher** (or multi-node **`run_owner`**) **registers** the platform run via **`launch_run`**, sets **`PRL_RUN_ID` / `RUN_ID` / W&B run id**, and **finishes or fails** the run when the launch ends; worker processes **attach** and only flush. RL registration sends the **full RL config**, not orchestrator-only. **SFT online evals** now upload metrics and episodes to that same training run instead of opening per-epoch Prime evaluations; standalone **`uv run eval`** still opens one evaluation per env/epoch. > > **Launch / SLURM:** Bundled multi-node templates wrap the job step in **`python -m prime_rl.entrypoints.run_owner`**. Multi-node SFT writes full **`sft.json`** for the owner and **`trainer.json`** for torchrun. **`run_links`** takes **`MonitorsConfig`**; link records use **`prime`** / **`wandb`** keys. > > **Other:** RL validates **`monitors.wandb`** and **`monitors.file`** are on or off consistently on trainer and orchestrator. Orchestrator file-monitor **`producer`** is **`orchestrator`** (annotation path rename). Docs/skills updated accordingly. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 7e0c55fc313db82c95f6f80e0a24aa3e3b0bdefd. 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 Opus 5.5 <noreply@anthropic.com> |
||
|
|
5c410c8350 |
fix(trainer): load lazy modules before compiling (#4350)
## Problem
On `main`, a compiled trainer run of a GatedDeltaNet model (Qwen3.5 /
Qwen3.8) with the W&B monitor on dies on the first forward:
```
torch._dynamo.exc.InternalTorchDynamoError: RuntimeError: dictionary changed size during iteration
```
It reproduces every time, with a single thread:
1. FLA's `tensor_cache` wraps `prepare_chunk_indices`, which
`causal_conv1d` calls from `GatedDeltaNet.forward`. Its
`cache_disabled()` does `sys.modules.get('fla.utils')`
(`fla/utils/decorators.py:61`), so Dynamo wraps all of `sys.modules`
while tracing.
2. Dynamo walks the live `sys.modules.items()` and runs an `isinstance`
check on every module.
3. `wandb.init` leaves a lazy `azure.storage.blob` placeholder in
`sys.modules`: wandb's `util.get_module` returns a `LazyModule` by
default. `azure-storage-blob` is in the lock through
`runai-model-streamer-azure`.
4. The `isinstance` check runs the placeholder's `__getattribute__`,
which imports `azure.storage.blob` for real. About 144 modules
(`azure.*`, `cryptography`, `isodate`, ...) land in `sys.modules`
mid-walk, and the trace aborts.
CI misses it: the GPU integration tests train Qwen3-0.6B or
mini-glm-moe, and the regression test runs without W&B.
## Fix
`apply_compile` first loads every lazy module in `sys.modules`, meaning
any `ModuleType` subclass that overrides `__getattribute__`. The
trainers set up monitors before `setup_model`, so W&B's placeholder
already exists when this runs.
The upstream fixes would be for Dynamo to iterate a snapshot instead of
the live view, or for FLA to keep its cache flag out of `sys.modules`.
Until then, this keeps the trace from triggering imports.
## Verification
- Minimal repro, single process, no trainer:
`torch.compile(backend="eager")` over `prepare_chunk_indices` compiles
fine, fails with the error above after
`wandb.util.get_module("azure.storage.blob")`, and compiles again once
`load_lazy_modules()` runs first.
- Qwen3.5-4B LoRA reverse-text RL with `compile` and W&B on, on 2× RTX
PRO 6000 (torch 2.13.0, wandb 0.27.0, FLA 413ad2c): crashed on the first
forward in 5 of 5 runs on `main`; completes with this change, with
Dynamo's 4 wraps of `sys.modules` passing.
|
||
|
|
ff6e1fb294 | fix(trainer): DeepEP with compile, full AC and gradient clipping; dispatch and combine in-graph (#3954) | ||
|
|
3c21123c16 |
fix(qwen3.5, qwen3.8): respect language_model_only so text-only checkpoints load without a vision tower (#4335)
Since #3916 (Qwen3.8) and the Qwen3.5 VLM unification, text-only Qwen3.5 (`qwen3_5`, `qwen3_5_moe`) and Qwen3.8 (`qwen4_exp`) composite checkpoints no longer load in the trainer. These configs have `language_model_only: true` and a `vision_config`, but their weights hold only `model.language_model.*` (plus `lm_head`). **Symptom.** On main, SFT on such a checkpoint fails while loading: `RuntimeError: Missing key in checkpoint state_dict: model.visual.blocks.0.attn.proj...`. Meta construction shows the cause: the model has `model.visual.*` keys that the checkpoint does not contain (153 for Qwen3.5-0.8B with the vision weights removed, 333 for a 4-layer Qwen3.8). **Root cause.** Both composite configs dropped `language_model_only`, and `vision_config` falls back to a default. `ForCausalLM` sets `is_vlm = hasattr(config, "vision_config")`, so it always builds the vision tower. **Fix (same for both models).** Keep `language_model_only` on the config. This follows vLLM's `--language-model-only`; official Qwen configs ship the field. When the flag is set: - the composite model sets `visual = None` and its forward calls the language model directly (the injected LM-head forward calls `model.model(...)`, so the branch lives there); - `is_vlm` and `supports_packed_multimodal_training` are False. The flag is kept on the config, so saved configs keep it. Key names stay `model.language_model.*`, so conversion and the weight names sent to vLLM do not change. `docs/advanced.md` notes that vLLM does not read the field, so text-only RL also needs `inference.vllm.language_model_only = true`. I did not derive that vLLM setting automatically. The config package never reads model files (the model can be a Hub id), so doing it there would mean loading the HF config inside config validation. **Test.** - Qwen3.8: the config fixture of `test_model.py` gets a `language_model_only` case. - Qwen3.5: a meta test checks that a `language_model_only` config has no vision encoder and only `model.language_model.*` / `lm_head` keys. GPU (H200): - Qwen3.5-0.8B with the vision weights removed and `language_model_only: true`: SFT fails on main with the missing-key error. With the fix, SFT runs 8 steps. - Qwen3.8, 4 layers, text-only: SFT on 4 GPUs, 8 steps, loss 12.88 -> 10.98. RL with vLLM `language_model_only = true` (4 trainer / 4 inference GPUs, NCCL broadcast) runs 6 steps, sending 133 layer state dicts per step, mismatch KL 0.075-0.09. - VLM checkpoints (Qwen3.5-0.8B and a tiny Qwen3.8) with `[model.vlm]`: the vision encoder is still built, frozen and wrapped with FSDP. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes Qwen3.5/Qwen3.8 model construction and checkpoint loading paths; behavior is scoped to the `language_model_only` flag with new unit coverage, but mistakes could affect weight loading or VLM vs text-only routing. > > **Overview** > Fixes loading and training for **text-only** Qwen3.5 / Qwen3.8 composite checkpoints that still carry a `vision_config` but only `model.language_model.*` weights (official `language_model_only: true` in `config.json`). > > **Trainer behavior:** The flag is preserved on `Qwen3_5Config` and `Qwen3_8FlashNextConfig` instead of being dropped. Composite `ForCausalLM` models now treat VLM mode as `vision_config` present **and** not `language_model_only`; the composite wrapper skips building `visual`, forwards through the language model only, and clears `is_vlm` / packed multimodal support. `init_buffers_post_meta` uses `get_language_model` so buffer setup still targets the decoder when the wrapper is composite but text-only. > > **Docs:** Notes that vLLM ignores the HF field, so text-only RL must set `inference.vllm.language_model_only = true`. > > **Tests:** Qwen3.5 meta test asserts no vision encoder and state dict keys under `model.language_model.*` / `lm_head`; Qwen3.8 config fixture adds a `language_model_only` variant. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f30d782233f0148685dbd5c42594ecb9a561bad7. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> |
||
|
|
4e94a86165 |
fix(qwen3_5): tie lm_head to input embeddings for tied checkpoints (#4144)
## Problem Training `Qwen/Qwen3.5-4B` (and other small Qwen3.5 checkpoints with `tie_word_embeddings: true`) learns nothing: from step 1 the trainer logs **entropy = 12.4225 = ln(vocab_size)**, **grad norm 0.0000**, and **mismatch KL ≈ 11**, every step. Those checkpoints ship no `lm_head.weight`. `load_dcp_from_hf` pops `lm_head.weight` from the state dict when `tie_word_embeddings` is set, on the assumption that the model ties it. `Qwen3_5ForCausalLM` builds a separate `VanillaOutputLinear` and never ties it, so the head stays at its meta-device init (zeros). The result is uniform logits and zero gradients through the head. With full fine-tuning it also breaks inference: vLLM ties `lm_head` to `embed_tokens`, so the trainer's startup weight broadcast writes the zero head into the shared tensor, and the policy then emits token 0 at logprob −ln(vocab) from the first rollout. ## Fix - When `config.tie_word_embeddings` is set, share the input embedding's weight with `lm_head` at construction. `inject_prime_lm_head` already carries `old_lm_head.weight` over to the injected head, so the tie survives injection, and `shard_norm_and_lm_head` already skips separate sharding for tied models. - `load_dcp_from_hf` now asserts that a tied model's `lm_head` is its input embedding before dropping `lm_head.weight`, so any model that misses the tie fails at startup instead of training silently with an unloaded head. ## Verification - `test_tied_word_embeddings_share_lm_head` builds a tied Qwen3.5 VLM config on the meta device (no CUDA, runs in the CPU unit job): passes with the fix, fails on `main`. - Qwen3.5-4B through `setup_model` on one GPU: per-token logprobs match HF transformers (mean |Δ| 0.012 nats vs 10.7 on `main`). With the fix reverted, the new assertion fires at load; tied Qwen3-0.6B and Qwen3.5-4B + LoRA load normally. - 8-step reverse-text RL on Qwen3.5-4B, 2× RTX PRO 6000 (trainer `compile` off): - LoRA: `main` logs entropy 12.4225, mismatch KL 9–11, grad norm 0 at every step; with the fix, entropy 2.5 → 1.7, staleness-0 mismatch KL ≈ 0.003, reward 0.41 → 0.56. - Full fine-tune: on `main` the policy outputs `!!!!` after the startup broadcast and no batch is ever admitted; with the fix it trains and staleness-0 mismatch KL stays 0.002–0.004 across weight updates. - In a LoRA RL run on Qwen3.5-4B, 2× A6000: before, entropy 12.42, mismatch KL 11.3, grad norm 0. After, entropy 0.08, mismatch KL 0.0001, grad norm 0.007, and the run trains normally. Co-authored-by: hallerite <git@hallerite.com> |
||
|
|
80385dd9de |
fix(trainer): count the step's tokens and samples before checkpointing it (#4349)
The SFT and RL trainers saved each in-loop checkpoint before adding the
step to `progress.total_tokens` and `progress.total_samples`. A resume
from such a checkpoint starts the counters one batch behind an
uninterrupted run, and they stay behind. The final checkpoint, written
after the loop, was already correct.
- **SFT:** `progress/num_tokens` stays one batch behind for the rest of
the run. `progress/num_samples` recovers after the first resumed step,
because it is re-read from the dataloader.
- **RL trainer:** both counters stay one batch behind. They are printed
in the resume log line ("Resuming from step N (total_tokens=…,
total_samples=…)") and saved in every later checkpoint. RL's
`progress/total_tokens` metric comes from the orchestrator, which
already updates its totals before checkpointing, so the logged metric
was correct.
The fix counts the step before the checkpoint block in both trainers, as
the orchestrator does. Training, data order and the dataloader state are
unchanged; only the saved counters move.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Reorders when existing counters are updated relative to checkpoint
I/O; no change to training math, data, or checkpoint format fields.
>
> **Overview**
> **Both SFT and RL training loops now update `progress.total_tokens`
and sample counters immediately after the optimizer step, before any
in-loop checkpoint write.**
>
> Previously those totals were incremented only after checkpointing (and
related logging), so checkpoints captured counters that omitted the step
just finished. Resuming from such a checkpoint left **`total_tokens` one
batch behind** for the rest of the run; RL also kept **`total_samples`
behind**, affecting resume logs and every subsequent checkpoint. SFT’s
sample count could catch up on the first post-resume step because it is
refreshed from the dataloader, but token totals did not.
>
> The moved block is unchanged in logic—same DP all-reduce over local
tokens/FLOPs—only its position relative to `ckpt_manager.save` changes,
matching the orchestrator’s ordering. Training data, step order, and
dataloader state are unaffected.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e67f0253012f9b0bbc252804f1038fbdbdff2c11. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
|
||
|
|
a566e5d8e2 |
perf(qwen3.8): fp32 fused hyper-connection mix, fused with the preceding combine (#4314)
Follow-up to #4211. It keeps the custom-op structure, the CUDA-only dispatch and the eager CPU path, and replaces the kernels with a fused read kernel that is more accurate and moves less memory. It also fuses the attention's `combine` into the MLP's `mix`. **Changes** - **Precision.** The projection GEMM runs on the unnormalized streams with the norm gain folded into `[down; inject]`, in fp32 (one cuBLAS `bmm` over the streams). Each stream's rstd scales its rows afterwards. `n` and the up logits are never rounded to bf16: the mix kernel recomputes the logits per tile in fp32 registers and normalizes in registers. #4211 rounds `n`, the `(tokens, 328)` projection and the up logits to bf16. - **Fewer HBM passes.** Forward: an rstd kernel, the `bmm`, a small gates kernel and the mix kernel. Only the output has size `(tokens, hidden)`, and nothing of size `(tokens, 4 x 2560)` is written. Backward: two Triton kernels recompute the logits in-tile (one for the gate gradient, one for the stream and norm gradient), and cuBLAS computes the weight gradients in fp32. It keeps #4211's 16,384-token chunks. - **`mix(x, pending_combine)`.** The previous sublayer's `combine` (`x + block_output * injection` per stream) runs inside the rstd pass, and its backward runs in one kernel. The decoder layer uses this for the attention -> MLP hand-off. That is one call site, and the layer's interface does not change. - `fused_hc_mix` keeps #4211's signature; `fused_hc_combine_mix` is new. The kernels now live in `kernels/qwen3_8_hyper_connection/` (`kernels.py`, `launch.py`, `ops.py`). On CPU, `mix` applies a pending combine eagerly. **Not included (possible follow-up):** handing each layer's last combine to the next layer's first mix. It would save one more combine pass per layer. But it puts the block output and the injection weights into every checkpointed layer input under full AC: +1/4 of the streams, about 7 GiB at 48 layers x 30k tokens per GPU. ## Numerics 32,768 tokens, bf16 inputs and weights (`hidden 2560, 4 streams, rank 320`), forward + backward. Mean relative error vs an fp64 evaluation of the same math (`mean|err| / mean|ref|`, x1e-3). "eager" is `HyperConnection`'s eager path in bf16; "eager compiled" is the same under `torch.compile`. `mix`: | tensor | eager bf16 | eager compiled | #4211 | this PR | |---|---:|---:|---:|---:| | block input | 3.17 | 2.20 | 2.20 | 1.42 | | injection weights | 1.48 | 1.48 | 1.48 | 1.47 | | grad streams | 3.04 | 1.46 | 2.35 | 1.45 | | grad norm weight | 3.78 | 1.48 | 2.89 | 1.47 | | grad down | 5.02 | 4.08 | 4.08 | 3.32 | | grad up | 5.03 | 4.09 | 4.09 | 3.29 | | grad inject weight | 4.07 | 3.27 | 2.78 | 2.30 | `combine + mix` (the #4211 column uses a compiled `combine`): | tensor | eager bf16 | eager compiled | #4211 | this PR | |---|---:|---:|---:|---:| | block input | 2.63 | 2.03 | 2.03 | 1.76 | | injection weights | 1.49 | 1.49 | 1.48 | 1.48 | | combined streams | 1.84 | 1.41 | 1.41 | 1.41 | | grad streams | 1.48 | 1.41 | 1.46 | 1.41 | | grad block output | 2.68 | 2.15 | 2.17 | 2.15 | | grad injection in | 2.85 | 2.28 | 2.30 | 2.29 | | grad norm weight | 4.28 | 2.31 | 3.30 | 2.31 | | grad down | 5.87 | 4.73 | 4.73 | 4.09 | | grad up | 5.85 | 4.73 | 4.72 | 4.06 | | grad inject weight | 4.66 | 3.71 | 3.26 | 2.86 | This PR has the lowest mean error for every output and gradient, at 16k, 32k and 65k tokens. The only exception is the gradient of the incoming injection weights, which ties with eager compiled (within 0.2%). The largest error (`max|err| / max|ref|`) is below #4211's everywhere except two `combine + mix` gradients at 65k tokens: the block output (3.65e-3 vs 3.61e-3) and the incoming injection weights (2.81e-3 vs 2.78e-3). The test tolerance is #4211's: relative L2 error < 1e-2 vs the CPU fp32 eager reference. ## Isolated HC microbenchmark (1x H100 80GB) Same shape, one call, CUDA events, median of 20. Cells are fwd / bwd / fwd+bwd in ms; the last column is #4211's fwd+bwd time over this PR's. | tokens | call | eager | eager compiled | #4211 | this PR | #4211 ÷ this PR | |---:|---|---:|---:|---:|---:|---:| | 16,384 | mix | 3.88 / 9.55 / 13.43 | 1.05 / 3.62 / 4.67 | 0.97 / 2.51 / 3.48 | 0.89 / 2.58 / 3.47 | 1.00x | | 16,384 | combine + mix | 4.66 / 11.07 / 15.73 | 1.18 / 4.03 / 5.21 | 1.21 / 3.13 / 4.34 | 1.05 / 2.84 / 3.88 | 1.12x | | 32,768 | mix | 7.68 / 18.94 / 26.61 | 2.06 / 7.16 / 9.22 | 1.83 / 4.97 / 6.80 | 1.64 / 5.25 / 6.89 | 0.99x | | 32,768 | combine + mix | 9.18 / 21.95 / 31.13 | 2.55 / 8.01 / 10.55 | 2.31 / 6.20 / 8.51 | 1.95 / 5.69 / 7.63 | 1.12x | | 65,536 | mix | 15.25 / 37.01 / 52.27 | 3.99 / 13.57 / 17.56 | 3.53 / 9.88 / 13.41 | 3.08 / 10.50 / 13.58 | 0.99x | | 65,536 | combine + mix | 18.24 / 43.02 / 61.26 | 4.98 / 15.32 / 20.30 | 4.51 / 12.35 / 16.86 | 3.70 / 11.42 / 15.12 | 1.11x | | tokens | call | saved after forward (GiB): eager / compiled / #4211 / this PR | peak over fwd+bwd (GiB): eager / compiled / #4211 / this PR | |---:|---|---|---| | 16,384 | mix | 1.97 / 0.72 / 0.09 / 0.10 | 3.84 / 1.65 / 1.42 / 1.25 | | 16,384 | combine + mix | 2.29 / 1.04 / 0.40 / 0.42 | 4.15 / 1.97 / 1.73 / 1.57 | | 32,768 | mix | 3.95 / 1.45 / 0.18 / 0.20 | 7.67 / 3.29 / 2.18 / 1.74 | | 32,768 | combine + mix | 4.57 / 2.07 / 0.80 / 0.83 | 8.29 / 3.92 / 2.81 / 2.36 | | 65,536 | mix | 7.89 / 2.89 / 0.35 / 0.40 | 15.33 / 6.58 / 3.00 / 2.60 | | 65,536 | combine + mix | 9.14 / 4.14 / 1.60 / 1.65 | 16.58 / 7.83 / 4.26 / 3.85 | A plain `mix` takes about the same time as #4211's: the forward is 8-13% faster, the backward 3-6% slower at rank 320. A `combine + mix` is 11-12% faster. Saved activations are higher because the projection is kept in fp32: +0.6 KB per token per call, i.e. +13-18% for a plain `mix` and +3-4% for `combine + mix`, whose saved tensors include the combined streams. The transient peak is 0.17-0.45 GiB lower. ## RL trainer steps (1 node, 8x H100 80GB) #4211's setup on H100 instead of H200: `Qwen/Qwen3.8-Flash-Next` config with `model.debug.num_layers = 8`, `random_init`, `force_balanced_routing`, n-gram table cut to 200K rows (`ngram_vocab_size_base = 200000`), EP8, `moe.dispatch = "torch"`, compiled, FSDP; "full AC" is `ac.mode = "full"` with the default activation offloading. Fake packed samples (`data.fake.generate_samples`, batch 16, i.e. 2 micro-batches per GPU), the trainer's default env (`expandable_segments:True`). One warm-up run, then 3 interleaved runs per arm. Median over steps 3-12 (AC on) or 4-12 (AC off), then over runs; range over runs in brackets. | config | main (#4211) step | tok/s | peak | this PR step | tok/s | peak | Δ tok/s | |---|---:|---:|---:|---:|---:|---:|---:| | 32k tokens per GPU, full AC | 6.46 s | 81.2k (81.0-81.5k) | 66.6 GiB | 6.35 s | 82.5k (82.5-82.6k) | 66.7 GiB | +1.7% | | 16k tokens per GPU, no AC | 2.79 s | 93.8k (93.8-94.0k) | 71.9 GiB | 2.78 s | 94.2k (94.1-94.5k) | 72.3 GiB | +0.4% | - Entropy and mismatch KL match main to 4 decimals on every step in both configs. - With full AC the forward runs twice, and that is where the gain comes from. Without AC the difference is within noise, and the peak is 0.4 GiB higher. The fp32 projection accounts for about 0.16 GiB of that (16 calls x 16k tokens x 0.6 KB). - Step 1 (with compilation) is unchanged: 25 s vs 25 s (AC on). - The isolated HC numbers transfer to the step only partly: HC is a small share of a Qwen3.8 layer. ## Tests - `tests/unit/train/models/qwen3_8_flash_next/test_model.py::test_fused_hyper_connection_matches_eager` (gpu): fused CUDA bf16 vs eager CPU fp32, forward and backward, with/without injection, with/without a pending combine. It runs at three shapes (`4 x 2560` rank 320, `4 x 1024` rank 128, `3 x 200` rank 24) with the backward chunk set to 256 tokens, so several chunks run and the last one is partial. All 12 cases pass on H100 (the whole file: 24 passed). - `-m "not gpu"` unit tests pass, except `test_cpu_adam`, which fails the same way on main in this environment. ruff 0.15.14 check + format clean. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Training forward/backward math for Qwen3.8 hyper-connections is replaced with new fused CUDA kernels and a cross-sublayer fusion path, though behavior is guarded by expanded GPU parity tests against eager fp32. > > **Overview** > Replaces the single-file Qwen3.8 hyper-connection CUDA path with a **`kernels/` / `launch` / `ops`** package and a **rewritten fp32 read**: projection runs as one fp32 stream `bmm` with norm gain folded into `[down; inject]`, gate logits are recomputed in Triton tiles instead of storing bf16 intermediates, and backward uses new gate/stream/write kernels with H100-tuned launch configs. > > Adds **`fused_hc_combine_mix`** (custom op `qwen3_8_hc_write_read`) so the previous sublayer’s **combine** (`streams + block_output * inject`) runs inside the rstd pass before the next **mix**. **`HyperConnection.mix`** accepts optional **`pending_combine`**; the decoder applies this on the **attention → MLP** hand-off so the explicit attn `combine` is dropped from the layer forward. **`fused_hc_mix`** keeps the same public signature; imports move to **`...ops`**. > > Unit tests broaden **`test_fused_hyper_connection_matches_eager`** (multiple shapes, pending combine, chunked backward). > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 2e60a99efec8a5cb40cba760dfb666ae5d6f53cd. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> |
||
|
|
f98f9937a2 |
refactor(trainer)!: fold multimodal into trainer/vlm.py; one VLM registry; drop vlm attr fields (#3861)
Folds the trainer's multimodal code into one module, keeps one VLM
registry, and removes VLM config fields that nothing reads.
## What changes
- **One module.** `src/prime_rl/multimodal/` (5 files),
`trainer/multimodal.py`, `utils/vlm.py` and `setup_processor` (from
`model.py`) become `src/prime_rl/trainer/vlm.py`: `get_vision_encoder`,
`get_language_model`, `get_layer_prefix`, `load_image`,
`setup_processor`.
- **Image processing lives on the model.** Each VLM class exposes
`materialize_images(refs, processor)`; the RL trainer calls
`model.materialize_images`, so a new VLM family brings its own. Qwen3.5
and Qwen3.8 Flash Next each define `materialize_qwen_vl_images` in their
own `vision.py` (the packages stay self-contained), which runs the
Qwen-VL image processor and checks placeholder lengths against vLLM; the
family-agnostic data-URL decoding is `load_image` in `trainer/vlm.py`.
- **Deleted:** `ForwardPolicy`, `MaterializedMM`, the
`MultimodalAdapter` Protocol and its registry, and the Kimi K2.5 /
Qwen3-VL image paths. No Kimi K2.5 or Qwen3-VL trainer model exists, so
`get_model` already rejected them.
- **One VLM registry.** `_CUSTOM_VLM_MAPPING`
(`trainer/models/__init__.py`) is the only one; `VLM_REGISTRY` and
`is_vlm_architecture` are gone. The vision encoder, language model and
NCCL layer prefix come from the model layout: `model.model.visual` and
`model.model.language_model`, with `model.model` for text models (Muse
Glimmer, Qwen3.8 Flash (`qwen4_exp`) and GLM-5.3 Flash (`glm5_next`)
resolve the same way; they load no vision tower).
- **Qwen3.5 VLM owns its positions and CP.** The model builds MRoPE
positions whenever `image_grid_thw` is given; `forward()` always passes
`position_ids`, used only for text-only rows. RL and SFT defer CP to the
model for every batch with images. `setup_context_parallel` refuses `cp
> 1` for a VLM without `cp_context`.
- **Config (breaking).** `[model.vlm]` keeps only
`freeze_vision_encoder`; `vision_encoder_attr` / `language_model_attr`
and `orchestrator.model.vlm` are removed (the orchestrator detects
images from message content). `vlm` moves to the trainer `ModelConfig`
and the shared `[model.vlm]` propagates only to `trainer.model.vlm`. The
VLM bfloat16 `optimization_dtype` / `reduce_dtype` validator is removed.
Old keys fail with "Extra inputs are not permitted".
Migration: delete `vision_encoder_attr` / `language_model_attr` and any
`[orchestrator.model.vlm]` block.
## Behavior
Training is unchanged for every trainable VLM (Qwen3.5 dense and MoE):
same MRoPE positions, same CP shards, same component lookup. Configs
with fp32 dtypes and `[model.vlm]` are no longer rejected.
## Checks
- `pytest -m "not gpu" tests/unit/orchestrator
tests/unit/test_configs.py tests/unit/train tests/unit/utils` after
merging main (
|
||
|
|
dc7ac3e6b9 |
perf(deepseek-v4): compute the mHC pre-pass projection with DeepGEMM's TF32 prenorm GEMM (#4333)
This PR computes the mHC pre-pass projection and per-token sum of squares with DeepGEMM's `tf32_hc_prenorm_gemm`, the kernel vLLM uses for DeepSeek V4's mHC, and keeps the existing fused Triton op for the collapse and the backward. The forward drops from 5.5 ms to 0.6 ms at 31k tokens per GPU on H200 under `matmul_precision = "highest"`. - Under `"highest"` the forward projection now runs in TF32, as [vLLM's does](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/model_executor/kernels/mhc/tilelang.py#L22-L72) (v0.32.0), instead of IEEE fp32. With bf16 weights and bf16 streams, as in training, TF32 holds both inputs exactly, so only the fp32 accumulation differs. - The backward still follows `matmul_precision`. - DeepGEMM takes at most 32 outputs in multiples of 8, so the 4-output `DeepseekV4HyperHead` keeps the in-kernel projection. - The weight is upcast to fp32 for DeepGEMM, since FSDP hands it over in bf16. - The split count is bucketed to 1, 4 or 16 as in vLLM, so DeepGEMM compiles at most three variants of the GEMM (21 without bucketing on H200). #4216 fused this input side so the fp32 normalized streams are no longer stored, saving 8 to 10 GiB of activations per layer at 64k tokens. Its timings and numerics checks ran at `"high"`, where it was faster than before. Under `"highest"`, which production RL uses to match inference, its `tl.dot` runs as an IEEE fp32 loop on CUDA cores, so the forward ended up slower than the compiled code it replaced, which projected through cuBLAS. This PR keeps #4216's memory savings and removes that slowdown. | mHC input side, 31k tokens, H200, fp32 weights | `"highest"` fwd / fwd+bwd | `"high"` fwd / fwd+bwd | |---|---|---| | before #4216 (compiled) | 2.01 / 6.77 ms | 1.69 / 5.67 ms | | #4216 | 5.50 / 9.70 ms | 1.39 / 4.47 ms | | this PR | 0.60 / 4.79 ms | 0.60 / 3.67 ms | With bf16 weights, as FSDP passes them in training, this PR measures 0.61 / 4.87 ms under `"highest"` and 0.69 / 3.59 ms under `"high"`. End to end, we ran a trainer-only proxy on one 8x H200 node: a DeepSeek V4 Flash checkpoint cut to 6 layers, cp 8, ep 8, FP8, `"highest"`, 262,144-token micro batches, 8 per step, 20 steps, each arm against a baseline on the same node. Medians over steps 4 to 20: | node | main fwd+bwd per step | this PR | change | |---|---|---|---| | H200 node A | 17.45 s | 16.52 s | -5.3% | | H200 node B | 17.35 s | 16.45 s | -5.2% | Entropy matches the baseline and peak memory drops from 125.0 to about 121.4 GiB. That is about 19 ms per layer per micro batch, so the full 43-layer model should save about 0.8 s of its roughly 16 s per micro batch on H200, about 5%. ## Verification - `uv run pytest "tests/unit/train/models/test_deepseek_v4_kernels.py::test_fused_mhc_pre_matches_reference"` on H200: all 36 pass, the fp64 reference test for 4 and 24 outputs, fp32 and bf16 weights, and hidden sizes 96, 128 and 512, which reach DeepGEMM split counts 1, 4 and 16. - In the end-to-end runs, DeepGEMM's JIT cache holds `sm90_tf32_hc_prenorm_gemm`, so the new path runs inside the model. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
0790ebb5d8 |
feat(modelexpress): test #3890 end to end on MX f24c721 (server launch, CI test, benchmark) (#4015)
Builds on #3890 (by @zhengluo-nv) to test ModelExpress weight broadcast end to end; their PR is untouched. This branch is #3890 rebased on main plus: - **MX client pin**: follows #3890's 957eda8 (cherry-picked): `modelexpress==0.8.0.dev20261022` from PyPI, the nightly built from ai-dynamo/modelexpress `446feec` (main after #886; includes TrainerMesh #835, transfer-plan reuse #882, coarser replay descriptors #885 and quantized bounded streaming #889). The same commit fixes a stable mesh `idempotency_key` and passes `roles` when pausing engines for an MX update. The benchmarks below ran at `f24c721`. - **MX server**: `scripts/install_modelexpress.sh` builds the matching `modelexpress-server` at `446feec` (+ Redis), bootstrapping Rust and `protoc` when the host has none. - **`uv run rl`**: starts a run-scoped MX server + Redis when `weight_broadcast.type = "modelexpress"` (logs in `logs/modelexpress/`). - **SLURM**: the multi-node template launches the MX server on the trainer head node for `modelexpress` as it already did for `nixl`. Dropped `--database-path`, which the current server no longer accepts. The template flag `uses_modelexpress_server` covers both transports, since both rendezvous through the MX server; the UCX checks stay `nixl`-only. - **Receiver conversion fix**: the vLLM worker builds its PrimeRL-to-HF conversion chain from the PrimeRL config class instead of vLLM's `hf_config`; the transformers class lacks PrimeRL-only fields such as DeepSeek-V4's `layer_types`, so `init_broadcaster` failed for that model. - **Weight-version labels**: `/update_weights_from_modelexpress` sets the engine weight version like `/update_weights` does on main, and MX updates record pause/transfer/resume times for the watcher gauges. - **CI**: new `tests/integration/test_reverse_text_modelexpress.py` (reverse-text, Qwen3-0.6B, 1+1 GPU) added to the `gpu.yml` integration matrix, with an MX server build step for that job. - **Docs**: the ModelExpress docs moved from `scaling.md` to their own page, `docs/model-express.md`. ## Results ### MX nightly `0.8.0.dev20261022` (server `446feec`) on main, 2026-10-26 Same setup as the `f24c721` table below: bounded staging (2 x 4 GiB), vLLM default `gpu_memory_utilization` (0.9), 10 steps, default `max_staleness`. Medians in seconds over warm updates 2-9. "Inference pause" is the orchestrator's per-update wait (`watcher/last_update_weights_time`); "startup sync" is the v0 transfer, which includes MX's cold transfer planning. | Model | Transport | Trainer weight send | Inference pause | Startup sync | Max mismatch KL | |---|---|---:|---:|---:|---:| | Qwen3-30B-A3B (1+1 nodes, TP=2) | NCCL | 5.99 | 4.34 | 4.3 | 0.034 | | Qwen3-30B-A3B (1+1 nodes, TP=2) | **MX** | **4.14** | **2.25** | 20.4 | 0.028 | | GLM-4.5-Air (2+1 nodes, TP=8) | NCCL | 14.56 | 7.20 | 6.4 | 0.0033 | | GLM-4.5-Air (2+1 nodes, TP=8) | **MX** | **9.05** | **3.53** | 24.7 (77 s on the trainer) | 0.0036 | - MX cuts the inference pause about 2x and the trainer send 30-40% vs NCCL; mismatch KL matches NCCL. - Cold planning on the first update dropped from 59 s / 108 s at `f24c721` to 20 s / 25 s (likely ai-dynamo/modelexpress#885). - NCCL is also faster on today's main than in the `f24c721` table, so compare within this table. ### MX `f24c721`, bounded staging (2 x 4 GiB), vLLM default `gpu_memory_utilization` (0.9) Run 2026-10-21. *Trainer* = `time/broadcast_weights` median (steps 3-10); *Inference* = inference pause per update (`watcher/last_update_weights_time`) median; *MX warm* = one inference GPU's MX update after the first. | Model | Inference dtype | Transport | Trainer (s) | Inference (s) | MX warm (s) | Pulled / GPU | Mismatch KL | |---|---|---|---:|---:|---:|---:|---| | Qwen3-30B-A3B, TP=2 | BF16 | NCCL | 9.76 | 5.66 | - | - | 0.020-0.033 | | Qwen3-30B-A3B, TP=2 | BF16 | MX bounded | 9.38 | **2.77** | 1.67 | 40.6 GB | 0.019-0.042 | | Qwen3-30B-A3B, TP=2 | FP8 per-block (online) | MX bounded | 10.19 | **3.42** | 1.97 | 40.6 GB | 0.061-0.153 | | GLM-4.5-Air, TP=8, 2 trainer nodes | BF16 | NCCL | 15.51 | 9.05 | - | - | 0.002-0.004 | | GLM-4.5-Air, TP=8, 2 trainer nodes | BF16 | MX bounded | 13.36 | **3.88** | 2.13 | 89.5 GB | 0.002-0.003 | | DeepSeek-V4-Flash, TP=8 + EP, 4 trainer nodes | BF16 | NCCL | 26.93 | 24.93 | - | - | 0.011-0.034 | | DeepSeek-V4-Flash, TP=8 + EP, 4 trainer nodes | BF16 | MX bounded | fails | fails | - | - | - | - With #882 the bounded transfer plan is built once (59 s for Qwen3-30B, 108 s for GLM-4.5-Air on the first update) and reused after: warm updates spend 0.00 s planning, ~1.5-1.9 s on the wire and 0.05-0.08 s installing (1.4 s with FP8 re-quantization). - Bounded staging holds 8 GiB per inference GPU, so vLLM runs at its default memory setting. Full staging OOMs on Qwen3-30B at 0.9 and on GLM-4.5-Air even at 0.6. - #889 makes FP8 bounded streaming work; mismatch KL matches NCCL with FP8 inference. - MX still pulls more than each GPU's shard: 40.6 GB for a 30.6 GB shard at TP=2 and 89.5 GB for a ~26.5 GB shard at TP=8. Slices that need more than `MX_RESHARD_MAX_SEGMENTS_PER_COPY` (64) reads are pulled whole and resliced on the GPU. - The first update of a run takes 60-110 s while MX plans the transfer. - DeepSeek-V4-Flash fails in MX's layout capture: MX records the vLLM load layout by replaying `load_weights` on meta tensors, and vLLM's DeepSeek-V4 `load_weights` runs `process_weights_after_loading` (`finalize_mhc_broadcast_weights`), which copies tensor data (`NotImplementedError: Cannot copy out of meta tensor; no data!`). DeepSeek-V4-Flash runs here train BF16 with SignSGD (MXFP8 needs Blackwell) and serve BF16 (online `fp8_per_block` crashes vLLM's DeepSeek-V4 CUDA-graph capture on H200), so it has no FP8 row. - Trainer-side times were higher for NCCL too on this day (9.8 s vs 5.9 s on 2026-10-10); compare rows within one table. - The trainer log floods with `metadata_stream.cpp ... Socket Bind failed ... Address already in use`: every trainer rank on a node binds NIXL's metadata listener to the same port. Transfers still work. ### MX `8512b8c`, 2026-10-10 | Inference dtype | Transport | Trainer (s) | Inference (s) | Mismatch KL | |---|---|---:|---:|---| | BF16 | NCCL | 5.86 | 4.34 | 0.019-0.034 | | BF16 | MX, full staging (`gpu_memory_utilization` 0.6) | 4.57 | 2.32 | 0.016-0.036 | | BF16 | MX, bounded 2 x 1 GiB | 92.87 | 89.28 | - | | FP8 per-block (online) | NCCL | 8.74 | 6.99 | 0.070-0.160 | | FP8 per-block (online) | MX, full staging (0.6) | 5.65 | 3.84 | 0.070-0.144 | Qwen3-30B-A3B, 1 trainer node + 1 inference node (TP=2). Bounded staging at `8512b8c` re-planned the transfer on every update (~88 s of CPU planning per update; ~2 s on the wire) and MX refused it for FP8. GLM-4.5-Air with full staging OOMed at `gpu_memory_utilization` 0.6. Single-node CI test (`test_reverse_text_modelexpress`, Qwen3-0.6B, 1+1 GPU) passes on `8512b8c`, `f24c721` and the `0.8.0.dev20261022` nightly (server `446feec`): reward 0.14 -> 0.80, mismatch KL < 0.008, ~0.5 s per update. ## Reproduce Run from this branch after `bash scripts/install_modelexpress.sh`. Save the base config and the overlays below to files, then compose them: `uv run rl @ qwen3-30b-a3b.toml @ <overlay>.toml`. <details><summary><code>qwen3-30b-a3b.toml</code> (1 train + 1 inference node, TP=2)</summary> ```toml max_steps = 10 seq_len = 2048 [model] name = "Qwen/Qwen3-30B-A3B-Instruct-2507" [deployment] type = "multi_node" num_train_nodes = 1 num_infer_nodes = 1 [slurm] job_name = "wb-qwen30b" partition = "all" [trainer.model] attn = "flash_attention_3" [trainer.model.ac] [trainer.optim] lr = 1e-7 [orchestrator] batch_size = 64 [orchestrator.train] group_size = 8 [orchestrator.train.sampling] max_completion_tokens = 128 [[orchestrator.train.source]] name = "reverse-text" env.taskset.id = "reverse-text" env.agent.harness.id = "null" env.agent.runtime.type = "subprocess" [inference] # Node-local compile caches: concurrent DP servers race on a shared NFS cache. [inference.env_vars] VLLM_CACHE_ROOT = "/tmp/.vllm-cache" FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache" TRITON_CACHE_DIR = "/tmp/.triton-cache" [inference.vllm] max_model_len = 2048 tensor_parallel_size = 2 ``` </details> <details><summary><code>glm-4.5-air.toml</code> (2 train + 1 inference node, TP=8)</summary> ```toml max_steps = 10 seq_len = 2048 [model] name = "zai-org/GLM-4.5-Air" [deployment] type = "multi_node" num_train_nodes = 2 num_infer_nodes = 1 [slurm] job_name = "wb-glm45air" partition = "all" [trainer.model] attn = "flash_attention_3" [trainer.model.ac] [trainer.optim] lr = 1e-7 [orchestrator] batch_size = 64 [orchestrator.train] group_size = 8 [orchestrator.renderer] name = "glm-4.5" [orchestrator.train.sampling] max_completion_tokens = 128 [[orchestrator.train.source]] name = "reverse-text" env.taskset.id = "reverse-text" env.agent.harness.id = "null" env.agent.runtime.type = "subprocess" [inference] # Node-local compile caches: concurrent DP servers race on a shared NFS cache. [inference.env_vars] VLLM_CACHE_ROOT = "/tmp/.vllm-cache" FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache" TRITON_CACHE_DIR = "/tmp/.triton-cache" [inference.vllm] max_model_len = 2048 tensor_parallel_size = 8 ``` </details> <details><summary>Transport overlays</summary> ```toml # nccl.toml [weight_broadcast] type = "nccl" ``` ```toml # modelexpress-default.toml: full staging at vLLM's default gpu_memory_utilization (0.9). # Qwen3-30B OOMs on the first weight update. [weight_broadcast] type = "modelexpress" ``` ```toml # modelexpress.toml: full staging with room for the staging copy. # Qwen3-30B fits; GLM-4.5-Air still OOMs. [weight_broadcast] type = "modelexpress" [inference.vllm] gpu_memory_utilization = 0.6 ``` ```toml # modelexpress-bounded.toml: bounded staging, ~90 s per update with MX defaults. [weight_broadcast] type = "modelexpress" staging_buffer_bytes = 1073741824 staging_buffers_count = 2 ``` ```toml # modelexpress-bounded4g.toml: bounded staging as in the f24c721 table. [weight_broadcast] type = "modelexpress" staging_buffer_bytes = 4294967296 staging_buffers_count = 2 ``` ```toml # fp8.toml: online per-block FP8 inference, as in the GLM-5 recipes. Combine with a transport overlay. [inference.vllm] quantization = "fp8_per_block" gpu_memory_utilization = 0.6 ``` </details> <details><summary><code>local-env.toml</code> (cluster workaround, 2026-10-21)</summary> The shared `/home` filesystem was slow enough that env-server harness processes hung importing from `~/.cache/uv`. This overlay keeps them on node-local disk: ```toml [orchestrator.env_vars] UV_CACHE_DIR = "/tmp/uv-cache-envs" PYTHONDONTWRITEBYTECODE = "1" UV_NO_SYNC = "1" ``` </details> ## Before merging - [ ] Not checked, out of scope for this PR: `weight_broadcast.type = "nixl"` against the bumped MX client (0.3.0 -> 0.8.0.dev20261022) and server. - [ ] GPU CI green on GitHub, including the new `reverse_text_modelexpress` job (builds the MX server from source, ~4 min uncached). - [ ] Agreement with #3890 on landing this as one PR. - [ ] Ideally, a stable MX release to pin instead of a nightly. ## Compatibility | Area | Status | |---|---| | Qwen3 MoE, GLM-4.5 MoE (BF16, online FP8) | works | | Trainer across 2 nodes | works (GLM-4.5-Air) | | DeepSeek-V4 | fails in MX layout capture (needs an MX fix) | | GLM-5 (DSA) | untested | | Expert-parallel inference | untested (only DeepSeek-V4 used it) | | P/D disaggregated inference | not supported | | LoRA, speculative decoding, SFT online evals | rejected by config validation | | Pipeline parallelism, resume, MXFP8 inference | untested | 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes the trainer–inference weight sync path and multi-node launch, but MX is opt-in, guarded by config validation, and covered by new integration tests. > > **Overview** > Adds **`modelexpress`** as a first-class `[weight_broadcast]` transport so FSDP trainers can push full weight updates to vLLM over ModelExpress (RDMA/NIXL) without an NCCL collective with inference. > > **Config and validation:** New `ModelExpressWeightBroadcastConfig` (staging mode, bounded receiver buffers, gRPC port). RL/SFT/trainer validators treat MX like other in-memory transports for `inference_world_size`, and reject incompatible setups (LoRA, Dynamo discovery, speculative decoding, SFT online evals). > > **Runtime wiring:** Trainer `ModelExpressWeightSender` and orchestrator `ModelExpressWeightReceiver` use the public `modelexpress_rl` clients; vLLM gets a `ModelExpressWeightUpdateWorker`, `/update_weights_from_modelexpress`, and optional staging args on `/init_broadcaster`. The orchestrator admin plane initializes workers and installs versioned weights under a lock, leaving inference paused on failure. > > **Launch:** `uv run rl` and SLURM templates start a run-scoped ModelExpress server + Redis when using `modelexpress` or `nixl` (`uses_modelexpress_server`); the installer pins server build **`446feec`** and bootstraps Rust/`protoc` when missing. The GPU extra bumps the MX client to **`0.8.0.dev20261022`**. > > **Tests and docs:** GPU CI runs `reverse_text_modelexpress` (builds the server in-job); unit tests guard the public client boundary. ModelExpress setup/limitations live in **`docs/model-express.md`**. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 62072b9c947b2f02228fee25e9b2dfc528ef6b5e. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Signed-off-by: Zheng Luo <zheluo@nvidia.com> Co-authored-by: Zheng Luo <zheluo@nvidia.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
91dce1f3c1 |
fix(ckpt): restore optimizer param groups when resuming with optimizer state offload (#4332)
Resuming a run with the default `model.offload = "optimizer"` did not restore the optimizer's param groups. - With CPU state offload, `AppState.load_state_dict` relies on DCP writing the loaded tensors in place, so it never calls `optimizer.load_state_dict`. - The param groups' values are not tensors, so they kept the values of the zero-grad step DCP runs to build its template. - dion's Muon keeps its step count in the param groups. After a resume it restarted at 1, so the AdamW part (embeddings, norms, biases) redid its bias correction as if training had just started. - torch AdamW is not affected, because its step lives in the per-parameter state. The fix copies the loaded param-group values back after the in-place load. Measured on Qwen3-0.6B reverse-text SFT, FSDP 8, Muon, checkpoint at step 10, resumed run vs uninterrupted run: - Before the fix: the losses split at step 12, and the resumed run drifts to about 2% lower loss by step 20. The same drift shows on main and with every Muon variant. - After the fix: bitwise equal on steps 11-20 (loss and grad norm), with `offload = "optimizer"` and with `offload = "none"`. Added a GPU regression test to `tests/unit/train/test_state_offload.py`. It runs dion's Muon behind `CPUOffloadOptimizer`, saves with DCP, loads into a fresh model, checks that the param groups' step is restored, and checks that 2 more steps give bitwise-equal weights. The test fails on main (`[1, 1] != [3, 3]`) and passes with the fix. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Small, targeted change to the CPU-offload checkpoint resume path with a regression test; no auth or data-path impact. > > **Overview** > Resuming with **`model.offload = "optimizer"`** restored tensor optimizer state in place via DCP but left **param group metadata** at the values from DCP’s template zero-grad step. That broke **dion Muon**, which stores its **step count in param groups**, so AdamW bias correction restarted after resume and training diverged from an uninterrupted run. > > **`AppState.load_state_dict`** now merges loaded **`param_groups`** entries (everything except **`params`**) onto each checkpoint optimizer after the in-place tensor load and packed-state write-back. > > A GPU regression test saves/loads through DCP with **`CPUOffloadOptimizer`** + Muon, asserts **`step`** is **`[3, 3]`** after resume, and checks two more steps match the uninterrupted model bitwise. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 09c622b11f7f671af25526dfab946da3dff3b556. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> |
||
|
|
34276fcc92 |
perf(deepseek-v4): balance indexer scoring across CP ranks (#4330)
This PR passes the CP group from the DeepSeek V4 indexer to `fp8_indexer`, opting DeepSeek V4 into the CP balancing that #4278 added for GLM-DSA. Each query scores every earlier compressed entry, so with contiguous CP sharding the last CP rank does the most indexer work and the other ranks wait for it at the next collective. Rank r pairs with rank CP-1-r. The busier rank of each pair sends some of its last query rows to its partner, which scores them and returns only their top-k indices, so the selected indices are unchanged. Indexer time per step on each CP rank, with CP = 8 and one long document per row: ``` before after rank 0 ### 24 ms ########## 78 ms rank 1 ##### 41 ms ######### 74 ms rank 2 ####### 55 ms ########## 76 ms rank 3 ######### 69 ms ########## 76 ms rank 4 ########### 84 ms ########## 76 ms rank 5 ############ 97 ms ########## 76 ms rank 6 ############## 110 ms ########## 78 ms rank 7 ################ 124 ms ######### 71 ms ``` On one 8x H200 node (DeepSeek V4 Flash cut to 6 layers, cp 8, ep 8, 262k-token rows of one long document each), forward plus backward time per step dropped 0.8 to 1.0% against same-node baselines, with entropy unchanged within run-to-run noise. That is about 10 ms per CSA layer per micro batch, or about 1.3% of a step for the full 43-layer model. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
cd58e4d3e3 |
refactor(configs): mark live fields with Annotated[T, Live()] (#4322)
Follow-up to #4318: mark live fields in the annotation, not in `Field`. Behaviour is unchanged. Config values and the live set stay the same. ```python - batch_size: int = Field(128, ge=1, json_schema_extra=LIVE) + batch_size: Annotated[int, Live()] = Field(128, ge=1) - sampling: TrainSamplingConfig = Field(TrainSamplingConfig(), json_schema_extra=FROZEN) + sampling: Annotated[TrainSamplingConfig, Frozen()] = TrainSamplingConfig() - length_penalty: LengthPenaltyConfig | None = Field(None, json_schema_extra=LIVE) + length_penalty: Annotated[LengthPenaltyConfig | None, Live()] = None ``` Same change for `max_staleness`, `concurrency.*_inflight`, `train.source[*].ratio`, `train.sampling.*` and `eval.source[*].interval`. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Refactor-only with parity tests; live-update rules and field sets are intended to stay the same. > > **Overview** > Live vs frozen config semantics are unchanged; only **how** fields are marked moved off `Field(json_schema_extra=…)` to **`Annotated[T, Live()]`** / **`Annotated[T, Frozen()]`**. > > `prime_rl.configs.diff` now exposes **`Live`** and **`Frozen`** as frozen dataclasses and resolves markers from **`FieldInfo.metadata`** instead of JSON schema extras. Orchestrator, algorithm, and related configs use the new annotations for the same live knobs (`batch_size`, `max_staleness`, concurrency, sampling, source ratios, eval intervals, GRPO `length_penalty`, etc.). Training docs describe **`Annotated[T, Live()]`**, and unit tests cover marker value equality plus existing diff/resume behavior. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 098fb0002fa75c6c91d57a62d27976038a52818c. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> |
||
|
|
e69efb15d2 |
feat(trainer): add a fixed sample length to fake RL data (#4309)
This PR adds `data.fake.doc_len`, which packs generated fake RL samples of one fixed length into each micro batch, cutting the last sample to fill the row. Fake data could not model long agentic rollouts packed into rows longer than one rollout (e.g. two 262k rollouts in a 524k row). ``` one micro batch row of seq_len tokens default: one document, ids 0 to 99 |---------------------------------------------------------------| --data.fake.generate-samples: random lengths up to seq_len / 8 |-------|---|----------|-----|--|--------|-----|----|-------|---| --data.fake.generate-samples --data.fake.doc-len N: every sample N tokens, last one cut |------------------|------------------|------------------|------| ``` - `doc_len` requires `data.fake.generate_samples`, whose random ids span 0 to 119999; the default ids 0 to 99 send a hash-routed MoE layer's tokens to only a few experts. - We ran `--data.fake.generate-samples --data.fake.doc-len 262144 --model.seq-len 524288` on 8 GPUs (6-layer and full DeepSeek-V4-Flash-architecture models) without issues. - A unit test in b4a5eaaa6 checked the packing (`[300, 300, 300, 100]` for a 1000-token row) and the validator; it passed and was removed in the next commit. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
2b3536ae02 |
feat(trainer): report peak GPU memory from all sources, max over ranks (#4320)
This PR changes `perf/peak_memory` and the console `Peak Mem.` in the RL and SFT trainers to report peak GPU memory from all sources, max over ranks, and adds `perf/non_torch_memory` for the part held outside PyTorch's caching allocator. Before, the metric was `torch.cuda.max_memory_reserved()` on rank 0. It missed Mega MoE's symmetric buffers, NCCL buffers, and the CUDA context, and it hid ranks that ran out of memory before rank 0 did. - The peak is the caching allocator's peak plus the current out-of-allocator memory (`mem_get_info` minus `memory_reserved`), assuming the latter is static over the step. - Expect `perf/peak_memory` to step up against older runs; in the run below it rose by about 8 GiB. - The one extra all-reduce per step sits next to the existing `global_counts` all-reduce, which every rank reaches. One-node check on 8 B300s: the RL trainer alone on fake data, with a DeepSeek-V4-Flash-architecture model cut to 2 layers, sequence length 262144, EP 8, CP 8, and PyTorch all-to-all MoE dispatch. This run used neither DeepEP nor Mega MoE, so `non_torch_memory` here is the CUDA context and NCCL buffers. Values are max over GPUs. | step | old `peak_memory` | new `peak_memory` | `non_torch_memory` | `nvidia-smi` max | |---|---|---|---|---| | 2 | 66.25 GiB | 74.03 GiB | 7.04 GiB | 74.03 GiB | 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
2170292047 |
fix(mega-moe): size the buffer for a rank's CP share of the micro batch (#4308)
## Problem Context parallelism splits every micro batch evenly over the `cp` ranks. Each rank's MoE layers therefore see `seq_len / cp` tokens: in RL, and in SFT too, since SFT requires `micro_batch_size = 1` under CP. `model.moe.dispatch.max_tokens_per_rank` defaulted to the whole micro batch and rejected anything smaller. With `seq_len = 262144` and `cp = 8`, the Mega MoE symmetric buffer was sized for 262,144 tokens per rank, 8x more than any rank holds. That size is aligned up to 263,040 tokens, which exceeds DeepGEMM's shared L2 pool, so the trainer fails at init (`num_shared_l2_pool_blocks <= kNumMaxSharedL2Blocks`). There was no way to set a smaller value. ## Change - `mega_moe_max_tokens_per_rank` now takes `cp`. It defaults to `ceil(micro_batch_tokens / cp)` and rejects values below that. - The RL and SFT validators pass `model.cp`. - Docstrings, the runtime comment and error message, and `docs/scaling.md` describe the new default. - At `cp = 1` the default doesn't change. ## Testing - Two new tests in `tests/unit/test_configs.py`: RL and SFT default to `seq_len` at `cp = 1` and to `seq_len / 8` at `cp = 8`, and a value below the CP share is rejected. - `tests/unit/test_configs.py` + `tests/unit/train/models/test_moe.py`: 285 passed, 2 failed. The 2 failures are `test_load_configs` for the VLM example configs (`examples/extra/vlm/rl-qwen3.5.toml`, `rl-qwen3.8.toml`), and they fail the same way on `main`. - GPU check: this change applied as a local patch on an earlier commit (this file hasn't changed since). - Setup: 8 nodes x 8 B300, a 43-layer DeepSeek-V4-Flash-sized model, `seq_len = 262144`, `cp = 8`, MXFP8 Mega MoE. - Result: `max_tokens_per_rank` resolved to 32,768 and 10 training steps ran with no buffer overflow. - Without the change, init fails as described above. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes MoE symmetric-buffer sizing at startup for CP and Mega MoE; wrong sizing would deadlock or overflow at runtime, but behavior at `cp=1` is unchanged and tests cover the new defaults. > > **Overview** > Fixes Mega MoE init failures under **context parallelism** (`model.cp > 1`), where `max_tokens_per_rank` defaulted to the **full** micro batch even though each rank only processes `ceil(micro_batch_tokens / cp)` tokens—often blowing DeepGEMM's shared L2 pool at large `seq_len`. > > **Config resolution** now divides by `cp`: `mega_moe_max_tokens_per_rank(..., cp)` defaults to that per-rank token count and rejects explicit values below it. **RL** also uses padded micro-batch size via new `rl_micro_batch_multiple` (CP, or `cp * 32` with MXFP8). **SFT** passes `model.cp` into the same helper. **RL orchestrator padding** reuses `rl_micro_batch_multiple` instead of duplicating MXFP8/CP logic. > > Docs (`scaling.md`), field docstrings, and runtime comments/errors are aligned with the CP-aware default. Unit tests cover RL/SFT defaults at `cp=1` vs `cp=8`, MXFP8 padding, and validation when the buffer is too small. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 2e73a1b33c5bac85eb217b9eaa392aa572fa11c7. 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 Opus 5.5 <noreply@anthropic.com> Co-authored-by: Neo <mario.sieg.64@gmail.com> |
||
|
|
1ecb2952a2 |
fix(trainer): skip NUMA binding when the GPU has no sysfs numa_node (#4202)
Fixes #4201 `bind_process_to_gpu_numa_node` crashed with `FileNotFoundError` when the GPU's PCI entry is missing from `/sys/bus/pci/devices/` (e.g. WSL2), which made `model.offload = "full"` unusable there. A missing `numa_node` file is now treated like `-1`, so it falls into the existing warn-and-skip path. ## Test plan - `uv run sft @ configs/debug/fake/sft.toml --model.offload full` on WSL2 (RTX 4070 Laptop, 8 GB): crashed before, now logs `GPU 0 (0000:01:00.0) reports no NUMA node; skipping NUMA binding` and completes all 5 steps (peak 6.0 GiB). - `uv run pytest tests/unit -m "not gpu"`: 910 passed, 1 skipped. - `pre-commit run`: ruff check and format pass. |