Compare commits

...
Author SHA1 Message Date
Konstantin DunasandGitHub 88faa6dc22 feat(sft): warn when renderer is not prefix stable (#3953)
Warn when SFT constructs a renderer that does not guarantee prefix
stability. The warning explains that each conversation is rendered once
into one training sample, that N assistant turns are not expanded into N
samples, and that earlier reasoning may be omitted by the template.
Cached renderers warn only on construction; stable renderers stay quiet.
Custom renderers without the capability are conservatively treated as
unknown.

Pin `deps/renderers` to merged main revision `41f9290`, which includes
https://github.com/PrimeIntellect-ai/renderers/pull/184. It provides the
resolved capability and the manual, opt-in witness audit. Sample
construction is unchanged.

Validation: all **73 SFT dataset tests passed**, including
stable/unstable renderer selection and cache-warning behavior. Prime-rl
unit-test CI passed on the preceding revision; this update changes only
the renderer gitlink to the merged revision. Dependency requirements are
unchanged apart from renderer Python >=3.11, compatible with prime-rl
Python 3.12. The manually invoked renderer audit passes **59 tests** and
is excluded from normal CI discovery.
2026-10-09 11:53:24 +02:00
Florian BrandandGitHub 083b8fe9ec ci: reduce GPU usage and parallelize test setup (#3944)
Reduce CI time and GPU usage by selecting the relevant test suites for
each PR, moving hosted eval to CPU, and running independent setup steps
in parallel.

- Select GPU unit tests, SFT, RL, and hosted eval from changed paths
before allocating runners. Shared runtime and dependency changes retain
broad coverage; pushes to `main` and manual runs execute the full suite.
- Keep RL/SFT coverage for checkpoint converters, dashboard code, and
the shared dashboard smoke helper.
- Run `gsm8k_eval` on `ubuntu-latest` because it uses hosted inference.
- Run public submodule initialization and `uv` setup concurrently, then
wait for both before installing dependencies. Keep dependency caching
keyed on `uv.lock` and the five-job limit on GPU integration tests.
- Cancel superseded CPU and style runs on the same PR.
- Give the GPU workflow read-only contents access and the test selector
PR read access.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Path-based GPU job gating can skip integration coverage on PRs if
filters miss a dependency; full suite still runs on main and manual
dispatch.
> 
> **Overview**
> **GPU CI now picks which jobs to run from the PR diff**, instead of
always running the full GPU unit + integration matrix on every non-draft
PR. A new **Select tests** job uses path filters for unit, SFT, RL, and
eval; pushes to `main` and `workflow_dispatch` still run everything.
RL/SFT integration scenarios are built dynamically (still capped at
`max-parallel: 5` on `prime-rl-2xh200`).
> 
> **`gsm8k_eval` is split out** into a dedicated job on `ubuntu-latest`
(hosted inference), so it no longer consumes GPU runners. Integration
pytest invocations use `tests/integration/test_${{ matrix.test }}.py`
from the dynamic matrix rather than per-row `pytest_args`.
> 
> **Setup and queueing tweaks:** submodule init and `setup-uv` run in
parallel in CPU/GPU jobs; CPU and style workflows cancel in-progress
runs per PR; GPU workflow gets `workflow_dispatch`, read-only
`contents`, and PR-scoped concurrency cancel. `docs/development.md`
documents the new triggers and runner split.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
20da35f30de85b2b18cf82e29598846a1228ca12. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 17:17:55 -07:00
853208336e feat(sft): pad to a multiple of cp and remove fp8 indexer dynamism (#3948)
SFT now pads packed rows only to a multiple of cp, as RL does, instead
of to `seq_len`. The fp8 indexer drops its autotuning, which
re-benchmarked configs on every new row length and made unpadded rows
slower than padded ones on DeepSeek-V4 (#3726).

- The indexer pads keys to a multiple of 16 and runs one fixed config,
within 1.05x of the best.
- Every rank, including RL on DeepSeek-V4 and GLM-5, runs that config
with bitwise-identical top-k.
- SFT and RL throughput count trained tokens, not `seq_len` × rows or
the first row × count.
- The SFT `seq_len % (2 * cp)` check is gone: CP only needs `seq_len %
cp`, which configs enforce.

Same samples per arm, time summed over steps 5 to 20, one H200 node:

| Workload | Padding on main | main | This PR | Speedup |
|---|---|---|---|---|
| DeepSeek-V4-Flash 6L, scaleswe, 256K rows, cp 8 | 19.8% | 61.2 s |
38.2 s | 1.60x |
| GLM-4.5-Air 8L, math, 131K rows, dp 4 cp 2 | 7.3% | 223.8 s | 200.1 s
| 1.12x |
| GLM-4.5-Air 8L, scaleswe, 131K rows, dp 4 cp 2 | 19.7% | 701.0 s |
623.0 s | 1.13x |

On DeepSeek-V4, the 1.60x exceeds the 1.25x that removing 19.8% of
tokens predicts because two effects multiply: main's token-0 pads crowd
onto the same experts, and the padding itself costs compute. The
DeepSeek-V4 ablation section below separates the two.

On GLM with scaleswe, removing 19.7% of the tokens would predict about
1.25x, but it measured 1.13x. Its 4 data-parallel ranks now get rows of
different lengths, and each step likely waits for the rank with the
longest rows.

Loss matches main to within 1e-3 per step. This overlaps
https://github.com/PrimeIntellect-ai/prime-rl/pull/3932 in
`CatDataset._finalize_pack`. Harness:
[`benchmarks/scripts/sft_pad_to_cp/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/0ed0e78b33e8533d7fd1e0d603759dc2ab50e5dd/benchmarks/scripts/sft_pad_to_cp)
(removed before merge).

## DeepSeek-V4 ablation

Each row changes one thing on the DeepSeek-V4 workload above, to
separate the cost of the padding length, of token-0 pads crowding onto
the same experts, and of indexer re-tuning:

| Arm | Time | Speedup vs main |
|---|---|---|
| main: pads every row to `seq_len` with token 0 | 61.2 s | 1.00x |
| main, but pads with the row's own tokens (#3932) | 49.6 s | 1.23x |
| pads only to a multiple of cp, indexer still autotuned | 73.6 s |
0.83x |
| pads only to a multiple of cp, fixed-config indexer (this PR) | 38.2 s
| **1.60x** |

## Alternatives considered

- Bucketing the autotune key on `next_power_of_2(S_q)` reached 1.47x on
DeepSeek-V4. Each bucket kept its first row's config (up to 1.44x slower
later), short rows paid extra tunes, and each rank still tuned on its
own rows, so ranks could run different kernels.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 19:13:22 -04:00
Konstantin DunasandGitHub 31281d88f9 feat(sft): pass per-message loss selection to renderers (#3950)
SFT samples can contain prefilled assistant turns that must remain in
context without becoming training targets. Read an optional
`message_loss_mask` dataset column and pass it directly to
`renderers.build_training_sample`; for a user/assistant/user/assistant
conversation, `[0, 0, 0, 1]` trains only the final assistant turn.

The renderer owns token attribution and mask validation, including GLM's
assistant-generated closing markers. prime-rl performs no owner walking
or template-specific mask reconstruction. Selection only removes
existing loss targets and preserves input/target token IDs. Missing or
null masks preserve normal supervision; fully masked samples follow the
existing skip behavior.

`data.columns.message_loss_mask` supports renamed columns. For
prompt/completion rows, the mask covers their concatenated message list.
This API reads a separate column; datasets with inline
`messages[].trainable_mask` need conversion before use.

Pins `deps/renderers` to upstream main commit
`e3ace557545274385abb30435975c134c7c2429d`, which merges
https://github.com/PrimeIntellect-ai/renderers/pull/181. The renderer
dependency is now merged.

Validation:
- Signed pin update `838828713` points to the merged renderer commit.
Its Git tree is identical to the previously tested renderer head; no
source changes accompany the pin update.
- The following tests and checks passed on signed implementation commit
`7e0800051`:
- 73 SFT dataset tests passed, including real GLM-5 and Qwen3
tokenizers, both dataset layouts, custom column names,
missing/null/all-enabled masks, excluded initial/final turns, fully
masked samples, and invalid values/lengths.
- Ruff 0.13.0 lint and formatting checks passed for the changed Python
files; `git diff --check` passed.
- CPU tests ran in an isolated Python 3.12 environment with Transformers
5.6.2 and PyTorch 2.14.1. No GPU training run performed.
- Commit signature verified locally.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes which tokens receive loss during SFT when datasets supply
masks; incorrect masks could silently train the wrong turns, though
behavior is opt-in and heavily tested against real renderers.
> 
> **Overview**
> Adds **optional per-message SFT loss selection** via a dataset
`message_loss_mask` column (0/1 or booleans, one entry per resolved
message—including prompt+completion rows). The trainer forwards the
column to `build_training_sample` so renderers drop supervision on
excluded turns **without changing token IDs** (e.g. `[0, 0, 0, 1]` keeps
context but trains only the last assistant reply). Missing/null masks
behave as today; all-zero masks still skip the sample.
> 
> **Config and docs:** `SFTColumnsConfig.message_loss_mask` defaults to
`"message_loss_mask"` and can be remapped (e.g. `"selection"`); dataset
init errors if a remap points at a missing column. `docs/training.md`
documents the format and semantics.
> 
> **Tests:** Coverage for GLM-5 and Qwen3, both dataset layouts, custom
column names, partial masks, fully masked rows, and invalid mask
values/lengths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
838828713529afa49a57cf441071f946ec195cdf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-09 00:36:22 +02:00
samsjaandGitHub bc250759bf fix(ci): uv cache on h200 runners, drop phantom 4xa6000 job, cap fan-out (#3909)
## Why

Since **Sep 2** the `4xa6000` runner has been offline. Since then,
`benchmark_regression` has queued on a dead label on **every single GPU
Tests run**, hit GitHub's 24h self-hosted queue timeout, and failed the
workflow. There has not been one green GPU Tests run in over a month, so
the per-PR GPU check is permanently red and real regressions hide in the
noise. Measured over Sep 29-Oct 6: all 28 completed runs failed at
exactly 1440 +/- 1 min, and 20+ phantom `benchmark_regression` jobs were
sitting in the queue at any time.

## What changes

1. **uv cache on the GPU jobs** (`enable-cache: true`, keyed on
`uv.lock`, mirroring `cpu_tests.yaml`) — each h200 pod currently
re-resolves and re-downloads the full dependency set from PyPI on every
job.
2. **`benchmark_regression` removed from the PR matrix.** It cannot
simply move to `prime-rl-2xh200`: the test unconditionally runs a 1-GPU
**and** a 4-GPU benchmark (a 2-GPU pod cannot host the latter), and it
asserts against A6000-captured baselines with a 15% tolerance (H200
results would blow through it). It belongs on benchmark hardware
(`benchmarks.yaml`) or behind a 4-GPU scale set when one exists — happy
to re-add once either exists.
3. **`max-parallel: 5` on the integration matrix** — a concrete per-PR
ceiling:
- 9 integration jobs + unit-tests = **6 h200 pods peak per PR**, 2 waves
- at current job durations (~10-15 min each) a PR finishes in ~25-35 min
- with 2-3 PRs in flight: <= ~18 pods steady-state; the ARC scale set
`maxRunners` (suggest 16-20) is the complementary global cap
4. `docs/development.md` CI table updated to match (also adds
`gsm8k_eval`, which was missing, and the current runner).

## Result

GPU Tests runs **only** on the `prime-rl-2xh200` scale set, and every PR
gets a real green or red within ~30-60 min instead of a guaranteed 24h
failure.

## Not in this PR (follow-ups)

- Bake git/uv into the CI image to kill the per-job `apt-get install
git`
- PVC-backed `~/.cache/uv` mount to avoid per-pod cache archive
downloads
- Nightly Tests still target a `research-cluster` runner that does not
exist — needs the same treatment or a cron disable

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> CI workflow and documentation only; no runtime or auth changes.
Benchmark regression no longer runs on every PR until re-homed to
suitable hardware.
> 
> **Overview**
> **GPU Tests** is adjusted so PR runs can finish on live hardware
instead of timing out on a dead runner label.
> 
> Both GPU jobs now enable **uv dependency caching** keyed on `uv.lock`
(same pattern as `cpu_tests.yaml`), cutting repeated PyPI
resolves/downloads on each H200 pod. The integration matrix **drops
`benchmark_regression`** (it targeted offline `4xa6000` hardware and
cannot run meaningfully on 2×H200), and adds **`max-parallel: 5`** so at
most five integration jobs run at once per PR. **`docs/development.md`**
updates the CI table to list the current integration scenarios
(`gsm8k_eval` included), `max-parallel`, and **`prime-rl-2xh200`** as
the runner.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8207cc05d9a731a4c5d7c561354284f1a79792d4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 15:18:58 -07:00
1983d8dfed chore: bump verifiers to main (#3934)
## Summary

- Bump `deps/verifiers` from `1fa2bbc42` to main `da75527ca`. This pulls
in the Harbor adapter changes from PrimeIntellect-ai/verifiers#2808:
  - Honor reward-file precedence and select named rewards explicitly.
  - Resolve separate verifier definitions by Harbor image precedence.
  - Align the adapter with Harbor 0.24.0 and reject multi-step tasks.
- Move the `harbor` upload cutoff in `[tool.uv.exclude-newer-package]`
from 2026-08-11 to 2026-10-08, which matches `deps/verifiers`. verifiers
now pins `harbor==0.24.0`, which the old cutoff excluded.
- Relock: `harbor` 0.21.0 → 0.24.0, and `semver` 3.1.0 is new.

`deps/prime-envs` is already at its main head (`89dcc7ffc`). The current
verifiers pin already has the network notice
(PrimeIntellect-ai/verifiers#2769), so this bump supersedes #3734.

## Verification

- `uv sync --all-extras --all-packages --locked` succeeds.
- `uv run pytest -m "not gpu" tests/unit`: 663 passed.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Lockfile and uv policy changes only; risk is mainly behavioral shifts
from Harbor 0.24.0 and updated verifiers Harbor adapter usage in
eval/training paths.
> 
> **Overview**
> Updates dependency resolution so **`harbor` 0.24.0** (via the
`verifiers[harbor]` pin) can install under uv’s rolling
**exclude-newer** policy by moving the bounded **`harbor` cutoff** from
`2026-08-11` to **`2026-10-08`** in `pyproject.toml`, mirrored in
`uv.lock`.
> 
> The lockfile refresh bumps **`harbor` 0.21.0 → 0.24.0**, records new
transitive deps **`jsonschema`** and **`semver`**, and aligns the
verifiers harbor extra specifier to **`==0.24.0`**. This pairs with the
verifiers main bump described in the PR (Harbor adapter alignment and
reward/verifier precedence behavior), even though those code changes
live outside this diff.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
69e62c1fc116896ce99c79dbfc454959c748cb47. 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>
2026-10-08 15:18:33 -07:00
26681fc6c7 fix(models): pass contiguous router-replay experts to compiled layers (#3947)
On torch 2.13.0 with compile and router replay, some MoE layers silently
replay layer 0's routing instead of their own from the second training
step on. This PR calls `.contiguous()` on each layer's routed-experts
slice, which removes the bug.

Each decoder layer `l` receives `routed_experts[:, :, l]`, a view into
one shared int32 tensor with axes (batch, sequence, layer, expert slot).
When `top_k` is not a multiple of 4, that view starts at a byte offset
that is not 16-byte aligned for some layers (odd layers on DeepSeek V4,
`top_k = 6`).

Inductor copies a misaligned input into a fresh aligned buffer, which
starts at offset 0. Once automatic dynamic shapes recompile the layer,
AOTAutograd mistakenly applies that offset 0 to the original shared
tensor when it rebuilds the layer's routed-experts output. Offset 0 of
the shared tensor holds layer 0's experts. A contiguous slice is its own
aligned tensor, so Inductor never makes the copy.

- Applied to the eight models that passed the raw view. `glm4_moe`
already called `.contiguous()`.
- Fixed upstream in pytorch/pytorch#191002 (torch 2.14.0 and 2.14.1, no
2.13.x release). The copy is cheap, so it can stay after an upgrade.
- Models with `top_k = 8` (Qwen3-30B-A3B, Trinity-Mini, GLM-4.5-Air)
were unaffected.

DeepSeek V4 Flash RL probe (compile on, router replay on, lr 0),
mismatch KL mean, lower is better:

| trainer | step 1 | steps 2-10 |
|---|---|---|
| compiled, strided slice (main) | 0.0008 | 0.022-0.11 |
| compiled, contiguous slice (this PR) | 0.0009 | 0.0007-0.0025 |

With compile off, the same probe spans 0.0008-0.0032 over steps 1-10.

## Verification

A standalone torch reproducer was added in
66641b0b0b31da76082edaadd70b4f601b13a53a and removed again at the end of
this branch, so main never carries it. Run it on one CUDA device from
that commit with `TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 uv run python
tools/repro_misaligned_replay_alias.py`. In earlier runs it printed `BUG
REPRODUCED` on torch 2.13.0 and was clean on the 2.14.0.dev20260809 and
2.16.0.dev20261008 nightlies.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 17:03:55 -04:00
Florian BrandandGitHub 6b0906c900 fix(eval): preserve sibling trace verdicts when an episode fails (#3824) 2026-10-08 12:12:16 -07:00
JannikStandGitHub 5e963f027a fix(monitors): send online-eval metrics to the parent training run (#3941)
Hosted runs with online evals score real rewards but the run dashboard
shows no `eval` metric group (ENG-6573).

The dashboard's `eval` group is built from the run's own metric keys
(`eval/{env}/...`). The orchestrator's in-process evals reach it through
the train monitor, but when evals run in a process of their own (SFT
online evals) the metrics are dropped: `PrimeEvalMonitor.log_metrics`
was a deliberate no-op.

- `PrimeEvalMonitor` now attaches to the parent training run via
`$RUN_ID` and forwards each epoch's `eval/...` metrics there.
- The eval process never reports the parent run's status: the SDK's
atexit crash hook is unregistered and `finalize()` only drains the
queue. Without that, an eval process exiting while the trainer is still
going would mark the whole run failed.
- No parent attached without `$RUN_ID`, so a standalone `prime eval` is
unchanged.

Note the ticket proposes exposing `environmentshub/resolve` on the
platform's internal API instead. That's a separate gap: it silences the
`EnvironmentResolutionError` warning and would create per-epoch
Evaluation records, but it does not produce the `eval` metric group, and
it needs four more `/evaluations` routes that the internal surface also
lacks.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how eval processes interact with the parent platform run
(metrics + SDK lifecycle hooks); mistakes could misreport run status or
drop metrics, but behavior is gated on $RUN_ID and explicitly avoids
finishing the parent.
> 
> **Overview**
> Fixes hosted runs where **SFT online evals** compute rewards but the
run dashboard never shows the **`eval`** metric group (keys like
`eval/{env}/...`).
> 
> **`PrimeEvalMonitor`** now attaches a metrics-only handle to the
parent training run when **`$RUN_ID`** is set, and **`log_metrics`**
forwards sanitized epoch aggregates there instead of being a no-op.
Standalone **`prime eval`** (no **`$RUN_ID`**) is unchanged.
> 
> Lifecycle is guarded so the eval subprocess cannot poison the parent
run: the SDK **atexit** hook on the attached parent is **unregistered**,
and **`finalize()`** only **`flush`**es the upload queue—never finishes
or reports status on the trainer’s run.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
892035628173119b14a591b2975a5b6176f4c357. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 19:44:51 +02:00
72834b3b52 feat(trainer): prepare RL micro batches on a background thread pool (#3917)
This is an alternative to #3907. The RL trainer decoded and preprocessed
each micro batch's images on the main thread right before its forward
pass, leaving the GPU idle. `WorkerPool`, a small ordered thread pool
configured by `data.num_workers` like torch's DataLoader, now prepares
micro batches ahead of the loop through a single `prepare_micro_batch`
hook.

- `num_workers` defaults to 0, which prepares on the main thread as
before, and one thread gives the full speedup. Here it counts threads,
unlike SFT's DataLoader processes.
- An earlier version used forked worker processes. They pickle data
through `/dev/shm`, risk copy-on-write memory, and were 0.6 s/step
slower than a thread.
- Pinned memory and `non_blocking` copies are left to a follow-up that
first removes the per-micro-step CUDA syncs.

Qwen3.5-9B trainer-only on 4 H200s, mock micro batches of 1024 px JPEGs
(about 1 s of CPU decoding each), median s/step, lower is better
(benchmark code added in
[`331fc83fe`](https://github.com/PrimeIntellect-ai/prime-rl/commit/331fc83fed9ff8b6fb435df5207a07e37b08c0e5)
and removed in the next commit):

| Arm | main thread | prepared ahead | time saved |
|---|---|---|---|
| this PR, 1 thread | 24.98 | 18.86 | 24.5% |
| this PR, 1 thread, optimizer CPU offload | 26.56 | 20.24 | 23.8% |
| earlier process version, 2 workers | 24.79 | 19.02 | 23.3% |
| #3907 (thread with pinned memory) | 24.98 | 18.63 | 25.4% |

Every arm matches the main-thread baseline bit for bit in loss and grad
norm. Host memory stays flat over 30 steps, 0.3 GiB above the baseline
for the prefetched images.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 12:15:19 -04:00
faresobeidandGitHub 0bcb868e91 fix(configs): size the single-node NCCL transfer group after the DP fill (#3841)
## Summary
Two bugs in how `rl` sets `weight_broadcast.inference_world_size` on
main:

1. **World size computed before the DP fill.**
`auto_setup_weight_broadcast` set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
before `auto_setup_deployment` fills the single-node inference GPUs with
DP ranks. With `num_infer_gpus = 4` and `data_parallel_size` unset, the
NCCL group was sized for 1 inference worker while vLLM started 4, so the
first weight update cannot form the group.
2. **A single-node SLURM job cannot re-parse its `rl.json`** (since
#3788). The resolved `rl.json` always contains
`weight_broadcast.inference_world_size` (default 1), and #3788's guard
rejects any config that sets it. So `rl @ rl.json` in the single-node
sbatch fails validation for every NCCL config.

## Fix
- Single-node: set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
right after the DP fill in `auto_setup_deployment` (non-filesystem
only). Multi-node already sets it there.
- `auto_setup_weight_broadcast` copies `weight_broadcast` to the trainer
and orchestrator without touching the world size, and the guard is
removed. The top-level value is now only passed through: `rl` overwrites
it whenever it knows the inference size.

This also fixes what #3924 fixes.

## Behavior change
Yes (bug fixes).
- Resolved configs for every TOML in `configs/`, `examples/`, `k8s/`
that parses as `RLConfig` (41 of 78) are identical before and after,
except `trainer`/`orchestrator.weight_broadcast.inference_world_size`
goes from 1 to 4 in `examples/basic/hendrycks-sanity/rl.toml` and
`configs/ci/nightly/multimodal_color_codeword.toml` (4 infer GPUs, DP
unset).
- Re-parsing the dumped config (as the single-node sbatch does) fails on
main for all 18 single-node NCCL configs and passes for all of them
here.
- With `inference = None` and NCCL against external servers, a user-set
`weight_broadcast.inference_world_size` is now passed through instead of
rejected.

## Checks
- `pytest tests/unit/test_configs.py tests/unit/orchestrator -m "not
gpu"`: 298 passed
- `ruff check`, `ruff format --check`: clean
- New test `test_single_node_nccl_resolved_json_roundtrips`: dumps a
single-node NCCL config like `rl`'s `write_config`, re-parses it, and
checks it is equal. It fails on main with the guard error.
- `rl @ examples/basic/reverse-text/rl.toml --deployment.num-infer-gpus
2 --slurm.partition all --dry-run`, then re-parse the written `rl.json`:
fails on main, passes here (world size 2).
- GPU (one node): running: `rl @ examples/basic/hendrycks-sanity/rl.toml
--max-steps 3` on main and on this branch, plus the rendered single-node
sbatch for reverse-text (2 infer GPUs) run end to end.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes when NCCL weight broadcast groups are sized for single-node
runs; mis-sizing previously caused deadlocks or init failures during
weight updates.
> 
> **Overview**
> Fixes incorrect **NCCL/NIXL** `inference_world_size` on single-node RL
runs when vLLM **data parallel size** is inferred from `num_infer_gpus`
rather than set explicitly.
> 
> **`auto_setup_weight_broadcast`** no longer derives
`trainer`/`orchestrator.weight_broadcast.inference_world_size` from
`data_parallel_size × tensor_parallel_size` (which ran before DP was
filled) and no longer rejects a user-set `inference_world_size`.
**`auto_setup_deployment`** (single-node) now sets
`inference_world_size` to `dp × tensor_parallel_size` immediately after
the DP/`api_server_count` fill, so the in-memory transfer group matches
every inference GPU that joins NCCL.
> 
> Unit tests assert the resolved world size (2 infer GPUs → size 2) and
that a dumped `rl.json` round-trips unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f5553f5c5dd2f91aa11003338ef13e285a6c9ee6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 12:56:47 +01:00
faresobeidandGitHub 746d8a96d0 chore(models): drop rms_norm re-export, move fp8 quantizer into its tool (#3858)
## Summary
- Delete `trainer/models/layers/rms_norm.py`. It only re-exported
`RMSNorm`/`RMSNormConfig` from `layers/norms.py`, and nothing imported
it.
- Move `quantize_to_fp8_blockwise` from `trainer/models/fp8.py` into
`tools/convert_bf16_to_fp8.py`, its only user.
`tools/convert_dcp_to_fp8.py` still imports it through
`convert_bf16_to_fp8`. While moving it, the 9-line zero-pad block
becomes `F.pad(weight, (0, pad_cols, 0, pad_rows)).contiguous()`; the
output is bitwise identical to the old function (bf16/fp16/fp32, padded
and unpadded shapes, contiguous and transposed inputs).

## Behavior change
None.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dead-code removal and relocating a tool-only quantizer; no trainer
inference or training path changes.
> 
> **Overview**
> Removes dead trainer surface area and keeps FP8 checkpoint conversion
self-contained in the tooling layer.
> 
> **`trainer/models/layers/rms_norm.py`** is deleted (it only
re-exported `RMSNorm` / `RMSNormConfig` with no importers).
**`trainer/models/fp8.py`** is removed and
**`quantize_to_fp8_blockwise`** now lives in
**`tools/convert_bf16_to_fp8.py`**, which was its only consumer;
**`convert_dcp_to_fp8.py`** continues to pull quantization helpers from
that script. Padding inside the moved helper uses **`F.pad`** instead of
manual zero-fill, with the same blockwise e4m3 logic otherwise
unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c35ca75057037c6d98f0080bdffae8efd24e2f85. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 12:46:12 +01:00
faresobeidandGitHub 765bbeba7b fix(launch): default TRITON_CACHE_DIR to a node-local path (#3877)
Processes that share `~/.triton` on a shared filesystem can hang or
crash (seen with Nemotron-H, where many ranks compile the Mamba Triton
kernels at once; reproduced below with Qwen3.5 and GLM-4.5-Air).

This PR adds `TRITON_CACHE_DIR = /tmp/triton-<uid>` to
`DEFAULT_COMMON_ENV_VARS`. It is per-user because `/tmp` is shared by
all users on a node. Like the other launcher defaults, it reaches every
launched component: the local `rl`/`sft`/`inference` launchers (also
used by the single-node sbatch scripts) and the trainer, orchestrator,
inference (incl. prefill/decode), and online-eval env blocks of the
multi-node and inference sbatch scripts. `[env_vars]` (or a component's
`env_vars`) overrides it; a value exported in the shell or `.env` does
not. It also removes the `TRITON_CACHE_DIR` overrides from six example
configs (glm-4.5-air swe/swe-budget/search/terminal, glm-5.3 and
qwen3-30b-a3b sft h200 base): they pointed every user at the same `/tmp`
dir and are now covered by the default. `docs/scaling.md` says so in one
paragraph.

vLLM 0.31's own default: when `TRITON_CACHE_DIR` is unset, its Inductor
adaptor points it at
`$VLLM_CACHE_ROOT/torch_compile_cache/<hash>/rank_<i>_<j>/triton_cache`
(`~/.cache/vllm` by default, so usually on the shared home). That only
covers Triton kernels compiled after torch.compile initializes, and it
is still on the shared filesystem. vLLM keeps a `TRITON_CACHE_DIR` that
is already set, so with this PR vLLM uses `/tmp/triton-<uid>` too.

### Measured cost (one H200 node, vLLM 0.31 venv, Triton 3.7.1)

Each run starts from a fresh process with the same config. "Ready" is
launch → first trainer step logged (Qwen) or launch → `/health` OK
(GLM). For GLM, the first generated token came 1.3–2 s after ready in
every run that came up. Inductor's cache dir was emptied before each run
except the warm node-local one.

| Triton cache | Qwen3.5-4B SFT, 8 GPUs, compiled blocks (step 1 time) |
GLM-4.5-Air vLLM TP8 |
|---|---|---|
| shared, cold (today on a new cluster / after a Triton or torch update)
| **failed 2/2**: `FileNotFoundError` on a cache file that another rank
was writing (`causal_conv1d_fwd_kernel.llir`, `l2norm_fwd_kernel.ptx`) |
**failed 2/2**: 4 of 8 ranks hit `FileNotFoundError` in the cache during
Inductor autotune, the other 4 hung in a collective until killed (1st
run). The 2nd run crashed instead of hanging. |
| shared, warm | not measured cleanly (see below) | 344 s |
| node-local, cold (this PR, first job on a node) | 233 s (step 1: 91
s), 164 kernels compiled | 375 s with vLLM's compile cache warm (106
kernels); 465 s if vLLM's cache is also cold (87 kernels) |
| node-local, warm (this PR, later jobs on the same node) | 138 s (step
1: 8.3 s) | 344 s |

- A cold node-local cache costs about **95 s per node for Qwen3.5** (FLA
+ Inductor kernels) and about **31 s for GLM-4.5-Air inference** when
vLLM's own compile cache is warm. Warm node-local and warm shared take
the same time.
- The rest of the GLM startup does not depend on the Triton cache: about
3.5 min of Python imports and process spawn from the shared venv, 13 s
to load weights.
- vLLM: `VLLM_CACHE_ROOT` (`~/.cache/vllm`, shared home) holds vLLM's
AOT/Inductor artifacts. With this PR it stays shared. On a new node,
vLLM loads those artifacts (`torch.compile` 0.6 s instead of 30 s), and
the Triton binaries are compiled into `/tmp/triton-<uid>` (106 kernels,
+31 s). `TORCHINDUCTOR_CACHE_DIR` (default `/tmp/torchinductor_<user>`,
already node-local) stayed empty in these runs. Inductor's Triton
kernels go to `TRITON_CACHE_DIR`.
- A crash on the shared cache can also break later starts. After the
first failed GLM run, the shared vLLM cache only had AOT artifacts from
the 4 ranks that got through. On the next start, those 4 ranks loaded
the artifacts and the other 4 recompiled, so the ranks diverged and hung
(Triton cache warm-ish, 60 kernels). For the same reason the Qwen
"shared, warm" run started from a partial cache and failed again. The
warm-shared GLM number comes from a shared dir seeded with a complete
cache.

### Possible middle ground (not implemented)

Because the cold cost is above 1 min per node for FLA-heavy models, a
run could seed the node-local cache from a shared read-only copy at job
start. For example, on each node before the components start:
`[ -n "$TRITON_CACHE_SEED" ] && cp -rn "$TRITON_CACHE_SEED"/.
"$TRITON_CACHE_DIR"/`
The seed would be a warm `/tmp/triton-<uid>` copied once to the shared
FS. Triton keys entries by source, compiler, and GPU, so stale entries
are never reused, only skipped. Only reads hit the shared FS, so the
concurrent-write race does not occur. I left it out to keep this PR
minimal.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Launch-time env default only; behavior is overridable via config and
fixes known multi-rank Triton cache races, with a one-time cold-compile
cost on each node.
> 
> **Overview**
> **Sets a global launcher default** so every trainer, orchestrator, and
inference process gets `TRITON_CACHE_DIR=/tmp/triton-<uid>` via
`DEFAULT_COMMON_ENV_VARS`, avoiding concurrent Triton kernel writes
under `~/.triton` on a shared filesystem (hangs / `FileNotFoundError`
under multi-rank compile).
> 
> **Removes redundant `[env_vars]` overrides** from six GLM-4.5-Air RL
and GLM-5.3 / Qwen3-30B SFT example configs that previously pinned
Triton cache paths under `/tmp`; those runs now inherit the per-user
node-local default (still overridable through config `env_vars`).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f21642046ea59cab0b9460863560b4df825f29c0. 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: faresobeid <111092724+faresobeid@users.noreply.github.com>
2026-10-08 11:59:17 +01:00
faresobeidandGitHub fec3acd8e7 chore(orchestrator): fold GenerationSource into TrainEnv (#3838)
## Summary
Fold `GenerationSource` into `TrainEnv`, its only owner. Move
`connect_frozen_client` from `algo/base.py` to `clients.py`, so `algo`
no longer imports `clients` lazily. Give `TrainEnv` `setup()`/`aclose()`
so orchestrator setup and teardown no longer reach into its parts.

## What changed
- `orchestrator/generation_source.py` is deleted. `TrainEnv` (`envs.py`)
now holds `clients`, `renderer_config`, `connected` (the frozen source
clients it connected) and `uses_live_policy`. Dropping `logprobs` for
frozen sources happens in `TrainEnv.__init__`.
- `TrainEnv.setup()` connects the frozen generation source and runs
`algorithm.setup()` concurrently. `TrainEnv.aclose()` closes `connected`
and `algorithm.connected`, never the shared policy clients.
- `connect_frozen_client` is a plain function in `clients.py`, next to
`check_inference_ready`. `algo/base.py` imports it at module level. It
is no longer re-exported from `prime_rl.orchestrator.algo`.
- `dispatcher.py` reads the `TrainEnv` directly at the four former
`generation_source` call sites. `orchestrator.py` calls `env.setup()`
and `env.aclose()`.
- `docs/algorithms.md` and the `algo/__init__.py` docstrings refer to
`TrainEnv`.

## Behavior change
None.

## Checks run
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 297 passed.
- `ruff check`, `ruff format --check`: clean.
- Equivalence script, old `GenerationSource` (`origin/main`) vs new
`TrainEnv`, on 4 configs: policy, policy with `top_p=0.9`, sft with a
frozen `sampling.source`, opd with a frozen teacher. Identical
`sampling_args`, `requires_sampling_masks` and `uses_live_policy`. After
`setup()`, the same generation clients (policy object, or the frozen
endpoint with the same train client config) and the same algorithm
clients. Teardown closes the same clients.
- GPU smoke on one node (vLLM 0.31): reverse-text RL (15 steps), sft
with a frozen `sampling.source` (5 steps), opd with a frozen teacher (5
steps). All three ran to "Training finished" and exited 0.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Internal orchestrator refactor with stated behavioral equivalence and
no changes to training algorithms or dispatch semantics beyond
indirection.
> 
> **Overview**
> **Refactors train rollout sourcing** by deleting `GenerationSource`
and moving its responsibilities onto `TrainEnv`: inference `clients`,
live-vs-frozen policy detection (`uses_live_policy`), sampling-arg
tweaks (e.g. dropping `logprobs` for frozen endpoints), and frozen-pool
connection in `setup()`.
> 
> `TrainEnv.setup()` now connects frozen `sampling.source` endpoints and
runs `algorithm.setup()` together; `TrainEnv.aclose()` closes only
env-owned clients (`connected` + algorithm pools), not the shared policy
pool. The orchestrator and dispatcher call these surfaces instead of
reaching into a nested `generation_source`.
> 
> `connect_frozen_client` moves from `algo/base.py` to `clients.py`
(next to `check_inference_ready`); it is no longer re-exported from
`prime_rl.orchestrator.algo`. Docs and package docstrings now describe
`TrainEnv` as owning the sampling half of the algorithm config.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e89ca1a663ae6ae808b05ff3326ce9ed63c9b467. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 11:52:10 +01:00
Florian BrandandGitHub adda4731fe fix(eval): salt inference caches only when policy weights change (#3825)
Apply a policy-version cache salt only when inference weights can change
during a run. Standalone evaluations and frozen-model requests omit the
training salt; live RL rollouts and online evaluation retain it so
caches distinguish policy versions.

## Before

The dispatcher added the policy version as `cache_salt` to every request
using the live policy source. Standalone evaluation used that same
source path, so fixed-weight evaluations received a training cache salt
even though no weight updates occurred. Frozen-model requests already
omitted it.

```mermaid
flowchart TD
    Standalone["Standalone evaluation with fixed weights"] --> Live["Live policy source"]
    Training["RL or online evaluation with changing weights"] --> Live
    Live --> Salt["Always add policy-version cache_salt"]
    Salt --> Request["Verifiers provider request"]
    Frozen["Frozen model source"] --> Plain["Omit training cache_salt"]
    Plain --> Request
```

## After

```mermaid
flowchart TD
    Request["Prime-RL dispatcher builds request sampling"] --> Mode{"Live policy source with changing weights?"}
    Mode -->|"Yes: RL or online evaluation"| Salt["Set cache_salt to policy version"]
    Mode -->|"No: standalone evaluation or frozen model"| Plain["Omit training cache_salt"]
    Salt --> Client["Verifiers client builds provider request"]
    Plain --> Client
    Client --> Provider["Inference provider"]
```

The dispatcher records whether policy weights can change. The standalone
evaluator disables version salting, SFT online evaluation enables it,
and RL orchestration keeps it enabled. The request decision also checks
whether the source uses the live policy.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Narrow behavior change to cache salting on eval paths; RL and online
eval keep prior salting via the default flag.
> 
> **Overview**
> Adds a **`policy_weights_change`** flag on `Dispatcher` so inference
**`cache_salt`** (policy version) is only attached when weights can
actually change during the run.
> 
> **Standalone eval** (`EvalConfig`) sets the flag to **false**, so
fixed-weight evaluation no longer invalidates prefix caches on every
training policy version. **SFT online eval** and **RL orchestration**
(default **true**) still salt live-sourced requests so caches stay
correct across weight updates.
> 
> The cache decision is now **`live_sourced and policy_weights_change`**
instead of salting all live policy paths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5a2d7d9652740106e63fee31a6e79da13816dae7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 01:52:39 -07:00
Florian BrandandGitHub a3f1f892c5 fix(eval): preserve empty outcomes and exclude zero-turn traces from training (#3809)
Keep successful empty environment outcomes in evaluation results. A
trace-less episode or clean zero-turn trace retains the verdict returned
by Verifiers, while training and curriculum logic exclude zero-turn
traces.

## Before

The dispatcher changed successful trace-less episodes into
`EmptyEpisode` failures. Clean, non-timeout zero-turn traces became
`EmptyTrajectory` failures, marking both the trace and episode
unsuccessful. Evaluation therefore recorded a failure even when the
environment had returned success, while training and curriculum filters
relied on those injected errors to exclude empty traces.

```mermaid
flowchart TD
    Env["Verifiers returns an empty successful outcome"] --> Dispatch["Prime-RL dispatcher"]
    Dispatch --> Episode["No traces: inject EmptyEpisode"]
    Dispatch --> Trace["Clean zero-turn trace: inject EmptyTrajectory"]
    Episode --> Failed["Rewrite outcome as failed"]
    Trace --> Failed
    Failed --> Eval["Evaluation records a failure"]
    Failed --> Training["Training and curriculum filter injected errors"]
```

## After

```mermaid
flowchart TD
    Env["Verifiers environment returns an episode"] --> Dispatch["Prime-RL dispatcher preserves empty outcome verdicts"]
    Dispatch --> Eval["Evaluation records and metrics"]
    Dispatch --> Filter["Training trace eligibility"]
    Filter --> Empty["Zero turns: no training sample"]
    Filter --> Sample["Eligible trace with sampled tokens: training sample"]
    Dispatch --> Curriculum["Curriculum ignores zero-turn traces and admits only trainable groups"]
```

Remove the synthetic `EmptyEpisode` and `EmptyTrajectory` errors.
`iter_trainable_traces()` filters empty traces alongside failed and
untrainable traces before advantages are assigned, so the advantage gate
needs no separate zero-turn check. Difficulty sampling also excludes
zero-turn traces. Empty groups finish without producing a trainer
payload, and mixed groups retain their eligible traces. Curriculum
admission also requires a trainable trace, so groups without training
samples cannot inflate admission metrics. Sampler observations of
completed turns are retained even when token metadata is unavailable.
Verifiers' no-agent validation and training timeout handling remain in
place.

[#3824](https://github.com/PrimeIntellect-ai/prime-rl/pull/3824) applies
the same ownership rule to partially failed episodes: preserve
environment results, then decide training eligibility explicitly.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes evaluation outcome recording and which rollouts feed
training/curriculum admission, which can shift eval metrics and training
batch composition without touching auth or data stores.
> 
> **Overview**
> Stops the dispatcher from **injecting** `EmptyEpisode` /
`EmptyTrajectory` errors on successful trace-less or zero-turn outcomes,
so **evaluation keeps Verifiers’ success verdict** instead of recording
synthetic failures.
> 
> Training and curriculum now **exclude zero-turn traces explicitly**:
`iter_trainable_traces()` skips `num_turns == 0`, difficulty-pool reward
updates require `num_turns > 0`, and curriculum admission requires
**both** passing gates **and** at least one trainable trace via
`iter_trainable_traces()`. Scored rollouts without token/advantage
metadata can still update sampler difficulty; groups with no trainable
samples no longer count as admitted.
> 
> Tests cover mixed groups with non-trainable traces, empty-only groups,
and reward-only observations for the sampler.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8582fb8c18e7cb4aa0dc7af58c6e0a4474bd7b40. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 01:51:52 -07:00
Florian BrandandGitHub e6acff78aa chore: align network prompt dependency pins (#3929) 2026-10-07 19:45:14 -07:00
3587b285f5 chore: require prime-runs 0.1.4 (#3928)
## Summary

Raises the `prime-runs[train]` floor from `>=0.1.3` to `>=0.1.4` and
updates `uv.lock` to match.

## Why

`prime-runs` 0.1.4 lets a run opt out of Prime Traces and upload its
samples to the legacy sample tables instead
(PrimeIntellect-ai/prime#998):

- `PRIME_TRACES_OPT_OUT=true`
- `prime config set-traces-opt-out true`, which sets `traces_opt_out` in
`~/.prime/config.json`
- `prime_runs.init(traces_opt_out=True)`

`prime-runs` 0.1.3 doesn't know about any of these. With 0.1.3
installed, which is what `uv sync` gives today, a user who sets the
environment variable or the config key gets no error and no warning, and
their runs keep uploading to Prime Traces. Requiring 0.1.4 makes the
setting take effect.

Nothing changes for runs that don't opt out. The Prime monitor calls
`prime_runs.init()` without the new argument, so the default (upload to
Prime Traces) is unchanged.

A training run that opts out needs pyarrow for the legacy sample
encoder. prime-rl already depends on `prime-runs[train]`, which includes
it.

## Changes

- `pyproject.toml`: `prime-runs[train]>=0.1.3` →
`prime-runs[train]>=0.1.4`.
- `uv.lock`: `prime-runs` 0.1.3 → 0.1.4. No other package moves;
`prime-traces` stays at 0.0.7.

The `deps/verifiers` submodule is not changed. Its own floor is raised
separately in PrimeIntellect-ai/verifiers#2805, and this PR doesn't
depend on it.

`uv lock --check` passes. I did not run the test suite.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dependency floor bump only; no application code changes and default
trace upload behavior stays the same.
> 
> **Overview**
> Raises the **`prime-runs[train]`** minimum from **`>=0.1.3`** to
**`>=0.1.4`** in `pyproject.toml` and pins **`prime-runs` 0.1.4** in
`uv.lock`.
> 
> This ensures installs pick up **Prime Traces opt-out** behavior
(`PRIME_TRACES_OPT_OUT`, `prime config set-traces-opt-out`, or
`prime_runs.init(traces_opt_out=True)`), which 0.1.3 silently ignored so
opted-out runs could still upload to Prime Traces. Default runs that do
not opt out are unchanged; `prime-rl` still depends on the **`[train]`**
extra for legacy sample encoding when opting out.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
06caa96109250b6b800d8e757de7133b4f152031. 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>
2026-10-07 19:38:03 -07:00
f3827c4ed2 perf(trainer): avoid eager fallback of MoE blocks with an fp32 router and activation checkpointing (#3925)
With `moe_router_dtype="float32"` (the RL default) and activation
checkpointing on, every MoE block ran eager under `torch.compile`. Two
things combine to cause it:

- The fp32 router is its own FSDP2 unit, and FSDP2 hooks are
dynamo-disabled, so the router always breaks the graph.
- Under `compile(AC(block))` the checkpoint compiles as a higher-order
op, which forbids breaks, so Dynamo ran the whole block eagerly.

This PR compiles inside the checkpoint instead: for any checkpointed
block that holds a nested FSDP unit (today, the fp32 router), an eager
checkpoint now wraps the compiled block (`AC(compile(block))`), so the
nested unit's break only splits the block into compiled graphs. To see
those units, compile now runs after FSDP. Compiling in place keeps the
same module object, so the order changes nothing at runtime.

The reorder is safe. The old `AC -> Compile -> FSDP` comment was ported
from TorchTitan in #923, when `apply_compile` still wrapped each block
with `torch.compile(block)`. #957 switched to in-place `.compile()` two
days later without revisiting it. With in-place compile, both orders
trace the same frames: graph breaks, loss and step time match on both
workloads, and `fullgraph=True` (with a bf16 router) still compiles with
zero graph breaks.

| Workload (8x H200, EP 8, full AC) | before (s/step) | after (s/step) |
MFU |
|---|---|---|---|
| GLM-4.5-Air, 16 layers, real data | 6.21, 6.17 | 5.22, 5.21 | 35% to
42% |
| Qwen3-30B-A3B, fake data | 5.96, 5.96 | 4.51, 4.51 | 32% to 42% |

Two runs per arm, each the median `time/step` over steps 5 to 20, no
offloading. Peak memory is unchanged, and loss and grad norm track the
baseline within run-to-run noise.

![Qwen3-30B-A3B MoE layer forward, before and
after](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/09e64ed1afc27e97fda6080556171522e29c9a0e/pr-figures/fp32-router-compile/qwen_layer_forward.png)

**Figure:** one MoE layer's forward on Qwen3-30B-A3B, before and after
this PR. The orange eager elementwise kernels collapse into a few pink
compiled Triton kernels, so the layer's forward drops from 16.4 to 11.3
ms.

<details><summary>Same view on GLM-4.5-Air</summary>

![GLM-4.5-Air MoE layer forward, before and
after](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/09e64ed1afc27e97fda6080556171522e29c9a0e/pr-figures/fp32-router-compile/glm_layer_forward.png)

</details>

## Alternative considered

Keeping recompute inside the compiler: drop the block-level checkpoint
and instead checkpoint two compiled regions that exclude the router, the
attention module and the post-router MoE work. It beat the baseline but
was slower than this PR (Qwen3-30B 5.50 vs 4.51 s/step, GLM-4.5-Air 5.85
vs 5.22 s/step) and used more memory, because the norms and the router's
fp32 activations stay outside any checkpoint.

## North star: fullgraph fp32 router support

Fullgraph compile with an fp32 router stays unsupported, and
`model.compile.fullgraph=true` still raises for it. The blocker is the
router's FSDP unit itself: FSDP2 applies one mixed-precision policy per
unit, so the fp32 router cannot share the block's bf16 unit, and its
dynamo-disabled hooks are the graph break above. PyTorch
[#196626](https://github.com/pytorch/pytorch/pull/196626) adds
per-parameter mixed precision, which lets the router stay in the block's
unit. That removes the break, enables fullgraph, and makes this PR's
compile-inside-AC path unnecessary, so it should be reverted then.
#196626 is on PyTorch `main` but not yet in a release.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 16:55:28 -04:00
faresobeidandGitHub 93a0fe0d6b refactor(trainer): add iter_moe_blocks for the MoE layer lookup (#3843)
## Summary
Add `iter_moe_blocks(model)` in `trainer/model.py`. It yields the `MoE`
MLP of each decoder layer. It replaces the five copies of the
decoder-layer MoE lookup in `freeze_moe_router`,
`apply_fp32_moe_router`, `get_full_offload_dtype_policy`,
`apply_force_balanced_routing` and `get_load_balance_stats`.

## What changed
- New `iter_moe_blocks` next to the helpers that use it. The helpers
stay in `model.py`, so no imports change.
- The four `layer.mlp if hasattr(...) else layer.feed_forward ...`
lookups and the `getattr(mlp)` + `hasattr(tokens_per_expert)` scan in
`get_load_balance_stats` now call `iter_moe_blocks`.
- Removed the stale "HF impl" comment in `get_expert_load_stats`. The HF
fallback was removed in #3773.

## Behavior change
None. The `feed_forward` fallback is gone. Every prime-rl decoder layer
uses `mlp`. `get_load_balance_stats` already looked only at `mlp`. Only
`MoE` registers `tokens_per_expert`, so it selects the same layers as
before.

## Checks
- CPU equivalence vs `main` (throwaway script, not in the repo). Tiny
Qwen3-MoE (`mlp_only_layers=[1]`) and GLM4-MoE
(`first_k_dense_replace=1`) models with fixed router-count buffers.
Compared `is_tt_moe_model`, `get_load_balance_stats`,
`get_global_moe_stats`, `compute_expert_load_stats`,
`get_expert_load_stats` and `get_full_offload_dtype_policy`, plus
parameter dtype and `requires_grad`, and router
`fp32_gate`/`force_balanced` after the three router helpers. All 16
outputs were bit-identical.
- `pytest tests/unit/train tests/unit/orchestrator
tests/unit/test_configs* -m "not gpu"`: 450 passed, 1 failed. The
failure is
`test_cpu_adam.py::test_native_cpu_adamw_matches_fused_torch_and_preserves_gradients`
(ninja build), which fails the same way on `main`.
- `ruff check` and `ruff format --check`.
- GPU: reverse-text MoE RL smoke vs `main` on one node, running.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Mechanical refactor of MoE traversal with no intended behavior change;
only risk is if a model relied on the removed feed_forward path (none in
this codebase).
> 
> **Overview**
> Introduces **`iter_moe_blocks`**, a single iterator over decoder
layers whose `mlp` is a **`MoE`**, and rewires MoE
router/offload/metrics helpers to use it instead of repeated per-layer
`mlp` / `feed_forward` lookups.
> 
> **`freeze_moe_router`**, **`apply_fp32_moe_router`**,
**`get_full_offload_dtype_policy`**, **`apply_force_balanced_routing`**,
and **`get_load_balance_stats`** now loop over that iterator; the unused
**`feed_forward`** fallback is removed. **`get_expert_load_stats`** only
drops an outdated comment on the empty tensor guard.
> 
> Intended as a no-op for supported models: same router freezing, fp32
gates, FSDP dtype policy, debug balanced routing, and load-balance /
expert-load metrics.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2cf0399ca4e467c9ae028082c2a03f02604abbf8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-07 20:22:19 +01:00
faresobeidandGitHub db2c00e9ed feat(trainer): freeze MoE router by default in RL (#3797)
Make `trainer.model.freeze_moe_router` default to on for RL.

## What changes
- `model.freeze_moe_router` is now `bool | "auto"`, default `"auto"`. It
resolves to `True` on the RL `TrainerConfig` and to `False` on
`SFTConfig`, following the per-trainer pattern of `moe_router_dtype`. An
explicit `true`/`false` still wins.
- `freeze_moe_router()` no longer raises on non-MoE models; it does
nothing, so dense RL runs keep working with the new default.
- `docs/training.md` knobs table lists the field.

## Why
In RL, router updates amplify the train/inference routing mismatch: the
trainer's expert choices drift away from the ones inference sampled. So
RL keeps the pretrained router by default. SFT is unchanged.

What gets frozen: the router gate parameters (`mlp.router.gate.weight`,
plus `gate.bias` on gpt-oss). The aux-loss-free `selection_bias` buffer
is not a parameter, and nothing on main updates it. Shared-expert gates
(Qwen3.5) and Nemotron-H latent projections are not touched. Frozen
routers get no optimizer state.

## Breaking changes
- RL runs on MoE models no longer train the router. All MoE RL examples
are affected (glm-5.3, glm-4.5-air, intellect-3.1, qwen3-30b-a3b,
minimax-m2.5, nemotron-3-super). Set `trainer.model.freeze_moe_router =
false` for the old behavior.
- An explicit `freeze_moe_router = true` on a non-MoE model is now a
no-op instead of an error.
- Resuming: a checkpoint saved before this change (trainable router)
loads into a frozen-router run; the extra router optimizer state is
ignored. The reverse, resuming a frozen-router checkpoint with
`freeze_moe_router = false`, fails on missing DCP keys (noted in the
field docstring).
- With LoRA, a router listed in `lora.modules_to_save` is frozen again
by the new default unless `freeze_moe_router = false` is set.

## GPU check
One node (8×H200), FSDP over 8 ranks, `samsja/mini-glm-moe` (23 MoE
layers), SFT with fake data, `freeze_moe_router = true`,
`moe_router_dtype = "float32"` (so each router is its own fp32 FSDP unit
whose params are all frozen), 5 steps with a checkpoint every step:
- Log: "Froze 23 MoE router parameters", "Running 23 MoE router gates in
fp32"; all 5 steps ran with finite loss and grad norm.
- DCP checkpoints step 1 vs step 5: all 23 fp32 router gate weights are
bitwise unchanged; expert weights changed; no optimizer state exists for
any router parameter.
2026-10-07 19:15:26 +01:00
4250d895bc fix(trainer): run FA2 and FA3 through custom ops so fullgraph compile works (#3911)
#3753 let MoE blocks compile with `model.compile.fullgraph = true`, but
it was validated on B300 with FA4. On H200, where FA3 is the default,
fullgraph still failed at the first forward, because FA2's and FA3's
`flash_attn_varlen_func` are autograd.Functions and Dynamo rejects the
same `cu_seqlens` tensor passed as both `cu_seqlens_q` and
`cu_seqlens_k`. FA2 and FA3 now run through `prime_rl_attn` custom ops
like FA4 (#3754), so the checkpointed MoE blocks compile with fullgraph
and no graph breaks on H200 too.

- AFMoE, Ulysses CP and the Qwen3.5 vision encoder now call the op
wrappers; FA4's op takes optional `max_seqlen_q/k` for Ulysses.
- The ops match the library functions bitwise, except FA3's GQA
`dk`/`dv`, which the library itself doesn't reproduce run to run.
- `apply_compile` traces `max_seqlen` symbolically: as a constant, each
rank recompiled on its first new value and stalled every rank for ~6 s.
A
[benchmark](https://github.com/PrimeIntellect-ai/prime-rl/blob/9db5336241304a0263664c8408e03159cbb8767e/tools/benchmark_flash_attn_max_seqlen.py)
shows the symbolic int costs nothing measurable.

| GLM-4.5-Air, 24 layers, 2 x 8 H200, ep 8, bf16 router | s/step (lower
is better) | tok/s/GPU (higher is better) |
|---|---|---|
| main, FA3, fullgraph off (fullgraph fails) | 4.64 | 3533 |
| this PR, FA3, fullgraph on | 3.83 | 4282 |

That is 17.5% less time per step, or 21.2% more tokens per second per
GPU. Medians over steps 5 to 20; loss tracks main within 0.03 over 20
steps. The GPU is about 99% busy in both arms, so the gain is fusion:
per step, about 1030 ms of unfused aten kernels (MoE routing glue, RoPE)
become 262 ms of Inductor-fused Triton kernels.

![Layer 12 forward
timeline](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/8e12d604f167480f14a2a3a34452c38a95ad07f7/pr-figures/fa-custom-op/layer12-forward.png)

**Figure:** one layer's forward, before (`main`, fullgraph off) and
after (this PR, fullgraph on). The strings of small yellow and
red-orange aten kernels on `main` become a few fused Triton kernels
(pink), and the layer finishes in 35.9 ms instead of 45.4 ms.

![Layer 12 recompute and backward
timeline](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/8e12d604f167480f14a2a3a34452c38a95ad07f7/pr-figures/fa-custom-op/layer12-backward.png)

**Figure:** the same layer's recompute and backward, 106.7 ms after
versus 131.6 ms before. The bottom panel totals the whole step: about 1
s of unfused aten kernels became 262 ms of fused Triton kernels, while
FlashAttention and GEMM time barely changed.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 13:26:59 -04:00
faresobeidandGitHub 78bc69ccc4 fix(inference): let the LoRA adapter take the base model name on vLLM 0.31 (#3913)
## Problem
`Integration tests (reverse_text_lora)` has failed since the vLLM 0.31
bump (#3888's own CI run, and main's GPU Tests at b9c0bfe87). The first
`POST /load_lora_adapter` returns `400 Bad Request` and the orchestrator
exits.

Root cause: vLLM 0.31 added a check to
`OpenAIServingModels._check_load_lora_adapter_request`. It rejects a
`lora_name` equal to a served base model name ("conflicts with a served
base model", 400). vLLM 0.30 had no such check. prime-rl registers its
adapter under the model name (`model.name`) on purpose, because every
client (rollouts, evals, the renderer client) sends that name. vLLM
serves the base model under the same name by default, so the two
collide.

## Change
No vLLM patch. With LoRA on, the inference server serves the base model
under a different name, and the adapter keeps the name clients already
send.
- `InferenceConfig.to_namespace` sets `served_model_name =
[f"{vllm.model}-base"]` when `vllm.enable_lora` is on, unless the user
sets `served_model_name` explicitly. Every launch path builds the vLLM
args here: local `rl`/`sft`, standalone `uv run inference`, SLURM
single/multi-node, and P/D prefill/decode ranks.
- `maybe_check_has_model` (startup readiness) also accepts the name as a
model's `root`. Before the first weight sync, a LoRA server lists only
`<model>-base`, whose `root` is the model path.
- The `load_lora_adapter` docstring, an orchestrator comment, and the
LoRA section of `docs/advanced.md` now describe the served name.

## Checks
- **Nothing on the policy server asks for the base model by name.**
Rollouts, evals, and the renderer/prefill scorer all send `model.name`,
which is now the adapter. OPD teachers and frozen reference models are
separate endpoints. A LoRA server also cannot serve a frozen reference
under `model.name`. Before this change that name would already have
resolved to the adapter, and the base model can now be reached as
`<model>-base`. Admin routes (`/pause`, `/update_weights`,
`/load_lora_adapter`, health, liveness) do not take a model name.
vllm-router and llm-d configs do not reference model names. Dynamo
workers are external, so this change does not affect them.
- **The v0 adapter is loaded before the first request.** The
orchestrator and online evals wait for the trainer's startup broadcast
(v0, or the resume step). They load it through `/load_lora_adapter`
before they dispatch any rollout or eval. Readiness is the only earlier
check that uses the model name, and the `root` match covers it.
- **`/metrics`:** vLLM's `model_name` label becomes `<model>-base`. The
inference-metrics collector and the concurrency controller group samples
by the `engine` label only, and the dashboard does not read vLLM's
`/metrics`.

## Tests
- `configs/ci/integration/reverse-text-lora/start.toml` on one H200 node
(vLLM 0.31.0, this commit, patch module absent): all 15 steps run and
16/16 `/load_lora_adapter` calls return 200. There are no 400s or 404s.
Reward goes from 0.145 to 0.798, matching the patched version (0.14 to
0.79). Before the first sync, `/v1/models` lists only
`...-Reverse-Text-SFT-base` (root `...-Reverse-Text-SFT`). After it, the
list also has the adapter `...-Reverse-Text-SFT` (parent
`...-SFT-base`).
- `reverse-text-sft-lora/start.toml` (5 steps) passes.
- `pytest tests/unit/orchestrator tests/unit/inference
tests/unit/test_configs.py tests/unit/test_parsers.py -m "not gpu"` (469
passed), `ruff check`, and `ruff format --check` all pass.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how LoRA vLLM instances advertise models at startup and during
readiness checks; client-facing model IDs stay the same, but anything
expecting the base under the policy name would need `<model>-base`.
> 
> **Overview**
> Fixes LoRA inference startup on **vLLM 0.31**, which returns 400 when
an adapter is registered under the same name as a served base model.
> 
> When `enable_lora` is on and `served_model_name` is not set
explicitly, **`InferenceConfig.to_namespace`** now serves the base
weights as ``<vllm.model>-base`` so the reloaded policy adapter can keep
**`model.name`** for all rollout/eval clients.
**`maybe_check_has_model`** treats a match on either the model **`id`**
or **`root`**, so readiness passes before the first `/load_lora_adapter`
when only the `-base` entry is listed. Docs and comments describe the
naming split.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
18064f3367009c265c11ffd58fb9d5b989ca7ec1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-07 15:35:07 +01:00
faresobeidandGitHub 81052082a9 fix(logger): disable loguru diagnose so crashes with large tensors exit instead of hanging (#3876)
Turn off loguru's `diagnose` on every handler.

With loguru's default `diagnose=True`, every logged exception (including
the `Fatal error in …` that `clean_exit` logs) `repr()`s the variables
in each traceback frame. A `torch` storage repr walks the storage in
Python, element by element. When a frame holds a multi-GB tensor or
storage (a checkpoint state dict, a staging buffer, model shards),
formatting the traceback takes hours. The crashing trainer then looks
hung instead of exiting, and the real error never reaches the log.

Seen while debugging async DCP checkpoint saves: the trainer stopped at
`Saving checkpoint at step 2` with no error. A faulthandler dump showed
the main thread inside `loguru/_better_exceptions.py` →
`torch/storage.py __repr__`. The actual exception (a staging error) only
showed up through `traceback.print_exc`.

Repro on CPU (a frame whose failing line references an 8 MB
`UntypedStorage`):
- main: formatting took 19.1 s. It scales with size, so about 40 min per
GB.
- this PR: 0.0 s.

Tracebacks are still logged in full; only the per-variable value
annotations are dropped.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Logging-only change that reduces exception detail slightly; improves
reliability when failures involve large tensor locals.
> 
> **Overview**
> Disables loguru’s **`diagnose`** mode on every handler installed in
`setup_logger` (JSON console, colorized stdout, and optional file sink).
> 
> With the default **`diagnose=True`**, exception formatting
**`repr()`s** locals in each traceback frame. When those locals are
large PyTorch tensors or storages, that step can take minutes or hours,
so a fatal error during logging looks like a hang and the real exception
may never appear in logs. **Full tracebacks are still logged**; only the
per-variable value annotations are omitted.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
93a682f6fedf415561d4e5f31cbf0ee8b92a2a04. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-07 15:05:05 +01:00
Florian BrandandGitHub b9c0bfe87b fix(eval): resolve endpoints and credentials through Verifiers clients (#3827)
Use Verifiers' client configuration and resolvers for Prime-RL
endpoints, credentials, headers, and timeouts. Standalone evaluation
honors an explicit URL, then `PRIME_INFERENCE_URL`, the Prime CLI
config, and the default Prime endpoint. Partial overrides retain the
correct defaults for each run type.

## Before

Prime-RL owned a separate client schema and credential/header resolvers.
Standalone eval supplied a hardcoded Prime endpoint, so changing
`PRIME_INFERENCE_URL` did not change that default. Client setup resolved
environment headers into static values, prefill scoring constructed its
own SDK client, and admin authentication reused the inference
configuration instead of resolving against the admin URL.

```mermaid
flowchart TD
    Eval["Standalone eval hardcodes Prime URL and key defaults"] --> Config["Prime-RL ClientConfig"]
    Config --> Local["Prime-RL credential and header resolvers"]
    Local --> Inference["Construct Verifiers client with resolved static headers"]
    Inference --> Prefill["Prefill builds its own OpenAI SDK client"]
    Local --> Admin["Admin client resolves using inference config"]
    AdminURL["Separate admin URL"] --> Admin
```

## After

```mermaid
flowchart TD
    Eval["Standalone eval: Prime endpoint defaults"] --> Config["Verifiers BaseClientConfig"]
    Train["Training and online eval: localhost vLLM defaults"] --> Config
    Config --> Inference["Inference client configuration"]
    Config --> Prefill["Shared SDK builder for prefill scoring"]
    Config --> Admin["Admin configuration with its own URL"]
    Inference --> Resolve["Resolve credentials and headers for actual destination"]
    Prefill --> Resolve
    Admin --> Resolve
    Runtime["Environment values and Prime CLI config"] --> Resolve
    Resolve --> Endpoint["Target endpoint"]
```

Training and online evaluation retain their vLLM defaults, including
when only part of the client config is overridden. Frozen models require
an explicit endpoint. Environment-backed headers remain references in
saved configs, and header overrides compare names case-insensitively.
Admin authentication uses the admin destination. Prefill scoring uses
the shared SDK builder's timeout and retry policy.

Depends on [Verifiers
#2766](https://github.com/PrimeIntellect-ai/verifiers/pull/2766). When
combining this with
[#3782](https://github.com/PrimeIntellect-ai/prime-rl/pull/3782) and
[#3808](https://github.com/PrimeIntellect-ai/prime-rl/pull/3808), pin a
Verifiers revision containing all three companion fixes.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how eval and inference clients pick URLs, API keys, and
headers at runtime; mis-resolution could break eval or admin traffic,
though behavior is covered by new default-preservation tests.
> 
> **Overview**
> **Client configuration now delegates to Verifiers** instead of a
duplicate Prime-RL schema and local credential/header resolvers.
`ClientConfig` extends Verifiers' `BaseClientConfig`; training and
online eval use `VLLMClientConfig` (`localhost:8000` / `VLLM_API_KEY`).
Standalone `uv run eval` drops the hardcoded Prime URL and inherits
Prime Inference defaults from Verifiers (honoring `PRIME_INFERENCE_URL`,
Prime CLI, then the standard endpoint). Frozen external models require
an explicit `base_url`.
> 
> **Runtime client setup** forwards unresolved config into Verifiers
train/eval clients (`setup_client` dumps `BaseClientConfig` fields),
resolves auth per destination in admin clients (including separate admin
URLs), and builds prefill scoring via `build_async_openai`. Docs
describe the eval endpoint precedence; tests assert partial `[client]`
overrides keep the right defaults per run type.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c643ef25637bfafb13af555d56167fdbd3525e57. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-06 15:49:52 -07:00
faresobeidandGitHub 51879014fc chore(models): sqrtsoftplus in the shared router, drop the DeepseekV4Router copy (#3854)
## Summary
`TokenChoiceTopKRouter` gets a `"sqrtsoftplus"` score function
(`sqrt(softplus(logits.float()))`, DeepSeek V4's). The copied
`DeepseekV4Router` (its whole `forward` was restated for that one
scoring line) is deleted. Standard V4 layers use `TokenChoiceTopKRouter`
directly, and `DeepseekV4HashRouter` subclasses it, forwarding the
router kwargs and only adding `tid2eid` and `selection_bias=False`. The
router signature uses `ScoreFuncType` instead of repeating the
`Literal`. The `DeepseekV4MoE` guard that rejected any `scoring_func`
other than `sqrtsoftplus` is removed, because the shared router
implements every score function.

Clamped activation: `GroupedExperts` and `FeedForward` now take either
an activation name or an `Activation` object. A new shared
`ClampedSilu(limit)` in `layers/activations.py` holds V4's clamp
(`silu(gate.clamp(max=limit)) * up.clamp(-limit, limit)`, limit from
`config.swiglu_limit`). V4's routed experts are a plain
`GroupedExperts(activation=ClampedSilu(...))` and its shared expert a
plain `FeedForward(activation=ClampedSilu(...))`. Deleted from
`deepseek_v4/moe.py`: `ClampedSwiglu`, `DeepseekV4Experts` and
`DeepseekV4MLP`. The one init difference (HF draws expert `up_proj` at
std 0.02, not `initializer_range`) is a 3-line
`DeepseekV4MoE.init_weights` override. The hash-routing table and
forward stay in the V4 file. gpt-oss's `clamped_swiglu` is different
math (`(up+1) * gate * sigmoid(1.702 * gate)`, limit fixed at 7), so it
is not merged with this. Sonic MoE rejects `ClampedSilu`, as it rejected
the old V4 experts.

## Behavior change
None for V4 checkpoints, which all ship `sqrtsoftplus`. A V4 config with
another `scoring_func` now builds with that score function instead of
raising. `sqrtsoftplus` takes the non-softmax confidence branch
(`top/sum(scores)`), the same as the deleted copy. State dict keys are
unchanged.

## Equivalence
- CPU: router and full `DeepseekV4MoE` (hash and standard layers, with
and without replay, fp32/bf16, active clamp) are bitwise identical to
main: forward, all grads, buffers and state-dict keys. Other MoE archs
(qwen3_moe, glm4_moe, minimax_m2, afmoe, laguna, gpt_oss) are unchanged.
- GPU (8×H200): qwen3_moe, glm4_moe, laguna and nemotron_h are bitwise
identical to main. deepseek_v4 is not deterministic on GPU even main vs
main; the branch is within that run-to-run spread.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches shared MoE routing and expert activation paths used beyond V4;
behavior change only for non-default V4 `scoring_func`, but incorrect
`sqrtsoftplus` parity would affect training/inference for V4
checkpoints.
> 
> **Overview**
> **DeepSeek V4 MoE is refactored onto shared layer primitives** instead
of V4-only router, expert, and MLP subclasses.
> 
> `TokenChoiceTopKRouter` now supports **`sqrtsoftplus`**
(`sqrt(softplus(logits))`), so the duplicated `DeepseekV4Router` is
removed and standard V4 layers use the shared router directly.
`DeepseekV4HashRouter` subclasses `TokenChoiceTopKRouter` and only adds
the `tid2eid` buffer. The config no longer documents `scoring_func` as
V4-only, and `DeepseekV4MoE` drops the guard that rejected
non-`sqrtsoftplus` values (other score functions now build through the
shared router).
> 
> **Clamped SwiGLU** moves into shared `ClampedSilu(limit)`;
`FeedForward` and `GroupedExperts` accept either an activation name or
an `Activation` instance. V4 wires `GroupedExperts` and optional
`FeedForward` shared experts with `ClampedSilu(config.swiglu_limit)`;
`DeepseekV4Experts`, `DeepseekV4MLP`, and local `ClampedSwiglu` are
deleted. HF-style expert `up_proj` init (std 0.02) lives in a small
`DeepseekV4MoE.init_weights` override. Unit tests target
`GroupedExperts` + `ClampedSilu` instead of `DeepseekV4Experts`.
> 
> Shipped V4 checkpoints (`sqrtsoftplus`) should behave the same;
configs with other `scoring_func` values now construct instead of
raising.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
019f42b643266b8be15ce15985b8a82034925d4b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-06 18:53:29 +01:00
faresobeidandGitHub 52e985ae9d fix(dashboard): keep replay Home/End mode when the output fits (#3878)
The dashboard smoke check at the end of the `alphabet_sort` integration
test flakes at `tests/integration/dashboard_smoke.py:164`. It asserts
that `#replay-top` is active after Home. It failed on #3767 and #3774,
which don't touch the dashboard.

**Root cause.** The smoke test presses `t` and then Home. When thinking
is hidden, a trace that overflowed the replay pane gets shorter and
fits. The browser then clamps `scrollTop` and queues a scroll event.
That event fires after Home. At that point the pane fits, so the scroll
handler sees the view as "at bottom", switches back to follow mode, and
clears `#replay-top`. The same thing happens when the pane overflows by
less than the 24px threshold, because top and bottom then count as the
same position.

**Fix.** When the replay output fits (overflow < 24px), the scroll
handler leaves the follow mode alone. Home and End decide it, and that
choice still applies if the output grows later. Scrolling a long trace
by hand still switches between the modes as before.

**Check.** I ran headless Chromium against a dashboard serving synthetic
runs, with the same steps as the smoke test (skip inference, `t`, Home,
End):
- trace that fits after hiding thinking: 4/4 failed before the fix, 4/4
passed after
- 14px overflow: 4/4 failed before the fix, 4/4 passed after
- short trace that always fits: passed before and after
- long scrollable trace: passed before and after
- long trace, scrolling up and back down by hand: still toggles follow
mode and the top/live buttons

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Small dashboard UI scroll-handler guard with no auth, data, or API
impact.
> 
> **Overview**
> Fixes flaky replay **Home/End** behavior when the trace output
**fits** (or barely overflows) in the replay pane.
> 
> The `#replay-output` scroll listener now **bails out** when
`scrollHeight - clientHeight < 24`, so clamped or near-no-op scroll
events (e.g. after hiding thinking shrinks the content) no longer force
**follow/live** mode and clear **`#replay-top`**. **Home/End** and
manual scrolling on long traces are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
83d2f3f9b71e5b4309b98146eb1ffa944db08c23. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-06 16:02:03 +01:00
63b3e85864 chore: bump vllm to 0.31.0 (#3888)
- Bump vLLM 0.30.0 → 0.31.0 (exempt `flashinfer-python` 0.7.0.post1 from
the `exclude-newer` cooldown).
- Read `enable_return_routed_experts` from
`VllmConfig.aux_output_config` (moved in 0.31).
- Router replay now always uses the V2 runner; router replay with
disaggregated P/D is rejected at config time (0.31 has no NIXL
routed-expert capture).
- Resync the copied LoRA loader in `_patch_lora_key_prefix` with 0.31
(`modules_to_save`).

Removed patches:
- `monkey_patch_deepseek_v4_request_tools_placement`: fixed upstream
(vllm#51856).
- `monkey_patch_return_routed_experts_with_nixl_connector`: crashes the
engine on 0.31.

Tested end to end: multi-node RL on SLURM (1 trainer + 1 inference
node), Qwen3-0.6B reverse-text, 10 steps. Eval reward 0.08 → 0.81.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 15:46:51 +01:00
faresobeidandGitHub 7133f8f8f2 chore(tests): delete permanently skipped tests and the vendored HF AFMoE model (#3850)
Deletes tests that are skipped unconditionally, plus the 777-line
vendored HF AFMoE model that only the skipped AFMoE test used (rev-infra
P4).

Deleted:
- `tests/unit/train/models/test_afmoe.py` (whole module skipped: "HF
afmoe model does not support flash attention 2") and
`tests/unit/train/models/afmoe_hf_modeling/` (vendored HF model;
transformers 5.6.2 ships `transformers.models.afmoe` anyway).
- `tests/unit/train/test_model.py::test_model_with_sequence_packing`
(skipped since 2025-05, "Sequence packing for Qwen not working") and
`::test_model_forward_custom_impl` (skipped, "need special token for
meta stuff in ci").
-
`tests/unit/train/rl/test_fused_lm_head.py::test_full_model_fused_vs_vanilla`
(skipped, "Produces NaNs in bf16 with FA3").
- `tests/unit/transports/test_nccl_broadcast.py` (skipped since 2025-12,
"fail only in ci").
- The `free_port` fixture in `tests/conftest.py`: only the NCCL test
used it (and it called the int as a function, so it was broken too).

No source changes. Behavior change: none. These tests never ran.

## Checks
- CI test selection: `pytest --collect-only -q tests/unit -m "not gpu"`
gives the same 673 ids before and after. `-m gpu` goes from 190 to 182
ids, and the diff is exactly the 8 skipped ids listed above. Nothing
that ran before is gone.
- `pytest -m "not gpu" tests/unit/orchestrator
tests/unit/test_configs.py tests/unit/train/rl/test_fused_lm_head.py`:
297 passed.
- `ruff check .`, `ruff format --check .`: clean.
- GPU: none needed (only skipped tests are removed).

## Conflicts
- #3833 (remove transformers modeling) edits `test_afmoe.py`,
`test_model.py::test_model_with_sequence_packing` and
`test_fused_lm_head.py::test_full_model_fused_vs_vanilla` to port them
to the new model API, but keeps them skipped. Text conflict only.
Whichever PR lands second resolves it by keeping the deletion.
- #3794 and #3698 edit the import block of `test_fused_lm_head.py`. This
PR drops `selective_log_softmax` from the same import line. Expect a
trivial text conflict.
- If an AFMoE parity check is still wanted, port it to upstream
`transformers.models.afmoe` with `sdpa` in a follow-up. That would need
a GPU run to validate.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Test-only deletions with no application code changes; CI coverage for
tests that actually ran is unchanged per PR checks.
> 
> **Overview**
> **Removes dead test code** that never executed in CI: unconditionally
skipped GPU/unit tests and the vendored HuggingFace AFMoE copy they
depended on.
> 
> Deleted the whole `tests/unit/train/models/afmoe_hf_modeling/` tree
(~777 lines) plus `test_afmoe.py`, since upstream `transformers` already
ships AFMoE and the module was skipped for flash-attention
incompatibility. Also drops skipped cases in `test_model.py` (sequence
packing, Meta Llama custom forward),
`test_fused_lm_head.py::test_full_model_fused_vs_vanilla`, and the
entire `test_nccl_broadcast.py` module.
> 
> `tests/conftest.py` loses the unused `free_port` fixture and its
`socket` import (only the NCCL test used it, and incorrectly).
`test_fused_lm_head.py` no longer imports `selective_log_softmax` after
removing the skipped full-model test.
> 
> **No production/runtime behavior change** — only fewer collected tests
(8 GPU-marked ids removed).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
61235f155a74f04ee3119deb9a4b557839313bec. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-05 16:34:20 -07:00
JannikStandGitHub b029ef253e fix(ci): move all 2-GPU GPU Tests jobs to h200 k8s runners (#3835)
Moves every GPU Tests job that fits in 2 GPUs onto the `prime-rl-2xh200`
ARC scale set, so runs stop queueing behind the two `vm` runners.
Stacked on #3834.

**Assignment**
- `prime-rl-2xh200` (9): unit-tests, reverse_text, reverse_text_sft,
reverse_text_sft_lora, reverse_text_lora, reverse_text_moe,
reverse_text_rl_opd, reverse_text_rl_sft, alphabet_sort, gsm8k_eval
- `4xa6000` (1): benchmark_regression, unchanged

The `vm` runners are left registered and untouched - just no longer on
the GPU Tests path.

**Sizing checks**
- Integration configs put inference on GPU 0 and trainer on GPU 1, so 2
GPUs each.
- Unit tests peak at `world_size=2` (NCCL broadcast test); `gsm8k_eval`
needs no GPU.
- benchmark_regression stays put: baselines are A6000-pinned
(`benchmark-4xa6000-*.json`) and the 4-GPU case exceeds a job pod. Note
`4xa6000` has zero registered runners today, so it queues regardless of
this PR.

**Worth knowing:** 12 tests in `test_deepseek_v4_kernels.py` are gated
on `requires_datacenter_gpu` (compute capability 9/10). They skip on
A6000 and will begin running on H200 - new coverage, but they have not
run in CI before.

Runners use `containerMode: kubernetes`, so `container:` blocks work
unchanged - each job gets a fresh pod, no Docker daemon, no privileged
containers.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> CI-only runner reassignment can surface new failures when
datacenter-GPU-gated unit tests run on H200 for the first time;
production code paths are untouched.
> 
> **Overview**
> **GPU Tests** CI now targets the `prime-rl-2xh200` Kubernetes runner
scale set instead of `vm` for every job that needs at most two GPUs.
> 
> The **unit-tests** job and nine **integration-tests** matrix entries
(`reverse_text*`, `alphabet_sort`, `gsm8k_eval`, etc.) all use
`prime-rl-2xh200`. **`benchmark_regression`** is unchanged on `4xa6000`
because it needs four GPUs and A6000-pinned baselines.
> 
> No test commands, containers, or matrix structure change—only
`runs-on` / `runner` labels. Unit tests on H200 may start executing
tests gated by `requires_datacenter_gpu` in
`test_deepseek_v4_kernels.py` that previously skipped on
`vm`/A6000-class hardware.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
579a43fe10fbd114a1bf935bd43917fc63873a18. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-05 19:50:31 +02:00
minh hoangandGitHub eae8bd9462 fix(docker): include FlashMLA in docker image (#3887)
Hosted image `v0.9.1.dev200` fails when GLM-5 selects `model.dsa_backend
= "cudnn_flashmla"`: the forward path imports `flash_mla`, but Docker's
explicit sync extras omit `flash-mla`. The [dev200 build
log](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/37265534904)
confirms the missing extra; `nvidia-cudnn-frontend` is already
installed.

Add `--extra flash-mla` to the dependency-image sync and the
source-override entrypoint sync. Add an amd64 package-presence check
before publishing the dependency image. The existing Linux/x86_64 marker
excludes the wheel on arm64, and the Dockerfile change invalidates the
dependency-image fingerprint.

## Verification

- Compared locked requirement exports with the exact Docker extras
before and after the fix: amd64 adds only the pinned FlashMLA wheel;
arm64 requirements are unchanged. Neither platform loses dependencies,
and both include `nvidia-cudnn-frontend==1.30.0`.
- Confirmed Docker and source-override entrypoint extras match.
- Downloaded the pinned CPython 3.12/CUDA 13/PyTorch 2.13 wheel and
verified its lockfile SHA256. Confirmed it exports
`flash_mla_sparse_fwd` and includes the native extension.
- Docker Buildx Dockerfile checks: no warnings. Bash syntax and `git
diff --check`: passed.

GPU import and execution checks on a rebuilt image are still pending.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Build-time dependency and publish-time presence checks only; arm64 is
unchanged because the extra is x86_64-gated in the lockfile.
> 
> **Overview**
> Adds the **`flash-mla`** optional dependency to CUDA image builds and
runtime source overlays so GLM-5 paths using `model.dsa_backend =
"cudnn_flashmla"` can import `flash_mla` in hosted images.
> 
> **`Dockerfile.cuda`** includes `--extra flash-mla` in the builder `uv
sync` (alongside the other GPU extras) and, on **x86_64 only**, asserts
`flash-mla` is present in the published dependency image via
`importlib.metadata`. **`scripts/docker-entrypoint.sh`** adds the same
extra to `uv sync` when `PRIME_RL_REF` overlays a checkout, keeping the
entrypoint extras list aligned with the Dockerfile comment.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
12329d455836ab80ac581e18de7339718312e7a9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-05 09:15:35 -07:00
faresobeidandGitHub c8af127357 chore: remove legacy config options (#3770)
Removes legacy config options and their code paths. They have had no
changes of their own in 4+ months.

## Removed
- **SGD optimizer** (`optim.type = "sgd"`): `SGDConfig`, its union
member, and the `torch.optim.SGD` branch in `trainer/optim`. AdamW,
Muon, and SignSGD stay.
- **`ckpt.skip_progress`** (orchestrator and trainer ckpt configs):
resume now always restores progress. This affects the orchestrator ckpt
loading and SFT resume.
- **`Jackmin108/` model-name special case** in
`validate_shared_model_name`. Trainer and orchestrator model names now
must always match when no inference config is given.

## Kept
- **`orchestrator.collect_inference_metrics`** stays, unchanged from
main. Hosted training uses Grafana for inference metrics and sets it to
`false` to turn off W&B mirroring. The `/metrics` poll for the
concurrency controller always runs either way.

## Also included (#3774, merged into this branch)
- `RLConfig`: top-level shared fields (including `resume`) go through
`propagate_shared_fields` only. The old `validate_shared_*` helpers in
`validation.py` are replaced by inline cross-component checks in
`RLConfig.validate_shared_configs`.

## Breaking changes
TOMLs/CLI args that set any of these now fail validation:
- `trainer.optim.type = "sgd"` (and `optim.momentum`, `optim.nesterov`)
- `orchestrator.ckpt.skip_progress`, `trainer.ckpt.skip_progress` (SFT
`ckpt.skip_progress`)

No configs, examples, docs, or skills in the repo reference these
options.

## Validation
- `pytest tests/unit -m "not gpu"` (excluding
`tests/unit/train/test_cpu_adam.py`, which needs `ninja` to build a C++
extension on this machine): 651 passed
- `ruff check .` and `ruff format --check .` (only `docs/algorithms.md`
is flagged, same as on main)
- GPU/integration tests were not run (no GPU on this machine).

Rebased on main f42630873; resolved conflicts in `configs/rl.py` and
`utils/validation.py` (main's #3788 already removed
`validate_shared_weight_broadcast`; kept that and this PR's removal of
the other `validate_shared_*` helpers).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking config validation for old TOMLs/CLI flags and stricter
cross-component model/resume rules; resume behavior changes if anything
relied on skipping progress restore.
> 
> **Overview**
> Removes **legacy config knobs** that are no longer supported:
**`optim.type = "sgd"`** (config type + `torch.optim.SGD` factory), and
**`ckpt.skip_progress`** on trainer/orchestrator checkpoints. Resume now
**always** restores orchestrator progress/curriculum state and SFT
training progress (step counter always advances after load).
> 
> **RL config validation** is consolidated: shared-field helpers in
`validation.py` are deleted in favor of
**`RLConfig.validate_shared_configs`** using a generic `require_equal`
check (model name, chat template, `max_steps`, `resume`, ckpt/W&B
parity, seq_len bound). Top-level **`resume`** is propagated via
**`propagate_shared_fields`** instead of a separate `auto_setup_resume`
validator; the **`Jackmin108/`** trainer/orchestrator model-name
exemption is gone.
> 
> CI slim-install smoke test imports **`propagate_shared_fields`** only.
Unit tests drop SGD from full-offload optimizer coverage.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1df3854c75fc652e2b0a5dbd7d019555e73736ba. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-05 11:53:03 +01:00
2b688edcf6 perf(dsa): cuDNN + FlashMLA kernels for GLM-5 sparse attention (model.dsa_backend) (#3829)
adding cudnn backward kernel for dsa, glm5 full training

- New `model.dsa_backend` flag: `tilelang` (default, old path) or
`cudnn_flashmla` (FlashMLA forward + cuDNN backward).
- GLM-5.3 SFT example: `base.toml` now uses `cudnn_flashmla`, and a new
`16k-12-node.toml` overlay runs 12 nodes at 16k (cp=1, no offloading,
fullgraph, full AC).

| Part | Old (`tilelang`) | New (`cudnn_flashmla`) | Kernel speedup
(H200) | Status |
|---|---|---|---|---|
| Sparse attention forward | TileLang | FlashMLA `flash_mla_sparse_fwd`
| 1.9–3.6× | Hopper tested; Blackwell built in the wheel, untested |
| Sparse attention backward | TileLang | cuDNN `dsa_bwd_sm90` | 3–4.7× |
Hopper tested; Blackwell wired in, untested |

Full GLM-5.3 (78 layers), H200, 16k.

**Fake data** (random init, balanced routing)

| setup | nodes | tok/s per GPU | MFU |
|---|---|---|---|
| original config (cp=2, offloading), `tilelang` | 8 | 465 | 22.3% |
| `16k-12-node.toml`, `tilelang` | 12 | 701 | 33.6% |
| `16k-12-node.toml`, `cudnn_flashmla` | 12 | 835 | 40.1% |

**Real weights + data** (INTELLECT-3-SFT-10K math, 12 nodes)

| `dsa_backend` | step | tok/s | MFU |
|---|---|---|---|
| `tilelang` | 31.2s | 50.4k | 25.2% |
| `cudnn_flashmla` | 24.2s | 64.9k | 32.5% |

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes sparse-attention forward/backward kernels and gradient
numerics (LSE/index flattening); `cudnn_flashmla` needs SM90+ and extra
deps, with SM100 paths noted as untested.
> 
> **Overview**
> Adds **`model.dsa_backend`** (`tilelang` default,
**`cudnn_flashmla`**) so GLM-5 DSA sparse MLA can use **FlashMLA sparse
prefill** forward and **cuDNN CuTe-DSL** backward instead of TileLang
for both directions. The trainer passes the setting through
`model_config` into `sparse_mla`, which now takes a `backend` argument;
autograd routes backward to the matching implementation and **normalizes
LSE to natural log** across paths (TileLang converts at the boundary).
> 
> Packaging adds **`nvidia-cudnn-frontend`** on the GPU extra, a
**`flash-mla`** optional extra (pinned x86_64 wheel), and lockfile
updates.
> 
> GLM-5.3 SFT examples: **`base.toml`** sets `dsa_backend =
"cudnn_flashmla"`; new **`16k-12-node.toml`** overlay documents 12-node
/ 16k training without CP or offloading; README expanded for both
setups.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0894aa8897544e3c2913b6a4274a3f9f7c6c9527. 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>
2026-10-04 21:54:55 -07:00
minh hoangandGitHub 883b8f32c5 feat(docker): reuse dependency images for fast Docker source builds (#3828) 2026-10-04 22:47:39 -06:00
faresobeidandGitHub 407e8ba223 refactor(algo): declare action_loss_type once on the config; drop finalize_group (#3845)
Two small cleanups in `orchestrator/algo/`. Item 4 of the orchestrator
review.

- `action_loss_type` is now declared once, on the algorithm config
classes. Before, it was declared on the config classes and again on the
runtime classes (`algo/base.py`, `sft.py`, `opd.py`, `opsd.py`), and
`build_algorithm` asserted that the two agreed. Now `Algorithm.__init__`
copies it from the config, so `train_sink`'s
`env.algorithm.action_loss_type` is unchanged.
- `Algorithm.finalize_group` is removed. It only called `score_group`,
and `train_sink` now calls `score_group` directly. `finalize_episode` is
kept: its "has sampled tokens" guard matters for `echo`, whose
`score_episode` does not filter on the mask.
- `docs/algorithms.md` is updated to match.

Behavior change: none. Every algorithm type gets the same loss routing
as before, because the old assert guaranteed that the config and runtime
values were equal.

## Checks
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 291 passed (`test_algorithms` covers the per-type
`action_loss_type`).
- `ruff check`, `ruff format --check`: clean.

GPU checks: none needed.

## Conflicts
`algo/base.py` and `algo/__init__.py`: #3802, #3803 (small). #3838 (fold
`GenerationSource`) also edits `algo/base.py` and `algo/__init__.py`
(`connect_frozen_client`), which needs a trivial rebase.
`train_sink.py:245`: #3652 rewrites `train_sink.py` (a one-line change
there).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Refactor-only: loss routing and group scoring call paths are unchanged
in effect; no auth, data, or trainer hot-path logic changes.
> 
> **Overview**
> **Single source of truth for loss routing:** runtime `Algorithm`
instances now take `action_loss_type` from the algorithm config in
`__init__` instead of duplicating it on each subclass and asserting
agreement in `build_algorithm`. Per-algorithm class variables on `OPD`,
`OPSD`, and `SFT` are removed; `train_sink` still reads
`env.algorithm.action_loss_type` when stamping samples.
> 
> **Thinner scoring API:** `Algorithm.finalize_group` is dropped and the
train sink calls `score_group` directly when a group has trainable
survivors. `finalize_episode` remains as the guarded entry point for
rollout-local `score_episode` (skips episodes with no trainable sampled
tokens).
> 
> **Docs:** `algorithms.md` is updated to describe this pipeline wiring
and config-owned `action_loss_type`.
> 
> No intended training behavior change—loss routing values are the same
as before when config and runtime matched.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1ebee7fec9fab8740b04de41e3aee9e89d4ca6d7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 16:56:44 -07:00
faresobeidandGitHub cf9962c13b refactor(orchestrator): fold packing.py into batch.py (#3842)
Moves `BatchPacker` (35 lines) from `orchestrator/packing.py` into
`orchestrator/batch.py` and deletes `packing.py`. The class only wraps
`build_bin_cost` and `prepare_batch`, which already live in `batch.py`.

Item 6 of the orchestrator review.

Behavior change: none (pure move; the import in `orchestrator.py` is
updated).

## Checks
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 291 passed
- `ruff check`, `ruff format --check`: clean
- `python -c "import prime_rl.orchestrator.orchestrator"` OK
- Equivalence: the class body is copied byte for byte (`git diff` shows
only the move and the import lines).

GPU checks: none needed.

## Conflicts
- #3840 (FLOP estimator): textual, in the `batch.py` imports only.
- #3652: its `Shipper` imports `BatchPacker` from `packing`, which
becomes a one-line change to `from prime_rl.orchestrator.batch import
BatchPacker`.
- #3819, #3836, #3794 touch other parts of `batch.py`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Pure file move and import path update with no logic changes to
training batch packing.
> 
> **Overview**
> **Colocates batch packing with the bin-packing helpers it already
delegates to.**
> 
> `BatchPacker` moves from `orchestrator/packing.py` into
`orchestrator/batch.py` next to `build_bin_cost` and `prepare_batch`;
`packing.py` is removed. The orchestrator now imports `BatchPacker` from
`batch` instead of `packing`. Class behavior and `pack()` semantics are
unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
986f5bf0f692cca69a2bf1d49bbec53b09ececef. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 16:50:30 -07:00
faresobeidandGitHub 34e26e39a5 chore(deps): drop duplicate and unused pyproject dependencies (#3856)
Removes duplicate and unused entries from `pyproject.toml` (rev-infra
P9). The set of installed packages does not change for any extra
combination (checked below).

| Removed | Reason |
|---|---|
| second `orjson>=3.10` in `dependencies` | Duplicate of
`orjson>=3.11.0` a few lines above. |
| `pandas>=2.0` | Nothing imports it: no `import pandas` / `pd.` in
`src/`, `tools/`, `scripts/`, `tests/`, `examples/`, `skills/`,
`packages/`. It was added for the nano bridge (7089ba1e4). It stays
installed because `datasets` depends on it. |
| `pyarrow>=21.0.0` | No direct use anywhere in those directories. The
one parquet writer, `tools/convert_traces_to_hf_dataset.py`, calls
`datasets.Dataset.to_parquet`, and `datasets` depends on `pyarrow`
itself. It stays installed. |
| `nixl-cu13==0.10.1` in the `disagg` extra | `disagg` already lists
`nixl`, and the `[[tool.uv.dependency-metadata]]` override for `nixl`
0.10.1 requires exactly `nixl-cu13==0.10.1`. The `gpu` extra keeps its
explicit pin, because `transports/weights/nixl/agent.py` imports
`nixl_cu13` directly. |
| `mamba-ssm` dependency group | Duplicate of the `gpu` extra entry,
which was added with the native Nemotron-H model (#3426). Every user of
the group also syncs `--extra gpu` or `--all-extras`, so I dropped
`--group mamba-ssm` from `Dockerfile.cuda` (2 places),
`scripts/docker-entrypoint.sh` and the `pre_run_command` in
`configs/advanced/nemotron-3-super/swe.toml`. The `[tool.uv.sources]`
git pin and the build dependencies for mamba-ssm stay. |

Behavior change:
- None for installs: same locked packages and versions.
- `uv sync --group mamba-ssm` no longer works; use `--extra gpu`, which
every repo caller already passes.
- `pandas` and `pyarrow` lose their direct lower bounds. They are still
pulled in by `datasets`.

## Checks
- `uv lock`: resolves 564 packages, the same set as before (568
`[[package]]` entries before and after). `uv lock --check` passes. The
`uv.lock` diff only touches prime-rl's own metadata. I reverted the
reordering of `[options.exclude-newer-package]` that my uv version
(0.12.10) introduced.
- I ran `uv export --frozen --all-packages` and compared the package
lists before and after, ignoring the `# via` comment lines. They are
identical for: no extras, `--extra disagg`, `--extra gpu`, `--extra
dashboard`, `--all-extras`, and `--all-extras --all-groups`. `--extra
disagg` still yields `nixl==0.10.1` and `nixl-cu13==0.10.1`, and
`--extra gpu` still yields `mamba-ssm` at the pinned rev.
- No Python changes, so no unit tests are affected. GPU: not needed. The
Docker image build in CI covers the Dockerfile and entrypoint edits.

## Conflicts
Text conflicts only in `pyproject.toml` / `uv.lock`, as with any
dependency PR. None of the open PRs that touch these files (e.g. #3829,
#3803, #3767, #3660) edit the lines removed here. A re-lock after rebase
is enough.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Metadata and sync-flag cleanup only; lockfile exports are unchanged
and runtime installs should match prior behavior.
> 
> **Overview**
> Cleans up **duplicate and redundant dependency declarations** in
`pyproject.toml` and aligns `uv.lock`, Docker, and Slurm sync commands
with the slimmer manifest. **No intended change to installed packages**
for existing extra combinations (`gpu`, `disagg`, `--all-extras`, etc.).
> 
> **Removed from core `dependencies`:** duplicate `orjson>=3.10`, unused
direct pins on `pandas` and `pyarrow` (they still come in via
`datasets`). **Removed from `disagg` extra:** explicit
`nixl-cu13==0.10.1` because `nixl` metadata already pulls that version;
the **`gpu` extra keeps** its explicit `nixl-cu13` pin for direct
imports. **Dropped the `mamba-ssm` dependency group** as a duplicate of
the `gpu` extra entry—`Dockerfile.cuda`, `scripts/docker-entrypoint.sh`,
and the Nemotron SWE `pre_run_command` no longer pass `--group
mamba-ssm`.
> 
> **Workflow note:** `uv sync --group mamba-ssm` alone is no longer
supported; use `--extra gpu` (or `--all-extras`), which callers already
use.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f0f2ff6b6365165a92be511c8029a47080f748e0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 16:49:27 -07:00
faresobeidandGitHub 8acaaf2baa docs(scaling): match ep="auto" to the code; NIXL wheel is nixl_cu13 (#3837)
Fixes two wrong statements in `docs/scaling.md` (from the whole-codebase
review, rev-infra P8 / rev-trainer §6). Docs only. No code or behavior
change.

- **`ep = "auto"`**: the doc said auto picks the largest divisor of
`num_experts` that divides the FSDP island, is a multiple of `cp`, and
is ≤ 8. The code (`trainer/parallel_dims.py:resolve_ep`) returns
`min(world_size // dp_replicate, 8)` for MoE models and 1 otherwise.
That matches the `ModelConfig.ep` docstring. The doc now describes what
the code does and says to set `ep` explicitly when the result does not
fit `cp` / `num_experts`.
- **NIXL wheel**: `scripts/install_nixl_from_source.sh` names the wheel
`nixl-cu13` (lines 85-88, 105). `docs/advanced.md:216` already says
`nixl_cu13-*.whl`, but `scaling.md` said `nixl_cu12-*.whl`, so that
install command did not match any file.

Checks: docs only. Compared against `resolve_ep` and the install script.

Conflicts with open PRs: none. No open PR touches `docs/scaling.md`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation-only corrections to scaling and install instructions; no
runtime or training behavior changes.
> 
> **Overview**
> Updates **`docs/scaling.md`** so it matches current behavior—no code
changes.
> 
> **Expert parallelism (`ep = "auto"`)**: Replaces the old description
(largest valid divisor of `num_experts` subject to FSDP island, `cp`,
and cap 8) with what **`resolve_ep`** actually does: for MoE,
`min(world_size // dp_replicate, 8)`; for non-MoE, `1`. The doc now
notes that auto does not consider `num_experts` or `cp`, and that you
should set **`ep`** explicitly when the resolved value fails those
constraints.
> 
> **NIXL install**: Changes the documented wheel from
`deps/nixl_cu12-*.whl` to **`deps/nixl_cu13-*.whl`**, consistent with
`scripts/install_nixl_from_source.sh` and other docs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
778befd26ff787ee71cb7308071a26542c9cc470. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 16:12:04 -07:00
faresobeidandGitHub f42630873d chore: remove Kubernetes deployment path (Helm chart, trainer metrics server) (#3767)
Removes the Kubernetes deployment path. The Helm chart has had no
functional change since its initial additions (last own change
2026-08-12 was a docs fix), and supported multi-node deployment is SLURM
(see docs/scaling.md). The trainer `metrics_server` (Prometheus
`/metrics` + `/health`) only existed to serve the chart's
liveness/readiness probes.

## Removed
- `k8s/` Helm chart (and `COPY k8s` from `Dockerfile.cuda`)
- `src/prime_rl/utils/metrics_server.py` (`MetricsServer`,
`HealthServer`) and its unit test
- `MetricsServerConfig` (configs/shared.py), trainer `metrics_server`
field, and its setup/update/teardown in `trainer/rl/train.py`
- Kubernetes sections/mentions in README,
`examples/basic/reverse-text/README.md`, `docs/training.md`; `k8s/`
TOMLs dropped from `test_configs.py`
- Inference `liveness_timeout_seconds` docstring reworded neutrally; the
`/liveness` endpoint stays (used by SLURM/router health checks)

`prometheus-client` stays in `pyproject.toml`:
`orchestrator/inference_metrics.py` still uses its parser.

## Breaking changes
- Trainer configs that set `metrics_server` now fail validation.
- The Helm chart and `/app/k8s` in the image are gone.

## Validation
- `pytest tests/unit/test_configs.py -m "not gpu"` (205 passed)
- `ruff check .` and `ruff format --check .`
- No GPU on the machine used; GPU/integration tests not run.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking for anyone using the Helm chart or trainer `metrics_server`
config; training/runtime core paths are unchanged but deployment and
observability options shrink.
> 
> **Overview**
> **Removes the Kubernetes/Helm deployment path** and related trainer
observability that existed mainly for chart probes.
> 
> The entire `k8s/` Helm chart (StatefulSets, services, PVC,
reverse-text example values/TOMLs, and `k8s/README.md`) is deleted.
**`Dockerfile.cuda`** no longer copies `k8s/` into the image, and
docs/README/example copy now describe **Slurm-only** multi-node
deployment (K8s sections dropped from `reverse-text` README).
> 
> **Trainer Prometheus/health HTTP server is removed:**
`MetricsServerConfig`, the `metrics_server` trainer config field,
`src/prime_rl/utils/metrics_server.py`, RL trainer
startup/update/shutdown hooks, and unit tests. Configs that still set
`metrics_server` will fail validation.
> 
> **Minor doc tweaks:** inference `liveness_timeout_seconds` help text
is generic (not K8s-specific); `env-server` docs refer to externally
managed hosts instead of pods. Config validation tests only scan
`configs/` and `examples/` TOMLs, not `k8s/`.
> 
> Inference `/liveness` and `prometheus-client` elsewhere (e.g.
orchestrator) are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
42e89b437dc19ae11abd0172672b89b9f03e6c30. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 23:49:24 +01:00
faresobeidandGitHub 1eeea3a047 chore: remove legacy dead code (#3769)
Removes legacy leftovers that were last touched 2025-11 to 2026-02 or
were orphaned by features that are already gone. Behavior does not
change.

- **`orchestrator/patches.py`**: deletes the OpenAI chat-type
monkeypatches, which were written for verifiers 0.1.8. The orchestrator
and eval processes no longer parse `ChatCompletion` or message objects
in-process. Rollouts run in separate env-server processes, which never
applied the patch, and `prefill_logprobs` reads the raw
`httpx.Response`.
- **`FileSystemWeightUpdateWorker.init_broadcaster`**: deletes this
no-op stub. `/init_broadcaster` is only called by the NCCL and NIXL
transports, whose workers define their own method. The stub took no
arguments, so the route could never have dispatched to it anyway.
- **`prime_rl.utils.utils` pathing re-export**: deletes the shim (its
TODO asked for this) and points the remaining imports at
`prime_rl.utils.pathing`. The shim's file-wide `noqa: F401` was hiding
three unused imports in `utils.py`; they are removed too.
- **`tests/unit/inference/test_serving_chat_with_tokens.py`**: deletes
this empty file.
- **`ConcurrencyController.record_episode`**: now takes only `tokens`.
`env_name`, `kind` and `duration` are left over from the removed per-env
cost model and were ignored. The dispatcher's `on_episode_complete`
callback type now matches, and the `ConcurrencyConfig` docstring no
longer mentions "learned per-env episode costs".
- **`@deprecate_kwarg("past_key_value", ...)`**: removed from the llama,
glm4_moe and glm_moe_dsa decoder layers. These layers never accepted
`past_key_value(s)`, and transformers is pinned to 5.6.2. The signatures
still accept everything their callers pass.

## Breaking changes
- `from prime_rl.utils.utils import get_ckpt_dir` (and the other pathing
helpers) no longer works. Import them from `prime_rl.utils.pathing`.
- `ConcurrencyController.record_episode(tokens)` and the
`Dispatcher(on_episode_complete=...)` callback now take one argument.
- `prime_rl.orchestrator.patches` no longer exists.

## Validation
- `ruff check .` and `ruff format --check .`
- `pytest tests/unit/orchestrator tests/unit/eval tests/unit/inference
tests/unit/train/models tests/unit/utils tests/unit/test_configs.py -m
"not gpu"`: 417 passed, 154 deselected
- Import check of every modified module.
- GPU and integration tests were not run: this machine has no GPU.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Mostly deletions and import-path changes with documented API breaks;
adaptive concurrency still uses token counts for growth gating.
> 
> **Overview**
> This PR deletes unused orchestration and compatibility shims and
tightens a few callback signatures. Runtime behavior for supported
entrypoints is intended to stay the same.
> 
> **Removed OpenAI monkey-patches** — `orchestrator/patches.py` and
startup calls in the orchestrator and eval runner are gone. Rollouts no
longer parse `ChatCompletion` in those processes.
> 
> **Concurrency hooks** — `ConcurrencyController.record_episode` and the
dispatcher `on_episode_complete` callback now only receive **token
count**; leftover per-env cost-model args were unused.
`ConcurrencyConfig` docs now describe KV-pressure sizing only.
> 
> **Misc cleanup** — Drops
`FileSystemWeightUpdateWorker.init_broadcaster`, the
`prime_rl.utils.utils` re-export of pathing helpers (call sites import
`prime_rl.utils.pathing` directly), `@deprecate_kwarg` on custom decoder
layers, and an empty inference unit test file.
> 
> **Breaking for downstream imports** — `prime_rl.orchestrator.patches`
is removed; pathing helpers must be imported from
`prime_rl.utils.pathing`; `record_episode` / `on_episode_complete` take
a single `int` argument.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
079daae952aeae8c1e6dd1a009ec3d950d0f4767. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 23:47:00 +01:00
JannikStandGitHub d9adc1e867 fix(dashboard): use relative static/api paths for path-prefixed reverse proxy (#3814)
Platform is adding a reverse proxy for the dashboard (platform#5719)
that forwards the bare path upstream with no prefix, so every
browser-side reference needs to be relative, not absolute.

- `index.html`: dropped the leading `/` from the icon, stylesheet, brand
image, and script `src`/`href` paths.
- `app.js`: the `api()` fetch helper now strips a leading `/` before
calling `fetch`, and the `EventSource("/api/view/events")` call is
relative too.
- `style.css` already only used `data:` URIs, no change needed.

Verification: served the static files through a throwaway reverse proxy
mounted under a sub-path prefix (mirroring the proxy's bare-path
forwarding), confirmed the HTML/JS no longer contain absolute `/static`
or `/api` references, and confirmed requests like
`.../prefix/static/app.js` and `.../prefix/api/runs` correctly resolve
relative to the page and reach the upstream dashboard.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> URL resolution-only changes for static assets and API/SSE calls; no
server or auth logic touched.
> 
> **Overview**
> Makes the dashboard work when it is served behind a reverse proxy that
mounts it under a sub-path and forwards **bare** paths upstream (no
`/prefix` on upstream requests).
> 
> **`index.html`** switches icon, CSS, images, and script tags from
root-absolute (`/static/...`) to **relative** (`static/...`) so assets
resolve against the current page URL.
> 
> **`app.js`** strips a leading `/` in the shared `api()` `fetch` helper
so existing `api("/api/...")` callers emit relative `api/...` URLs, and
changes the live view **`EventSource`** from `/api/view/events` to
`api/view/events`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9efe2aa17fc084cf71491dabd88e9b039ff40555. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 01:49:10 +02:00
faresobeidandGitHub 0bd0a71254 chore(orchestrator): remove token_batch_size batching (#3775)
Removes the orchestrator `token_batch_size` option (token-budget batch
cutting). Batches are now always cut by sample count (`batch_size`).

**Why:** the train sink had two parallel batch-cut paths. Sample-count
batching is the one every shipped config uses, including GLM-5.3.
Removing the token path drops the `pending_tokens` / `payload_tokens`
accounting and the token branches in `process_batch`, `_drop_stale`,
`_maybe_batch` and `_record_zero_output`.

**Changes**
- `OrchestratorConfig.batch_size` is now a plain `int = 128` field.
Before, it was `int | None` and the validator set the 128 default.
- Removed `token_batch_size` and the "set exactly one of batch_size or
token_batch_size" check. The `batch_size` divisibility check by group
size stays.
- `TrainSink` takes `batch_size: int` only. `batch_progress()` now
returns `(count, target)` without the unit string. Its only caller is
the orchestrator status log.
- `constant_trainer_batch_size` is unchanged. No metric keys changed.

**Breaking:** configs that set `orchestrator.token_batch_size` now fail
validation. Use `batch_size` instead. No config, example, doc or skill
in the repo set it.

## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 300 passed
- `ruff check .` and `ruff format --check .`: clean
- GPU and integration tests were not run (no GPU on this machine).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how train batches are formed at the orchestrator; configs
using token batching break, but sample-count batching behavior for
existing runs should be unchanged.
> 
> **Overview**
> Removes **token-budget batching** from the orchestrator so training
batches are always cut by **sample count** (`batch_size`).
> 
> `OrchestratorConfig` drops `token_batch_size` and the mutual-exclusion
validator; `batch_size` is now a required `int` defaulting to **128**
(no longer optional with a validator fallback). `TrainSink` only tracks
trace count for readiness, staleness drops, zero-output warnings, and
`process_batch`—`pending_tokens`, `payload_tokens`, and token-based
partial cuts are gone. `batch_progress()` returns `(count, target)`
only; pipeline status logs no longer show a traces/tokens unit.
> 
> **Breaking:** configs that set `orchestrator.token_batch_size` fail
validation; use `batch_size` instead.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
be797adb554eb5ba99aeb0cd3c3c210eac6e2e0d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 16:06:23 -07:00
faresobeidandGitHub a27c5f195a feat: opt-in exact prompt-mean loss aggregation for GRPO (#3798)
Adds `GRPOAlgoConfig.loss_aggregation: Literal["token", "prompt"] =
"token"`. `echo` gets it too because it subclasses GRPO.

**Why:** the trainer averages the `rl` loss over every loss token in the
batch. Prompts whose groups produce long trajectories therefore dominate
the gradient. SWE groups can differ by about 10x in total tokens.
`"prompt"` implements MiMo-V2.6's prompt-mean aggregation exactly (Eq.
1, p8): `L = mean_q (1/T_q) Σ_{i,t ∈ q} ℓ_{i,t}`. MiMo uses it to keep
response length from growing too fast.

**How:**
- **Trainer:** the `rl` component now divides by the global sum of its
per-token weights, not by the count of nonzero-weight tokens. Every `rl`
weight set in prime-rl today is 0/1, so the sum equals the old count,
and the default path is bit-identical to main. `ce` and `ref_kl` still
divide by their token counts. This is on purpose: echo's fractional `ce`
weight (`alpha`) must keep scaling the loss instead of cancelling out.
- **Orchestrator:** with `"prompt"`, `GRPOAlgorithm.score_group` gives
each trainable token of group q the `rl` weight `1/T_q`. `T_q` is the
group's trainable tokens, the same tokens the advantage is assigned to.
Each group's weights sum to 1, so the `rl` denominator becomes the
number of groups in the step, all-reduced across ranks like before.
There is no extra state.
- **Config:** a validator rejects runs that mix `"token"` and `"prompt"`
across envs with an `rl` loss. In a mixed batch, a whole prompt-mean
group would weigh as much as one token of a token-mean env.
- **Known difference from MiMo:** zero-advantage pruning still drops
zero-advantage tokens from `rl`. A group with a zero-advantage rollout
therefore keeps less than its full weight of 1. MiMo divides by all of
the group's tokens.
- **#3789 (length-weighted baseline):** compatible. Within a group the
weights are uniform, so a length-weighted baseline still keeps the
per-token advantage zero-mean.

**Breaking changes:** none for the default. One behavior change: an `rl`
weight stream with fractional weights would now be normalized by its
sum. Nothing in the repo produces such a stream today.

## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 301 passed. This includes an updated test in `test_advantage.py`:
each group's `rl` weights are exactly `1/T_q` and sum to 1, for two
groups of different length.
- Manual check that the config validator rejects mixed
`loss_aggregation` across envs.
- `ruff check .` and `ruff format --check .`: clean.
- Not run, because this machine has no GPU:
- `tests/unit/train/rl/test_loss.py`, which needs CUDA and also fails
here on main.
  - The trainer denominator change in `train.py`.
  - GPU and integration tests.
  - A training run.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how the RL loss denominator is computed globally; default
token aggregation should be numerically equivalent, but prompt-mean
alters gradient weighting for long trajectories and mixed configs are
blocked at validation time.
> 
> **Overview**
> Adds **opt-in prompt-mean RL loss aggregation** for GRPO and echo via
`loss_aggregation = "prompt"` (default `"token"` stays unchanged).
> 
> When enabled, **`GRPOAlgorithm.score_group`** stamps each trainable
token with `rl` weight `1/T_q` so each prompt group’s weights sum to 1
(MiMo-style prompt mean). The **trainer** now normalizes the `rl`
component by the **global sum of `rl_weights`** (not nonzero-token
count); with the default 0/1 weights this matches prior behavior. **`ce`
/ `ref_kl`** still divide by token counts so fractional echo `ce`
weights behave correctly.
> 
> **Orchestrator config** rejects mixing `"token"` and `"prompt"` across
envs that use an `rl` loss. **Docs** describe the knob; a **unit test**
checks per-group `rl` weights sum to 1.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
91cf0629f13c3fa39d7c78f476e549b097efa025. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 16:02:59 -07:00
faresobeidandGitHub c8ce6fa283 chore(trainer): remove HF model-implementation fallback (model.impl) (#3773)
## What

Removes the Hugging Face model-implementation fallback (`model.impl =
"hf"`). The trainer now only builds PrimeRL model implementations
(`src/prime_rl/trainer/models/`). An unsupported architecture fails at
setup with `'<model_type>' has no PrimeRL model implementation`.

- `model.impl` is removed. With `"hf"` gone, `"auto"` and `"custom"`
resolved to the same thing.
- `trainer/model.py`: removed impl resolution, `AutoModelForCausalLM` /
`AutoModelForImageTextToText` loading, the CPU-load fallback
(`can_reinit_empty_buffers`, `fix_model_post_empty`), HF weight
re-tying, the HF router-freeze branch, and the HF output handling in
`forward`.
- Removed `lm_head_gemma.py` and its hook in `inject_prime_lm_head`. It
only served HF-impl models with final-logit softcapping.
- Removed the HF CP patches (`substitute_hf_flash_attn`,
`substitute_hf_ulysses_attn`). The config already rejected CP for the HF
impl.
- Removed the `qwen3_vl`, `qwen3_vl_moe` and `gemma4` entries from the
trainer VLM registry. They could only be loaded through the HF path.
Orchestrator and inference multimodal adapters are unchanged.
- Removed the config validators that only checked `impl` (EP, CP, FA4,
quantization, router replay, VLM, trust_remote_code).
- `hendrycks-sanity` (`examples/basic`, `configs/basic`,
`configs/ci/nightly-fft`) used
`deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` (Qwen2 architecture, which
has no PrimeRL implementation). It now uses `Qwen/Qwen3-1.7B`. No other
settings changed.
- Dropped `impl = ...` from all configs/examples/docs, and updated
README, docs, and tests.
- `test_fused_lm_head.py`: the HF-model tests now use a tiny PrimeRL
Qwen3 (same config as #3768, which removes PrimeRL Llama), built in bf16
because the PrimeRL attention is FlashAttention-only (the fp32 build
failed CI with `FlashAttention only supports fp16, bf16, and fp8_e4m3`).

## Why

The HF fallback is an aging path: added 2025-09, last changed on its own
on 2026-07-17. It keeps a second loading, buffer-reinit, LM-head and CP
code path alive next to the custom implementations. After the
hendrycks-sanity switch, custom implementations cover every shipped
example and config.

## Breaking changes

- `model.impl` / `--trainer.model.impl` is no longer accepted. Configs
that set it fail validation (`extra_forbidden`), so delete the line.
- Architectures without a PrimeRL implementation (for example Qwen2,
Gemma, Qwen3-VL, Mistral) can no longer be trained.
- hendrycks-sanity now trains `Qwen3-1.7B`. Its dataset
(`mikasenghaas/Sanity-Test-R1D-1.5B`) was filtered to problems that
R1-Distill-Qwen-1.5B solves 20-80% of the time, and that band was not
measured for Qwen3-1.7B. **The expected reward, curves, and the nightly
thresholds (`MIN_TRAIN_REWARD = 0.75`, the mismatch-KL band in
`tests/nightly/test_hendrycks_sanity.py`) need GPU re-validation.**

## Validation

- `pytest tests/unit/test_configs.py tests/unit/train -m "not gpu"`: 356
passed, 2 failed. The 2 failures are in `test_cpu_adam.py` (ninja is
missing on this machine). They fail the same way on `origin/main`.
- `ruff check .` and `ruff format --check .`: clean.
- `test_fused_lm_head.py` inject tests: checked on CPU that the tiny
Qwen3 resolves to `flash_attention_3` / `FlashAttention`; the GPU run is
left to CI.
- Manual CPU check: `get_model` builds `Qwen/Qwen3-1.7B` on the meta
device, and a Qwen2 config raises the new setup error.
- Not run: GPU unit tests (including the edited `test_fused_lm_head.py`,
`test_model.py`, `qwen3_5/test_vlm.py`), integration tests, and nightly
runs. There is no GPU on this machine.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> This is a breaking API and behavior change: unsupported architectures
hard-fail, and the hendrycks-sanity model swap can invalidate nightly
reward/KL gates until re-validated on GPU.
> 
> **Overview**
> **Removes the Hugging Face training path** by deleting `model.impl`
(`hf` / `custom` / `auto`). The trainer always loads PrimeRL classes
from `src/prime_rl/trainer/models/`; unknown `model_type` values fail at
setup with a clear error.
> 
> **Trainer/runtime cleanup:** `get_model` no longer branches to
`AutoModelForCausalLM` or HF VLMs, drops the CPU/meta fallback
(`can_reinit_empty_buffers`, `fix_model_post_empty`), and always uses
PrimeRL weight conversion and `init_buffers_post_meta`. **Removed**
Gemma softcapped LM head (`lm_head_gemma.py`), HF context-parallel
patches, and HF-specific MoE router freeze / forward handling.
> 
> **Config & docs:** `impl = "custom"` (and related validators tying EP,
CP, VLM, etc. to `impl`) are stripped from Pydantic configs, examples,
and docs. VLM registry narrows to Qwen3.5 families (drops `qwen3_vl`,
`gemma4` trainer paths). Sampling-replay docs no longer mention Gemma
rejection.
> 
> **Hendrycks sanity** now trains **`Qwen/Qwen3-1.7B`** instead of
`DeepSeek-R1-Distill-Qwen-1.5B` (no PrimeRL Qwen2 impl); dataset
filtering is still keyed to the distill model’s 20–80% band.
> 
> **Breaking:** configs with `model.impl` fail validation;
Qwen2/Gemma/Qwen3-VL and other unregistered archs cannot be trained.
Nightly sanity thresholds may need re-baselining on GPU.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3524e2eeabd2642b1e607a0b59ff0af6489ad3a8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

rebased on main 243cfba0f; resolved conflicts in
src/prime_rl/trainer/model.py (kept main's parallelize_module import),
src/prime_rl/utils/vlm.py (kept native qwen4_exp from #3434), and
dropped configs/basic/hendrycks-sanity + configs/debug/concurrency.toml
(deleted on main by #3777).
2026-10-03 15:45:27 -07:00
samsjaandGitHub 4c7c0d5d18 feat(configs): default optim.weight_decay to "auto" (0.0 for RL, 0.01 for SFT) (#3815)
## Summary

`optim.weight_decay` defaults to `"auto"` and resolves per trainer at
config-construction time: **`0.0` for RL**, **`0.01` for SFT** (the
historical default). Explicit values are untouched.

Follow-up to #2422, which flipped the shared default to `0.0` for both
trainers. Resolving per trainer keeps the RL motivation (no silent L2
decay of the policy during reward optimization) without changing SFT
behavior.

## How it works

Same pattern as `model.moe_router_dtype = "auto"`:

- `BaseOptimizerConfig.weight_decay` is now `Annotated[float,
Field(ge=0)] | Literal["auto"] = "auto"`.
- A `resolve_weight_decay_auto` model validator on `TrainerConfig` (RL)
resolves to `0.0`, and one on `SFTConfig` resolves to `0.01`.
- Because resolution happens at model construction, dumped configs
(`trainer.json` / `sft.json`) and `--help` always show the concrete
float — a resumed or reparsed run never sees `"auto"`.
- TOML / JSON / CLI overrides all keep working, including `weight_decay
= "auto"` explicitly.

| Trainer | `weight_decay` default |
| ------- | ---------------------- |
| RL (`rl`, `trainer`) | `0.0` |
| SFT (`sft`) | `0.01` (unchanged) |

## Notes

- Example configs that already set `weight_decay` explicitly are left
as-is; `examples/basic/wiki-search/rl.toml` and
`examples/advanced/glm-5.3/swe.toml` (`0.0`) now match the default and
could be simplified in a follow-up.
- LoRA runs resolve the same way (the optimizer is built from the same
`config.optim`).

## Testing

-
`tests/unit/test_configs.py::test_weight_decay_auto_resolves_per_trainer`
covers defaults, explicit floats, and the explicit `"auto"` string.
- Verified end-to-end locally: defaults, `RLConfig` sub-config,
`dump_resolved_config` output, TOML round-trip through `cli()`, and the
param group the optimizer receives.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Config-default change only at construction time; RL gets no weight
decay by default while SFT behavior stays at 0.01 unless users override.
> 
> **Overview**
> **`optim.weight_decay` now defaults to `"auto"`** on shared optimizer
config instead of a fixed `0.01`. At config construction, each trainer
resolves it to a concrete float—the same pattern as
`model.moe_router_dtype`.
> 
> RL **`TrainerConfig`** maps `"auto"` → **`0.0`** so policy training
does not apply L2 decay toward zero by default. SFT **`SFTConfig`** maps
`"auto"` → **`0.01`**, preserving the historical supervised default.
Explicit numeric values (and leaving `"auto"` in user input until
validation) behave as before; resolved dumps should show floats, not
`"auto"`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5219af74484473a3b4d884ec0569530e3521fa93. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 15:24:19 -07:00
faresobeidandGitHub 1f537d187b feat(trainer): MoE expert-load metrics (cv, max/mean, cold fraction) (#3799)
## What

Adds step-level MoE expert-load metrics to the RL and SFT trainers,
logged as mean and max over MoE layers:

- `expert_load/cv/{mean,max}`: std/mean of the per-expert token counts
in a layer.
- `expert_load/max_mean/{mean,max}`: the busiest expert's count divided
by the mean count.
- `expert_load/cold_frac/{mean,max}`: the fraction of experts that
receive under 0.1x the mean count. This is the MiMo-V2.6 §5.4
definition, so values compare directly with the paper.

## Why

MiMo-V2.6 §5.4 uses these three numbers to show that a trainable router
collapses expert load during RL (CV 0.78→2.0, cold experts 0.5%→22%
within 20 steps) and that freezing the router prevents it. We need the
same evidence to validate #3797 (freeze the router by default for RL) on
our models. The metrics also help catch EP load imbalance.

## How

- The MoE layers already add routed-token counts into the
`tokens_per_expert` buffer inside the forward pass. This uses the
existing `record_moe_routing_statistics` custom op, so it works with
compile without graph breaks. It covers both the torch and DeepEP
dispatch paths because the counts come from the router. **No model or
compiled code changes.**
- `get_global_moe_stats` now also returns this rank's raw per-layer
counts for the micro-step, captured before the existing EP reduction and
reset. The train loop sums them over the step. At step end, one
`all_reduce(SUM)` over `dp_cp` (which includes the EP ranks) produces
global counts, and the stats are computed from them. Extra cost: one
`[num_moe_layers, num_experts]` add per micro-step and one all-reduce
per step.
- Only aggregates over layers are logged, with no per-layer keys. This
follows the existing `max_vio`/`routing_confidence` convention, which
also reduces over layers. It also keeps the key count fixed for 75-layer
models. The max over layers catches a single collapsing layer, like
MiMo's layer 9.
- `max_vio` and `routing_confidence` are unchanged: they are still
per-micro-step.
- `docs/training.md` describes the new metrics.

No breaking changes. Existing metric keys are unchanged;
`get_global_moe_stats` now returns `(stats, tokens_per_expert)`
(internal function).

## Validation

- `pytest
tests/unit/train/models/{test_moe,test_checkpointing,test_qwen3_moe,test_glm4_moe,test_gpt_oss,test_deepseek_v4_cpu}.py
tests/unit/train/test_model.py tests/unit/test_configs.py -m "not gpu"`:
243 passed. This includes one new CPU test of the metric computation.
- `ruff check .` and `ruff format --check .`

Not run: there is no GPU on this machine. GPU checks still needed:
- [ ] EP>1 run (torch and DeepEP dispatch): `expert_load/*` values are
identical across ranks and plausible.
- [ ] Compiled run: no new recompiles or graph breaks
(`TORCH_LOGS=recompiles`).
- [ ] A short RL run with a frozen router vs a trainable router: the
trainable run should show `cv`/`cold_frac` rising.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Logging-only path using existing routing counters plus one optional
all_reduce per MoE step; no changes to loss, routing, or model forward
behavior.
> 
> **Overview**
> Adds **step-level MoE expert-load observability** aligned with
MiMo-V2.6 §5.4: trainers now log
`expert_load/{cv,max_mean,cold_frac}/{mean,max}` (coefficient of
variation, hottest-expert/mean ratio, and fraction of “cold” experts
under 0.1× mean load), aggregated as mean and max over MoE layers.
> 
> **Implementation:** `get_load_balance_stats` captures each rank’s
per-layer `tokens_per_expert` before EP reduction; micro-steps
accumulate counts across the step; `get_expert_load_stats` sums globally
over `dp_cp` and computes the three stats. Existing per-microstep
`max_vio` and `routing_confidence` logging is unchanged. RL and SFT
training loops wire the new metrics into step logs; `docs/training.md`
documents how to read them (e.g. rising `cv`/`cold_frac` when a
trainable router drifts).
> 
> A CPU unit test covers `compute_expert_load_stats`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9dde6e6ac625b4469c67ad2d20350d1bfbde9311. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 14:19:49 -07:00
faresobeidandGitHub f6fc1f7adc refactor(configs): define the weight-broadcast config once (#3788)
## Summary

The weight-broadcast config (filesystem | nccl | nixl) was declared four
times: the inference `WeightBroadcastConfig`, the trainer
`*WeightBroadcastConfig`, the orchestrator `*WeightBroadcastConfig`, and
the rl.py `Shared*WeightBroadcastConfig`.
`RLConfig.auto_setup_weight_broadcast` then copied each field between
them by hand. Every new transport field had to be added in four places
and in the copy code.

Design: one discriminated union `WeightBroadcastConfig` (`FileSystem` /
`NCCL` / `NIXL` variants) in `configs/shared.py`. The trainer,
orchestrator, inference, RLConfig, SFTConfig and the online eval config
all use it.
- `auto_setup_weight_broadcast` now does `model_copy()` of
`[weight_broadcast]` into the trainer and orchestrator, and sets
`inference_world_size` for in-memory transports. Inference gets a plain
copy. The inference server still reads only `type`.
- `validate_shared_weight_broadcast` is deleted. All three sub-configs
are now copies of the same object, so their types can't differ.
- SFT assigns the whole object to inference instead of mutating
`inference.weight_broadcast.type`.
- All three transports are kept.

Net: 82 lines added, 223 removed. Three class hierarchies, the
field-copy mapping and one validator are gone. No new abstractions.

## Breaking changes (all minor)

- `[weight_broadcast]` in `rl` now accepts `inference_world_size`. Like
before, the value is ignored: rl computes it.
- `[inference.weight_broadcast]` now accepts the transport fields
(`host`, `port`, `timeout`, ...). The inference server ignores them. The
resolved `inference.json` now contains them.
- Standalone `trainer.weight_broadcast.inference_world_size` must now be
`>= 1`. This matches the orchestrator, which already enforced it.
Before, `0` was accepted.
- Import paths: the classes now live in `prime_rl.configs.shared`. They
are no longer in `prime_rl.configs.trainer`, `.orchestrator` or
`.inference`.

## Validation

- Throwaway script (not committed): for every TOML in `configs/` and
`examples/`, parse it with every config class, plus sibling-base
overlays such as `glm-5.3/swe.toml @ swe-llmd.toml`. Dump the resolved
config on base and on this branch, then diff. Also covered: CLI cases
for rl/trainer/orchestrator/inference/sft with nccl/nixl/filesystem and
custom host/port/timeout/session_id. The only differences are the
additive or tightened cases listed under breaking changes. The trainer
and orchestrator `weight_broadcast` values are identical everywhere,
including glm-5.3 `swe.toml`, `swe.toml@swe-llmd.toml` and
nemotron-3-super.
- `rl --dry-run` / `sft --dry-run` on base vs branch for glm-5.3 swe,
glm-5.3 swe+llmd, nemotron-3-super swe, minimax-m2.5 swe, glm-4.5-air
swe+2-node, reverse-text (nccl and nixl), reverse-text sft and dynamo.
After normalizing paths, `trainer.json`, `orchestrator.json`, env
configs and `rl.sbatch` are byte-identical. `inference.json` only gains
the extra `weight_broadcast` fields.
- `pytest tests/unit -m "not gpu"`: 683 passed. 1 failure
(`test_cpu_adam`) also fails on main.
- `ruff check` and `ruff format --check` pass.
- No GPU on this machine, so GPU and integration tests (actual NCCL/NIXL
transfers) were not run.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches how RL/SFT wire trainer–orchestrator–inference weight transfer
(NCCL/NIXL sizing and config propagation); behavior is intended to match
prior dry-runs but import-path and validation changes could break custom
configs.
> 
> **Overview**
> **Consolidates trainer-to-inference weight broadcast settings** into a
single discriminated union (`filesystem` / `nccl` / `nixl`) in
`prime_rl.configs.shared`, removing parallel class hierarchies that
lived under trainer, orchestrator, RL `Shared*`, and manual per-field
copying.
> 
> `RLConfig.auto_setup_weight_broadcast` now **`model_copy()`**s the
shared `[weight_broadcast]` onto trainer and orchestrator (auto-filling
`inference_world_size` for in-memory transports) and sets inference to a
type-only config. **SFT** does the same for inference instead of
mutating `.type` alone. **`validate_shared_weight_broadcast`** is
dropped because all components share one schema.
> 
> Weight transport code (`transports/weights/*`, online eval) **imports
the shared types** instead of `configs.trainer`. Minor behavior/doc
shifts: RL rejects user-set `inference_world_size`, standalone trainer
enforces `inference_world_size >= 1`, and resolved `inference.json` may
include full broadcast fields the server ignores.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
937fc8a870e5559f40bc390653dd6c45dbd912d5. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 14:11:26 -07:00
faresobeidandGitHub 716d1cfac8 feat(orchestrator): optional length-weighted GRPO baseline (#3789)
Adds `length_weighted_baseline: bool = False` to `GRPOAlgoConfig`.

When enabled, the GRPO group baseline is the token-length-weighted mean
reward `b = sum_i(L_i * r_i) / sum_i(L_i)` instead of the plain mean.
`L_i` is the number of trainable (mask-True, policy-sampled) tokens of
rollout `i`, summed across all turns. Advantage is `r_i - b`. The
baseline is applied after the length penalty, same as the plain mean.
There is no fallback for a group with zero trainable tokens: then every
trace has `L_i = 0`, so `assign_advantages` writes no tokens, and no
metric, annotation or sample reads the (NaN) baseline.

Why: with token-level loss normalization, long rollouts carry more
gradient weight. A length-weighted baseline makes the per-token
advantage zero-mean across the group's tokens instead of across
rollouts.

- `routing.py`: pulls the trainable-node selection out of
`assign_advantages` into `trainable_nodes(trace)`, so `L_i` counts
exactly the tokens that receive the advantage.
- `echo` inherits the option because it subclasses GRPO.
- With the flag off, results are bit-identical to today: same `rewards -
rewards.mean()` computation.
- No breaking changes.

## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 301 passed. Includes the new
`test_grpo_length_weighted_baseline`, which covers the flag alone and
the flag combined with the length penalty (ordering).
- `ruff check .` and `ruff format --check .`: clean.
- GPU and integration tests were not run (no GPU on this machine).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Opt-in GRPO baseline change with default off; touches advantage math
only on the orchestrator scoring path, with targeted unit tests.
> 
> **Overview**
> Adds an opt-in **`length_weighted_baseline`** flag on GRPO-family
config (`GRPOAlgoConfig`, inherited by `echo`). When enabled, the group
baseline becomes the trainable-token-weighted mean of
(length-penalty-)shaped rewards instead of a plain rollout mean, so
advantages are **zero-mean per token** rather than per rollout—aligned
with token-normalized RL loss when long completions dominate gradient
mass.
> 
> **`GRPOAlgorithm.score_group`** now computes `shaped_rewards` first,
then either `mean(shaped_rewards)` or `sum(L_i * r_i) / sum(L_i)` with
`L_i` counting mask-True policy tokens across turns.
**`routing.trainable_nodes`** is extracted so `L_i` matches the tokens
that receive broadcast advantages via `assign_advantages`. Default
`false` preserves the existing centered-mean behavior.
> 
> Docs describe the math and ordering (after length penalty). Unit tests
cover the flag alone and combined with linear length penalty.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8f8d988d4957d02e61f28dfe0e46b1af3fefab7d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 14:00:33 -07:00
faresobeidandGitHub 87766fda3c refactor(launcher): share local launch-and-monitor code between rl and sft (#3792)
Unifies the local launch-and-monitor code in `rl_local` and `sft_local`.
Before this PR, both repeated the same machinery: Popen → log file →
monitor thread → error queue → SIGTERM/Ctrl-C/exception cleanup, GPU
partitioning from `CUDA_VISIBLE_DEVICES`, and the trainer torchrun
command. Each copy had small differences, which made the two launchers
drift.

## Design
`utils/process.py` already holds the launcher primitives
(`monitor_process`, `cleanup_processes`, env defaults). This PR adds
three small pieces there:
- `ProcessGroup`: a context manager. `start(name, cmd, env, log_path)`
starts a process with its log file and monitor thread. `wait(*names)`
blocks until the named processes exit and fails fast (exit 1) on the
first error from any process. SIGTERM, Ctrl-C, exceptions and normal
exit all clean up every process. The messages and ordering are the same
as the old inline code.
- `partition_gpus(num_infer, num_train)`: splits the physical GPUs into
inference GPUs followed by trainer GPUs, and raises the same
`ValueError` as before.
- `torchrun_cmd(module, config_path, nproc, log_dir, ranks_filter)`: the
shared single-node trainer command.

`rl_local` and `sft_local` keep their own commands and env dicts
unchanged. Only the plumbing moves. Net: −126 lines.

`inference.py` is not changed. Its only subprocess is the vllm-router.
The router inherits stdout (no log file), and its watcher SIGTERMs the
inference process itself. That does not fit the start/monitor/fail-fast
pattern, and forcing it in would change behavior. `eval.py` env servers
are also unmonitored on purpose, so they stay as they are. SLURM
rendering is not touched.

## Behavior
Behavior is the same: commands, env vars (including key order), log
paths, start order, kill order, exit codes and info/warning/error logs.
Two small differences:
- rl `--log-level debug` "command" lines now read `Inference command:
...` / `Train env server <name> command: ...` / `Trainer command: ...`
instead of `... start command: ...`.
- The rl wait loop is now the sft one: it checks errors before it checks
completion. Before, if the trainer failed *after* the orchestrator had
already exited, rl logged `Trainer failed with exit code N` from a
post-loop check. Now it logs `Error: Trainer failed with exit code N` /
`Terminating all processes...`. The exit code (1) and cleanup are the
same. The post-loop returncode checks could no longer be reached, so
they are removed. Side effect: if inference or an env server crashes in
the last ~1s, when the trainer and orchestrator also finish, the run now
fails instead of being ignored.

No config, metric, or checkpoint changes. No breaking changes.

## Validation
- I ran a throwaway (uncommitted) script against `rl_local`/`sft_local`,
once on `origin/main` and once on this branch, and diffed the results.
It fakes `subprocess.Popen` and `cleanup_process`, pins the free port,
uuid and `CUDA_VISIBLE_DEVICES=3,5,6,7`, and records each launch's exact
cmd, env delta, log path, kill sequence, exit code and logs. Configs:
reverse-text `rl.toml`, `configs/debug/multi-env/rl.toml`, reverse-text
`sft.toml` (online eval + inference), `configs/debug/fake/sft.toml`.
Scenarios: success;
trainer/orchestrator/inference/env-server/online-eval failure; trainer
failing after the orchestrator exits; SIGTERM; SIGINT; too many GPUs
requested. All records and exit codes were identical. The only log
differences are the two listed above.
- `pytest tests/unit -m "not gpu"`: 683 passed, 1 failed. The failure is
`test_cpu_adam.py::test_native_cpu_adamw_matches_fused_torch_and_preserves_gradients`,
which also fails on `origin/main` on this machine.
- `ruff check .` and `ruff format --check .` pass.
- No GPU on this machine, so I did not run any real launch or
integration test.

## Reviewer GPU checks (not run here)
- rl reverse-text e2e exits 0, and inference/env servers have no late
non-zero exits.
- SIGTERM and Ctrl-C mid-run leave no vLLM or torchrun workers.
- Trainer and inference logs are unchanged.
- sft with online eval waits for the eval to drain before it exits.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches core multi-process launcher lifecycle (spawn, monitor,
teardown) for training runs; behavior is mostly preserved but wait/error
ordering changes can alter exit outcomes at run end.
> 
> **Overview**
> **Refactors local RL and SFT launchers** so they no longer duplicate
subprocess orchestration; shared behavior lives in
`prime_rl.utils.process`.
> 
> Adds **`ProcessGroup`** (context manager with `start` / `wait`),
**`partition_gpus`**, and **`torchrun_cmd`**. Both `rl` and `sft`
entrypoints now start inference, env servers, orchestrator/online-eval,
and trainer through `ProcessGroup` instead of inline `Popen`, monitor
threads, error queues, and hand-rolled SIGTERM/Ctrl-C cleanup.
> 
> Commands, env vars, log paths, and start order are intended to stay
the same. **Minor differences:** debug log lines drop the `"start"`
prefix on command logs; RL’s wait loop now checks the error queue before
completion (aligned with SFT), so late failures from non-terminal
processes (e.g. inference/env server in the last second) can fail the
run where RL previously might have exited successfully.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fb27b22cf76aa28b094caedb07a646b7d5db7c7e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 13:53:33 -07:00
faresobeidandGitHub 73c4736352 refactor: move packing to orchestrator, DSv4 eager reference to tests, inline conversion_utils (#3785)
Pure moves + import updates. No logic change.

**Design / target structure**
- `trainer/batch.py` -> `orchestrator/batch.py`. Only
`orchestrator/packing.py` uses it. Nothing in `trainer/` imports it. Its
test already lives at `tests/unit/orchestrator/test_batch.py`.
- `trainer/models/deepseek_v4/eager_reference.py` ->
`tests/unit/train/models/deepseek_v4_eager_reference.py`. Only the DSv4
tests import it. Its docstring says nothing in production calls it.
- `trainer/conversion_utils.py` (one 10-line function) is inlined into
`transports/weights/nccl.py`, its only user.

**Left as is (not equivalent)**
- FLOPs models: `orchestrator/batch.py` (forward-cost coefficients for
bin balancing) and `trainer/perf.py` `_get_num_flop_per_token` (train
FLOPs for MFU, LoRA-aware) give different numbers. For example, o_proj
is `2*h*h` vs `h*heads*head_dim`, router params are counted only in
perf, and attention uses `head_dim` vs `h/heads`. On Qwen3-0.6B/1.7B,
Qwen3-VL-4B, Qwen3.5-2B and debug-moe they differ by 4-11%, so merging
them would change either the packing or the MFU metric.
- `list_shards` duplicate in `tools/convert_fp8_to_bf16.py` and
`tools/convert_bf16_to_fp8.py`: kept so `convert_fp8_to_bf16.py` stays
standalone (torch + safetensors only, no `prime_rl` import).
- Blockwise FP8 dequant: the tools version takes the block size from
`quantization_config` and handles shapes that are not multiples of the
block (via ceil + slice). The DSv4 version infers the block size from
the shape ratio, needs exact divisibility, and also handles MXFP4. They
are not interchangeable.
- `tools/convert_dcp_to_fp8.py` sibling imports: these already work from
the repo root and from any cwd. Python puts the script's directory on
`sys.path`, and the same holds under `torchrun`. I checked `--help` from
the repo root and from `/tmp`. No change needed.

**Breaking changes**
- Import paths: `prime_rl.trainer.batch` ->
`prime_rl.orchestrator.batch`. `prime_rl.trainer.conversion_utils` and
`prime_rl.trainer.models.deepseek_v4.eager_reference` are removed from
the package.

**Validation**
- `pytest tests/unit/orchestrator/test_batch.py
tests/unit/train/models/test_deepseek_v4_cpu.py
tests/unit/train/models/test_deepseek_v4.py
tests/unit/train/models/test_deepseek_v4_kernels.py
tests/unit/transports tests/unit/train/test_perf.py -m "not gpu"`: 31
passed, 97 deselected. Both DSv4 test modules import fine. No GPU on
this machine, so the GPU DSv4 tests and integration tests were not run.
- `ruff check .` and `ruff format --check .` both pass.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Import-path-only refactor with inlined helper code; no training,
packing, or NCCL broadcast logic changes, aside from downstream breakage
if anything still imports the removed modules.
> 
> **Overview**
> This PR reorganizes modules so orchestrator-only, test-only, and
single-use code no longer lives under `trainer/`. **Batch packing**
moves from `prime_rl.trainer.batch` to `prime_rl.orchestrator.batch`,
with `packing.py` and orchestrator unit tests updated to the new import
path.
> 
> **DeepSeek V4 eager reference** implementations move out of the
production package into
`tests/unit/train/models/deepseek_v4_eager_reference.py`; DSv4 GPU tests
import from there instead of
`prime_rl.trainer.models.deepseek_v4.eager_reference`.
> 
> **Layer counting for NCCL weight broadcast** drops the standalone
`trainer/conversion_utils.py` module: `get_max_layer_num` is defined
inline in `transports/weights/nccl.py`, its only caller. Behavior is
unchanged; callers must switch imports for batch and remove use of the
deleted trainer modules.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9287ae8ce22ba8731b80ebc1634ee0d5bbb25ea3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 13:42:11 -07:00
178 changed files with 2751 additions and 5716 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
# .git stays: docker-editable-pretend-versions.sh reads .git/modules via the bind mount.
.git
**/.git
outputs
**/.venv
**/__pycache__
+46 -9
View File
@@ -172,7 +172,7 @@ jobs:
- name: Checkout
uses: actions/checkout@v7
with:
ref: ${{ needs.prepare.outputs.ref }}
ref: ${{ needs.prepare.outputs.full_sha }}
fetch-depth: 0
submodules: false
@@ -193,21 +193,55 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Set up uv
uses: astral-sh/setup-uv@v7
with:
version: "0.11.9"
enable-cache: false
- name: Resolve dependency image and package versions
id: dependency
env:
GH_TOKEN: ${{ github.token }}
SUFFIX: ${{ matrix.suffix }}
run: |
set -euo pipefail
key=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py fingerprint .)
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-${SUFFIX}"
digest=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py resolve "$image")
echo "image=${image}" >> "$GITHUB_OUTPUT"
echo "digest=${digest}" >> "$GITHUB_OUTPUT"
bash scripts/docker-editable-pretend-versions.sh --github-output . >> "$GITHUB_OUTPUT"
- name: Build and push dependencies
id: dependencies
if: steps.dependency.outputs.digest == ''
uses: docker/build-push-action@v7
with:
context: .
file: ./Dockerfile.cuda
target: dependencies
outputs: type=image,push=true,compression=zstd,compression-level=3
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: ${{ steps.dependency.outputs.image }}
- name: Build and push
id: build
uses: docker/build-push-action@v7
with:
context: .
file: ./Dockerfile.cuda
# zstd compresses the multi-GB venv layers several times faster than gzip at a
# comparable ratio. No `force-compression`, so base-image layers are reused as-is
# rather than needlessly recompressed. Pulling zstd layers needs containerd >= 1.5
# or Docker >= 23.
target: runtime
build-args: |
DEPENDENCY_IMAGE=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ steps.dependencies.outputs.digest || steps.dependency.outputs.digest }}
VERIFIERS_PRETEND_VERSION=${{ steps.dependency.outputs.verifiers }}
RENDERERS_PRETEND_VERSION=${{ steps.dependency.outputs.renderers }}
PYDANTIC_CONFIG_PRETEND_VERSION=${{ steps.dependency.outputs.pydantic_config }}
outputs: type=image,push=true,compression=zstd,compression-level=3
# The per-job builder is ephemeral; mode=max caches builder-stage
# layers so warm builds skip the dependency sync.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
@@ -223,6 +257,8 @@ jobs:
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
DEPENDENCY_IMAGE: ${{ steps.dependency.outputs.image }}
DEPENDENCY_DIGEST: ${{ steps.dependencies.outputs.digest || steps.dependency.outputs.digest }}
PLATFORM: ${{ matrix.platform }}
SUFFIX: ${{ matrix.suffix }}
run: |
@@ -236,6 +272,7 @@ jobs:
echo "| **Image** | \`${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}-${SUFFIX}\` |"
echo "| **Commit** | \`${IMAGE_SHA}\` |"
echo "| **Digest** | \`${IMAGE_DIGEST}\` |"
echo "| **Dependencies** | \`${DEPENDENCY_IMAGE}@${DEPENDENCY_DIGEST}\` |"
} >> "$GITHUB_STEP_SUMMARY"
manifest:
+15 -10
View File
@@ -6,6 +6,10 @@ on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
unit-tests:
name: Unit tests
@@ -15,15 +19,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run tests
@@ -75,7 +80,7 @@ jobs:
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
from prime_rl.utils.validation import validate_shared_ckpt_config
from prime_rl.utils.validation import propagate_shared_fields
# `verifiers` (+ its `datasets` dep) is a declared slim dep: the v1 config types
# (EnvConfig, Task, ...) extend verifiers.v1, which is pure-pydantic and pulls no
+157 -48
View File
@@ -5,20 +5,103 @@ on:
branches: [main]
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
changes:
name: Select tests
runs-on: ubuntu-latest
if: github.event_name != 'pull_request' || github.event.pull_request.draft == false
permissions:
pull-requests: read
outputs:
unit: ${{ github.event_name != 'pull_request' || steps.filter.outputs.unit == 'true' }}
integration: ${{ steps.matrix.outputs.tests }}
eval: ${{ github.event_name != 'pull_request' || steps.filter.outputs.eval == 'true' }}
steps:
- uses: dorny/paths-filter@v4
id: filter
if: github.event_name == 'pull_request'
with:
filters: |
unit:
- &runtime
- '.github/workflows/gpu_tests.yaml'
- '{pyproject.toml,uv.lock,.python-version,.gitmodules}'
- 'deps/**'
- 'packages/**/pyproject.toml'
- 'packages/prime-rl-configs/src/prime_rl/configs/{trainer,shared,__init__}.py'
- 'packages/prime-rl-configs/src/prime_rl/utils/**'
- 'src/prime_rl/*.py'
- 'src/prime_rl/{trainer,multimodal,transports,utils}/**'
- 'tests/{__init__.py,conftest.py,utils.py}'
- 'tests/integration/{__init__.py,conftest.py}'
- 'tests/unit/{train,inference}/**'
- 'src/prime_rl/inference/**'
sft:
- *runtime
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
- 'src/prime_rl/dashboard/**'
- 'tests/integration/dashboard_smoke.py'
- 'packages/prime-rl-configs/src/prime_rl/configs/{sft,eval,monitors}.py'
- 'src/prime_rl/entrypoints/{sft,dashboard}.py'
- 'src/prime_rl/monitors/**'
- 'src/prime_rl/eval/{online,runner}.py'
- 'tests/integration/test_reverse_text_sft{,_lora}.py'
- 'configs/ci/integration/reverse-text-sft{,-lora}/**'
rl:
- *runtime
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
- 'src/prime_rl/dashboard/**'
- 'tests/integration/dashboard_smoke.py'
- 'packages/prime-rl-configs/src/prime_rl/configs/{rl,orchestrator,inference,env_server,algorithm,eval,monitors}.py'
- 'src/prime_rl/entrypoints/{rl,trainer,inference,orchestrator,env_server,dashboard}.py'
- 'src/prime_rl/{inference,orchestrator,monitors}/**'
- 'src/prime_rl/eval/{online,runner}.py'
- 'tests/integration/test_reverse_text{,_lora,_moe,_rl_opd,_rl_sft}.py'
- 'tests/integration/test_alphabet_sort.py'
- 'configs/ci/integration/reverse-text{,-lora,-moe,-rl-opd,-rl-sft}/**'
- 'configs/ci/integration/alphabet_sort.toml'
eval:
- *runtime
- 'packages/prime-rl-configs/src/prime_rl/configs/{eval,orchestrator,inference,env_server,algorithm,monitors}.py'
- 'src/prime_rl/{eval,orchestrator,monitors}/**'
- 'src/prime_rl/entrypoints/{eval,env_server}.py'
- 'tests/integration/test_gsm8k_eval.py'
- 'configs/ci/integration/gsm8k-eval.toml'
- name: Build integration matrix
id: matrix
env:
# Main and manual runs retain the full suite.
RUN_ALL: ${{ github.event_name != 'pull_request' }}
SFT: ${{ steps.filter.outputs.sft || 'false' }}
RL: ${{ steps.filter.outputs.rl || 'false' }}
run: |
tests=$(jq -cn --argjson all "$RUN_ALL" --argjson sft "$SFT" --argjson rl "$RL" '[
if $all or $sft then "reverse_text_sft", "reverse_text_sft_lora" else empty end,
if $all or $rl then
"reverse_text", "reverse_text_rl_opd", "reverse_text_rl_sft",
"alphabet_sort", "reverse_text_lora", "reverse_text_moe"
else empty end
]')
echo "tests=$tests" >> "$GITHUB_OUTPUT"
unit-tests:
name: Unit tests
runs-on: vm
needs: changes
runs-on: prime-rl-2xh200
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
timeout-minutes: 45
if: github.event_name == 'push' || github.event.pull_request.draft == false
if: needs.changes.outputs.unit == 'true'
steps:
- name: Install Git
run: |
@@ -29,12 +112,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run unit tests
@@ -50,46 +137,20 @@ jobs:
integration-tests:
name: Integration tests (${{ matrix.test }})
runs-on: ${{ matrix.runner }}
needs: changes
runs-on: prime-rl-2xh200
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
timeout-minutes: 60
if: github.event_name == 'push' || github.event.pull_request.draft == false
if: needs.changes.outputs.integration != '[]'
strategy:
fail-fast: false
# Bound per-PR fan-out: at most 5 integration jobs at a time (plus unit-tests),
# i.e. 6 h200 pods per PR. Tune together with the ARC scale set maxRunners.
max-parallel: 5
matrix:
include:
- test: reverse_text_sft
runner: vm
pytest_args: "tests/integration/test_reverse_text_sft.py"
- test: reverse_text_sft_lora
runner: vm
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
- test: reverse_text
runner: vm
pytest_args: "tests/integration/test_reverse_text.py"
- test: reverse_text_rl_opd
runner: vm
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
- test: reverse_text_rl_sft
runner: vm
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
- test: alphabet_sort
runner: vm
pytest_args: "tests/integration/test_alphabet_sort.py"
- test: reverse_text_lora
runner: vm
pytest_args: "tests/integration/test_reverse_text_lora.py"
- test: reverse_text_moe
runner: vm
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py"
- test: gsm8k_eval
runner: vm
pytest_args: "tests/integration/test_gsm8k_eval.py"
test: ${{ fromJSON(needs.changes.outputs.integration) }}
steps:
- name: Install Git
run: |
@@ -100,12 +161,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run integration tests
@@ -120,7 +185,7 @@ jobs:
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
VLLM_WORKER_MULTIPROC_METHOD: spawn
run: uv run pytest -vvs ${{ matrix.pytest_args }}
run: uv run pytest -vvs tests/integration/test_${{ matrix.test }}.py
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v7
@@ -129,3 +194,47 @@ jobs:
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
eval-tests:
name: Integration tests (gsm8k_eval)
needs: changes
if: needs.changes.outputs.eval == 'true'
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
submodules: false
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run eval tests
env:
USERNAME_CI: CI_RUNNER
WANDB_MODE: offline
HF_TOKEN: ${{ secrets.HF_TOKEN }}
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
GITHUB_REF_NAME: ${{ github.ref_name }}
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
run: uv run pytest -vvs tests/integration/test_gsm8k_eval.py
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: gsm8k_eval-logs
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
+4
View File
@@ -9,6 +9,10 @@ on:
# This will trigger the workflow for pull requests to any branch
types: [opened, synchronize, reopened]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
ruff:
name: Ruff
+55 -78
View File
@@ -1,21 +1,27 @@
# syntax=docker/dockerfile:1
# ^ `COPY --exclude` (used to split the venv into parallel-compressible layers) needs
# Dockerfile syntax >= 1.19; `docker/dockerfile:1` resolves to the latest stable 1.x.
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
ARG DEPENDENCY_IMAGE=dependencies
FROM ghcr.io/astral-sh/uv:0.11.9@sha256:6b6fa841d71a48fbc9e2c55651c5ad570e01104d7a7d701f57b2b22c0f58e9b1 AS uv
FROM ubuntu:24.04@sha256:a853f94d226358a79c740cfc7bce0c289748f3fe3488d921d038ccd752c61b60 AS python-builder
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates python3.12 python3.12-venv \
&& rm -rf /var/lib/apt/lists/*
COPY --from=uv /uv /uvx /usr/local/bin/
ENV UV_PYTHON_PREFERENCE=only-system UV_LINK_MODE=copy
# Every pyproject.toml + uv.lock, so the dependency sync below caches
# independently of source edits.
FROM nvidia/cuda:13.0.1-base-ubuntu24.04 AS manifests
# .git is ~735 MB, changes every commit, and would land in the registry cache.
COPY --exclude=.git . /ctx
FROM python-builder AS manifests
COPY . /ctx
RUN mkdir -p /manifests \
&& cd /ctx \
&& find . -name .git -prune -o -type f -name pyproject.toml -exec cp --parents {} /manifests/ \; \
&& cp uv.lock /manifests/
# Build stage - multi-arch base (supports amd64 + arm64)
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04 AS builder
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04@sha256:8b2705ea7a8653ad3451b46ab835eced92d77b44e671b9cf3ad4f95fbb2efe5e AS builder
LABEL maintainer="prime intellect"
LABEL repository="prime-rl"
@@ -72,18 +78,12 @@ RUN git clone --depth 1 --branch v${UCX_VERSION} https://github.com/openucx/ucx.
&& make install \
&& rm -rf /tmp/ucx
# Download the latest installer
ADD https://astral.sh/uv/install.sh /uv-installer.sh
# Set install dir to location accessible to non-root users
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
COPY --from=uv /uv /uvx /usr/local/bin/
ENV PATH="/usr/local/bin:$PATH"
# Build .venv against the system CPython, so the venv's recorded interpreter
# matches the runtime interpreter and no bin/python relink is needed at runtime.
ENV UV_PYTHON_PREFERENCE=only-system
ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
# Explicity set venv dir inside /app so to ensure it gets copied over during
# the runtime stage's `COPY /app`
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
# Install Python dependencies
@@ -91,51 +91,11 @@ WORKDIR /app
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# Third-party deps only — source edits don't bust this layer. First-party
# editables install in the source-layer sync below. No build-context bind
# mount here: .git would bust the cache every commit.
# `--extra dashboard` (fastapi/uvicorn) is baked in so the fft chart's dashboard pod needs no runtime uv sync (see PR body).
# The runtime dependency image contains no first-party source or editable installs.
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
--no-install-package renderers \
--no-install-package prime-pydantic-config
COPY pyproject.toml /app/pyproject.toml
COPY uv.lock /app/uv.lock
COPY README.md /app/README.md
COPY src/ /app/src/
COPY packages/ /app/packages/
COPY deps/ /app/deps/
COPY configs /app/configs
COPY examples /app/examples
COPY k8s /app/k8s
COPY benchmarks/scripts /app/benchmarks/scripts
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
# Use submodule git metadata from the build context when present. Docker copies
# only the submodule .git pointer files into /app/deps, so we temporarily link
# /app/.git/modules to the read-only context before resolving versions.
ARG VERIFIERS_PRETEND_VERSION
ARG RENDERERS_PRETEND_VERSION
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
--mount=type=bind,source=.,target=/build-context,readonly \
if [ -d /build-context/.git/modules ]; then mkdir -p /app/.git && ln -s /build-context/.git/modules /app/.git/modules; fi \
&& \
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
&& \
if [ -L /app/.git/modules ]; then rm /app/.git/modules && rmdir /app/.git 2>/dev/null || true; fi \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" /app/deps/verifiers/pyproject.toml \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra flash-mla --extra disagg --extra quack --extra kernels --locked --no-dev \
--no-install-local
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
# ships its own UCX which segfaults on prefill→decode KV transfer (#2883);
@@ -185,7 +145,7 @@ RUN find /usr/local/cuda-13.0/targets/*/lib \
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
# Runtime image
FROM nvidia/cuda:13.0.1-base-ubuntu24.04
FROM nvidia/cuda:13.0.1-base-ubuntu24.04@sha256:f8ef28f579ea42a44b415d2c5d46f788e6a9b395c6c83f2929416e1fc192c143 AS dependencies
ENV DEBIAN_FRONTEND=noninteractive
@@ -263,19 +223,12 @@ RUN userdel -r ubuntu 2>/dev/null || true; \
echo "appuser ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
# Install uv for development use
ADD https://astral.sh/uv/install.sh /uv-installer.sh
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
COPY --from=uv /uv /uvx /usr/local/bin/
USER appuser
ENV PATH="/usr/local/bin:$PATH"
WORKDIR /app
# Copy the application from the builder, splitting the venv's largest trees into their
# own layers. BuildKit compresses and pushes layers in parallel, so shipping the whole
# ~20 GB venv as one layer serialized the export behind a single compressor. Splitting
# also lets nodes pull the image in parallel. Keep the excludes below in sync with the
# per-tree copies above, or the data lands in the image twice.
# The volatile /app remainder goes last so a source edit re-pushes one layer,
# not all of them.
# Split the largest dependency trees so compression and pulls can run in parallel.
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/nvidia /app/.venv/lib/python3.12/site-packages/nvidia
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/torch /app/.venv/lib/python3.12/site-packages/torch
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/vllm /app/.venv/lib/python3.12/site-packages/vllm
@@ -283,17 +236,17 @@ COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packa
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so /app/.venv/lib/python3.12/site-packages/
COPY --from=builder /opt/ucx /opt/ucx
# Copy and set up entrypoint script
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
RUN chmod +x /app/docker-entrypoint.sh
COPY --from=builder --chown=appuser:appuser \
--exclude=.venv/lib/python3.12/site-packages/nvidia \
--exclude=.venv/lib/python3.12/site-packages/torch \
--exclude=.venv/lib/python3.12/site-packages/vllm \
--exclude=.venv/lib/python3.12/site-packages/flash_attn \
--exclude=.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so \
/app /app
--exclude=lib/python3.12/site-packages/nvidia \
--exclude=lib/python3.12/site-packages/torch \
--exclude=lib/python3.12/site-packages/vllm \
--exclude=lib/python3.12/site-packages/flash_attn \
--exclude=lib/python3.12/site-packages/flash_attn_2_cuda*.so \
/app/.venv /app/.venv
RUN /app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]' \
&& if [ "$(uname -m)" = "x86_64" ]; then \
/app/.venv/bin/python -c 'from importlib.metadata import version; version("flash-mla")'; \
fi
# Place executables in the environment at the front of the path
ENV PATH="/app/.venv/bin:$PATH"
@@ -304,6 +257,30 @@ ENV LD_LIBRARY_PATH="/opt/ucx/lib:/opt/ucx/lib/ucx${LD_LIBRARY_PATH:+:${LD_LIBRA
ENV HF_HUB_ETAG_TIMEOUT=500
ENV HF_HUB_DOWNLOAD_TIMEOUT=300
# Use entrypoint for setup (ulimit, etc) but default to sleep infinity for K8s
FROM python-builder AS application-builder
WORKDIR /app
COPY pyproject.toml uv.lock README.md /app/
COPY src /app/src
COPY packages /app/packages
COPY deps /app/deps
COPY configs /app/configs
COPY examples /app/examples
COPY benchmarks/scripts /app/benchmarks/scripts
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
COPY scripts/docker_application.py /build/docker_application.py
ARG VERIFIERS_PRETEND_VERSION
ARG RENDERERS_PRETEND_VERSION
ARG PYDANTIC_CONFIG_PRETEND_VERSION
RUN --mount=type=cache,target=/root/.cache/uv \
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
&& uv run --no-project --python /usr/bin/python3.12 /build/docker_application.py /app /out/app
# COPY --link and numeric ownership let source builds reuse dependency blobs without unpacking them.
FROM ${DEPENDENCY_IMAGE} AS runtime
ARG USER_ID=1000
ARG GROUP_ID=1000
COPY --link --from=application-builder --chown=${USER_ID}:${GROUP_ID} /out/app /app
# Preserve the executable Git mode; --chmod disables BuildKit's linked-copy optimization.
COPY --link --chown=${USER_ID}:${GROUP_ID} scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
ENTRYPOINT ["/app/docker-entrypoint.sh"]
CMD ["sleep", "infinity"]
+6 -8
View File
@@ -35,8 +35,8 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
2. Performant: built to train 1T+ MoE models on 1000+ GPUs with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) for training and [vLLM](https://github.com/vllm-project/vllm) for inference, with FP8 inference, PD disaggregation, EP and CP parallelism, and more.
3. Native integration with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments through the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars), including built-in support for SWE and agentic environments.
4. End-to-end post-training: SFT, RL training, and evals.
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
5. Multi-node deployment with Slurm support.
6. Multimodal support for VLMs such as Qwen3.5.
7. Hackable, modular, and extensible by design.
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.3/).
@@ -44,16 +44,14 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
## Models support
The trainer works with both Hugging Face and Prime custom `ModelForCausalLM` out of the box. For selected families (especially large MoE) we also ship highly optimized training code under `src/prime_rl/trainer/models/`, including expert parallelism (EP) for MoE layers and context parallelism (CP) for long sequences (see the table), and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels).
With `[model] impl = "auto"` (the default), the trainer selects that custom stack when the Hugging Face config type is registered.
The trainer runs the PrimeRL model implementations under `src/prime_rl/trainer/models/`: dense Llama, Qwen3 and Qwen3.5, plus the families in the table below, with expert parallelism (EP) for MoE layers, context parallelism (CP) for long sequences, and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels). Other architectures fail at trainer setup.
| Family | Example IDs | MoE | EP | CP |
|--------|-------------|-----|----|-----|
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | yes | ✅ | ✅ |
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
@@ -178,12 +176,12 @@ Follow this guide to learn the basics of prime-rl. You can train your own models
2. [**Wordle**](examples/basic/wordle/README.md): Train `Qwen3-1.7B` to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
3. [**Alphabet Sort**](examples/basic/alphabet-sort/README.md): Train `Qwen3-4B-Instruct-2507` to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
4. [**Wiki Search**](examples/basic/wiki-search/README.md): Train `Qwen3-4B-Instruct-2507` to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
5. [**Hendrycks Sanity**](examples/basic/hendrycks-sanity/README.md): Run a sanity check experiment on `DeepSeek-R1-Distill-Qwen-1.5B` using a filtered subset of MATH where the model already partially solves 20-80% of problems. Useful for algorithm ablations.
5. [**Hendrycks Sanity**](examples/basic/hendrycks-sanity/README.md): Run a sanity check experiment on `Qwen3-1.7B` using a subset of MATH filtered to problems that `DeepSeek-R1-Distill-Qwen-1.5B` partially solves (20-80%). Useful for algorithm ablations.
### Advanced Training: 32 - 2048 GPUs:
Follow this guide to train large models on hard reasoning and agentic tasks.
These guides are designed to be run from a Slurm cluster but can also be adapted to k8s deployments.
These guides are designed to be run from a Slurm cluster.
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
@@ -23,7 +23,6 @@ max_steps = 20
[model]
name = "deepseek-ai/DeepSeek-V4-Flash-0731"
impl = "custom"
ep = 8
# Torch all-to-all, not DeepEP. At full depth DeepEP dies on the first backward with
-1
View File
@@ -24,7 +24,6 @@ interval = 100
project = "minimax-swe"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
ep = 8
cp = 4
+2 -3
View File
@@ -9,8 +9,8 @@ PYTORCH_CUDA_ALLOC_CONF = "expandable_segments:True"
[slurm]
job_name = "nemotron-3-super-swe"
partition = "prod"
# Nemotron-H needs the mamba-ssm kernels; sync that group, then clear this run's orphaned sandboxes.
pre_run_command = 'uv sync --all-extras --all-packages --group mamba-ssm ; timeout 120 prime sandbox delete --label "nemotron-3-super-swe" -y || true'
# Sync the env (the gpu extra brings Nemotron-H's mamba-ssm kernels), then clear this run's orphaned sandboxes.
pre_run_command = 'uv sync --all-extras --all-packages ; timeout 120 prime sandbox delete --label "nemotron-3-super-swe" -y || true'
[deployment]
type = "multi_node"
@@ -40,7 +40,6 @@ dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
# Hybrid-Mamba model: ring CP is unsupported, so use ulysses (capped at 8 by n_groups).
cp = 8
@@ -15,9 +15,6 @@ name = "samsja/mini-glm-moe"
[trainer.optim]
lr = 3e-6
[trainer.model]
impl = "custom"
[orchestrator]
batch_size = 128
+1 -1
View File
@@ -11,7 +11,7 @@ name = "hendrycks-sanity"
[ckpt]
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
name = "Qwen/Qwen3-1.7B"
[orchestrator]
batch_size = 512
@@ -35,7 +35,6 @@ env.agent.runtime.type = "subprocess"
[trainer]
[trainer.model]
impl = "custom"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
+1 -1
+1 -1
+3 -11
View File
@@ -16,19 +16,14 @@ This page covers the specialized features layered on top of the core training st
## Custom Modeling
`prime-rl` ships custom optimized model implementations for several MoE families. With `model.impl = "auto"` (default) the trainer picks the custom path when the HF config type is registered, falling back to plain HF otherwise. To force one:
```toml
[trainer.model]
impl = "custom" # or "hf" to force the HF path
```
The trainer only runs `prime-rl`'s own model implementations, selected from the HF config type. Besides dense Llama, Qwen3 and Qwen3.5, these cover the families below. Other architectures fail at trainer setup.
| Family | HF config types | EP | CP |
|---|---|---|---|
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
| Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
| Laguna | `poolside/Laguna-XS.2` | ✅ | ✅ |
| MiniMax M2 | `MiniMax/MiniMax-M2` | ✅ | ✅ |
| Nemotron H | `nvidia/Nemotron-3-Nano-30B-A3B`, … | ✅ | ❌ |
@@ -37,8 +32,6 @@ impl = "custom" # or "hf" to force the HF path
| GPT-OSS | `unsloth/gpt-oss-20b-BF16`, … | ✅ | ✅ |
| DeepSeek V4 | `deepseek-ai/DeepSeek-V4-Flash-0731` | ✅ | ✅ |
Selective activation checkpointing works with either implementation. The custom path additionally enables EP, CP, low-precision training, and grouped MoE kernels. Forcing `impl = "hf"` is mostly useful when debugging and disables those model-specific runtime features.
GPT-OSS uses FlashAttention 4 with learned attention sinks. Training requires SM90 or SM100/SM110 GPUs
and a BF16 checkpoint such as `unsloth/gpt-oss-20b-BF16`; the original MXFP4 checkpoints are not supported.
@@ -161,7 +154,6 @@ Add `[model.vlm]` and bfloat16 dtypes:
```toml
[model]
name = "Qwen/Qwen3.5-4B"
impl = "custom"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
@@ -195,7 +187,7 @@ dropout = 0.0
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`). With LoRA on, the inference server registers the adapter under the model name and serves the base model as `<model>-base`.
## Disaggregated Prefill/Decode Inference
+14 -4
View File
@@ -139,7 +139,7 @@ algo.type = "echo"
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
At runtime, each env's `TrainEnv` (`prime_rl.orchestrator.envs`) resolves the `sampling.source` model into the inference pool used for train episodes, and its resolved config builds one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
@@ -157,9 +157,9 @@ Algorithms operate on native verifier artifacts and annotate their message graph
- `async score_episode(episode)` — rollout-local scoring as one episode arrives.
- `async score_group(episodes)` — group-relative scoring after the cohort completes.
The pipeline drives these through `finalize_episode` and `finalize_group`. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
The pipeline calls `score_group` directly and `score_episode` through `finalize_episode`, which skips episodes with no trainable sampled tokens. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.train.algo.advantage`.
The algorithm config states which loss component its action tokens feed (`action_loss_type`, a class variable on each config class). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). Writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.train.algo.advantage`.
## Async / Off-Policy Training
@@ -188,7 +188,7 @@ $$
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens, so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens — for `rl`, the sum of its weights, which is the same count while weights are 0/1 — so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
### IPO Loss
@@ -325,6 +325,16 @@ type = "grpo"
type = "linear"
```
A **length-weighted baseline** (`length_weighted_baseline = true` on the `grpo`-family algorithms) replaces the plain group mean with $b = \sum_i L_i s_i / \sum_i L_i$, where $L_i$ is the number of trainable (policy-sampled, loss-masked) tokens of rollout $i$, summed across all its turns; it applies after the length penalty. With token-level loss normalization, long rollouts carry more gradient weight, so this baseline makes the per-token advantage zero-mean across the group's tokens rather than across rollouts.
**Prompt-mean loss aggregation** (`loss_aggregation = "prompt"` on `grpo` and `echo`; default `"token"`). By default every `rl` token in the batch weighs the same, so prompts whose groups produce long trajectories dominate the gradient. With `"prompt"`, the loss is MiMo-V2.6's prompt-mean (Eq. 1): the mean over prompt groups $q$ of $\frac{1}{T_q}\sum_{t \in q} \mathcal{L}_{rl,t}$, where $T_q$ is the group's total trainable tokens. MiMo uses it to keep response length from growing too fast. `score_group` gives each trainable token of the group the `rl` weight $1/T_q$, so each group's weights sum to 1 and $N_{rl}$ (the summed weights) is the number of groups in the step. Zero-advantage tokens are still dropped from the `rl` component, so a group with a zero-advantage rollout keeps less than its full weight of 1. All envs with an `rl` loss in a run must use the same `loss_aggregation`.
```toml
[orchestrator.train.algo]
type = "grpo"
loss_aggregation = "prompt"
```
### Hierarchical GRPO
GRPO gives each rollout its reward minus the average reward of comparable rollouts. In an ordinary single-agent group, every rollout answers the same task, so one group average is enough.
+1 -1
View File
@@ -246,7 +246,7 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
- [**Wordle**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/wordle) — `Qwen3-1.7B` playing Wordle. Multi-turn SFT + RL; 2–4 H100s.
- [**Alphabet Sort**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/alphabet-sort) — `Qwen3-4B-Instruct-2507` sorting names alphabetically. Multi-turn LoRA RL without SFT warmup; one H100.
- [**Wiki Search**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/wiki-search) — `Qwen3-4B-Instruct-2507` answering trivia by searching a Wikipedia corpus. Multi-turn with tool use.
- [**Hendrycks Sanity**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/hendrycks-sanity) — `DeepSeek-R1-Distill-Qwen-1.5B` on a filtered MATH subset. Useful for algorithm ablations.
- [**Hendrycks Sanity**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/hendrycks-sanity) — `Qwen3-1.7B` on a filtered MATH subset. Useful for algorithm ablations.
**Advanced** (32–2048 GPUs, SLURM):
+1 -2
View File
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
| Workflow | Trigger | What runs | Where |
|---|---|---|---|
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | relevant changes in non-draft PRs; full suite on push to `main` or manual dispatch | `pytest tests/unit -m gpu`, plus RL/SFT integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_sft_lora`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `alphabet_sort`) with `max-parallel: 5`; separate hosted `gsm8k_eval` job | self-hosted `prime-rl-2xh200` k8s scale set (2xH200); `ubuntu-latest` for test selection and hosted eval |
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
@@ -117,7 +117,6 @@ Then run the full RL stack on reverse-text:
```bash
uv run rl @ configs/ci/integration/reverse-text-moe/start.toml \
--model.name samsja/mini-glm-moe \
--trainer.model.impl custom \
--inference.vllm.gpu-memory-utilization 0.7 \
--inference.vllm.max-model-len 2048
```
+2
View File
@@ -25,6 +25,8 @@ uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Infe
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
```
The default endpoint comes from `PRIME_INFERENCE_URL`, then the Prime CLI's `inference_url`, then the standard Prime Inference URL. An explicit `client.base_url` wins. API keys and environment-backed headers are resolved when clients are built; Prime CLI credential and team fallbacks apply only to Prime Inference hosts, including for a separate admin URL.
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
```bash
+3 -3
View File
@@ -287,7 +287,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Standard deployments use the V2 model runner. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Capture runs on vLLM's V2 model runner (forced automatically). Router replay is not supported with disaggregated P/D: vLLM does not capture routed experts across NIXL KV transfer.
```toml
[trainer]
@@ -311,8 +311,8 @@ top_p = 0.95
top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling mask)
```
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`; Gemma-family (softcapped) lm_heads fail loudly. Frozen-source envs are exempt.
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`. Frozen-source envs are exempt.
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run together with router replay. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
+4 -7
View File
@@ -92,13 +92,12 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
### Expert Parallelism
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput.
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is at most 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
`ep` defaults to `"auto"`. At startup it loads the model config to check whether the model is MoE. For MoE models it resolves to `min(world_size // dp_replicate, 8)`: the FSDP island size, capped at 8. For non-MoE models it resolves to 1 (no-op). `"auto"` does not look at `num_experts` or `cp`; the resolved degree must still be a multiple of `cp` and divide `num_experts`, so set it explicitly when it does not. Set `ep` to an explicit integer to override:
```toml
[trainer.model]
impl = "custom"
ep = 8 # explicit EP degree; must divide num_experts
[trainer.model.moe.dispatch]
@@ -116,7 +115,6 @@ CP shards a single sequence across multiple GPUs along the token dimension — f
```toml
[trainer.model]
impl = "custom"
attn = "auto" # auto = FA3 on Hopper, FA4 on datacenter Blackwell, FA2 otherwise; or flash_attention_2/3/4
cp = 2 # CP degree
cp_style = "ulysses" # "ring"
@@ -157,7 +155,7 @@ fused_lm_head_token_chunk_size = 1024 # default
# fused_lm_head_token_chunk_size = "disabled" # vanilla LM head
```
Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. SFT training silently disables this (not supported yet). Only available with `model.impl = "custom"`.
Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. SFT training silently disables this (not supported yet).
## Memory-Tight Recipe
@@ -165,7 +163,6 @@ The kitchen-sink config for fitting large MoE on limited GPUs at acceptable thro
```toml
[trainer.model]
impl = "custom"
ep = 8
cp = 2
@@ -244,7 +241,7 @@ Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transf
```bash
bash scripts/install_nixl_from_source.sh
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
uv pip install --reinstall --no-deps deps/nixl_cu13-*.whl
bash scripts/install_modelexpress.sh
```
+8 -2
View File
@@ -37,7 +37,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-server` per source. |
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. on their own host) and the launcher expects the server to already run there. |
## RL Trainer
@@ -62,6 +62,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| `orchestrator.train.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.train.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `trainer.model.freeze_moe_router` | Freeze MoE router gates (default `true` for RL, `false` for SFT). Router updates in RL shift the trainer's expert choices away from the ones inference sampled, amplifying the train-inference mismatch, so RL keeps the pretrained router. Set `false` to train it. |
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
@@ -158,6 +159,10 @@ messages = "conversation"
tools = "schemas"
```
**Per-message loss selection.** An optional `message_loss_mask` column contains one boolean or integer 0/1 per message. For example, `[0, 0, 0, 1]` on a user/assistant/user/assistant conversation trains only the final assistant turn while retaining the full context. For prompt-completion rows, the mask covers the concatenated prompt and completion messages. Zero excludes a message; one preserves the normal role and renderer loss settings. A missing or null mask leaves those settings unchanged. The renderer applies selection without changing token IDs, including ownership of assistant closing tokens. Invalid mask lengths or entries raise an error.
To read a differently named column, set `data.columns.message_loss_mask = "selection"`.
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column in OpenAI function-calling format. Each row's value can be either a list of dicts or a JSON-encoded string of a list.
Renderer-backed SFT reads template controls from the typed `[renderer]` config in the SFT TOML. For example:
@@ -191,7 +196,7 @@ The same config selects the renderer for RL under `[orchestrator.renderer]`. The
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5.
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) requires `model.impl = "custom"` and only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectories) for the full picture.
@@ -280,6 +285,7 @@ Pulled from the console log and mirrored to W&B.
- `optim/grad_norm` — spikes precede divergence.
- `optim/lr` — LR schedule.
- For MoE: `max_vio/mean`, `max_vio/max` — mean and max over the step's microsteps of the largest load-balancing violation across layers and EP groups, computed from expert token counts summed across each EP group. `routing_confidence/mean` — mean routing confidence.
- For MoE: `expert_load/{cv,max_mean,cold_frac}/{mean,max}` — expert load per layer over the whole step, from token counts summed across all ranks, as the mean and max over MoE layers. `cv` is std/mean of the per-expert token counts, `max_mean` the busiest expert's count over the mean, and `cold_frac` the fraction of experts receiving under 0.1x the mean. A trainable router that drifts shows up as a rising `cv`/`cold_frac` (MiMo-V2.6 §5.4).
**Performance:**
@@ -5,10 +5,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-search"
partition = "all"
@@ -45,7 +41,6 @@ dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
@@ -23,11 +23,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
partition = "all"
@@ -59,7 +54,6 @@ enable_router_replay = true
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
-6
View File
@@ -19,11 +19,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-swe"
partition = "all"
@@ -60,7 +55,6 @@ enable_router_replay = true
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
@@ -6,10 +6,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-terminal"
partition = "all"
@@ -46,7 +42,6 @@ dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
+12
View File
@@ -113,5 +113,17 @@ This will start a SFT run with the following configuration:
- The model is `zai-org/GLM-5.3-BF16`
- The data is `PrimeIntellect/INTELLECT-3-SFT-10K` (math split)
- 8 nodes at 131k context: CP 8, EP 8, full activation checkpointing with activation offloading, optimizer state offloaded to CPU
- DSA attention runs on the FlashMLA sparse forward and the cuDNN sparse backward (`model.dsa_backend = "cudnn_flashmla"`)
For a fake-data dry run, append [`fake.toml`](sft/h200/fake.toml) instead. You can use the same dashboard to monitor the SFT run.
### 12 nodes at 16k
For 16k-token samples, append [`16k-12-node.toml`](sft/h200/16k-12-node.toml) after the data overlay:
```bash
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml @ examples/advanced/glm-5.3/sft/h200/16k-12-node.toml
```
On 12 nodes the sharded model state fits in GPU memory without CP or any offloading. Each GPU runs one 16k sequence per step (batch 96), and transformer blocks compile with `fullgraph = true`. Full activation checkpointing stays on; peak memory is about 115 GiB per GPU.
@@ -0,0 +1,19 @@
# 12-node, 16k-token overlay: enough GPUs that the model state fits without CP or offloading,
# so each GPU runs one 16k sequence per micro-batch and blocks compile with fullgraph.
# Compose after the data overlay, e.g. base.toml @ math-10k.toml @ 16k-12-node.toml.
[model]
cp = 1
optim_cpu_offload = false
ac_offloading = "None"
[model.compile]
fullgraph = true
[data]
seq_len = 16384
batch_size = 96
micro_batch_size = 1
[deployment]
num_train_nodes = 12
+1 -2
View File
@@ -2,15 +2,14 @@ clean = true
[env_vars]
HF_HOME = "/home/huggingface"
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "zai-org/GLM-5.3-BF16"
impl = "custom"
attn = "flash_attention_2"
cp = 8
ep = 8
optim_cpu_offload = true
dsa_backend = "cudnn_flashmla"
[model.ac]
freq = 1
-1
View File
@@ -85,7 +85,6 @@ dist_timeout_seconds = 1800
[trainer.model]
name = "zai-org/GLM-5.3-BF16"
impl = "custom"
attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
-1
View File
@@ -24,7 +24,6 @@ interval = 100
project = "intellect-3.1"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
ep = 8
cp = 2
@@ -24,7 +24,6 @@ interval = 100
project = "qwen30b-math"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
ep = 8
@@ -2,11 +2,9 @@ clean = true
[env_vars]
HF_HOME = "/home/huggingface"
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
impl = "custom"
attn = "flash_attention_3"
ep = 8
-1
View File
@@ -24,7 +24,6 @@ interval = 100
project = "qwen30b-swe"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
ep = 8
cp = 2
-3
View File
@@ -11,9 +11,6 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
project = "alphabet-sort"
name = "alphabet-sort"
[trainer.model]
impl = "auto"
[trainer.model.ac]
freq = 1
+1 -1
View File
@@ -1,6 +1,6 @@
# Hendrycks Sanity
This example runs the Hendrycks Sanity Check experiment proposed in [Defeating the Training-Inference Mismatch](https://arxiv.org/abs/2510.26788). The sanity check tests whether an RL algorithm can reliably improve a model on problems it can *already partially solve*. The dataset is filtered from MATH to only include problems where the base model (`DeepSeek-R1-Distill-Qwen-1.5B`) solves 20-80% of the time across 40 rollouts. A reliable algorithm should push training accuracy on this "perfectible" subset above 95%.
This example runs the Hendrycks Sanity Check experiment proposed in [Defeating the Training-Inference Mismatch](https://arxiv.org/abs/2510.26788). The sanity check tests whether an RL algorithm can reliably improve a model on problems it can *already partially solve*. The dataset is filtered from MATH to only include problems that `DeepSeek-R1-Distill-Qwen-1.5B` solves 20-80% of the time across 40 rollouts. A reliable algorithm should push training accuracy on this "perfectible" subset above 95%. This example trains `Qwen3-1.7B` on that subset; the 20-80% band was measured for the distill model, not for `Qwen3-1.7B`.
Because our trainer is asynchronous, we perform only one gradient step per batch (the inference engine generates the next batch while the trainer processes the current one).
+1 -1
View File
@@ -9,7 +9,7 @@ num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
name = "Qwen/Qwen3-1.7B"
[orchestrator]
batch_size = 512
-120
View File
@@ -98,123 +98,3 @@ uv run eval @ examples/basic/reverse-text/eval.toml -m PrimeIntellect/Qwen3-0.6B
```
Way better! Now we get an **average reward of ~0.8**.
## Kubernetes Deployment
If you're running on Kubernetes, you can deploy this example using the provided Helm chart. The Helm chart automatically configures all components with proper networking and shared storage.
### Step 1: Deploy for SFT Training
The reverse-text example is configured with `autoStart: true` for RL training, but we need to run SFT first. Deploy with autoStart disabled:
```bash
cd k8s
helm install my-exp ./prime-rl -f ./prime-rl/examples/reverse-text.yaml \
--set orchestrator.autoStart=false \
--set inference.autoStart=false \
--set trainer.autoStart=false
# Check pods are ready
kubectl get pods -l app=prime-rl,example=reverse-text
# All pods should show 1/1 Running
```
### Step 2: Run SFT Training
Exec into the trainer pod and run SFT:
```bash
kubectl exec -it my-exp-trainer-0 -- bash
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs --run.name sft
# This will save DCP checkpoints to /data/outputs/sft/checkpoints/step_100
```
### Step 3: Deploy RL Training
Now upgrade the deployment to enable autoStart (uses the default `autoStart: true` from reverse-text.yaml):
```bash
# Exit the pod first (Ctrl+D)
cd k8s
helm upgrade my-exp ./prime-rl -f ./prime-rl/examples/reverse-text.yaml
# Check pods have restarted
kubectl get pods -l app=prime-rl,example=reverse-text
```
The RL components will automatically start. Monitor the logs:
```bash
# View inference server logs
kubectl logs -f my-exp-inference-0
# View orchestrator logs
kubectl logs -f my-exp-orchestrator-0
# View trainer logs
kubectl logs -f my-exp-trainer-0
```
### Alternative: Manual RL Training
If you prefer to run RL components manually, keep `autoStart: false` and exec into each pod:
```bash
# Terminal 1 - Inference
kubectl exec -it my-exp-inference-0 -- bash
uv run inference @ /app/k8s/prime-rl/examples/reverse-text/infer.toml
# Terminal 2 - Orchestrator
kubectl exec -it my-exp-orchestrator-0 -- bash
uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url '["'$INFERENCE_URL'"]'
# Terminal 3 - Trainer
kubectl exec -it my-exp-trainer-0 -- bash
uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml --output-dir /data/outputs
```
### Access Outputs and Checkpoints
All outputs are written to `/data/outputs` on the shared NFS storage:
```bash
# Exec into any pod to access outputs
kubectl exec -it my-exp-trainer-0 -- bash
ls -lh /data/outputs/weights/
ls -lh /data/outputs/rollouts/
```
### Step 4: Run Evaluation
To evaluate the trained RL model:
```bash
# Exec into trainer pod
kubectl exec -it my-exp-trainer-0 -- bash
# If inference server isn't running with the RL model, start it in another terminal:
kubectl exec -it my-exp-inference-0 -- bash
uv run inference --vllm.model /data/outputs/weights_hf/step_20
# Back in trainer pod, run evaluation
uv run eval @ examples/basic/reverse-text/eval.toml \
-m /data/outputs/weights_hf/step_20 \
--client.base-url $INFERENCE_URL
```
### Clean Up
```bash
helm uninstall my-exp
# Optionally delete shared data. The PVC is named <release-name>-shared-data:
kubectl delete pvc my-exp-shared-data
```
**What the Helm chart provides:**
- Predictably named pods: `<release-name>-trainer-0`, `<release-name>-inference-0`, `<release-name>-orchestrator-0`
- Shared NFS storage at `/data` for model checkpoints and outputs
- GPU resources (1 GPU per inference/trainer pod)
- Kubernetes services for component communication
- Auto-start capability with proper networking configured
See the [K8s deployment guide](../../../k8s/README.md) for more details on scaling, distributed training, and advanced configurations.
+1 -1
View File
@@ -1,6 +1,6 @@
# VLM SFT
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training requires a custom PrimeRL implementation (`impl = "custom"`, `[model.vlm]` set — see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training (`[model.vlm]` set) requires a PrimeRL VLM implementation (see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
| Config | Model | Hardware |
|---|---|---|
-1
View File
@@ -6,7 +6,6 @@ dist_timeout_seconds = 3600
name = "Qwen/Qwen3.6-35B-A3B"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
impl = "custom"
attn = "flash_attention_2"
ep = 8 # keep in sync with deployment.num_train_gpus
-1
View File
@@ -6,7 +6,6 @@ max_steps = 20
name = "Qwen/Qwen3.5-0.8B"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
impl = "custom"
[renderer]
name = "auto"
-72
View File
@@ -1,72 +0,0 @@
# Kubernetes Deployment with Helm
This directory contains a Helm chart for deploying prime-rl training infrastructure on Kubernetes clusters.
## Quick Start
```bash
# Deploy with the reverse-text example
helm install my-exp ./prime-rl -f ./prime-rl/examples/reverse-text.yaml
# Verify deployment
kubectl get pods -l app.kubernetes.io/instance=my-exp
# Exec into trainer and run training
kubectl exec -it my-exp-trainer-0 -- bash
cd /data && uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml
```
## Prerequisites
- Kubernetes cluster with GPU nodes
- [NVIDIA GPU Operator](https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/getting-started.html) installed
- [Helm 3.x](https://helm.sh/docs/intro/install/) installed
- Storage class that supports `ReadWriteMany` (e.g., NFS, CephFS)
## Chart Structure
```
prime-rl/
├── Chart.yaml
├── values.yaml # Default configuration
├── examples/
│ ├── reverse-text.yaml # Example values for reverse-text
│ └── reverse-text/ # Split orchestrator/inference/trainer configs the example runs
└── templates/
├── deployment.yaml # StatefulSets for orchestrator, inference, trainer
├── service.yaml # Headless services for pod discovery
└── pvc.yaml # Shared storage
```
## Configuration
See [values.yaml](./prime-rl/values.yaml) for all available options. Common overrides:
```bash
# Custom GPU allocation
helm install my-exp ./prime-rl \
--set inference.gpu.count=4 \
--set trainer.gpu.count=2
# With secrets for W&B/HF
kubectl create secret generic prime-rl-secrets \
--from-literal=wandb-api-key=YOUR_KEY \
--from-literal=hf-token=YOUR_TOKEN
helm install my-exp ./prime-rl \
--set config.secrets.enabled=true \
--set config.secrets.name=prime-rl-secrets
```
## Uninstalling
```bash
helm uninstall my-exp
# The PVC is named <release-name>-shared-data (see templates/pvc.yaml)
kubectl delete pvc my-exp-shared-data # Warning: deletes data!
```
## Learn More
- [Scaling guide](https://docs.primeintellect.ai/prime-rl/scaling) - Non-Kubernetes multi-node deployment (SLURM), parallelism, benchmarking
-16
View File
@@ -1,16 +0,0 @@
apiVersion: v2
name: prime-rl
description: A Helm chart for deploying PRIME-RL training infrastructure on Kubernetes
type: application
version: 0.1.0
appVersion: "main"
keywords:
- machine-learning
- reinforcement-learning
- training
- gpu
maintainers:
- name: Prime Intellect
url: https://github.com/PrimeIntellect-ai/prime-rl
sources:
- https://github.com/PrimeIntellect-ai/prime-rl
-44
View File
@@ -1,44 +0,0 @@
# Values for reverse_text example
# Small model (Qwen3-0.6B) - runs on single consumer GPU
config:
example: "reverse-text"
image:
tag: "main"
# Orchestrator - no GPU needed
orchestrator:
enabled: true
autoStart: true
command: "uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL ; sleep infinity"
resources:
requests:
memory: "1Gi"
cpu: "500m"
# Inference - 1 GPU
inference:
enabled: true
autoStart: true
command: "uv run inference @ /app/k8s/prime-rl/examples/reverse-text/infer.toml ; sleep infinity"
gpu:
enabled: true
count: 1
resources:
requests:
memory: "4Gi"
cpu: "1"
# Trainer - 1 GPU
trainer:
enabled: true
autoStart: true
command: "uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml --output-dir /data/outputs ; sleep infinity"
gpu:
enabled: true
count: 1
resources:
requests:
memory: "4Gi"
cpu: "1"
@@ -1,2 +0,0 @@
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -1,27 +0,0 @@
max_steps = 20
seq_len = 2048
batch_size = 128
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
[train]
group_size = 16
[train.sampling]
max_completion_tokens = 128
[[train.source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[renderer]
name = "prime-qwen3"
[ckpt] # Checkpoint at the end of training
@@ -1,14 +0,0 @@
max_steps = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
seq_len = 2048
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
[optim]
lr = 3e-6
[ckpt] # Checkpoint at the end of training
-59
View File
@@ -1,59 +0,0 @@
{{/*
Expand the name of the chart.
*/}}
{{- define "prime-rl.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Create a default fully qualified app name.
*/}}
{{- define "prime-rl.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "prime-rl.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Common labels
*/}}
{{- define "prime-rl.labels" -}}
helm.sh/chart: {{ include "prime-rl.chart" . }}
{{ include "prime-rl.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
{{/*
Selector labels
*/}}
{{- define "prime-rl.selectorLabels" -}}
app.kubernetes.io/name: {{ include "prime-rl.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{/*
Component labels
*/}}
{{- define "prime-rl.componentLabels" -}}
app: prime-rl
{{- if .Values.config.example }}
example: {{ .Values.config.example }}
{{- end }}
{{- end }}
-378
View File
@@ -1,378 +0,0 @@
{{- if .Values.orchestrator.enabled }}
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: {{ .Release.Name }}-orchestrator
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: orchestrator
spec:
serviceName: {{ .Release.Name }}-orchestrator-headless
replicas: {{ .Values.orchestrator.replicas }}
selector:
matchLabels:
{{- include "prime-rl.componentLabels" . | nindent 6 }}
role: orchestrator
template:
metadata:
labels:
{{- include "prime-rl.selectorLabels" . | nindent 8 }}
{{- include "prime-rl.componentLabels" . | nindent 8 }}
role: orchestrator
spec:
{{- with .Values.orchestrator.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
containers:
- name: prime-rl-orchestrator
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.orchestrator.autoStart }}
command: ["/bin/bash", "-c"]
args:
- {{ .Values.orchestrator.command }}
{{- else }}
command: ["sleep", "infinity"]
{{- end }}
ports:
- containerPort: {{ .Values.orchestrator.service.port }}
name: api
- containerPort: {{ .Values.orchestrator.service.ncclPort }}
name: nccl
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: ROLE
value: "orchestrator"
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.orchestrator.replicas }}"
{{- $releaseName := .Release.Name }}
{{- $namespace := .Values.namespace }}
{{- $port := int .Values.inference.service.port }}
{{- $replicas := int .Values.inference.replicas }}
{{- $urls := list }}
{{- range $i := until $replicas }}
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
{{- $urls = append $urls $url }}
{{- end }}
- name: INFERENCE_URL
value: {{ first $urls | quote }}
- name: ADMIN_INFERENCE_URLS
value: {{ $urls | join "," | quote }}
{{- with .Values.orchestrator.env }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- if .Values.config.secrets.enabled }}
- name: WANDB_API_KEY
valueFrom:
secretKeyRef:
name: {{ .Values.config.secrets.name }}
key: wandb-api-key
optional: true
- name: HF_TOKEN
valueFrom:
secretKeyRef:
name: {{ .Values.config.secrets.name }}
key: hf-token
optional: true
{{- end }}
resources:
{{- toYaml .Values.orchestrator.resources | nindent 10 }}
{{- if .Values.storage.enabled }}
volumeMounts:
- name: shared-data
mountPath: {{ .Values.storage.mountPath }}
{{- end }}
{{- if .Values.storage.enabled }}
volumes:
- name: shared-data
persistentVolumeClaim:
claimName: {{ .Release.Name }}-shared-data
{{- end }}
{{- end }}
---
{{- if .Values.inference.enabled }}
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: {{ .Release.Name }}-inference
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: inference
spec:
serviceName: {{ .Release.Name }}-inference-headless
replicas: {{ .Values.inference.replicas }}
podManagementPolicy: Parallel
selector:
matchLabels:
{{- include "prime-rl.componentLabels" . | nindent 6 }}
role: inference
template:
metadata:
labels:
{{- include "prime-rl.selectorLabels" . | nindent 8 }}
{{- include "prime-rl.componentLabels" . | nindent 8 }}
role: inference
spec:
{{- if .Values.inference.runtimeClassName }}
runtimeClassName: {{ .Values.inference.runtimeClassName }}
{{- end }}
containers:
- name: prime-rl-inference
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.inference.autoStart }}
command: ["/bin/bash", "-c"]
args:
- {{ .Values.inference.command }}
{{- else }}
command: ["sleep", "infinity"]
{{- end }}
ports:
- containerPort: {{ .Values.inference.service.port }}
name: api
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: ROLE
value: "inference"
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.inference.replicas }}"
{{- with .Values.inference.env }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- if .Values.config.secrets.enabled }}
- name: WANDB_API_KEY
valueFrom:
secretKeyRef:
name: {{ .Values.config.secrets.name }}
key: wandb-api-key
optional: true
- name: HF_TOKEN
valueFrom:
secretKeyRef:
name: {{ .Values.config.secrets.name }}
key: hf-token
optional: true
{{- end }}
resources:
requests:
{{- if .Values.inference.gpu.enabled }}
nvidia.com/gpu: {{ .Values.inference.gpu.count }}
{{- end }}
memory: {{ .Values.inference.resources.requests.memory }}
cpu: {{ .Values.inference.resources.requests.cpu }}
limits:
{{- if .Values.inference.gpu.enabled }}
nvidia.com/gpu: {{ .Values.inference.gpu.count }}
{{- end }}
{{- if .Values.inference.resources.limits }}
memory: {{ .Values.inference.resources.limits.memory }}
cpu: {{ .Values.inference.resources.limits.cpu }}
{{- end }}
{{- if and .Values.inference.probes .Values.inference.probes.enabled }}
startupProbe:
httpGet:
path: /health
port: {{ .Values.inference.service.port }}
periodSeconds: {{ .Values.inference.probes.startup.periodSeconds }}
failureThreshold: {{ .Values.inference.probes.startup.failureThreshold }}
timeoutSeconds: {{ .Values.inference.probes.startup.timeoutSeconds }}
livenessProbe:
httpGet:
path: /liveness
port: {{ .Values.inference.service.port }}
periodSeconds: {{ .Values.inference.probes.liveness.periodSeconds }}
failureThreshold: {{ .Values.inference.probes.liveness.failureThreshold }}
timeoutSeconds: {{ .Values.inference.probes.liveness.timeoutSeconds }}
readinessProbe:
httpGet:
path: /health
port: {{ .Values.inference.service.port }}
periodSeconds: {{ .Values.inference.probes.readiness.periodSeconds }}
failureThreshold: {{ .Values.inference.probes.readiness.failureThreshold }}
timeoutSeconds: {{ .Values.inference.probes.readiness.timeoutSeconds }}
{{- end }}
{{- if .Values.storage.enabled }}
volumeMounts:
- name: shared-data
mountPath: {{ .Values.storage.mountPath }}
{{- end }}
{{- if .Values.storage.enabled }}
volumes:
- name: shared-data
persistentVolumeClaim:
claimName: {{ .Release.Name }}-shared-data
{{- end }}
{{- end }}
---
{{- if .Values.trainer.enabled }}
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: {{ .Release.Name }}-trainer
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: trainer
spec:
serviceName: {{ .Release.Name }}-trainer-headless
replicas: {{ .Values.trainer.replicas }}
podManagementPolicy: Parallel
selector:
matchLabels:
{{- include "prime-rl.componentLabels" . | nindent 6 }}
role: trainer
template:
metadata:
labels:
{{- include "prime-rl.selectorLabels" . | nindent 8 }}
{{- include "prime-rl.componentLabels" . | nindent 8 }}
role: trainer
spec:
{{- if .Values.trainer.runtimeClassName }}
runtimeClassName: {{ .Values.trainer.runtimeClassName }}
{{- end }}
containers:
- name: prime-rl-trainer
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.trainer.autoStart }}
command: ["/bin/bash", "-c"]
args:
- {{ .Values.trainer.command }}
{{- else }}
command: ["sleep", "infinity"]
{{- end }}
ports:
- containerPort: {{ .Values.trainer.service.port }}
name: api
- containerPort: {{ .Values.trainer.service.ncclPort }}
name: nccl
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: ROLE
value: "trainer"
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.trainer.replicas }}"
{{- if .Values.trainer.pytorchCudaAllocConf }}
- name: PYTORCH_CUDA_ALLOC_CONF
value: {{ .Values.trainer.pytorchCudaAllocConf | quote }}
{{- end }}
{{- $releaseName := .Release.Name }}
{{- $namespace := .Values.namespace }}
{{- $port := int .Values.inference.service.port }}
{{- $replicas := int .Values.inference.replicas }}
{{- $urls := list }}
{{- range $i := until $replicas }}
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
{{- $urls = append $urls $url }}
{{- end }}
- name: INFERENCE_URL
value: {{ first $urls | quote }}
- name: ADMIN_INFERENCE_URLS
value: {{ $urls | join "," | quote }}
{{- with .Values.trainer.env }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- if .Values.config.secrets.enabled }}
- name: WANDB_API_KEY
valueFrom:
secretKeyRef:
name: {{ .Values.config.secrets.name }}
key: wandb-api-key
optional: true
- name: HF_TOKEN
valueFrom:
secretKeyRef:
name: {{ .Values.config.secrets.name }}
key: hf-token
optional: true
{{- end }}
resources:
requests:
{{- if .Values.trainer.gpu.enabled }}
nvidia.com/gpu: {{ .Values.trainer.gpu.count }}
{{- end }}
memory: {{ .Values.trainer.resources.requests.memory }}
cpu: {{ .Values.trainer.resources.requests.cpu }}
limits:
{{- if .Values.trainer.gpu.enabled }}
nvidia.com/gpu: {{ .Values.trainer.gpu.count }}
{{- end }}
{{- if .Values.trainer.resources.limits }}
memory: {{ .Values.trainer.resources.limits.memory }}
cpu: {{ .Values.trainer.resources.limits.cpu }}
{{- end }}
{{- if and .Values.trainer.probes .Values.trainer.probes.enabled }}
startupProbe:
httpGet:
path: /health
port: {{ .Values.trainer.service.port }}
periodSeconds: {{ .Values.trainer.probes.startup.periodSeconds }}
failureThreshold: {{ .Values.trainer.probes.startup.failureThreshold }}
timeoutSeconds: {{ .Values.trainer.probes.startup.timeoutSeconds }}
livenessProbe:
httpGet:
path: /health
port: {{ .Values.trainer.service.port }}
periodSeconds: {{ .Values.trainer.probes.liveness.periodSeconds }}
failureThreshold: {{ .Values.trainer.probes.liveness.failureThreshold }}
timeoutSeconds: {{ .Values.trainer.probes.liveness.timeoutSeconds }}
readinessProbe:
httpGet:
path: /health
port: {{ .Values.trainer.service.port }}
periodSeconds: {{ .Values.trainer.probes.readiness.periodSeconds }}
failureThreshold: {{ .Values.trainer.probes.readiness.failureThreshold }}
timeoutSeconds: {{ .Values.trainer.probes.readiness.timeoutSeconds }}
{{- end }}
{{- if .Values.storage.enabled }}
volumeMounts:
- name: shared-data
mountPath: {{ .Values.storage.mountPath }}
{{- end }}
{{- if .Values.storage.enabled }}
volumes:
- name: shared-data
persistentVolumeClaim:
claimName: {{ .Release.Name }}-shared-data
{{- end }}
{{- end }}
-16
View File
@@ -1,16 +0,0 @@
{{- if .Values.storage.enabled }}
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: {{ .Release.Name }}-shared-data
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
spec:
accessModes:
{{- toYaml .Values.storage.accessModes | nindent 4 }}
storageClassName: {{ .Values.storage.storageClassName }}
resources:
requests:
storage: {{ .Values.storage.size }}
{{- end }}
-141
View File
@@ -1,141 +0,0 @@
{{- if .Values.orchestrator.enabled }}
{{- if .Values.orchestrator.service.enabled }}
apiVersion: v1
kind: Service
metadata:
name: {{ .Release.Name }}-orchestrator
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: orchestrator
spec:
type: {{ .Values.orchestrator.service.type }}
selector:
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: orchestrator
ports:
- port: {{ .Values.orchestrator.service.port }}
targetPort: api
protocol: TCP
name: api
- port: {{ .Values.orchestrator.service.ncclPort }}
targetPort: nccl
protocol: TCP
name: nccl
{{- end }}
---
apiVersion: v1
kind: Service
metadata:
name: {{ .Release.Name }}-orchestrator-headless
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: orchestrator
spec:
clusterIP: None # Headless service for StatefulSet
selector:
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: orchestrator
ports:
- port: {{ .Values.orchestrator.service.port }}
name: api
- port: {{ .Values.orchestrator.service.ncclPort }}
name: nccl
{{- end }}
---
{{- if .Values.inference.enabled }}
{{- if .Values.inference.service.enabled }}
apiVersion: v1
kind: Service
metadata:
name: {{ .Release.Name }}-inference
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: inference
spec:
type: {{ .Values.inference.service.type }}
selector:
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: inference
ports:
- port: {{ .Values.inference.service.port }}
targetPort: api
protocol: TCP
name: api
{{- end }}
{{- end }}
---
{{- if .Values.trainer.enabled }}
{{- if .Values.trainer.service.enabled }}
apiVersion: v1
kind: Service
metadata:
name: {{ .Release.Name }}-trainer
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: trainer
spec:
type: {{ .Values.trainer.service.type }}
selector:
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: trainer
ports:
- port: {{ .Values.trainer.service.port }}
targetPort: api
protocol: TCP
name: api
- port: {{ .Values.trainer.service.ncclPort }}
targetPort: nccl
protocol: TCP
name: nccl
{{- end }}
{{- end }}
---
{{- if .Values.inference.enabled }}
apiVersion: v1
kind: Service
metadata:
name: {{ .Release.Name }}-inference-headless
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: inference
spec:
clusterIP: None # Headless service for StatefulSet
selector:
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: inference
ports:
- port: {{ .Values.inference.service.port }}
name: api
{{- end }}
---
{{- if .Values.trainer.enabled }}
apiVersion: v1
kind: Service
metadata:
name: {{ .Release.Name }}-trainer-headless
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: trainer
spec:
clusterIP: None # Headless service for StatefulSet
selector:
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: trainer
ports:
- port: {{ .Values.trainer.service.port }}
name: api
- port: {{ .Values.trainer.service.ncclPort }}
name: nccl
{{- end }}
-156
View File
@@ -1,156 +0,0 @@
# Default values for prime-rl
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
# Global settings
namespace: default
# Docker image configuration
image:
repository: primeintellect/prime-rl
pullPolicy: IfNotPresent
tag: "main"
# Shared storage configuration
storage:
enabled: true
# PVC name will be automatically set to {{ .Release.Name }}-shared-data
storageClassName: nfs
accessModes:
- ReadWriteMany
size: 1Ti
mountPath: /data
# Orchestrator component
orchestrator:
enabled: true
replicas: 1
# Auto-start configuration (set to false to use sleep infinity for debugging)
autoStart: false
# Example command - use $INFERENCE_URL directly (the first inference server URL)
command: "" # e.g., 'uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL'
# $INFERENCE_URL is auto-set to 'http://<release>-inference-0...:8000/v1'. With more than one
# inference replica, put a router in front and point --client.base-url at it; admin operations
# (weight updates, health checks) fan out to every replica via
# --client.admin-base-url $ADMIN_INFERENCE_URLS (comma-separated list of all replica URLs).
resources:
requests:
memory: "2Gi"
cpu: "1"
service:
enabled: true
type: ClusterIP
port: 8000
ncclPort: 29501
env: []
# - name: CUSTOM_ENV
# value: "value"
nodeSelector: {}
# nvidia.com/gpu.present: "true" # Orchestrator doesn't need GPUs
# Inference component
inference:
enabled: true
replicas: 1
# Auto-start configuration (set to false to use sleep infinity for debugging)
autoStart: false
command: "" # e.g., "uv run inference @ /app/k8s/prime-rl/examples/reverse-text/infer.toml"
gpu:
enabled: true
count: 1
resources:
requests:
memory: "4Gi"
cpu: "1"
service:
enabled: true
type: ClusterIP
port: 8000
runtimeClassName: nvidia
# Health probes for inference server (/health for startup/readiness, /liveness for engine liveness)
probes:
enabled: false
# Startup probe: allows long model loading time (up to 45 min by default)
startup:
periodSeconds: 10
failureThreshold: 270 # 270 * 10s = 45 min max startup time
timeoutSeconds: 5
liveness:
periodSeconds: 10
failureThreshold: 3
timeoutSeconds: 10
readiness:
periodSeconds: 5
failureThreshold: 2
timeoutSeconds: 5
# Trainer component
trainer:
enabled: true
replicas: 1
# Auto-start configuration (set to false to use sleep infinity for debugging)
autoStart: false
command: "" # e.g., "uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml --output-dir /data/outputs"
# Helps reduce CUDA memory fragmentation with PyTorch allocator
pytorchCudaAllocConf: "expandable_segments:True"
gpu:
enabled: true
count: 1
resources:
requests:
memory: "4Gi"
cpu: "1"
service:
enabled: true
type: ClusterIP
port: 8000
ncclPort: 29501
env: []
runtimeClassName: nvidia
# Health probes for trainer (requires metrics_server config)
probes:
enabled: false
# Startup probe: allows time for model loading
startup:
periodSeconds: 10
failureThreshold: 60 # 60 * 10s = 10 min max startup time
timeoutSeconds: 30
liveness:
periodSeconds: 30
failureThreshold: 6 # 6 * 30s = 3 min before restart
timeoutSeconds: 30
readiness:
periodSeconds: 10
failureThreshold: 3
timeoutSeconds: 30
# Additional configuration
config:
# Example name (used for labeling)
example: "reverse-text"
# Secrets (optional)
secrets:
enabled: false
name: prime-rl-secrets
# wandbApiKey: ""
# hfToken: ""
@@ -40,11 +40,11 @@ import verifiers.v1 as vf
from pydantic import Field, model_validator
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.configs.shared import VLLMClientConfig
from prime_rl.utils.config import BaseConfig
class FrozenModelConfig(ClientConfig):
class FrozenModelConfig(VLLMClientConfig):
"""An externally hosted model behind an OpenAI-compatible endpoint: the
client config plus the served model's ``name``.
@@ -57,14 +57,7 @@ class FrozenModelConfig(ClientConfig):
name: str
"""Served model name, sent as the ``model`` field of every request."""
@model_validator(mode="after")
def require_explicit_endpoint(self):
if "base_url" not in self.model_fields_set:
raise ValueError(
"a frozen model reference needs base_url — frozen models are externally "
"hosted; prime-rl only ever hosts the trainable policy."
)
return self
base_url: str
ModelReference: TypeAlias = Literal["policy"] | FrozenModelConfig
@@ -208,6 +201,12 @@ class GRPOAlgoConfig(BaseAlgoConfig):
length_penalty: LengthPenaltyConfig | None = None
"""Linear length penalty subtracted from each reward before the GRPO baseline (see ``LinearLengthPenaltyConfig``): a ``pass_rate``-scaled sum of output-token, input-token, and turns terms, each normalized by the group's own max for that quantity. None disables it."""
length_weighted_baseline: bool = False
"""Use the token-length-weighted group mean reward ``sum_i(L_i * r_i) / sum_i(L_i)`` as the baseline instead of the plain mean, where ``L_i`` is the number of trainable (mask-True, policy-sampled) tokens of rollout ``i`` summed across all its turns."""
loss_aggregation: Literal["token", "prompt"] = "token"
"""How the rl loss weights tokens across prompt groups. ``token``: every loss token in the batch weighs the same, so groups with more total tokens dominate the gradient. ``prompt``: prompt-mean (MiMo-V2.6 Eq. 1) — each trainable token of group ``q`` gets rl weight ``1 / T_q`` (``T_q`` = the group's trainable tokens), and the trainer divides the rl loss by the summed weights, i.e. the number of groups. All rl envs of a run must use the same value."""
class EchoAlgoConfig(GRPOAlgoConfig):
type: Literal["echo"] = "echo" # type: ignore[assignment]
@@ -6,8 +6,14 @@ from pydantic import AliasChoices, Field, model_validator
from prime_rl.configs.monitors import EvalMonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.configs.shared import (
ClientConfig,
HeartbeatConfig,
LogConfig,
RunConfig,
VLLMClientConfig,
WeightBroadcastConfig,
)
from prime_rl.utils.config import default_output_dir
@@ -15,7 +21,7 @@ class ServedEvalConfig(EvalSourcesConfig):
"""Eval sources run against a live inference server: the server's client and the
adaptive concurrency band."""
client: ClientConfig = ClientConfig()
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
"""Client of the inference server evals run against."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
@@ -44,9 +50,6 @@ class ServedEvalConfig(EvalSourcesConfig):
return {("eval", source.resolved_name): source.serve.address for source in self.source}
PRIME_INFERENCE_URL = "https://api.pinference.ai/api/v1"
class EvalConfig(ServedEvalConfig):
"""``uv run eval``: evaluate the configured sources once against a live inference
server, then exit. Every source's env server is spawned by the eval process unless
@@ -56,7 +59,7 @@ class EvalConfig(ServedEvalConfig):
model: str = Field("deepseek/deepseek-v4.1-flash", validation_alias=AliasChoices("model", "m"))
"""Model id — the ``model`` field of every eval request and the startup model check."""
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
client: ClientConfig = Field(default_factory=ClientConfig)
"""Client of the inference server. Defaults to Prime Inference."""
select: vf.SelectCLIConfig = vf.SelectCLIConfig()
@@ -21,7 +21,7 @@ class ServerConfig(BaseConfig):
"""Port to bind to."""
liveness_timeout_seconds: float = Field(30.0, gt=0)
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. With Kubernetes liveness probes, keep the probe ``timeoutSeconds`` at least this high."""
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. Health checks polling this endpoint should use a timeout at least this high."""
# Valid vLLM max_lora_rank values (`vllm.config.lora.MaxLoRARanks`), excluding 1 so
@@ -509,16 +509,12 @@ class InferenceConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_disaggregated_combined_replay(self):
"""NIXL routed-expert capture uses the V1 runner, while sampling replay needs V2."""
if (
self.deployment.type == "disaggregated"
and self.enable_return_sampling_mask
and self.vllm.enable_return_routed_experts
):
def validate_disaggregated_no_routed_experts(self):
"""vLLM rejects routed-expert capture with NIXL KV transfer."""
if self.deployment.type == "disaggregated" and self.vllm.enable_return_routed_experts:
raise ValueError(
"Combined router and sampling replay is not supported with disaggregated P/D: "
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
"Routed-expert return (enable_return_routed_experts) is not supported with disaggregated P/D: "
"vLLM does not capture routed experts across NIXL KV transfer."
)
return self
@@ -662,6 +658,11 @@ class InferenceConfig(BaseConfig):
if self.enable_return_sampling_mask:
namespace.return_sampling_mask = True
# The LoRA adapter is registered under the model name clients send, and vLLM rejects
# an adapter named like a served base model, so serve the base under another name.
if self.vllm.enable_lora and "served_model_name" not in extra_fields:
namespace.served_model_name = [f"{self.vllm.model}-base"]
kv_transfer_config = self.build_kv_transfer_config()
if kv_transfer_config is not None:
namespace.kv_transfer_config = kv_transfer_config
@@ -14,13 +14,14 @@ from prime_rl.configs.algorithm import (
from prime_rl.configs.monitors import TrainMonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
BaseWeightBroadcastConfig,
ClientConfig,
EnvVars,
FileSystemWeightBroadcastConfig,
HeartbeatConfig,
LogConfig,
ResumeConfig,
TransportConfig,
VLLMClientConfig,
WeightBroadcastConfig,
ZMQTransportConfig,
)
from prime_rl.configs.trainer import TokenizerConfig
@@ -39,7 +40,7 @@ class ModelConfig(BaseModelConfig):
lora: LoRAConfig | None = None
"""Per-run LoRA configuration. If None, LoRA is disabled."""
client: ClientConfig = ClientConfig()
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
"""Client of the live deployment (``[orchestrator.model.client]``)."""
@@ -480,55 +481,11 @@ class CheckpointConfig(BaseConfig):
keep_interval: int | None = Field(None, ge=1)
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
skip_progress: bool = False
"""Skip loading the progress from checkpoint."""
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["filesystem"] = "filesystem"
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
host: str = "localhost"
"""Weight transfer host."""
port: int
"""Weight transfer port."""
inference_world_size: int = Field(1, ge=1)
"""Total inference workers across all servers."""
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nccl"] = "nccl"
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
port: int = 8001
"""ModelExpress gRPC port."""
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
Field(discriminator="type"),
]
class ConcurrencyConfig(BaseConfig):
"""Adaptive in-flight concurrency control. The orchestrator sizes the
in-flight episode cap from engine KV capacity and learned per-env episode
costs; these fields only bound and seed it."""
in-flight episode cap from engine KV pressure; these fields only bound and
seed it."""
initial_inflight: int | None = Field(None, ge=1)
"""Optional initial in-flight episodes to start from. Set it when a good value is known to skip the initial ramp; otherwise auto-derive a pessimistic bound at runtime."""
@@ -610,15 +567,12 @@ class OrchestratorConfig(BaseConfig):
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
batch_size: int | None = Field(None, ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
batch_size: int = Field(128, ge=1)
"""Samples to train on per step."""
constant_trainer_batch_size: bool = True
"""Require each batch to reach its effective sample target."""
token_batch_size: int | None = Field(None, ge=1)
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight concurrency control (``[orchestrator.concurrency]``)."""
@@ -665,6 +619,19 @@ class OrchestratorConfig(BaseConfig):
env_cfg.algo.validate_env(env_cfg.env)
return self
@model_validator(mode="after")
def validate_loss_aggregation(self):
"""The trainer divides the rl loss by the batch's summed rl weights, so token-mean (weight
1 per token) and prompt-mean (weight 1 per group) envs can't share a batch."""
algos = [env.algo for env in self.train.source if env.algo.action_loss_type == "rl"]
aggregations = {algo.loss_aggregation if isinstance(algo, GRPOAlgoConfig) else "token" for algo in algos}
if len(aggregations) > 1:
raise ValueError(
"All train envs with an rl loss must use the same loss_aggregation: a prompt-mean group "
"would weigh as much as a single token of a token-mean env."
)
return self
@model_validator(mode="after")
def setup_truncated_sampling(self):
"""Truncated policy sampling trains with sampling replay (rollout
@@ -755,17 +722,8 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def resolve_batching(self):
has_rollout_batch = self.batch_size is not None
has_token_batch = self.token_batch_size is not None
if has_rollout_batch and has_token_batch:
raise ValueError("Set exactly one of batch_size or token_batch_size")
if not has_rollout_batch and not has_token_batch:
self.batch_size = 128
group_sizes = [source.group_size for source in self.train.source] or [self.train.group_size]
if self.batch_size is not None and any(self.batch_size % size for size in group_sizes):
if any(self.batch_size % size for size in group_sizes):
raise ValueError(
f"Batch size {self.batch_size} must be divisible by every train source's group_size {sorted(set(group_sizes))}"
)
@@ -8,50 +8,24 @@ from pydantic import Field, model_validator
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
from prime_rl.configs.monitors import FileMonitorConfig, PrimeTrainMonitorConfig
from prime_rl.configs.orchestrator import (
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
NIXLWeightBroadcastConfig as OrchestratorNIXLWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
OrchestratorConfig,
)
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.shared import (
EnvVars,
FileSystemWeightBroadcastConfig,
NCCLWeightBroadcastConfig,
ResumeConfig,
RunConfig,
SlurmConfig,
TransportConfig,
VLMConfig,
)
from prime_rl.configs.trainer import (
FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig,
)
from prime_rl.configs.trainer import (
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
)
from prime_rl.configs.trainer import (
NIXLWeightBroadcastConfig as TrainerNIXLWeightBroadcastConfig,
WeightBroadcastConfig,
)
from prime_rl.configs.trainer import (
TokenizerConfig,
TrainerConfig,
)
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
from prime_rl.utils.validation import (
propagate_shared_fields,
validate_shared_ckpt_config,
validate_shared_max_steps,
validate_shared_model_name,
validate_shared_seq_len,
validate_shared_tokenizer,
validate_shared_wandb_config,
validate_shared_weight_broadcast,
)
from prime_rl.utils.validation import propagate_shared_fields
class SharedLogConfig(BaseConfig):
@@ -128,50 +102,6 @@ class SharedModelConfig(BaseConfig):
"""VLM configuration. Set this to enable vision-language model support."""
class SharedInMemoryWeightBroadcastConfig(BaseConfig):
host: str = "localhost"
"""Weight transfer host."""
port: int
"""Weight transfer port."""
timeout: int = 1200
"""Timeout in seconds for the broadcast handshake and transfer."""
class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
type: Literal["nccl"] = "nccl"
port: int = 29501
"""Port for NCCL weight broadcast."""
class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
port: int = 8001
"""ModelExpress gRPC port."""
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
class SharedFileSystemWeightBroadcastConfig(BaseConfig):
type: Literal["filesystem"] = "filesystem"
timeout: int = 1200
"""Timeout in seconds for the broadcast handshake and transfer."""
SharedWeightBroadcastConfig: TypeAlias = Annotated[
SharedFileSystemWeightBroadcastConfig | SharedNCCLWeightBroadcastConfig | SharedNIXLWeightBroadcastConfig,
Field(discriminator="type"),
]
class BaseDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
"""GPUs per node."""
@@ -290,7 +220,7 @@ class RLConfig(BaseConfig):
seq_len: int | None = None
"""Shared sequence length. Propagates to ``trainer.model.seq_len`` and ``orchestrator.seq_len`` only when those values were not explicitly set; explicit per-component values always win."""
weight_broadcast: SharedWeightBroadcastConfig | None = None
weight_broadcast: WeightBroadcastConfig | None = None
rollout_transport: TransportConfig | None = None
@@ -395,15 +325,6 @@ class RLConfig(BaseConfig):
sub.output_dir = run_dir
return self
@model_validator(mode="after")
def auto_setup_resume(self):
"""Propagate the top-level resume onto the sub-configs."""
if self.resume is None:
return self
self.trainer.resume = self.resume.model_copy()
self.orchestrator.resume = self.resume.model_copy()
return self
@model_validator(mode="after")
def auto_setup_run_identity(self):
"""Default the W&B and Prime platform run names to ``run.name``.
@@ -427,13 +348,70 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def validate_shared_configs(self):
"""Validate consistency of shared configs across trainer, orchestrator, and inference."""
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
validate_shared_tokenizer(self.trainer, self.orchestrator, self.inference)
validate_shared_max_steps(self.trainer, self.orchestrator)
validate_shared_seq_len(self.trainer, self.orchestrator)
validate_shared_ckpt_config(self.trainer, self.orchestrator)
validate_shared_wandb_config(self.trainer, self.orchestrator)
"""Cross-component constraints for values set per sub-config rather than through the
shared fields (``propagate_shared_fields`` already rejects shared vs sub-config conflicts)."""
trainer, orchestrator, inference = self.trainer, self.orchestrator, self.inference
def require_equal(name: str, values: dict[str, Any]) -> None:
if len({repr(v) for v in values.values()}) > 1:
found = ", ".join(f"{path}={value!r}" for path, value in values.items())
raise ValueError(f"{name} must match across components ({found}). Set the shared [{name}] instead.")
# The orchestrator queries the inference server it is paired with; without one, it
# must match the trainer whose weights the external server receives.
if inference is not None:
require_equal(
"model.name",
{"inference.vllm.model": inference.vllm.model, "orchestrator.model.name": orchestrator.model.name},
)
else:
require_equal(
"model.name",
{"trainer.model.name": trainer.model.name, "orchestrator.model.name": orchestrator.model.name},
)
# ``tokenizer.name`` / ``trust_remote_code`` may differ (e.g. FP8-quantized inference variants).
chat_templates = {
"trainer.tokenizer.chat_template": trainer.tokenizer.chat_template,
"orchestrator.tokenizer.chat_template": orchestrator.tokenizer.chat_template,
}
if inference is not None:
chat_templates["inference.vllm.chat_template"] = inference.vllm.chat_template
require_equal("tokenizer.chat_template", chat_templates)
require_equal(
"max_steps", {"trainer.max_steps": trainer.max_steps, "orchestrator.max_steps": orchestrator.max_steps}
)
require_equal("resume", {"trainer.resume": trainer.resume, "orchestrator.resume": orchestrator.resume})
if trainer.model.seq_len < orchestrator.seq_len:
raise ValueError(
f"trainer.model.seq_len ({trainer.model.seq_len}) must be >= orchestrator.seq_len "
f"({orchestrator.seq_len}) so the trainer can handle every sequence the orchestrator produces."
)
if (trainer.ckpt is None) != (orchestrator.ckpt is None):
raise ValueError(
"Checkpointing must be configured on both trainer and orchestrator. Use the shared [ckpt]."
)
if trainer.ckpt and orchestrator.ckpt:
require_equal(
"ckpt.interval",
{
"trainer.ckpt.interval": trainer.ckpt.interval,
"orchestrator.ckpt.interval": orchestrator.ckpt.interval,
},
)
trainer_wandb, orchestrator_wandb = trainer.monitors.wandb, orchestrator.monitors.wandb
if (trainer_wandb is None) != (orchestrator_wandb is None):
raise ValueError(
"W&B must be configured on both trainer and orchestrator, otherwise only one side's "
"metrics are logged. Use the shared [monitors.wandb]."
)
if trainer_wandb and orchestrator_wandb:
require_equal(
"monitors.wandb.project",
{
"trainer.monitors.wandb.project": trainer_wandb.project,
"orchestrator.monitors.wandb.project": orchestrator_wandb.project,
},
)
return self
@model_validator(mode="after")
@@ -446,52 +424,19 @@ class RLConfig(BaseConfig):
"""
if self.weight_broadcast is None:
if self.trainer.model.lora is not None or self.inference is None:
self.weight_broadcast = SharedFileSystemWeightBroadcastConfig()
self.weight_broadcast = FileSystemWeightBroadcastConfig()
else:
self.weight_broadcast = SharedNCCLWeightBroadcastConfig()
self.weight_broadcast = NCCLWeightBroadcastConfig()
if self.weight_broadcast.type != "filesystem" and self.trainer.model.lora is not None:
raise ValueError(
"LoRA requires weight_broadcast.type = 'filesystem': vLLM loads adapters only from a "
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
"have no disk artifact to load from."
)
if self.weight_broadcast.type in ("nccl", "nixl"):
inference_world_size = (
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
if self.inference
else 1
)
common_config = dict(
host=self.weight_broadcast.host,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
inference_world_size=inference_world_size,
)
if self.weight_broadcast.type == "nccl":
transport_config = {}
trainer_config_type = TrainerNCCLWeightBroadcastConfig
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
else:
transport_config = dict(
session_id=self.weight_broadcast.session_id,
overlap_transfer_and_replay=self.weight_broadcast.overlap_transfer_and_replay,
)
trainer_config_type = TrainerNIXLWeightBroadcastConfig
orchestrator_config_type = OrchestratorNIXLWeightBroadcastConfig
self.trainer.weight_broadcast = trainer_config_type(**common_config, **transport_config)
self.orchestrator.weight_broadcast = orchestrator_config_type(**common_config, **transport_config)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig(
timeout=self.weight_broadcast.timeout
)
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig(
timeout=self.weight_broadcast.timeout
)
self.trainer.weight_broadcast = self.weight_broadcast.model_copy()
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy()
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
@@ -641,17 +586,17 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_disaggregated_combined_replay(self):
def validate_disaggregated_no_routed_experts(self):
"""Runs after ``auto_setup_router_replay``, which sets the inference flag after InferenceConfig's validators."""
inference = self.inference
if (
inference is not None
and inference.deployment.type == "disaggregated"
and inference.enable_return_sampling_mask
and inference.vllm.enable_return_routed_experts
):
raise ValueError(
"Combined router and sampling replay is not supported with disaggregated P/D: "
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
"Router replay (inference.vllm.enable_return_routed_experts / trainer.enable_router_replay) "
"is not supported with disaggregated P/D: vLLM does not capture routed experts across NIXL KV transfer."
)
return self
@@ -705,6 +650,11 @@ class RLConfig(BaseConfig):
dp = self.inference.vllm.data_parallel_size
if self.inference.vllm.api_server_count < dp and not self.inference.vllm.enable_lora:
self.inference.vllm.api_server_count = dp
if self.weight_broadcast.type != "filesystem":
# Every inference GPU joins the in-memory transfer group, so size it after the DP fill.
world_size = dp * self.inference.vllm.tensor_parallel_size
self.trainer.weight_broadcast.inference_world_size = world_size
self.orchestrator.weight_broadcast.inference_world_size = world_size
elif self.deployment.type == "multi_node": # multi-node
self.orchestrator.num_train_workers = (
@@ -10,27 +10,28 @@ from renderers.base import MODEL_RENDERER_MAP
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
from prime_rl.configs.monitors import TrainMonitorsConfig
from prime_rl.configs.shared import (
EnvVars,
FileSystemWeightBroadcastConfig,
HeartbeatConfig,
NCCLWeightBroadcastConfig,
ResumeConfig,
RunConfig,
SlurmConfig,
TrainerLogConfig,
WeightBroadcastConfig,
)
from prime_rl.configs.trainer import (
AdamWConfig,
CheckpointConfig,
ConstantSchedulerConfig,
FileSystemWeightBroadcastConfig,
GCConfig,
ModelConfig,
NCCLWeightBroadcastConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
WeightBroadcastConfig,
validate_scheduler,
)
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
@@ -100,6 +101,9 @@ class SFTColumnsConfig(BaseConfig):
tools: str = "tools"
"""Column with the tool schemas in OpenAI function-calling format."""
message_loss_mask: str = "message_loss_mask"
"""Optional column of booleans or integer 0/1 flags, one per resolved message (prompt + completion for split rows). Zero excludes a message from loss; one preserves its normal supervision. Missing or null masks leave supervision unchanged."""
renderer: dict[str, str] = {"reasoning_effort": "reasoning_effort"}
"""Per-sample renderer arguments as ``renderer field = dataset column``, e.g. ``reasoning_effort = "effort"``. A row's non-null value overrides the ``[renderer]`` setting; rows and datasets without the column use it unchanged."""
@@ -275,6 +279,20 @@ class SFTConfig(BaseConfig):
self.model.moe_router_dtype = "bfloat16"
return self
@model_validator(mode="after")
def resolve_weight_decay_auto(self):
"""Resolve ``optim.weight_decay='auto'``: SFT keeps the historical 0.01 default — standard L2 regularization for supervised training."""
if self.optim.weight_decay == "auto":
self.optim.weight_decay = 0.01
return self
@model_validator(mode="after")
def resolve_freeze_moe_router_auto(self):
"""Resolve ``model.freeze_moe_router='auto'``: SFT trains the router."""
if self.model.freeze_moe_router == "auto":
self.model.freeze_moe_router = False
return self
@model_validator(mode="after")
def auto_setup_run_identity(self):
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
@@ -456,7 +474,7 @@ class SFTConfig(BaseConfig):
self.weight_broadcast.inference_world_size = (
self.deployment.num_infer_nodes * self.deployment.gpus_per_node
)
self.inference.weight_broadcast.type = self.weight_broadcast.type
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
if self.max_steps is None:
warnings.warn(
"Online evals without max_steps: the evals process never sees a final checkpoint, "
@@ -507,7 +525,7 @@ class SFTConfig(BaseConfig):
vllm.api_server_count = vllm.data_parallel_size
if self.weight_broadcast.type == "nccl":
self.weight_broadcast.inference_world_size = vllm.data_parallel_size * vllm.tensor_parallel_size
self.inference.weight_broadcast.type = self.weight_broadcast.type
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
host = self.inference.server.host or "localhost"
client = self.eval.client
@@ -609,13 +627,6 @@ class SFTConfig(BaseConfig):
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
@model_validator(mode="after")
def ep_only_with_custom_impl(self):
if self.model.ep != 1 and self.model.ep != "auto" and self.model.impl not in ("custom", "auto"):
raise ValueError("EP is only supported with the custom implementation or auto mode")
return self
### Auto-setup and validate shared configs
@model_validator(mode="after")
@@ -4,6 +4,7 @@ from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import AfterValidator, Field, model_validator
from verifiers.v1.configs.client import BaseClientConfig
from prime_rl.utils.config import BaseConfig
@@ -43,6 +44,48 @@ class BaseWeightBroadcastConfig(BaseConfig):
fails the run when no consumer acknowledges an offered version in time."""
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["filesystem"] = "filesystem"
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
host: str = "localhost"
"""Weight transfer host."""
port: int
"""Weight transfer port."""
inference_world_size: int = Field(1, ge=1)
"""Total inference workers across all servers. Set automatically by ``rl`` and ``sft``."""
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nccl"] = "nccl"
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
port: int = 8001
"""ModelExpress gRPC port."""
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
Field(discriminator="type"),
]
"""Weight transfer from trainer to inference. ``rl`` copies its ``[weight_broadcast]`` to the trainer and orchestrator."""
class RunConfig(BaseConfig):
name: str | None = None
"""Run name. Auto-generated as ``<envs>--<model>--<short-id>`` when unset, so every launch gets a fresh, readable run directory; set an explicit name (e.g. an experiment name) to get a predictable run directory, which is also required to resume a previous run. Unless set explicitly, the W&B run name and the Prime platform run name inherit it."""
@@ -170,22 +213,10 @@ class DynamoConfig(BaseConfig):
"""Dynamo frontend URL used to discover inference workers for RL control."""
class ClientConfig(BaseConfig):
class ClientConfig(BaseClientConfig):
wait_for_ready_timeout: int = 3600
"""Seconds to wait at startup for the inference pool to become ready."""
base_url: str = "http://localhost:8000/v1"
"""Base URL for the OpenAI API. For multi-replica deployments, point this at a router in front of the replicas."""
api_key_var: str = "VLLM_API_KEY"
"""Environment variable name containing the API key, resolved via ``os.getenv``. Can be any string when the server is not protected by an API key; the same key is used for every URL."""
headers: dict[str, str] = {}
"""Static headers sent with every request."""
headers_from_env: dict[str, str] = {}
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
skip_model_check: bool = False
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
@@ -196,6 +227,13 @@ class ClientConfig(BaseConfig):
"""Dynamo RL worker-discovery configuration."""
class VLLMClientConfig(ClientConfig):
"""Client defaults for the live inference deployment managed by training."""
base_url: str = "http://localhost:8000/v1"
api_key_var: str = "VLLM_API_KEY"
class LogConfig(BaseConfig):
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
"""Log level for the process. Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``."""
@@ -228,14 +266,6 @@ class HeartbeatConfig(BaseConfig):
rate limit. Size it well under the monitor's period."""
class MetricsServerConfig(BaseConfig):
port: int = Field(8000, ge=1, le=65535)
"""Port to expose metrics and health endpoints on."""
host: str = "0.0.0.0"
"""Host to bind the server to."""
class BaseTransportConfig(BaseConfig):
pass
@@ -8,13 +8,13 @@ from pydantic import BeforeValidator, Field, field_validator, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
BaseWeightBroadcastConfig,
EnvVars,
FileSystemWeightBroadcastConfig,
HeartbeatConfig,
MetricsServerConfig,
ResumeConfig,
TrainerLogConfig,
TransportConfig,
WeightBroadcastConfig,
ZMQTransportConfig,
)
from prime_rl.utils.config import BaseConfig, default_output_dir
@@ -22,6 +22,7 @@ from prime_rl.utils.config import BaseConfig, default_output_dir
# -- Shared trainer configs (used by both SFT and RL trainers) --
AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]
DSABackend: TypeAlias = Literal["tilelang", "cudnn_flashmla"]
class GCConfig(BaseConfig):
@@ -314,9 +315,6 @@ class ModelConfig(BaseModelConfig):
cp_style: Literal["ring", "ulysses"] = "ring"
"""CP communication style. ``ring`` uses ring-attention all-gather/reduce-scatter (requires custom kernels per attention type). ``ulysses`` uses all-to-all to redistribute Q/K/V from sequence-sharded to head-sharded, runs vanilla attention locally on the full sequence, then all-to-all back — works out-of-the-box with any attention kernel (softmax FA, linear attention, mamba, etc.)."""
impl: Literal["hf", "custom", "auto"] = "auto"
"""Model implementation. ``auto`` selects ``custom`` if supported by the model, otherwise ``hf``."""
optimization_dtype: Literal["bfloat16", "float32"] = "float32"
"""dtype for model optimization."""
@@ -324,15 +322,18 @@ class ModelConfig(BaseModelConfig):
"""dtype for gradient/parameter reductions."""
moe_router_dtype: Literal["bfloat16", "float32", "auto"] = "auto"
"""Compute dtype for MoE router gates. ``float32`` keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. ``auto`` (default) resolves to ``float32`` for RL and ``bfloat16`` for SFT. Router score functions (sigmoid/softmax) run in fp32 regardless. Only affects the custom MoE implementation; a no-op for non-MoE and HF-impl models."""
"""Compute dtype for MoE router gates. ``float32`` keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. ``auto`` (default) resolves to ``float32`` for RL and ``bfloat16`` for SFT. Router score functions (sigmoid/softmax) run in fp32 regardless. A no-op for non-MoE models."""
quantization: QuantizationConfig | None = None
dsa_backend: DSABackend = "tilelang"
"""Kernels for the DSA sparse MLA attention (``glm_moe_dsa``, e.g. GLM-5). ``tilelang`` runs the TileLang forward and backward. ``cudnn_flashmla`` runs the FlashMLA sparse prefill forward with the cuDNN frontend CuTe-DSL backward; it needs the ``flash-mla`` extra and an SM90 GPU (SM100/SM103 are wired up but untested)."""
index_cache: IndexCacheConfig | None = None
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
freeze_moe_router: bool = False
"""Freeze MoE router parameters during training."""
freeze_moe_router: bool | Literal["auto"] = "auto"
"""Freeze MoE router gate parameters. ``auto`` (default): ``True`` for RL, ``False`` for SFT; a no-op on non-MoE models. Frozen routers get no optimizer state, so resuming a checkpoint saved with a frozen router with ``freeze_moe_router=false`` fails on missing DCP keys."""
lora: LoRAConfig | None = None
"""LoRA configuration. If None, LoRA is disabled."""
@@ -343,20 +344,6 @@ class ModelConfig(BaseModelConfig):
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 8192
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. In SFT the fused head computes the summed cross-entropy and its gradients chunk by chunk, holding one chunk's full-vocab logits at a time."""
@model_validator(mode="after")
def trust_remote_code_only_with_hf(self):
"""Trust remote code only if the model is from HF."""
if self.trust_remote_code:
if self.impl not in ("hf", "auto"):
raise ValueError("Trust remote code is only supported with the HF implementation or auto mode.")
return self
@model_validator(mode="after")
def vlm_only_with_custom_impl(self):
if self.vlm is not None and self.impl != "custom":
raise ValueError("VLM training requires model.impl='custom'")
return self
@model_validator(mode="after")
def vlm_cp_requires_ulysses(self):
if self.vlm is not None and self.cp > 1 and self.cp_style != "ulysses":
@@ -367,11 +354,6 @@ class ModelConfig(BaseModelConfig):
def validate_cp(self):
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]:
raise ValueError("CP is only supported with flash attention 2, 3, or 4")
if self.cp > 1 and self.impl not in ("custom", "auto"):
raise ValueError(
"Context parallelism requires model.impl='custom' or 'auto' "
"(resolved to a custom PrimeRL implementation)"
)
return self
@model_validator(mode="after")
@@ -392,19 +374,6 @@ class ModelConfig(BaseModelConfig):
)
return self
@model_validator(mode="after")
def flash_attention_4_only_with_custom_impl(self):
# "auto" may resolve to FA4 on Blackwell, so apply the same impl constraint.
if self.attn in ("flash_attention_4", "auto") and self.impl not in ("custom", "auto"):
raise ValueError("Flash attention 4 is only supported with model.impl='custom' or 'auto'")
return self
@model_validator(mode="after")
def quantization_only_with_custom_impl(self):
if self.quantization is not None and self.impl not in ("custom", "auto"):
raise ValueError(f"{self.quantization.type} training is only supported with model.impl='custom' or 'auto'.")
return self
@model_validator(mode="after")
def validate_moe_runtime(self):
if self.ep == 1:
@@ -490,23 +459,13 @@ class BaseOptimizerConfig(BaseConfig):
lr: float = Field(1e-6, ge=0)
"""Peak learning rate."""
weight_decay: float = Field(0.01, ge=0)
"""L2 weight-decay coefficient."""
weight_decay: Annotated[float, Field(ge=0)] | Literal["auto"] = "auto"
"""L2 weight-decay coefficient. ``"auto"`` (default) resolves to ``0.0`` for RL and ``0.01`` for SFT."""
max_norm: float | None = Field(1.0, ge=0)
"""Maximum gradient norm to clip to. If None, gradient clipping is disabled."""
class SGDConfig(BaseOptimizerConfig):
type: Literal["sgd"] = "sgd"
nesterov: bool = True
"""Use Nesterov momentum."""
momentum: float = 0.9
"""SGD momentum factor."""
class AdamWConfig(BaseOptimizerConfig):
type: Literal["adamw"] = "adamw"
@@ -534,9 +493,7 @@ class SignSGDConfig(BaseOptimizerConfig):
type: Literal["sign_sgd"] = "sign_sgd"
OptimizerConfig: TypeAlias = Annotated[
SGDConfig | AdamWConfig | MuonConfig | SignSGDConfig, Field(discriminator="type")
]
OptimizerConfig: TypeAlias = Annotated[AdamWConfig | MuonConfig | SignSGDConfig, Field(discriminator="type")]
class CheckpointConfig(BaseConfig):
@@ -552,9 +509,6 @@ class CheckpointConfig(BaseConfig):
keep_interval: int | None = Field(None, ge=1)
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
skip_progress: bool = False
"""Skip loading the progress from checkpoint."""
skip_scheduler: bool = False
"""Skip loading the scheduler from checkpoint."""
@@ -658,47 +612,8 @@ class DataLoaderConfig(BaseConfig):
fake: FakeDataLoaderConfig | None = None
"""Use a fake data loader sampling random micro-batches (for debugging)."""
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["filesystem"] = "filesystem"
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
host: str = "localhost"
"""Weight transfer host."""
port: int
"""Weight transfer port."""
# TODO: Should not be configurable, but auto-inferred
inference_world_size: int = 1
"""Number of inference workers."""
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nccl"] = "nccl"
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
port: int = 8001
"""ModelExpress gRPC port."""
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two staging arenas so inference can replay one weight group while receiving the next."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
Field(discriminator="type"),
]
num_workers: int = Field(0, ge=0)
"""Number of background threads that prepare micro batches ahead of the training loop, analogous to torch DataLoader's ``num_workers`` but with threads instead of processes. 0 prepares them on the main thread."""
class TrainerConfig(BaseConfig):
@@ -759,9 +674,6 @@ class TrainerConfig(BaseConfig):
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
metrics_server: MetricsServerConfig | None = None
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
env_vars: EnvVars = {}
"""Extra environment variables for the trainer process(es). Merged on top of the launcher defaults."""
@@ -772,6 +684,20 @@ class TrainerConfig(BaseConfig):
self.model.moe_router_dtype = "float32"
return self
@model_validator(mode="after")
def resolve_weight_decay_auto(self):
"""Resolve ``optim.weight_decay='auto'``: RL optimizes the reward objective, not a fixed dataset — L2 decay toward zero fights it, so default to no weight decay."""
if self.optim.weight_decay == "auto":
self.optim.weight_decay = 0.0
return self
@model_validator(mode="after")
def resolve_freeze_moe_router_auto(self):
"""Resolve ``model.freeze_moe_router='auto'``: RL keeps the pretrained router."""
if self.model.freeze_moe_router == "auto":
self.model.freeze_moe_router = True
return self
@model_validator(mode="after")
def deepep_disables_grad_clipping(self):
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
@@ -852,17 +778,3 @@ class TrainerConfig(BaseConfig):
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def ep_only_with_custom_impl(self):
if self.model.ep != 1 and self.model.ep != "auto" and self.model.impl not in ("custom", "auto"):
raise ValueError("EP is only supported with the custom implementation or auto mode")
return self
@model_validator(mode="after")
def router_replay_only_with_custom_impl(self):
if self.enable_router_replay and self.model.impl not in ("custom", "auto"):
raise ValueError("Router replay is only supported with the custom implementation or auto mode")
return self
@@ -1,10 +1,6 @@
from __future__ import annotations
from typing import Any, Optional
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.trainer import TrainerConfig
from typing import Any
def propagate_shared_fields(data: Any) -> Any:
@@ -128,6 +124,8 @@ def propagate_shared_fields(data: Any) -> Any:
"inference.vllm.chat_template",
)
propagate("resume", "trainer.resume", "orchestrator.resume")
# [rollout_transport] → both sub-configs (host is launcher-injected for zmq multi-node).
propagate("rollout_transport", "trainer.rollout_transport", "orchestrator.rollout_transport")
@@ -147,7 +145,7 @@ def propagate_shared_fields(data: Any) -> Any:
# - shared ``[tokenizer] chat_template`` (already filled all three above,
# this re-fill is a no-op via fill-if-absent), and
# - ``[trainer.tokenizer] chat_template`` set directly without shared
# (only path that reaches inference; ``validate_shared_tokenizer``
# (only path that reaches inference; ``RLConfig.validate_shared_configs``
# would otherwise complain about the missing inference value).
trainer_chat_template = get("trainer.tokenizer.chat_template")
if trainer_chat_template is not None:
@@ -190,130 +188,3 @@ def propagate_shared_fields(data: Any) -> Any:
raise ValueError("\n".join(lines))
return data
def validate_shared_ckpt_config(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.ckpt and not orchestrator.ckpt:
raise ValueError(
"Trainer checkpoint config is specified, but orchestrator checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
)
if orchestrator.ckpt and not trainer.ckpt:
raise ValueError(
"Orchestrator checkpoint config is specified, but trainer checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
)
if trainer.ckpt and orchestrator.ckpt and trainer.ckpt.interval != orchestrator.ckpt.interval:
raise ValueError(
f"Trainer checkpoint interval ({trainer.ckpt.interval}) and orchestrator checkpoint interval ({orchestrator.ckpt.interval}) are not the same. Please specify the same checkpoint interval for both."
)
if trainer.resume != orchestrator.resume:
raise ValueError(
f"Trainer resume ({trainer.resume}) and orchestrator resume ({orchestrator.resume}) are not the same. Please specify the same resume config for both."
)
def validate_shared_model_name(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
# Orchestrator must match inference (it queries the inference server)
if inference is not None:
if inference.vllm.model != orchestrator.model.name:
raise ValueError(
f"Inference model name ({inference.vllm.model}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
"The orchestrator queries the inference server and must use the same model name."
)
return
if trainer.model.name.startswith("Jackmin108/"): # The TT MoE models will have a different name on the orchestrator
return
if trainer.model.name != orchestrator.model.name:
raise ValueError(
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
)
def validate_shared_wandb_config(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.monitors.wandb and not orchestrator.monitors.wandb:
raise ValueError(
"Trainer W&B config is specified, but orchestrator W&B config is not. "
"This means only trainer metrics will be logged. Please specify [orchestrator.monitors.wandb] to log orchestrator metrics as well, "
"or use [monitors.wandb] to configure both at once."
)
if orchestrator.monitors.wandb and not trainer.monitors.wandb:
raise ValueError(
"Orchestrator W&B config is specified, but trainer W&B config is not. "
"This means only orchestrator metrics will be logged. Please specify [trainer.monitors.wandb] to log trainer metrics as well, "
"or use [monitors.wandb] to configure both at once."
)
if trainer.monitors.wandb and orchestrator.monitors.wandb:
if trainer.monitors.wandb.project != orchestrator.monitors.wandb.project:
raise ValueError(
f"Trainer W&B project ({trainer.monitors.wandb.project}) and orchestrator W&B project ({orchestrator.monitors.wandb.project}) are not the same. Please specify the same W&B project for both."
)
def validate_shared_max_steps(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.max_steps != orchestrator.max_steps:
raise ValueError(
f"Trainer max steps ({trainer.max_steps}) and orchestrator max steps ({orchestrator.max_steps}) are not the same. Please specify the same max steps for both."
)
def validate_shared_seq_len(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.model.seq_len < orchestrator.seq_len:
raise ValueError(
f"Trainer model seq_len ({trainer.model.seq_len}) must be >= orchestrator seq_len ({orchestrator.seq_len}). "
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
)
def validate_shared_tokenizer(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
# Validate chat_template is consistent across all components.
# We only check chat_template (not name/trust_remote_code) because those
# are auto-derived from model names which may legitimately differ (e.g.
# when inference uses an FP8 quantized variant of the same model).
if trainer.tokenizer.chat_template != orchestrator.tokenizer.chat_template:
raise ValueError(
f"Trainer chat_template ({trainer.tokenizer.chat_template!r}) and orchestrator "
f"chat_template ({orchestrator.tokenizer.chat_template!r}) do not match. "
f"Use the shared [tokenizer] config to set chat_template for both."
)
if inference is not None:
if trainer.tokenizer.chat_template != inference.vllm.chat_template:
raise ValueError(
f"Inference chat_template ({inference.vllm.chat_template!r}) does not match "
f"the shared tokenizer chat_template ({trainer.tokenizer.chat_template!r}). "
f"Use the shared [tokenizer] config to set chat_template for all components."
)
def validate_shared_weight_broadcast(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
if trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
raise ValueError(
f"Trainer weight broadcast type ({trainer.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
)
if inference is not None and inference.weight_broadcast.type != trainer.weight_broadcast.type:
raise ValueError(
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and trainer/orchestrator weight broadcast type ({trainer.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for all components."
)
+18 -14
View File
@@ -11,13 +11,12 @@ dependencies = [
"datasets>=4.0.0",
"jaxtyping>=0.3.2",
"loguru>=0.7.3",
"pyarrow>=21.0.0",
"numpy>=2.2.6",
"transformers==5.6.2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
"prime>=0.8.0",
"prime-runs[train]>=0.1.3",
"prime-runs[train]>=0.1.4",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
@@ -32,8 +31,6 @@ dependencies = [
"verifiers[harbor]>=0.3.2.dev158",
"renderers[multimodal]>=0.1.12.dev2",
"pybase64>=1.4.2",
"orjson>=3.10",
"pandas>=2.0",
"msgspec>=0.18",
]
@@ -56,12 +53,14 @@ gpu = [
"torchvision ; sys_platform == 'linux'",
"torchaudio ; sys_platform == 'linux'",
"torchdata>=0.11.0 ; sys_platform == 'linux'",
"vllm>=0.30.0 ; sys_platform == 'linux'",
"vllm>=0.31.0 ; sys_platform == 'linux'",
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
"torchtitan ; sys_platform == 'linux'",
"dion ; sys_platform == 'linux'",
"tilelang>=0.1.8 ; sys_platform == 'linux'",
# DSA sparse MLA backward kernel (CuTe DSL); >=1.29 matches the pinned CUTLASS DSL 4.7.
"nvidia-cudnn-frontend>=1.30.0 ; sys_platform == 'linux'",
"flash-linear-attention ; sys_platform == 'linux'",
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
@@ -91,13 +90,15 @@ disagg = [
"deep-ep ; sys_platform == 'linux'",
"deep-gemm ; sys_platform == 'linux'",
"nixl ; sys_platform == 'linux'",
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
"vllm-router ; sys_platform == 'linux'",
]
quack = [
"quack-kernels>=0.4.1 ; sys_platform == 'linux'",
]
sonic-moe = ["sonic-moe ; sys_platform == 'linux'"]
# FlashMLA sparse prefill forward for `model.dsa_backend = "cudnn_flashmla"` (sm_90a + sm_100f).
# FlashMLA is not on PyPI and only an x86_64 wheel is published.
flash-mla = ["flash-mla ; sys_platform == 'linux' and platform_machine == 'x86_64'"]
# Prebuilt `prime-kernels` wheels from a release (see the `kernels` skill). Compiled for
# sm_100a; on other GPUs the package installs fine and reports its kernels unavailable.
kernels = [
@@ -111,12 +112,10 @@ all = [
"prime-rl[sonic-moe]",
"prime-rl[flash-attn-3]",
"prime-rl[flash-attn-cute]",
"prime-rl[flash-mla]",
]
[dependency-groups]
mamba-ssm = [
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
]
dev = [
"ipykernel>=6.29.5",
"ipywidgets>=8.1.7",
@@ -148,7 +147,7 @@ override-dependencies = [
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
"apache-tvm-ffi==0.1.11",
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
# vLLM 0.30.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
# vLLM 0.31.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
"nvidia-cutlass-dsl==4.7.1",
"transformers==5.6.2",
@@ -226,10 +225,12 @@ requires-dist = [
]
[tool.uv.exclude-newer-package]
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
# verifiers pins harbor==0.24.0, published inside the rolling window;
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
harbor = "2026-08-11T00:00:00Z"
harbor = "2026-10-08T00:00:00Z"
tokenspeed-mla = false
# vLLM 0.31.0 pins flashinfer-python 0.7.0.post1, published inside the rolling window
flashinfer-python = false
fastokens = false
flash_attn_3 = false
# PrimeIntellect-published packages in this project's dependency closure —
@@ -253,6 +254,7 @@ deep-gemm = false
nixl-cu13 = false
torchao = false
prime-kernels = false
flash-mla = false
[tool.uv.sources]
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
@@ -278,8 +280,8 @@ vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
@@ -293,6 +295,8 @@ prime-kernels = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
# FlashMLA nv_dev @ b7643bd built against torch 2.13.0+cu130 (see the release notes for the recipe).
flash-mla = { url = "https://github.com/NovaSky-AI/skyrl-wheels/releases/download/cu13torch2.13-flashmla-b7643bd/flash_mla-1.0.0%2Bcu.13.0.torch.2.13.b7643bd-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
mamba-ssm = { git = "https://github.com/state-spaces/mamba", rev = "f577286" }
flash_attn_3 = { index = "pytorch-cu130-test" }
+15 -2
View File
@@ -53,8 +53,8 @@ describe_tag() {
sed -E 's/-[0-9]+-g[0-9a-f]+$//' <<< "$1"
}
verifiers_git_version() {
local dir="$root/deps/verifiers"
standard_git_version() {
local dir="$1"
local desc tag distance
[ -d "$dir" ] || return 1
@@ -64,6 +64,14 @@ verifiers_git_version() {
next_patch_dev_version "$tag" "$distance"
}
verifiers_git_version() {
standard_git_version "$root/deps/verifiers"
}
pydantic_config_git_version() {
standard_git_version "$root/deps/pydantic-config"
}
renderers_git_version() {
local dir="$root/deps/renderers"
local desc tag distance version
@@ -111,22 +119,27 @@ resolve_version() {
verifiers_version="$(resolve_version verifiers VERIFIERS_PRETEND_VERSION verifiers_git_version)"
renderers_version="$(resolve_version renderers RENDERERS_PRETEND_VERSION renderers_git_version)"
pydantic_config_version="$(resolve_version prime-pydantic-config PYDANTIC_CONFIG_PRETEND_VERSION pydantic_config_git_version)"
printf 'Resolved verifiers pretend version: %s\n' "$verifiers_version" >&2
printf 'Resolved renderers pretend version: %s\n' "$renderers_version" >&2
printf 'Resolved pydantic-config pretend version: %s\n' "$pydantic_config_version" >&2
case "$mode" in
shell)
printf "export VERIFIERS_PRETEND_VERSION='%s'\n" "$verifiers_version"
printf "export RENDERERS_PRETEND_VERSION='%s'\n" "$renderers_version"
printf "export PYDANTIC_CONFIG_PRETEND_VERSION='%s'\n" "$pydantic_config_version"
;;
github-output)
printf 'verifiers=%s\n' "$verifiers_version"
printf 'renderers=%s\n' "$renderers_version"
printf 'pydantic_config=%s\n' "$pydantic_config_version"
;;
env)
printf 'VERIFIERS_PRETEND_VERSION=%s\n' "$verifiers_version"
printf 'RENDERERS_PRETEND_VERSION=%s\n' "$renderers_version"
printf 'PYDANTIC_CONFIG_PRETEND_VERSION=%s\n' "$pydantic_config_version"
;;
*)
printf 'Unknown output mode: %s\n' "$mode" >&2
+1 -2
View File
@@ -113,8 +113,7 @@ HEAVY_PINS_PY
echo "[prime-rl] syncing ${DEST} into /app/.venv"
( cd "$DEST" && uv sync --inexact --locked --no-dev --all-packages \
--extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 \
--extra flash-attn-cute --extra disagg --extra quack --extra kernels \
--group mamba-ssm )
--extra flash-attn-cute --extra flash-mla --extra disagg --extra quack --extra kernels )
# The chart's `uv run --no-sync <entrypoint>` commands resolve the
# project from the cwd; the venv itself stays /app/.venv via
# UV_PROJECT_ENVIRONMENT above.
+88
View File
@@ -0,0 +1,88 @@
import argparse
import os
import re
import shutil
import subprocess
import tomllib
from pathlib import Path
def editable_paths(root: Path) -> list[Path]:
lock = tomllib.loads((root / "uv.lock").read_text())
paths = set()
for package in lock["package"]:
source = package["source"]
if "directory" in source:
raise ValueError(f"Non-editable local package: {package['name']}")
if "editable" not in source:
continue
path = (root / source["editable"]).resolve()
if not path.is_relative_to(root):
raise ValueError(f"Editable package outside the application: {path}")
paths.add(path)
return sorted(paths)
def set_fallback_version(pyproject: Path, version: str) -> None:
if not re.fullmatch(r"[0-9][A-Za-z0-9.+-]*", version):
raise ValueError(f"Invalid package version: {version!r}")
content, count = re.subn(
r'(?m)^fallback-version = "[^"]*"$', f'fallback-version = "{version}"', pyproject.read_text()
)
if count != 1:
raise ValueError(f"Expected one fallback-version in {pyproject}")
pyproject.write_text(content)
def copy_installation_artifacts(venv: Path, baseline: set[Path], output: Path) -> None:
# The runtime supplies the interpreter and third-party environment.
for directory in (venv / "bin", venv / "lib/python3.12/site-packages"):
for path in directory.iterdir():
relative = path.relative_to(venv)
if relative in baseline:
continue
target = output / ".venv" / relative
target.parent.mkdir(parents=True, exist_ok=True)
if path.is_dir():
shutil.copytree(path, target, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
else:
shutil.copy2(path, target)
def application_layer(root: Path, output: Path) -> None:
if output.is_relative_to(root):
raise ValueError("The output directory must be outside the application")
if output.exists():
raise FileExistsError(output)
venv = root / ".venv"
if venv.exists() or venv.is_symlink():
raise FileExistsError(venv)
versions = {
"deps/verifiers": "VERIFIERS_PRETEND_VERSION",
"deps/renderers": "RENDERERS_PRETEND_VERSION",
"deps/pydantic-config": "PYDANTIC_CONFIG_PRETEND_VERSION",
}
for path, variable in versions.items():
set_fallback_version(root / path / "pyproject.toml", os.environ[variable])
subprocess.run(["uv", "venv", "--python", "/usr/bin/python3.12", str(venv)], check=True)
baseline = {path.relative_to(venv) for path in venv.rglob("*")}
command = ["uv", "pip", "install", "--python", str(venv / "bin/python"), "--no-deps"]
for path in editable_paths(root):
command.extend(["--editable", str(path)])
subprocess.run(command, check=True, cwd=root)
shutil.copytree(root, output, ignore=shutil.ignore_patterns(".venv", ".git", "__pycache__", "*.pyc"))
copy_installation_artifacts(venv, baseline, output)
def main() -> None:
parser = argparse.ArgumentParser(description="Build a source and editable-package Docker layer")
parser.add_argument("root", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
application_layer(args.root.resolve(), args.output.resolve())
if __name__ == "__main__":
main()
+80
View File
@@ -0,0 +1,80 @@
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
def dependency_fingerprint(root: Path) -> str:
inputs = [root / path for path in ("Dockerfile.cuda", ".dockerignore", "uv.lock", "scripts/docker_dependencies.py")]
for directory, children, files in os.walk(root):
children[:] = [name for name in children if name not in {".git", ".venv", "outputs"}]
if "pyproject.toml" in files:
inputs.append(Path(directory) / "pyproject.toml")
digest = hashlib.sha256()
for path in sorted(inputs):
name = path.relative_to(root).as_posix().encode()
content = path.read_bytes()
digest.update(len(name).to_bytes(8, "big"))
digest.update(name)
digest.update(len(content).to_bytes(8, "big"))
digest.update(content)
return digest.hexdigest()
def registry_digest(image: str) -> str | None:
registry, _, reference = image.partition("/")
if registry != "ghcr.io":
raise ValueError("Dependency images must use ghcr.io")
repository, separator, tag = reference.rpartition(":")
if not separator or not repository or not tag:
raise ValueError("Expected ghcr.io/<owner>/<image>:<tag>")
query = urlencode({"service": registry, "scope": f"repository:{repository}:pull"})
headers = {}
if token := os.environ.get("GH_TOKEN"):
credentials = f"{os.environ['GITHUB_ACTOR']}:{token}".encode()
headers["Authorization"] = f"Basic {base64.b64encode(credentials).decode()}"
request = Request(f"https://{registry}/token?{query}", headers=headers)
with urlopen(request, timeout=30) as response:
token = json.load(response)["token"]
request = Request(
f"https://{registry}/v2/{repository}/manifests/{tag}",
headers={
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json",
},
method="HEAD",
)
try:
with urlopen(request, timeout=30) as response:
digest = response.headers["Docker-Content-Digest"]
if not digest or not digest.startswith("sha256:"):
raise ValueError(f"Missing or invalid image digest for {image}")
return digest
except HTTPError as error:
if error.code != 404:
raise
return None
def main() -> None:
parser = argparse.ArgumentParser(description="Fingerprint and resolve Docker dependency images")
commands = parser.add_subparsers(dest="command", required=True)
fingerprint = commands.add_parser("fingerprint")
fingerprint.add_argument("root", type=Path)
resolve = commands.add_parser("resolve")
resolve.add_argument("image")
args = parser.parse_args()
if args.command == "fingerprint":
print(dependency_fingerprint(args.root.resolve()))
else:
print(registry_digest(args.image) or "")
if __name__ == "__main__":
main()
+4 -2
View File
@@ -4,7 +4,7 @@
const $ = (sel) => document.querySelector(sel);
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const api = async (path) => {
const res = await fetch(path);
const res = await fetch(path.replace(/^\//, ""));
if (!res.ok) throw new Error(`${path}: ${res.status} ${await res.text()}`);
return res.json();
};
@@ -6441,7 +6441,7 @@ function showViewToast(cmd) {
}
function connectViewEvents() {
const source = new EventSource("/api/view/events");
const source = new EventSource("api/view/events");
source.onmessage = (e) => {
let cmd;
try {
@@ -7314,6 +7314,8 @@ $("#tm-messages").addEventListener(
"scroll",
(e) => {
if (!e.target.matches?.("#replay-output") || !replay) return;
// top and bottom coincide when the output fits; keep the mode Home/End chose
if (e.target.scrollHeight - e.target.clientHeight < 24) return;
const atBottom = e.target.scrollHeight - e.target.scrollTop - e.target.clientHeight < 24;
replay.followOutput = atBottom;
$("#replay-top")?.classList.toggle("active", !atBottom);
+6 -6
View File
@@ -5,14 +5,14 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>prime-rl dashboard</title>
<link rel="icon" href="/static/butterfly-white.svg">
<link rel="stylesheet" href="/static/vendor/uPlot.min.css">
<link rel="stylesheet" href="/static/style.css">
<link rel="icon" href="static/butterfly-white.svg">
<link rel="stylesheet" href="static/vendor/uPlot.min.css">
<link rel="stylesheet" href="static/style.css">
</head>
<body>
<header id="topbar">
<div class="brand">
<img src="/static/butterfly-white.svg" alt="Prime Intellect">
<img src="static/butterfly-white.svg" alt="Prime Intellect">
</div>
<select id="run-select" title="run"></select>
<div id="compare-wrap" class="dd-wrap">
@@ -295,7 +295,7 @@
</div>
</template>
<script src="/static/vendor/uPlot.iife.min.js"></script>
<script src="/static/app.js"></script>
<script src="static/vendor/uPlot.iife.min.js"></script>
<script src="static/app.js"></script>
</body>
</html>
+62 -216
View File
@@ -1,13 +1,9 @@
import json
import os
import signal
import subprocess
import sys
import time
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from urllib.parse import urlparse
from prime_rl.configs.algorithm import FrozenModelConfig
@@ -35,11 +31,10 @@ from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
DEFAULT_TRAINER_ENV_VARS,
cleanup_processes,
cleanup_threads,
get_physical_gpu_ids,
monitor_process,
ProcessGroup,
partition_gpus,
set_proc_title,
torchrun_cmd,
)
RL_CONFIG = "rl.json"
@@ -141,25 +136,9 @@ def rl_local(config: RLConfig):
)
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs from deployment config
gpu_offset = 0
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
infer_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_infer_gpus))
gpu_offset += num_infer_gpus
trainer_local_gpu_ids = list(range(gpu_offset, gpu_offset + config.deployment.num_train_gpus))
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
physical_gpu_ids = get_physical_gpu_ids()
if total_requested_gpus > len(physical_gpu_ids):
raise ValueError(
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
)
physical_gpu_mapping = {local_id: physical_gpu_ids[local_id] for local_id in range(total_requested_gpus)}
logger.info(f"Using local->physical GPU mapping: {physical_gpu_mapping}")
infer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in infer_local_gpu_ids]
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
infer_gpu_ids, trainer_gpu_ids = partition_gpus(num_infer_gpus, config.deployment.num_train_gpus)
logger.info(f"Using local->physical GPU mapping: {dict(enumerate(infer_gpu_ids + trainer_gpu_ids))}")
start_command = sys.argv
logger.debug(f"RL start command: {' '.join(start_command)}")
@@ -185,53 +164,22 @@ def rl_local(config: RLConfig):
f"Update the base_url to use port {expected_port} to match the inference server."
)
# Start processes
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
stop_events: dict[str, Event] = {}
def sigterm_handler(signum, frame):
logger.warning("Received SIGTERM, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
signal.signal(signal.SIGTERM, sigterm_handler)
try:
# Optionally, start inference process
with ProcessGroup() as processes:
if config.inference:
inference_cmd = ["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()]
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
# If we don't log stdout, the server hangs
with open(log_dir / "inference.log", "w") as log_file:
inference_process = Popen(
inference_cmd,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
)
processes.append(inference_process)
# Start monitoring thread
stop_event = Event()
stop_events["inference"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(inference_process, stop_event, error_queue, "inference"),
daemon=True,
processes.start(
"inference",
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
},
log_path=log_dir / "inference.log",
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
else:
logger.warning(
"No [inference] block configured - the policy inference server will not be started here. "
@@ -259,167 +207,65 @@ def rl_local(config: RLConfig):
# orchestrator start in parallel.
for split, source in env_servers(config):
name = source.resolved_name
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
logger.info(f"Starting {name} server")
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
env_server_log.parent.mkdir(parents=True, exist_ok=True)
with open(env_server_log, "w") as log_file:
env_server_process = Popen(
env_server_cmd,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**config.env_vars,
**config.orchestrator.env_vars,
},
stdout=log_file,
stderr=log_file,
)
processes.append(env_server_process)
# Start monitoring thread
stop_event = Event()
stop_events[f"env/{split}/{name}"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(env_server_process, stop_event, error_queue, f"{split} env server {name}"),
daemon=True,
processes.start(
f"{split} env server {name}",
["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars, **config.orchestrator.env_vars},
log_path=log_dir / ENVS_DIR / split / f"{name}.log",
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()]
logger.info("Starting orchestrator")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
with open(log_dir / "orchestrator.log", "w") as log_file:
orchestrator_process = Popen(
orchestrator_cmd,
stdout=log_file,
stderr=log_file,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.orchestrator.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "orchestrator",
},
)
processes.append(orchestrator_process)
# Start monitoring thread
stop_event = Event()
stop_events["orchestrator"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(orchestrator_process, stop_event, error_queue, "orchestrator"),
daemon=True,
processes.start(
"orchestrator",
["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.orchestrator.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "orchestrator",
},
log_path=log_dir / "orchestrator.log",
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Start training process
from prime_rl.utils.utils import get_free_port
trainer_cmd = [
"torchrun",
"--role=trainer",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
# Pipe all logs to file, and only master rank logs to stdout
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
f"--local-ranks-filter={','.join(map(str, config.trainer.log.ranks_filter))}",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={len(trainer_gpu_ids)}",
"-m",
"prime_rl.trainer.rl.train",
"@",
(config_dir / TRAINER_CONFIG).as_posix(),
]
logger.info(f"Starting trainer on GPU(s) {' '.join(map(str, trainer_gpu_ids))}")
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
with open(log_dir / "trainer.log", "w") as log_file:
trainer_process = Popen(
trainer_cmd,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.trainer.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "trainer",
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
)
processes.append(trainer_process)
# Start monitoring thread
stop_event = Event()
stop_events["trainer"] = stop_event
monitor_thread = Thread(
target=monitor_process, args=(trainer_process, stop_event, error_queue, "trainer"), daemon=True
processes.start(
"trainer",
torchrun_cmd(
"prime_rl.trainer.rl.train",
config_dir / TRAINER_CONFIG,
len(trainer_gpu_ids),
log_dir,
config.trainer.log.ranks_filter,
),
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.trainer.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "trainer",
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
},
log_path=log_dir / "trainer.log",
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Trainer and orchestrator completion is the successful stop condition.
completion_events = (stop_events["trainer"], stop_events["orchestrator"])
while not all(event.is_set() for event in completion_events):
if error_queue:
error = error_queue[0]
logger.error(f"Error: {error}")
logger.error("Terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
# Small delay to avoid busy waiting
time.sleep(1)
# Check if any critical process failed
if orchestrator_process.returncode != 0:
logger.error(f"Orchestrator failed with exit code {orchestrator_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
processes.wait("trainer", "orchestrator")
logger.success("Training finished!")
# Cleanup threads and processes
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script_path: Path) -> None:
"""Write the SLURM script to disk."""
+25 -101
View File
@@ -1,12 +1,9 @@
import json
import os
import signal
import subprocess
import sys
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.monitors import EvalMonitorsConfig, PrimeEvalMonitorConfig, TrainMonitorsConfig
@@ -34,11 +31,10 @@ from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
DEFAULT_TRAINER_ENV_VARS,
cleanup_processes,
cleanup_threads,
get_physical_gpu_ids,
monitor_process,
ProcessGroup,
partition_gpus,
set_proc_title,
torchrun_cmd,
)
SFT_CONFIG = "sft.json"
@@ -333,21 +329,14 @@ def sft_local(config: SFTConfig):
)
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
# launcher must partition GPUs between processes; plain SFT leaves them to torchrun.
# Partition GPUs (inference first, then the trainer) only when the launcher must split
# them between processes; plain SFT leaves them to torchrun.
infer_gpu_ids: list[int] = []
trainer_gpu_ids: list[int] = []
if config.inference is not None:
num_infer_gpus = config.deployment.num_infer_gpus
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
physical_gpu_ids = get_physical_gpu_ids()
if total_requested_gpus > len(physical_gpu_ids):
raise ValueError(
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
)
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
infer_gpu_ids, trainer_gpu_ids = partition_gpus(
config.deployment.num_infer_gpus, config.deployment.num_train_gpus
)
# Trainer and online-eval log to a single shared W&B run whose id ($WANDB_RUN_ID)
# equals $PRL_RUN_ID, one label per process.
@@ -364,37 +353,11 @@ def sft_local(config: SFTConfig):
"WANDB_ARGS": json.dumps(sys.argv),
}
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
stop_events: dict[str, Event] = {}
def sigterm_handler(signum, frame):
logger.warning("Received SIGTERM, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
signal.signal(signal.SIGTERM, sigterm_handler)
def start_process(name: str, cmd: list[str], env: dict[str, str], log_path: Path) -> Popen:
logger.debug(f"{name.capitalize()} command: {' '.join(cmd)}")
log_path.parent.mkdir(parents=True, exist_ok=True)
with open(log_path, "w") as log_file:
process = Popen(cmd, env=env, stdout=log_file, stderr=log_file)
processes.append(process)
stop_event = Event()
stop_events[name] = stop_event
monitor_thread = Thread(target=monitor_process, args=(process, stop_event, error_queue, name), daemon=True)
monitor_thread.start()
monitor_threads.append(monitor_thread)
return process
try:
with ProcessGroup() as processes:
# Optionally, start the inference server for online evals
if config.inference is not None:
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
start_process(
processes.start(
"inference",
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
env={
@@ -413,7 +376,7 @@ def sft_local(config: SFTConfig):
for source in eval_env_servers(config):
name = source.resolved_name
logger.info(f"Starting {name} server")
start_process(
processes.start(
f"env/eval/{name}",
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars},
@@ -422,7 +385,7 @@ def sft_local(config: SFTConfig):
if config.eval is not None:
logger.info("Starting online evals")
start_process(
processes.start(
"online-eval",
[sys.executable, "-m", "prime_rl.eval.online", "@", (config_dir / ONLINE_EVAL_CONFIG).as_posix()],
env={
@@ -439,23 +402,6 @@ def sft_local(config: SFTConfig):
log_path=log_dir / "eval.log",
)
from prime_rl.utils.utils import get_free_port
trainer_cmd = [
"torchrun",
"--role=trainer",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={config.deployment.num_train_gpus}",
"-m",
"prime_rl.trainer.sft.train",
"@",
config_path.as_posix(),
]
gpus_suffix = f" on GPU(s) {' '.join(map(str, trainer_gpu_ids))}" if trainer_gpu_ids else ""
logger.info(f"Starting SFT trainer with {config.deployment.num_train_gpus} GPU(s){gpus_suffix}")
trainer_env = {
@@ -470,48 +416,26 @@ def sft_local(config: SFTConfig):
trainer_env["WANDB_SHARED_LABEL"] = "trainer"
if trainer_gpu_ids:
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
processes.start(
"trainer",
torchrun_cmd(
"prime_rl.trainer.sft.train",
config_path,
config.deployment.num_train_gpus,
log_dir,
config.log.ranks_filter,
),
env=trainer_env,
log_path=log_dir / "trainer.log",
)
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Wait for the trainer (and the online-eval process, which drains its final evals
# after the trainer's last checkpoint) while surfacing any process failure.
terminal_events = [stop_events["trainer"]]
if "online-eval" in stop_events:
terminal_events.append(stop_events["online-eval"])
while True:
pending = [event for event in terminal_events if not event.is_set()]
if error_queue:
logger.error(f"Error: {error_queue[0]}")
logger.error("Terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
if not pending:
break
pending[0].wait(timeout=1)
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
processes.wait("trainer", *(["online-eval"] if config.eval is not None else []))
logger.success("SFT training finished!")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
+1 -1
View File
@@ -18,7 +18,7 @@ import os
from prime_rl import monitors
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
from prime_rl.configs.shared import FileSystemWeightBroadcastConfig
from prime_rl.eval.runner import POLL_INTERVAL_S, EvalRunner
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.config import cli, dump_resolved_config
+1 -7
View File
@@ -34,10 +34,6 @@ from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.metrics import dispatch_failure_metrics
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
from prime_rl.orchestrator.utils import (
@@ -49,9 +45,6 @@ from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_config_dir
monkey_patch_oai_iterable_types()
monkey_patch_chat_completion_logprobs()
# How often ``run_epoch`` re-checks for a superseding checkpoint while it waits for episodes.
POLL_INTERVAL_S = 2.0
@@ -121,6 +114,7 @@ class EvalRunner:
eval_source=self.eval_source,
policy_clients=self.clients,
policy=self.policy,
policy_weights_change=isinstance(config, SFTOnlineEvalConfig),
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
+2 -106
View File
@@ -18,11 +18,9 @@ def apply_shared_vllm_patches():
_patch_qwen35_moe_lora_format()
monkey_patch_nano_v3_reasoning_parser()
monkey_patch_minimax_m2_think_end_passthrough()
monkey_patch_return_routed_experts_with_nixl_connector()
monkey_patch_kv_xfer_finished_tolerate_freed()
monkey_patch_online_fp8_parameter_cast()
monkey_patch_deepseek_v4_allowed_layer_types()
monkey_patch_deepseek_v4_request_tools_placement()
monkey_patch_tokenize_params_validation()
monkey_patch_strip_routed_experts_from_chat()
monkey_patch_dp_coordinator_startup_timeout()
@@ -49,64 +47,6 @@ def monkey_patch_deepseek_v4_allowed_layer_types():
allow_deepseek_v4_layer_types()
def monkey_patch_deepseek_v4_request_tools_placement():
"""Attach request-level tools to the first existing DSV4 system message.
vLLM 0.29.0's Python DeepSeek-V4 tokenizer always prepends a synthetic
system message for request-level tools. That puts the tool schema before
an existing system prompt, unlike DeepSeek's reference encoder, vLLM's
Rust renderer, and prime-rl's training renderer. Upstream fixed this in
https://github.com/vllm-project/vllm/pull/51856 (commit 2909ad8f).
The fix is expected to ship in vLLM 0.31.
Wrap the tokenizer factory so existing-system requests take the corrected
path through the stock implementation: shallow-copy the conversation,
attach tools to its first system message, and suppress the stock synthetic
insertion. Requests without a system message retain the stock behavior.
Remove this patch once the vLLM pin includes the upstream fix (likely 0.31).
"""
import copy
from vllm.tokenizers import deepseek_v4 as dsv4_tokenizer
original_get_tokenizer = dsv4_tokenizer.get_deepseek_v4_tokenizer
if getattr(original_get_tokenizer, "_prime_rl_places_request_tools", False):
return
def _get_deepseek_v4_tokenizer(tokenizer):
wrapped = original_get_tokenizer(tokenizer)
tokenizer_cls = wrapped.__class__
original_apply_chat_template = tokenizer_cls.apply_chat_template
# Each factory call creates a fresh dynamic tokenizer subclass, but be
# defensive if vLLM starts caching that class in a future release.
if getattr(original_apply_chat_template, "_prime_rl_places_request_tools", False):
return wrapped
def _apply_chat_template(self, messages, tools=None, **kwargs):
if tools:
conversation = kwargs.get("conversation", messages)
system_idx = next(
(i for i, message in enumerate(conversation) if message.get("role") == "system"),
None,
)
if system_idx is not None:
conversation = conversation.copy()
conversation[system_idx] = copy.copy(conversation[system_idx])
conversation[system_idx]["tools"] = tools
kwargs["conversation"] = conversation
tools = None
return original_apply_chat_template(self, messages, tools=tools, **kwargs)
_apply_chat_template._prime_rl_places_request_tools = True
tokenizer_cls.apply_chat_template = _apply_chat_template
return wrapped
_get_deepseek_v4_tokenizer._prime_rl_places_request_tools = True
dsv4_tokenizer.get_deepseek_v4_tokenizer = _get_deepseek_v4_tokenizer
def monkey_patch_online_fp8_parameter_cast():
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
@@ -243,51 +183,6 @@ def monkey_patch_minimax_m2_think_end_passthrough():
minimax_m2.minimax_m2_config = _patched_config
def monkey_patch_return_routed_experts_with_nixl_connector():
from vllm.config.vllm import VllmConfig
from vllm.logger import init_logger
logger = init_logger(__name__)
original_post_init = VllmConfig.__post_init__
if getattr(original_post_init, "_prime_rl_allows_nixl_routed_experts", False):
return
def _is_nixl_routed_experts_pd_config(config: VllmConfig) -> bool:
kv_transfer_config = config.kv_transfer_config
return (
config.model_config is not None
and config.model_config.enable_return_routed_experts
and kv_transfer_config is not None
and kv_transfer_config.kv_connector == "NixlConnector"
and kv_transfer_config.is_kv_transfer_instance
)
def _post_init(config: VllmConfig):
if not _is_nixl_routed_experts_pd_config(config):
return original_post_init(config)
if config.parallel_config.pipeline_parallel_size > 1:
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
if config.use_v2_model_runner:
raise ValueError(
"Routed-expert capture with NIXL requires the V1 model runner. Set VLLM_USE_V2_MODEL_RUNNER=0."
)
# vLLM rejects every KV connector, but our P/D path uses NIXL and
# stitches prefill/decode routed experts in the router. CPU KV offload
# remains rejected by prime-rl config validation.
config.model_config.enable_return_routed_experts = False
try:
return original_post_init(config)
finally:
config.model_config.enable_return_routed_experts = True
_post_init._prime_rl_allows_nixl_routed_experts = True
VllmConfig.__post_init__ = _post_init
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
def monkey_patch_strip_routed_experts_from_chat():
"""Drop routed_experts from chat-completions responses.
@@ -431,6 +326,7 @@ def _patch_lora_key_prefix():
if skip_prefixes and cls._should_skip_module(lora_module, skip_prefixes):
continue
module_name, _ = parse_fine_tuned_lora_name(lora_module, weights_mapper)
base_name = module_name.rsplit(".", 1)[-1]
# Case for expert lora weights.
## START PATCHED CODE (upstream only accepts the qualified form)
if ".experts" in module_name:
@@ -440,7 +336,7 @@ def _patch_lora_key_prefix():
unexpected_modules.append(module_name)
## END PATCHED CODE
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
elif base_name not in expected_lora_modules and base_name not in (peft_helper.modules_to_save or ()):
unexpected_modules.append(module_name)
if unexpected_modules:
+3 -8
View File
@@ -10,15 +10,10 @@ def setup_vllm_env(config: InferenceConfig):
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
# Standard deployments use V2 for both capture modes. NIXL P/D also uses V2
# for sampling-mask capture, but router replay remains on V1 because vLLM
# rejects routed-expert capture with KV connectors and prime-rl's stitching
# patch is V1-only. setdefault keeps an explicit env-var choice authoritative.
if config.enable_return_sampling_mask:
# vLLM captures sampling masks and routed experts only on the V2 model runner.
# setdefault keeps an explicit env-var choice authoritative.
if config.enable_return_sampling_mask or config.vllm.enable_return_routed_experts:
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1")
elif config.vllm.enable_return_routed_experts:
use_v2_runner = config.deployment.type != "disaggregated"
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1" if use_v2_runner else "0")
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
# grammar-constrains generation (xgrammar structural tags) for tool_choice
+6 -8
View File
@@ -62,14 +62,12 @@ async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: R
"""Wrapper around vLLM's /v1/load_lora_adapter.
prime-rl reloads a fixed-name adapter with fresh weights every step (the path
changes per policy version; the name is constant — the base model name, which
the adapter shadows: ``_maybe_get_adapters`` resolves ``lora_requests`` before
the base-model match, so requests keep addressing one stable name. If a future
vLLM rejects registering an adapter under a served model name, fall back to a
distinct constant adapter name set once at startup.) vLLM's native loader
rejects a same-name reload unless ``load_inplace=True``, so we force it here —
that makes the worker re-read the new weights during ``add_lora``, reusing the
existing ``lora_int_id``.
changes per policy version; the name is constant — the model name every client
sends. vLLM rejects an adapter named like a served base model, so with LoRA on
the base model is served as ``<model>-base``; see ``InferenceConfig.to_namespace``.)
vLLM's native loader rejects a same-name reload unless ``load_inplace=True``, so
we force it here — that makes the worker re-read the new weights during
``add_lora``, reusing the existing ``lora_int_id``.
We then reset the stored request's flag back to ``False``. ``load_inplace`` is
a sticky field on the ``LoRARequest`` that ``_maybe_get_adapters`` hands to
@@ -66,7 +66,7 @@ class PrimeRlServingTokens(ServingTokens):
request_metadata: RequestResponseMetadata,
) -> ErrorResponse | GenerateResponse:
routed_experts: _GenerateRoutedExpertsCapture | None = None
if self.model_config.enable_return_routed_experts:
if self.engine_client.vllm_config.aux_output_config.enable_return_routed_experts:
routed_experts = _GenerateRoutedExpertsCapture(
result_generator,
start=request.sampling_params.routed_experts_prompt_start,
@@ -17,10 +17,6 @@ else:
class FileSystemWeightUpdateWorker(Worker):
"""vLLM worker extension for updating weights in-place using shared filesystem."""
def init_broadcaster(self) -> None:
"""Initialize the broadcaster."""
...
def liveness_probe(self) -> None:
"""No-op RPC used by the API server liveness endpoint."""
return None
+45 -2
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
import atexit
import fcntl
import os
import time
@@ -251,7 +252,12 @@ class PrimeEvalMonitor(Monitor):
evaluation per env and step, opened when the epoch starts (``log_eval_plan``), fed
every episode as it lands (``log_episodes``) and finished with the epoch's aggregates
(``log_eval_epoch``), so the platform page follows the run from its first episode.
Metrics are not forwarded; the evaluation is the epoch."""
Under a managed launch ($RUN_ID) the epoch's ``eval/{env}/...`` metrics ALSO go to
the parent training run, which is what the run dashboard groups into its `eval`
section. The orchestrator's in-process evals reach it through the train monitor, but
an eval process of its own (SFT online evals) has no other way there, so without
this the run shows every metric group except the one its evals produced."""
config: PrimeEvalMonitorConfig
@@ -268,6 +274,7 @@ class PrimeEvalMonitor(Monitor):
# (env, step) -> its open evaluation; None once opening it failed, so the epoch's
# episodes do not retry the platform on every arrival
self.runs: dict[tuple[str, int], pr.Run | None] = {}
self.parent: pr.Run | None = None
self._lock = asyncio.Lock()
self.evaluation_id = os.getenv(EVAL_ID_VAR)
if self.evaluation_id and len(self.sources) != 1:
@@ -277,6 +284,7 @@ class PrimeEvalMonitor(Monitor):
)
if self.mode == "online":
self.logger.info("Streaming eval epochs to the Prime platform")
self.parent = await asyncio.to_thread(self._attach_parent)
if output_dir is not None:
# Merge, not overwrite: when the eval process shares the
# trainer's run dir (SFT online evals), the train record's
@@ -294,8 +302,39 @@ class PrimeEvalMonitor(Monitor):
else:
self.logger.info(f"Platform evaluations disabled ({pr.MODE_ENV}=disabled)")
def _attach_parent(self) -> pr.Run | None:
"""The parent training run this eval process belongs to, for metrics only.
Blocking: runs in a worker thread.
Attaching is a local handle, not a request, so a run that turns out to be
unreachable costs the eval nothing. The caller owns the run's lifecycle: we
drop the SDK's atexit crash hook, because an eval process that exits while the
trainer is still going would otherwise report the WHOLE run failed."""
run_id = os.getenv("RUN_ID")
if not run_id:
return None
run = pr.init(
kind="train",
mode=self.mode,
base_url=_base_url(),
id=run_id,
finish_timeout=FINISH_TIMEOUT,
)
atexit.unregister(run._atexit_hook) # the SDK's own unregister handle
self.logger.info(f"Logging eval metrics to parent training run {run.id}")
return run
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
pass
"""An epoch's aggregates (``eval/{env}/...``) onto the parent training run.
Only there: a standalone eval has no parent, and the per-epoch evaluation
carries its own aggregates through ``log_eval_epoch``."""
if self.parent is None:
return
metrics, dropped = sanitize(metrics)
if dropped:
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
# A queue put that can block briefly under backpressure - off the loop.
await asyncio.to_thread(self.parent.log_metrics, metrics, step=step)
def open(self, env_name: str, step: int, expected: int | None) -> pr.Run:
"""Open the platform evaluation of one epoch. Blocking: runs in a worker thread."""
@@ -400,3 +439,7 @@ class PrimeEvalMonitor(Monitor):
await asyncio.to_thread(run.finish, status=pr.RunStatus.CANCELLED, error="interrupted")
except Exception as e:
self.logger.warning(f"Failed to close the {env_name} (Step {step}) evaluation: {type(e).__name__}: {e}")
if self.parent is not None:
# Drain only. The parent run belongs to the trainer and the platform: an
# eval process must never report its status, not even a clean completion.
await asyncio.to_thread(self.parent.flush, FINISH_TIMEOUT)
+4 -6
View File
@@ -2,8 +2,8 @@
The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm
is — a bundle of sampling and the per-token training signal. This package
turns the signal half into runtime objects (the sampling half is the env's
:class:`~prime_rl.orchestrator.generation_source.GenerationSource`):
turns the signal half into runtime objects (the sampling half is interpreted by
:class:`~prime_rl.orchestrator.envs.TrainEnv`):
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``, ``debug``) — each named
@@ -22,7 +22,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_client
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.orchestrator.algo.debug import DebugAlgorithm
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
@@ -55,9 +55,8 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
cls = ALGORITHM_CLASSES[config.type]
assert cls.action_loss_type == config.action_loss_type # config and runtime declare in two places
# The Algorithm is the runtime of the algorithm config's training signal
# (its sibling GenerationSource interprets the sampling half). Every algorithm is
# (its TrainEnv interprets the sampling half). Every algorithm is
# handed the live policy pool — opsd self-distills against it, others may
# judge against it or ignore it. Other models (a frozen teacher, a hint
# renderer) are built from the algorithm's own config in setup().
@@ -76,7 +75,6 @@ __all__ = [
"RAEAlgorithm",
"SFTDistillAlgorithm",
"build_algorithm",
"connect_frozen_client",
"assign_advantages",
"stamp_loss_routing",
]
+4 -33
View File
@@ -2,41 +2,17 @@
from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar
import verifiers.v1 as vf
from prime_rl.configs.algorithm import ActionLossType, AlgoConfig, FrozenModelConfig
from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.orchestrator.clients import InferenceClient
async def connect_frozen_client(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferenceClient:
"""Connect to an externally hosted frozen model and wait for it."""
from prime_rl.orchestrator.clients import InferenceClient, check_inference_ready
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
if renderer_config is not None:
clients = InferenceClient(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
clients = InferenceClient(config, model_name=config.name)
await check_inference_ready(config, config.name)
return clients
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
def iter_trainable_traces(episodes: list[vf.Episode]):
"""Yield clean trainable traces that contain sampled tokens."""
for episode in episodes:
for trace in episode.traces:
if trace.has_error or not trace.agent.trainable:
if not episode.ok or trace.has_error or not trace.agent.trainable or trace.num_turns == 0:
continue
if any(any(node.mask) for node in trace.nodes):
yield episode, trace
@@ -50,9 +26,8 @@ class Algorithm:
annotated traces into transport samples only after admission.
"""
action_loss_type: ClassVar[ActionLossType] = "rl"
def __init__(self, config: AlgoConfig, clients: InferenceClient):
self.action_loss_type = config.action_loss_type
self.clients = clients
self.connected: InferenceClient | None = None
@@ -74,7 +49,3 @@ class Algorithm:
"""Run rollout-local scoring when the episode has trainable traces."""
if any(True for _ in iter_trainable_traces([episode])):
await self.score_episode(episode)
async def finalize_group(self, episodes: list[vf.Episode]) -> None:
"""Run group-relative scoring over the native episodes."""
await self.score_group(episodes)
+18 -3
View File
@@ -6,7 +6,7 @@ import verifiers.v1 as vf
from prime_rl.configs.algorithm import GRPOAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
from prime_rl.orchestrator.algo.routing import assign_advantages
from prime_rl.orchestrator.algo.routing import assign_advantages, trainable_nodes
if TYPE_CHECKING:
from prime_rl.orchestrator.clients import InferenceClient
@@ -20,6 +20,8 @@ class GRPOAlgorithm(Algorithm):
def __init__(self, config: GRPOAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.length_penalty = config.length_penalty
self.length_weighted_baseline = config.length_weighted_baseline
self.loss_aggregation = config.loss_aggregation
async def score_group(self, episodes: list[vf.Episode]) -> None:
import torch # only the trainer-side extras ship torch; an eval process never scores a group
@@ -28,7 +30,7 @@ class GRPOAlgorithm(Algorithm):
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
length_penalty = self.length_penalty
if length_penalty is None:
advantages = rewards - rewards.mean()
shaped_rewards = rewards
else:
output = torch.tensor([trace.num_output_tokens for trace in traces], dtype=rewards.dtype)
total = torch.tensor([trace.num_total_tokens for trace in traces], dtype=rewards.dtype)
@@ -41,6 +43,19 @@ class GRPOAlgorithm(Algorithm):
)
penalty = rewards.mean() * penalty_frac
shaped_rewards = rewards - penalty
advantages = shaped_rewards - shaped_rewards.mean()
baseline = shaped_rewards.mean()
if self.length_weighted_baseline:
lengths = torch.tensor(
[sum(sum(node.mask) for node in trainable_nodes(trace)) for trace in traces], dtype=rewards.dtype
)
baseline = (lengths * shaped_rewards).sum() / lengths.sum()
advantages = shaped_rewards - baseline
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
assign_advantages(trace, advantage)
nodes = [node for trace in traces for node in trainable_nodes(trace)]
if self.loss_aggregation == "prompt" and nodes:
# rl weight 1/T_q per token: each group's weights sum to 1, and the trainer divides the
# rl loss by the sum of rl weights, i.e. the number of groups.
weight = 1.0 / sum(sum(node.mask) for node in nodes)
for node in nodes:
node.loss_weights = {**(node.loss_weights or {}), "rl": [weight if m else 0.0 for m in node.mask]}
-2
View File
@@ -24,8 +24,6 @@ class OPDAlgorithm(Algorithm):
credit is assigned — rollouts keep ``advantages=None`` and samples ship no
advantage stream; ``group_size`` only fans out sampling."""
action_loss_type = "ref_kl"
def __init__(self, config: OPDAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.teacher = config.teacher
-2
View File
@@ -31,8 +31,6 @@ class OPSDAlgorithm(Algorithm):
multimodal prompts and any number of turns. No scalar advantage is
assigned."""
action_loss_type = "ref_kl"
def __init__(self, config: OPSDAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.demo_key = config.demo_key
+7 -2
View File
@@ -8,10 +8,15 @@ from prime_rl.configs.algorithm import ActionLossType
from prime_rl.transports.batch import TrainingSample
def trainable_nodes(trace: vf.Trace) -> list[vf.MessageNode]:
"""Nodes with sampled (mask-True) tokens on the trace's trainable branches, in graph order."""
on_trainable_branch = {id(node) for branch in trace.branches if branch.trainable for node in branch.nodes}
return [node for node in trace.nodes if id(node) in on_trainable_branch and any(node.mask)]
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
"""Assign credit in compact sampled-token order across trainable graph paths."""
trainable_nodes = {id(node) for branch in trace.branches if branch.trainable for node in branch.nodes}
nodes = [node for node in trace.nodes if id(node) in trainable_nodes and any(node.mask)]
nodes = trainable_nodes(trace)
for node in nodes:
if len(node.mask) != len(node.token_ids):
raise ValueError(
-2
View File
@@ -10,5 +10,3 @@ class SFTDistillAlgorithm(Algorithm):
Assigns no advantage — the ``ce`` loss ignores credit, and SFT trains on
every sampled token. A curriculum can reject results using reward or any
other finalized rollout data."""
action_loss_type = "ce"
@@ -5,8 +5,11 @@ from dataclasses import dataclass, field
from typing import Any
import numpy as np
from transformers import AutoConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.transports.batch.types import MicroBatch, MMImageRef, MMRefs, RoutedExperts, SamplingMask, TrainingSample
from prime_rl.utils.logger import get_logger
# Backfill value per component weight stream when a packed sample doesn't
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
@@ -693,11 +696,10 @@ def _distribute_group(
def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBatch:
"""
Pad a micro batch with the given padding size sample
Return the padded micro batch.
Pad a micro batch with loss-masked tokens up to the next multiple of `pad_to_multiple_of`.
Args:
micro_batch: The micro batch to pad.
padding_size: The number of padding tokens to add.
pad_to_multiple_of: The multiple to pad the sequence length up to.
Returns:
The padded micro batch.
"""
@@ -858,3 +860,32 @@ def prepare_batch(
batches_per_gpu[worker_idx].extend(worker_batches)
return batches_per_gpu
class BatchPacker:
"""Bin-packs a step's training samples into one micro-batch list per trainer DP rank."""
def __init__(self, config: OrchestratorConfig):
self.seq_len = config.seq_len
self.num_train_workers = config.num_train_workers
self.pad_to_multiple_of = config.pad_to_multiple_of
try:
model_config = AutoConfig.from_pretrained(
config.model.name, trust_remote_code=config.tokenizer.trust_remote_code
)
except Exception as e:
get_logger().warning(
f"Could not load model config for {config.model.name} ({e}) - "
"packing balances by token count instead of estimated FLOPs"
)
model_config = None
self.bin_cost = build_bin_cost(model_config)
def pack(self, samples: list[TrainingSample]) -> list[list[MicroBatch]]:
return prepare_batch(
rollouts=samples,
seq_len=self.seq_len,
num_train_workers=self.num_train_workers,
bin_cost=self.bin_cost,
pad_to_multiple_of=self.pad_to_multiple_of,
)
+10 -13
View File
@@ -55,19 +55,16 @@ class CheckpointManager:
raise FileNotFoundError(f"Orchestrator checkpoint not found at {state_file}")
get_logger().debug(f"Loading checkpoint from {state_file}")
start = time.perf_counter()
if self.config.skip_progress:
get_logger().info("Skipping progress and train source loading from checkpoint")
else:
with open(state_file, "rb") as f:
state = torch.load(f, weights_only=False)
saved: Progress = state["progress"]
for key, value in asdict(saved).items():
if hasattr(progress, key):
setattr(progress, key, value)
train_source.load_state_dict(state["train_source"])
for name in state["train_source"]["envs"]:
if name in train_source.curricula:
get_logger().info(f"Resumed curriculum state for env {name}")
with open(state_file, "rb") as f:
state = torch.load(f, weights_only=False)
saved: Progress = state["progress"]
for key, value in asdict(saved).items():
if hasattr(progress, key):
setattr(progress, key, value)
train_source.load_state_dict(state["train_source"])
for name in state["train_source"]["envs"]:
if name in train_source.curricula:
get_logger().info(f"Resumed curriculum state for env {name}")
get_logger().debug(f"Orchestrator checkpoint loaded in {format_time(time.perf_counter() - start)}")
+33 -45
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
import asyncio
import os
from collections.abc import Callable
from pathlib import Path
from typing import Literal
@@ -12,40 +11,20 @@ from httpx import AsyncClient
from openai import AsyncOpenAI
from renderers import RendererConfig
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
from verifiers.v1.configs.client import EvalClientConfig, TrainClientConfig
from verifiers.v1.clients.base import build_async_openai
from verifiers.v1.configs.client import (
BaseClientConfig,
EvalClientConfig,
TrainClientConfig,
resolve_api_key,
resolve_headers,
)
from prime_rl.configs.eval import PRIME_INFERENCE_URL
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.logger import get_logger
def resolve_api_key(api_key_var: str) -> str:
"""The API key named by ``api_key_var``; ``PRIME_API_KEY`` also falls back to the prime
CLI config (``prime login``), like the verifiers client does. ``"EMPTY"`` when unset."""
api_key = os.environ.get(api_key_var)
if not api_key and api_key_var == "PRIME_API_KEY":
from prime_sandboxes import Config as PrimeConfig
api_key = PrimeConfig().api_key
return api_key or "EMPTY"
def resolve_headers(client_config: ClientConfig) -> dict[str, str]:
"""The static headers plus those read from the environment. A Prime Inference client
without a team header gets the team from ``$PRIME_TEAM_ID`` or the prime CLI config,
like the verifiers client: a team's internal models are served only under it."""
env_headers = {
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
}
headers = {**client_config.headers, **env_headers}
if client_config.base_url.startswith(PRIME_INFERENCE_URL) and "X-Prime-Team-ID" not in headers:
from prime_sandboxes import Config as PrimeConfig
if team_id := os.environ.get("PRIME_TEAM_ID") or PrimeConfig().team_id:
headers["X-Prime-Team-ID"] = team_id
return headers
class PrefillScorer:
"""Prefill-scores token ids against a pool's endpoint, lazily resolving
a single OpenAI client from the pool's train client config."""
@@ -55,14 +34,8 @@ class PrefillScorer:
async def score(self, config: vf.ClientConfig, model: str, token_ids: list[int]) -> list[float]:
if self._client is None:
# Build the OpenAI client straight from the config fields — works for any
# ClientConfig type; resolve_client would hand back an EvalClient (no `.openai`)
# for these chat-completions teacher configs.
self._client = AsyncOpenAI(
base_url=config.base_url,
api_key=resolve_api_key(config.api_key_var),
default_headers=config.headers or None,
)
# Prefill scoring uses the SDK even when generation uses the eval relay.
self._client = build_async_openai(config)
return await prefill_logprobs(self._client, model, token_ids)
async def aclose(self) -> None:
@@ -256,6 +229,21 @@ async def check_inference_ready(client_config: ClientConfig, model_name: str) ->
await admin.aclose()
async def connect_frozen_client(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferenceClient:
"""Connect to an externally hosted frozen model and wait for it."""
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
if renderer_config is not None:
clients = InferenceClient(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
clients = InferenceClient(config, model_name=config.name)
await check_inference_ready(config, config.name)
return clients
def setup_client(
client_config: ClientConfig,
client_type: str = "openai_chat_completions",
@@ -274,10 +262,7 @@ def setup_client(
"renderer": renderer_config,
"renderer_model_name": renderer_model_name,
}
headers = resolve_headers(client_config)
return config_cls(
base_url=client_config.base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra
)
return config_cls(**client_config.model_dump(include=set(BaseClientConfig.model_fields)), **renderer_extra)
def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
@@ -290,8 +275,9 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
urls = client_config.admin_base_url if client_config.admin_base_url else [client_config.base_url]
def _setup_admin_client(base_url: str) -> httpx.AsyncClient:
headers = resolve_headers(client_config)
api_key = resolve_api_key(client_config.api_key_var)
config = client_config.model_copy(update={"base_url": base_url})
headers = resolve_headers(config)
api_key = resolve_api_key(config)
if api_key != "EMPTY":
headers["Authorization"] = f"Bearer {api_key}"
@@ -324,7 +310,9 @@ async def maybe_check_has_model(
f"{result.text[:300]}"
)
models = body["data"]
if not any(model["id"] == model_name for model in models):
# A LoRA server lists the model name only once the adapter is loaded; until then
# the base model (served as ``<model>-base``) carries it as its ``root``.
if not any(model_name in (model["id"], model.get("root")) for model in models):
raise ValueError(f"Model {model_name} was not found in the inference pool on {admin_client.base_url}")
logger.debug(f"Model {model_name} was found in the inference pool")
+1 -1
View File
@@ -163,7 +163,7 @@ class ConcurrencyController:
# ── inbound hooks ────────────────────────────────────────────────────────
def record_episode(self, env_name: str, kind: str, tokens: int, duration: float) -> None:
def record_episode(self, tokens: int) -> None:
"""One completed unit (from the dispatcher). Advances the turnover
clock and, while the last poll was green, grows the cap — so growth
is paced by the pipeline itself at any concurrency scale."""
+3 -2
View File
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any
import verifiers.v1 as vf
from prime_rl.orchestrator.algo.base import iter_trainable_traces
from prime_rl.orchestrator.curriculum.gates import AdmissionGate
from prime_rl.orchestrator.curriculum.samplers import TaskSampler
@@ -48,7 +49,7 @@ class Curriculum:
self.gates[name] = gate
def on_result(self, group: list[vf.Episode]) -> bool:
"""Observe every result, evaluate every gate, and combine with AND."""
"""Observe every result and admit trainable groups that pass every gate."""
if not group:
raise ValueError("Cannot report an empty rollout group")
task_keys = {episode.task.key for episode in group}
@@ -63,7 +64,7 @@ class Curriculum:
if not isinstance(decision, bool):
raise TypeError(f"AdmissionGate {name!r}.admit() must return bool, got {type(decision).__name__}")
decisions.append(decision)
return all(decisions)
return all(decisions) and any(iter_trainable_traces(group))
def state_dict(self) -> dict[str, Any]:
return {
@@ -27,7 +27,7 @@ class AdvRangeGate(AdmissionGate):
advantage
for episode in group
for trace in episode.traces
if not trace.has_error and trace.agent.trainable
if episode.ok and not trace.has_error and trace.agent.trainable
for node in trace.nodes
for advantage in node.advantages or []
]
@@ -68,7 +68,7 @@ class DifficultyPoolSampler(TaskSampler):
trace.reward
for episode in group
for trace in episode.traces
if not trace.has_error and trace.agent.trainable
if episode.ok and not trace.has_error and trace.agent.trainable and trace.num_turns > 0
]
if not rewards:
return
+22 -30
View File
@@ -143,9 +143,11 @@ class Dispatcher:
max_off_policy_steps: int,
run_id: str,
run_name: str | None,
on_episode_complete: Callable[[str, str, int, float], None] | None = None,
policy_weights_change: bool = True,
on_episode_complete: Callable[[int], None] | None = None,
) -> None:
self.policy = policy
self.policy_weights_change = policy_weights_change
self.progress = progress
self.train_envs = train_envs
self.eval_envs = eval_envs
@@ -157,7 +159,7 @@ class Dispatcher:
self.max_off_policy_steps = max_off_policy_steps
self.run_id = run_id
self.run_name = run_name
# ``(env_name, kind, total_tokens, duration_s)`` per completed episode
# Called with ``total_tokens`` per completed episode
self.on_episode_complete = on_episode_complete
# Starting value of the dynamic cap (the concurrency controller moves
@@ -214,10 +216,10 @@ class Dispatcher:
"""``(clients, model_name, is_live)`` for *train* rollouts of this env —
eval always uses the policy."""
assert self.train_envs is not None # train groups only exist when train is configured
source = self.train_envs.get(env_name).generation_source
if source.uses_live_policy:
return source.clients, self.policy.model_name, True
return source.clients, source.clients.model_name, False
env = self.train_envs.get(env_name)
if env.uses_live_policy:
return env.clients, self.policy.model_name, True
return env.clients, env.clients.model_name, False
@property
def inflight_train_count(self) -> int:
@@ -316,7 +318,7 @@ class Dispatcher:
return [
(self.progress.step - 1) - meta.policy_version
for meta in self.inflight.values()
if meta.kind == "train" and self.train_envs.get(meta.env_name).generation_source.uses_live_policy
if meta.kind == "train" and self.train_envs.get(meta.env_name).uses_live_policy
]
# ── lifecycle ──────────────────────────────────────────────────────────
@@ -423,7 +425,7 @@ class Dispatcher:
gid
for gid, group in self.groups.items()
if group.kind == "train"
and self.train_envs.get(group.env_name).generation_source.uses_live_policy
and self.train_envs.get(group.env_name).uses_live_policy
and group.policy_version_at_start < min_version
]
cancelled = 0
@@ -556,10 +558,8 @@ class Dispatcher:
if env_collection is None:
return False
env = env_collection.get(group.env_name)
# Frozen-sourced train rollouts hit a frozen pool; salting per policy
# version would invalidate its prefix cache every weight update for
# no reason.
if live_sourced:
# Only endpoints receiving policy weight updates need a cache salt.
if live_sourced and self.policy_weights_change:
cache_salt = str(group.policy_version_at_start)
else:
cache_salt = None
@@ -665,10 +665,6 @@ class Dispatcher:
)
return
if not episode.traces and episode.ok:
episode.ok = False
episode.errors.append(vf.Error(type="EmptyEpisode", message="Episode returned with no traces"))
for trace in episode.traces:
if trace.is_timeout and not trace.has_error and meta.kind == "train":
# Training keeps a timed-out rollout out of the batch: an error,
@@ -676,14 +672,6 @@ class Dispatcher:
trace.errors.append(vf.Error(type="Timeout", message=f"Trace stopped by {trace.stop_condition}"))
trace.ok = False
episode.ok = False
if not trace.has_error and not trace.is_timeout and trace.num_turns == 0:
# Empty trajectory: promote to an explicit error so the sink
# treats it like any other failure (``has_error`` reads ``ok``).
# A timed-out eval trace with no turns stays a timeout: scored, no samples.
trace.errors.append(vf.Error(type="EmptyTrajectory", message="Trace returned with no trajectory steps"))
trace.ok = False
episode.ok = False
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
if trace.has_error:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if trace.last_error is not None:
@@ -691,12 +679,16 @@ class Dispatcher:
f"Trace failed in group {meta.group_id} ({meta.env_name}) — "
f"{trace.last_error.type}: {trace.last_error.message}"
)
if not episode.ok and not episode.traces:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if self.on_episode_complete is not None and meta.started_at > 0:
self.on_episode_complete(
meta.env_name, meta.kind, episode.num_total_tokens, time.monotonic() - meta.started_at
if not episode.ok:
if not any(trace.has_error for trace in episode.traces):
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
error = episode.last_error
get_logger().warning(
f"Episode failed in group {meta.group_id} ({meta.env_name})"
+ (f" — {error.type}: {error.message}" if error is not None else "")
)
if self.on_episode_complete is not None and meta.started_at > 0:
self.on_episode_complete(episode.num_total_tokens)
await self.emit_episode(meta, group, episode)
def complete_group_member(self, meta: InflightEpisode, group: GroupState | None) -> int:
@@ -724,7 +716,7 @@ class Dispatcher:
live_policy = meta.kind == "eval"
if meta.kind == "train":
assert self.train_envs is not None
live_policy = self.train_envs.get(meta.env_name).generation_source.uses_live_policy
live_policy = self.train_envs.get(meta.env_name).uses_live_policy
policy = vf.PolicySpan(start=policy_version, end=self.policy.version) if live_policy else None
work: vf.WorkInfo = (
vf.EvalWorkInfo(step=meta.step, policy=policy)
+36 -22
View File
@@ -26,11 +26,13 @@ from pathlib import Path
from typing import Generic, TypeVar
import verifiers.v1 as vf
from renderers import RendererConfig
from verifiers.v1.serve import EnvClient
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
from prime_rl.orchestrator.generation_source import GenerationSource
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import env_address_file
@@ -121,25 +123,16 @@ class Env:
task_data: dict,
on_delta: Callable[[dict], None] | None = None,
) -> vf.WireEpisode:
"""Run and return one typed episode. A failed multi-trace episode marks
its otherwise-clean traces failed so partial episodes never train.
"""Run and return the native typed episode.
``on_delta`` sees each delta of the env server's stream — a turn or a phase
change of one of the episode's traces — as it lands."""
episode = await self.env_client.run(
return await self.env_client.run(
task_data=task_data,
client=client,
model=model_name,
sampling=self._sampling(cache_salt),
on_delta=on_delta,
)
for trace in episode.traces:
if not episode.ok and trace.ok:
error = episode.last_error or vf.Error(
type="EpisodeFailed", message="A sibling trace in this episode failed"
)
trace.errors = [*trace.errors, error]
trace.ok = False
return episode
class TrainEnv(Env):
@@ -150,17 +143,38 @@ class TrainEnv(Env):
config: TrainSourceConfig,
address: str | None,
address_file: Path,
generation_source: GenerationSource,
clients: InferenceClient,
renderer_config: RendererConfig | None,
algorithm: Algorithm,
):
super().__init__(config, address, address_file)
self.generation_source = generation_source
# Train rollouts are generated from `clients`: the policy, or the frozen
# `sampling.source` connected in setup() with the renderer (token-in/out) client.
self.clients = clients
self.renderer_config = renderer_config
self.connected: InferenceClient | None = None
self.algorithm = algorithm
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
self.uses_live_policy = config.algo.sampling.source == "policy"
self.sampling_args = config.sampling.to_sampling_args()
if not self.uses_live_policy:
# Logprobs only feed importance ratios on policy-sampled tokens; frozen endpoints may reject the knob.
self.sampling_args.pop("logprobs", None)
# Truncated policy sampling must ship the sampling masks the trainer replays.
self.requires_sampling_masks = (
config.sampling.truncates_distribution() and config.algo.sampling.source == "policy"
)
self.requires_sampling_masks = config.sampling.truncates_distribution() and self.uses_live_policy
async def setup(self) -> None:
async def connect_source() -> None:
source = self.config.algo.sampling.source
if isinstance(source, FrozenModelConfig):
self.connected = await connect_frozen_client(source, renderer_config=self.renderer_config)
self.clients = self.connected
await asyncio.gather(connect_source(), self.algorithm.setup())
async def aclose(self) -> None:
for clients in (self.connected, self.algorithm.connected):
if clients is not None:
await clients.aclose()
class EvalEnv(Env):
@@ -218,9 +232,8 @@ class Envs(Generic[EnvT]):
class TrainEnvs(Envs[TrainEnv]):
"""Collection of training environments, each paired with its
:class:`GenerationSource` and runtime :class:`Algorithm`, built from the env's
resolved algorithm config."""
"""Collection of training environments, each with its runtime
:class:`Algorithm`, built from the env's resolved algorithm config."""
def __init__(
self,
@@ -238,7 +251,8 @@ class TrainEnvs(Envs[TrainEnv]):
config,
addresses[("train", config.resolved_name)],
env_address_file(config_dir, "train", config.resolved_name),
GenerationSource(config.algo.sampling, clients, renderer_config),
clients,
renderer_config,
build_algorithm(config.algo, clients),
)
self._envs[env.name] = env
@@ -1,49 +0,0 @@
"""Resolve the model source used to generate an env's train episodes."""
from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import FrozenModelConfig, SamplingConfig
from prime_rl.orchestrator.algo import connect_frozen_client
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.orchestrator.clients import InferenceClient
class GenerationSource:
"""One env's generation model and inference clients.
``clients`` is what train rollouts are generated from: the policy clients,
swapped for a connected frozen endpoint in :meth:`setup` when the source is
an inline frozen model. A frozen source *generates* rollouts, so it uses
the renderer (token-in/out) client (built from ``renderer_config``) — the
rollout must carry tokens for training."""
def __init__(self, config: SamplingConfig, clients: InferenceClient, renderer_config: RendererConfig | None = None):
assert config.source is not None, "sampling.source must be resolved by config validation"
self.config = config
self.clients: InferenceClient = clients
self.renderer_config = renderer_config
self.connected: InferenceClient | None = None # frozen clients connected in setup(); closed at shutdown
async def setup(self) -> None:
"""Connect clients to a frozen generation source and wait for
readiness. Must run before dispatching."""
if isinstance(self.config.source, FrozenModelConfig):
self.clients = await connect_frozen_client(self.config.source, renderer_config=self.renderer_config)
self.connected = self.clients
@property
def uses_live_policy(self) -> bool:
return self.config.source == "policy"
def sampling_args(self, args: dict) -> dict:
"""Source-specific sampling-arg overrides. Sampling logprobs are only
needed for importance ratios on policy-sampled tokens — frozen
endpoints may reject the knob."""
if not self.uses_live_policy:
args.pop("logprobs", None)
return args
+10 -26
View File
@@ -38,6 +38,7 @@ from prime_rl import monitors
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.algo.routing import is_trainable
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.batch import BatchPacker
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient, setup_admin_plane
from prime_rl.orchestrator.concurrency import ConcurrencyController
@@ -47,11 +48,6 @@ from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.metrics import TrainEpisodes, dispatch_failure_metrics
from prime_rl.orchestrator.packing import BatchPacker
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.train_sink import TrainSink
from prime_rl.orchestrator.train_source import TrainSource
@@ -78,12 +74,8 @@ from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import get_broadcast_dir, get_config_dir
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
monkey_patch_oai_iterable_types()
monkey_patch_chat_completion_logprobs()
from prime_rl.utils.pathing import get_broadcast_dir, get_config_dir, resolve_latest_ckpt_step
from prime_rl.utils.utils import clean_exit
# Wall-clock budget for post-training cleanup; force-exit if graceful
# shutdown wedges (env-server ZMQ recv, vLLM admin aclose, etc)
@@ -250,8 +242,7 @@ class Orchestrator:
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
# trainer even when ``ckpt.skip_progress`` leaves the counter unrestored. The curricula
# themselves are restored below, once the envs are loaded.
# trainer. The curricula themselves are restored below, once the envs are loaded.
if self.resume_step is not None:
self.progress.step = self.resume_step + 1
get_logger().info(f"Resuming from step {self.resume_step}")
@@ -291,16 +282,12 @@ class Orchestrator:
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
# Build + ready pools for each env's frozen generation source and the
# algorithm's frozen reference model
await asyncio.gather(
*(env.generation_source.setup() for env in self.train_envs),
*(env.algorithm.setup() for env in self.train_envs),
)
await asyncio.gather(*(env.setup() for env in self.train_envs))
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
# A LoRA run's adapter is registered under the base model name: the
# single adapter shadows it (vLLM resolves lora_requests before the
# base-model match), so requests keep addressing one stable name.
# A LoRA run's adapter is registered under the model name clients send;
# the inference server serves the base model as ``<model>-base``.
self.receiver = setup_weight_receiver(
get_broadcast_dir(config.output_dir),
config.weight_broadcast,
@@ -372,7 +359,6 @@ class Orchestrator:
train_envs=self.train_envs,
progress=self.progress,
batch_size=config.batch_size,
token_batch_size=config.token_batch_size,
on_result=self.train_source.on_result,
)
@@ -814,7 +800,7 @@ class Orchestrator:
inflight_by_env = self.dispatcher.inflight_by_env
inflight_train = self.dispatcher.inflight_train_count
inflight_eval = self.dispatcher.inflight_eval_count
train_batch, train_target, _train_unit = self.train_sink.batch_progress()
train_batch, train_target = self.train_sink.batch_progress()
train_buffered = self.train_sink.buffered_count()
train_batch_by_env = self.train_sink.pending_batch_by_env()
eval_batches = self.eval_sink.batch_progress() if self.eval_sink is not None else []
@@ -1035,11 +1021,9 @@ class Orchestrator:
if self.admin_plane is not None:
await self.admin_plane.aclose()
if self.train_envs is not None:
get_logger().debug("Stopping generation source and algorithm clients")
get_logger().debug("Stopping train env clients")
for env in self.train_envs:
for clients in (env.generation_source.connected, env.algorithm.connected):
if clients is not None:
await clients.aclose()
await env.aclose()
get_logger().info("Stopping orchestrator components")
t0 = time.perf_counter()
-35
View File
@@ -1,35 +0,0 @@
from transformers import AutoConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
from prime_rl.transports.batch.types import MicroBatch, TrainingSample
from prime_rl.utils.logger import get_logger
class BatchPacker:
"""Bin-packs a step's training samples into one micro-batch list per trainer DP rank."""
def __init__(self, config: OrchestratorConfig):
self.seq_len = config.seq_len
self.num_train_workers = config.num_train_workers
self.pad_to_multiple_of = config.pad_to_multiple_of
try:
model_config = AutoConfig.from_pretrained(
config.model.name, trust_remote_code=config.tokenizer.trust_remote_code
)
except Exception as e:
get_logger().warning(
f"Could not load model config for {config.model.name} ({e}) - "
"packing balances by token count instead of estimated FLOPs"
)
model_config = None
self.bin_cost = build_bin_cost(model_config)
def pack(self, samples: list[TrainingSample]) -> list[list[MicroBatch]]:
return prepare_batch(
rollouts=samples,
seq_len=self.seq_len,
num_train_workers=self.num_train_workers,
bin_cost=self.bin_cost,
pad_to_multiple_of=self.pad_to_multiple_of,
)
-115
View File
@@ -1,115 +0,0 @@
from typing import Any, Optional, TypedDict, Union
import openai.types.chat
from openai.types.chat.chat_completion import ChatCompletion, Choice
from openai.types.chat.chat_completion_assistant_message_param import (
Audio,
ContentArrayOfContentPart,
)
from openai.types.chat.chat_completion_content_part_param import ChatCompletionContentPartParam
from openai.types.chat.chat_completion_content_part_text_param import ChatCompletionContentPartTextParam
from openai.types.chat.chat_completion_developer_message_param import ChatCompletionDeveloperMessageParam
from openai.types.chat.chat_completion_function_message_param import ChatCompletionFunctionMessageParam
from openai.types.chat.chat_completion_message import FunctionCall
from openai.types.chat.chat_completion_message_tool_call_union_param import ChatCompletionMessageToolCallUnionParam
from openai.types.chat.chat_completion_system_message_param import ChatCompletionSystemMessageParam
from openai.types.chat.chat_completion_user_message_param import ChatCompletionUserMessageParam
from typing_extensions import Literal, Required
def monkey_patch_oai_iterable_types():
"""
This monkey patch is necessary to avoid Pydantic validating fields using
typing.Iterable (e.g. in multimodal or tool call messages) lazily which
leads to tokenization errors, for more info see
https://github.com/PrimeIntellect-ai/prime-rl/pull/1249
"""
class ModdedChatCompletionDeveloperMessageParam(TypedDict, total=False):
"""Same as openai.types.chat.chat_completion_developer_message_param.ChatCompletionDeveloperMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
content: Required[Union[str, list[ChatCompletionContentPartTextParam]]]
role: Required[Literal["developer"]]
name: str
class ModdedChatCompletionSystemMessageParam(TypedDict, total=False):
"""Same as openai.types.chat.chat_completion_system_message_param.ChatCompletionSystemMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
content: Required[Union[str, list[ChatCompletionContentPartTextParam]]]
role: Required[Literal["system"]]
name: str
class ModdedChatCompletionUserMessageParam(TypedDict, total=False):
"""Same as openai.types.chat.chat_completion_user_message_param.ChatCompletionUserMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
content: Required[Union[str, list[ChatCompletionContentPartParam]]]
role: Required[Literal["user"]]
name: str
class ModdedChatCompletionAssistantMessageParam(TypedDict, total=False):
"""Same as openai.types.chat.chat_completion_assistant_message_param.ChatCompletionAssistantMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
role: Required[Literal["assistant"]]
audio: Optional[Audio]
content: Union[str, list[ContentArrayOfContentPart], None]
function_call: Optional[FunctionCall]
name: str
refusal: Optional[str]
tool_calls: list[ChatCompletionMessageToolCallUnionParam]
class ModdedChatCompletionToolMessageParam(TypedDict, total=False):
"""Same as openai.types.chat.chat_completion_tool_message_param.ChatCompletionToolMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
content: Required[Union[str, list[ChatCompletionContentPartTextParam]]]
role: Required[Literal["tool"]]
tool_call_id: Required[str]
# Patch OAI types
openai.types.chat.chat_completion_developer_message_param.ChatCompletionDeveloperMessageParam = (
ModdedChatCompletionDeveloperMessageParam
)
openai.types.chat.chat_completion_system_message_param.ChatCompletionSystemMessageParam = (
ModdedChatCompletionSystemMessageParam
)
openai.types.chat.chat_completion_user_message_param.ChatCompletionUserMessageParam = (
ModdedChatCompletionUserMessageParam
)
openai.types.chat.chat_completion_assistant_message_param.ChatCompletionAssistantMessageParam = (
ModdedChatCompletionAssistantMessageParam
)
openai.types.chat.chat_completion_tool_message_param.ChatCompletionToolMessageParam = (
ModdedChatCompletionToolMessageParam
)
openai.types.chat.chat_completion_message_param.ChatCompletionMessageParam = Union[
ChatCompletionDeveloperMessageParam,
ChatCompletionSystemMessageParam,
ChatCompletionUserMessageParam,
ModdedChatCompletionAssistantMessageParam,
ModdedChatCompletionToolMessageParam,
ChatCompletionFunctionMessageParam,
]
def monkey_patch_chat_completion_logprobs():
"""
At large batch sizes and context, constructing OAI's Pydantic model
ChatCompletion with logprobs is causing heavy CPU overhead (~200ms per
object at 32K context, which translates to >10min overhead at 4K batch
size). This function monkey-patches the OAI type and verifiers'
post-processing utils to avoid validating the complex logprobs field.
"""
class ChoiceAny(Choice):
"""Same as openai.types.chat.chat_completion.Choice, but without type validation for logprobs field."""
logprobs: Optional[Any] = None
class ModdedChatCompletion(ChatCompletion):
"""Same as openai.types.chat.chat_completion.ChatCompletion, but using ChoiceAny instead of Choice."""
choices: list[ChoiceAny] # type: ignore
# Patch OAI types
openai.types.chat.chat_completion.Choice = ChoiceAny
openai.types.chat.chat_completion.ChatCompletion = ModdedChatCompletion

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