Compare commits

...
Author SHA1 Message Date
samsjaandGitHub ada6bd26db fix(docs): mark Qwen3/Qwen3.5 VLM CP as supported, drop stale 'Other HF' row (#3749)
**What**
- README Models-support table: CP for Qwen3 / Qwen3.5 VLMs was listed as
not supported (red cross) — changed to supported.
- Removed the stale 'Other HF causal LMs' row from the README table.
- Updated the same Qwen VLM CP claim in docs/advanced.md for
consistency.

**Why it's true**
CP works for the Qwen VLMs since #3099 (CP for hybrid + VLM SFT) and
#3103 (pack multimodal samples with CP): Qwen3_5ForCausalLM is the
unified class for the qwen3_5 / qwen3_5_moe VLM configs, cp_support()
returns ring + ulysses for them, and image grids / positions are sharded
under CP.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation-only changes to support matrices; no runtime or config
behavior is modified.
> 
> **Overview**
> Updates the **Models support** tables in `README.md` and
`docs/advanced.md` so **Qwen3 / Qwen3.5 VLMs** show **context
parallelism (CP) as supported** (✅), replacing the outdated ❌ that no
longer matches trainer behavior after recent CP + multimodal work.
> 
> The README also **drops the “Other HF causal LMs” row**, which was
redundant/stale relative to the family-specific table above it.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1f56cb4438ed93bf387a43019c4bd1982aa7f7f6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-01 19:29:51 -07:00
Konstantin DunasandGitHub 70149e9e49 chore: bump verifiers to 185b67d and prime-envs to e82de8b (#3750) 2026-10-02 02:25:38 +02:00
Scott CabrinhaandGitHub 80f9bd1a63 fix(sft): reshard FSDP2 params after validation before grad clipping (#3737)
## Summary

SFT validation runs between backward and `clip_grad_norm_` (deliberate:
`torch.compile` sees the training graph first, and `eval_on_start`
evaluates untrained weights). The `[lm_head, norm]` FSDP2 group opts out
of `reshard_after_forward`, so the no-grad validation forward leaves it
unsharded. FSDP2 keeps the reduced gradients on the *sharded*
parameters, so `clip_grad_norm_` — which walks `model.parameters()` —
sees the grad-less unsharded parameters and skips them. The gradient
norm is too low on validation steps, and the skipped gradients are not
scaled.

Fix: reshard the FSDP modules right after `run_validation` (one call to
the existing `reshard_module` helper), before clipping. Affected runs:
SFT with `optim.max_norm` set and `[val]` enabled, on the GPU optimizer
or `optim_cpu_offload` (the `full_offload` path disables clipping by
config validation, and the RL trainer has no validation step between
backward and clipping, so both are unaffected).

Seen on prime-rl `7f9de649aa80` (GLM-5.3 SFT): on validation steps the
norm was 13.7% low (66.6 vs 77.2) and clipping saw 112 of 114
parameters.

- [ENG-6447](https://linear.app/primeintellect/issue/ENG-6447)

## Testing

- The GPU test that originally accompanied this fix was removed on
request; coverage of the reshard-before-clipping behavior now relies on
the external GLM-5.3 SFT run and the code-path trace in the ticket
below.
- `ruff check` + `ruff format` (v0.13.0, as pinned by pre-commit) pass
on the changed file.
- No CUDA locally, so the suite was not run here; nothing else in the
diff is behaviorally load-bearing beyond the 5-line fix.

## Notes for reviewers

- The 13.7% figure was measured on an external GLM-5.3 SFT cluster; we
could not reproduce it locally and did not try — the mechanism is
confirmed from the code path (see the Linear ticket for the full trace).
- `reshard_module` already existed in `trainer/model.py` but had no
callers.
2026-10-01 16:13:03 -06:00
15dc2c6f40 feat(sft): map dataset columns in data.columns (#3744)
## Summary

- add `[data.columns]`, which names the dataset columns the SFT trainer
reads. `messages`, `prompt`, and `completion` hold lists of OpenAI chat
messages and `tools` holds OpenAI function-calling schemas; each
defaults to today's name. `SFTDataset` reads the configured names per
row, so no dataset is rewritten up front. The defaults are optional
because a dataset carries either `messages` or `prompt`/`completion`; a
name set in the config must exist in the dataset
- add `[data.columns.renderer]`, a `renderer field = dataset column`
mapping that sets any renderer template control per sample, e.g.
`reasoning_effort = "effort"` for a dataset whose column is named
differently from the renderer field. It defaults to `reasoning_effort =
"reasoning_effort"` on the config. `RendererResolver` reads the mapped
columns per row and merges a row's non-null values through
`merge_chat_template_kwargs`, so the renderer's config validates them
and custom renderers' fields work too. Rows and datasets without a
mapped column use the configured renderer unchanged
- the trainer reads `tools` as OpenAI schemas as is (a list of dicts or
a JSON-encoded string of one); it no longer rewrites other shapes
- docs in `training.md`; unit tests for the resolver with default and
mapped renderer columns, for a renderer without the field, for mapped
message columns, and for tools passing through from the mapped column

## Breaking

- The trainer no longer falls back to a `tool_defs` column when `tools`
is absent, and no longer converts verifiers-shaped tool entries
(`name`/`description`/`parameters` at the top level) into OpenAI
function-calling schemas. Provide the `tools` column in OpenAI format,
under any name via `[data.columns] tools = "..."`.

## Verification

- `tests/unit/test_configs.py` and `tests/unit/train/sft`: 284 passed;
the two `test_prime_monitor.py` failures also fail on `main` in this
setup
- SFT e2e on 2 GPUs with the renderer mapping in place (reverse-text, 10
steps, custom renderer, dataset without a `reasoning_effort` column):
loss 4.64 → 3.56, matching the run without the mapping step for step

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking SFT dataset contract for `tool_defs` and non-OAI tool shapes;
column mapping misconfiguration fails at dataset init or render time.
> 
> **Overview**
> Adds **`[data.columns]`** so SFT can read chat data and tool schemas
from differently named HF columns (`messages`, `prompt`/`completion`,
`tools`) without rewriting datasets. **`[data.columns.renderer]`**
generalizes per-row renderer overrides: any renderer template field can
map to a dataset column (default still `reasoning_effort`), merged via
`merge_chat_template_kwargs` in **`RendererResolver`**.
> 
> **Breaking:** the trainer no longer accepts a **`tool_defs`** fallback
or converts verifiers-style tool dicts to OpenAI function-calling
format—**`tools`** must be OpenAI-shaped (list or JSON string),
optionally under a custom name via **`[data.columns]`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a07ffb838c5c6cbf1e9ab9f20662078c85b69ebf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-01 14:47:50 -07:00
db699f39ee feat: custom renderers from local modules and files (#3743)
## Summary

- pin `deps/renderers` to `d43c430`, the PrimeIntellect-ai/renderers#168
merge on `main`, which adds `CustomRendererConfig` and
`renderers.custom`. `[renderer] name = "custom"` with `import_path =
"my_module.Class"` or `"path/to/file.py:Class"` selects a renderer that
lives outside the renderers package, for SFT and for RL via
`[orchestrator.renderer]`. The renderer's own `config_class` validates
the remaining `[renderer]` keys, which sit inline like every other
renderer config; the key names match `type = "custom"` + `import_path`
on custom losses and filters
- SFT applies a `reasoning_effort` column through
`merge_chat_template_kwargs`, so custom renderer configs honour the
column and renderers without the field reject it with the renderers
error
- docs in `training.md` and `algorithms.md`; unit tests for a custom
renderer in SFT and orchestrator configs, unknown fields rejected, and
the SFT resolver with a custom renderer's `reasoning_effort`, each
against a toy renderer written to `tmp_path`

#3744 stacks on this PR with a `[data.columns]` mapping.

## Verification

- `tests/unit/test_configs.py`, `tests/unit/inference`,
`tests/unit/train/sft`, `tests/unit/orchestrator/test_clients.py`: 308
passed (config tests rerun after the fixture change: 204 passed); the
two `test_prime_monitor.py` failures also fail on `main` in this setup
(they read source files by package path)
- the e2e runs below use a PrimeIntellect Qwen3 subclass that appends an
`instruction` template control to the system prompt (not checked in).
Rendered with the real `PrimeIntellect/Qwen3-0.6B` tokenizer, the
instruction lands in the system turn, and a conversation without a
system message gets one whose tokens carry message index -1 while the
user and assistant tokens match the base renderer exactly
- loaded the renderers README's GLM-5.3 no-thinking custom renderer
through an SFT config on this branch: it resolves and renders the
generation prompt as `<|assistant|><think></think>`
- SFT e2e on 2 GPUs (the reverse-text SFT config with that renderer as
`[renderer]`, 10 steps, evals at 5 and 10 with 8 rollouts): loss 4.64 →
3.56, no errors. Re-rendering the first dataset row with the run's
resolved config shows the instruction appended to the dataset's system
prompt
- RL e2e on 2 GPUs (the reverse-text RL config with that renderer as
`[orchestrator.renderer]`, 5 steps, 32-rollout eval at steps 0 and 5):
train reward 0.22 → 0.56, eval reward 0.05 → 0.74, no errors. Decoding
the prompt tokens of every trace in the run's stream: all 781 train
rollouts carry the instruction, the 64 eval rollouts (chat-completions
through vLLM's template) do not
- a downstream custom renderer passes 88 of its 94 tests against this
branch; the 6 per-sample column tests pass with #3744

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



<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are config/docs plus SFT renderer resolution; behavior for
built-in renderers should stay equivalent via
`merge_chat_template_kwargs`, with risk limited to misconfigured custom
`import_path` at launch.
> 
> **Overview**
> Adds **custom renderer** support documented end-to-end: set
`[renderer]` or `[orchestrator.renderer]` to `name = "custom"` with
`import_path` pointing at a user class (`module.Class` or
`path/to/file.py:Class`). Extra TOML keys are validated by that class’s
`config_class`, matching the pattern used for custom losses/filters.
> 
> SFT **per-row `reasoning_effort`** now goes through the renderers
helper `merge_chat_template_kwargs` instead of hand-rolled Pydantic
checks, so custom configs that declare `reasoning_effort` (via
`_template_fields`) honor the dataset column and invalid values fail at
validation time.
> 
> **Tests** cover SFT and orchestrator config loading with a toy
renderer on disk, rejection of unknown renderer keys, and
`RendererResolver` caching when `reasoning_effort` overrides a custom
config.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b051050d57b2acd707b07346081d8f229e2227b8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-01 14:20:07 -07:00
2d7a753320 examples: 2-node Qwen3-30B-A3B SFT config (#3728)
Adds a multi-node SFT example for `Qwen/Qwen3-30B-A3B-Instruct-2507` on
**2 train nodes**. It uses the same layout as the GLM-5.3 SFT example
(`examples/advanced/glm-5.3/sft/h200/`).

### Files
- `examples/advanced/qwen3-30b-a3b/sft/h200/base.toml`: custom MoE
implementation, `ep = 8`, FA3, full AC with offloading, AdamW (lr 1e-5,
linear schedule, 50 warmup steps), `multi_node` with `num_train_nodes =
2` and a `[slurm]` block. Trains only, with no inference nodes.
- `sft/h200/math-10k.toml`: data overlay for
`PrimeIntellect/INTELLECT-3-SFT-10K` (math split), seq_len 32k,
batch_size 16.
- `sft/h200/fake.toml`: fake-data smoke test with
`force_balanced_routing`.
- README: adds a table row and an `## SFT` section.

```bash
uv run sft @ examples/advanced/qwen3-30b-a3b/sft/h200/base.toml @ examples/advanced/qwen3-30b-a3b/sft/h200/math-10k.toml
```

### Testing
- Both `base + math-10k` and `base + fake` parse and validate against
`SFTConfig` (slim `prime-rl-configs` package). The renderer
auto-resolves to `qwen3` for this checkpoint.
- **Not run on a cluster yet.** Memory and throughput on 2×8 H200 are
unverified.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Example TOML and documentation only; no changes to training,
inference, or auth paths.
> 
> **Overview**
> Adds a **supervised fine-tuning (SFT)** example for
`Qwen/Qwen3-30B-A3B-Instruct-2507`, mirroring the GLM-5.3 `sft/h200/`
layout: **`base.toml`** (custom MoE, `ep = 8`, FA3, activation
checkpointing with offloading, AdamW, **2 train nodes** only),
**`math-10k.toml`** (`PrimeIntellect/INTELLECT-3-SFT-10K` math split,
32k seq, batch 16), and **`fake.toml`** for smoke tests.
> 
> The Qwen3 README gains a config-table row and an **`## SFT`** section
with `uv run sft @ ...` compose instructions, cluster tweaks
(`partition`, `HF_HOME`), and notes on longer context via `model.cp`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
565709d38fe835c161c984f26f0810e23029b3bf. 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-01 14:17:29 -07:00
1bddcf6b11 feat(moe): add SonicMoE BF16 expert compute backend (#3535)
Adds `model.moe.compute.backend = "sonicmoe"` for BF16 MoE expert
computation. Sonic consumes already-dispatched expert rows and fused
gate/up weights; dispatchers retain routing-score application and
combination.

`GroupedExperts` owns its parameters and delegates execution through the
structural `ExpertCompute` protocol. Concrete backends do not inherit
from the protocol. `set_compute()` validates compatibility before
assignment: Sonic requires fused gate/up weights, standard SwiGLU, and
bias-free experts. Unsupported structures, including DeepSeek V4's
clamped SwiGLU, raise during setup without replacing the active backend.

Native BF16, DeepGemmFP8, and MXFP8 share the grouped-GEMM
implementation. Sonic uses its fused expert pipeline. Selective
checkpointing saves `quack::gemm_out`, `quack::gemm_gated_out`, and
`quack::gemm_act_out`; compiled expert traces verify that saving
eliminates the repeated gate/up GEMM.

```toml
[trainer.model]
name = "Qwen/Qwen3-30B-A3B"
ep = 8

[trainer.model.moe.compute]
type = "bf16"
backend = "sonicmoe"

[trainer.model.moe.dispatch]
type = "torch"
```

Install with the `sonic-moe` extra, also included in `all`. Uses default
gate/up fusion and retains optimization/reduction dtype defaults.

Rebased onto main `9eacd477f`. Pins SonicMoE's EP-aware token bucketing
at `0bf06ac` and [QuACK's checkpoint-isolation
fix](https://github.com/Dao-AILab/quack/pull/204) at `f62009f`, based
directly on QuACK 0.6.5 and compatible with main's vLLM 0.30 / CUTLASS
4.7.1 stack.

Validation:

- After rebase and dependency update: 224 MoE, checkpoint, and
configuration tests pass; Ruff, formatting, whitespace, lockfile
consistency, and all-extras installation pass.
- After the QuACK 0.6.5 update: six realistic-shape GPU comparisons pass
at 32,896 and 65,664 routed rows (16 experts, dimensions 2048/768),
including uneven routing, eager execution, and fullgraph compiled
selective checkpointing with/without GEMM saving. Zero graph breaks;
maximum output and gradient relative errors were 0.454% and 0.402%.
- Before this rebase: 18 realistic expert-shard comparisons passed
across 8,192–65,664 routed rows, 16 local experts, dimensions 2048/768,
eager and compiled selective-checkpoint paths. Maximum relative errors
were 0.454% for outputs and 0.402% for gradients.
- Paired full-model B300 EP8 runs completed 20 Qwen3-30B-A3B math SFT
steps with sequence length 8192, batch 8, seed 42, selective
checkpointing, and SignSGD 1e-5. FA4, FA2, and a separate FA4 experiment
with #3676 all produced finite losses/gradients and readable final
checkpoints. These E2E runs used the pre-rebase QuACK 0.6.4 stack; #3676
was only an experimental overlay and is not included here.

Performance follow-up: Sonic's later-step overhead was 14.3% with
original FA4, 16.9% with FA2, and 21.1% in the #3676 FA4 experiment.
These are separate pairs of single runs, not controlled cross-backend
attention comparisons. Shared compilation breaks prevented compiled
checkpointed-block execution: #3676 removed the attention break, then
both expert backends hit the FP32 router's nested FSDP hook. This limits
conclusions about effective Sonic GEMM saving in E2E. It does not
establish that fixing the shared breaks eliminates all Sonic overhead.

Sonic also retains long first-step autotuning and occasional
approximately 37-second bucket-transition steps without a Dynamo
recompile. These remain performance follow-ups; no correctness blocker
was found in the realistic-shape and E2E checks.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core MoE forward/backward paths and adds a new optional kernel
backend with strict structural requirements; misconfiguration fails at
setup, but numeric parity depends on the pinned Sonic/QuACK stack.
> 
> **Overview**
> Adds an optional **SonicMoE** path for BF16 routed-expert compute via
`model.moe.compute.backend = "sonicmoe"` (default remains `"torch"`).
Install with the new `sonic-moe` extra; `quack-kernels` is pinned from
git for Sonic’s dependency stack.
> 
> MoE execution is refactored from injectable **grouped GEMM** objects
to an **`ExpertCompute`** protocol: `GroupedExperts` delegates forward
to `set_compute()`, which runs **`validate()`** before switching
backends. Torch BF16, DeepGEMM FP8, and MXFP8 share
**`GroupedGemmExpertCompute`**; Sonic uses a fused
**`moe_general_routing_inputs`** path and rejects unfused gate/up,
non-SwIGLU activations, and expert biases at setup.
> 
> Runtime wiring in **`configure_moe_runtime`** picks the backend from
config; selective activation checkpointing now retains
**`quack::gemm_*`** ops for recomputation with Sonic/QuACK. Docs and
unit tests cover config defaults, Sonic compatibility checks, and
unchanged BF16 fallback when layers are excluded by **`apply_to`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0609006b661abe2a79de59a02b66fac2c24d91e9. 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: matejsirovatka <matejsirovatka@users.noreply.github.com>
2026-09-30 22:42:07 +02:00
Scott CabrinhaandGitHub 2476f6360c fix(disagg): disable breakable CUDA graphs on DeepEP high-throughput prefill (#3669)
## What

- **Templates:** both P/D sbatch templates (`inference.sbatch.j2`,
`multi_node_rl.sbatch.j2`) export `VLLM_USE_BREAKABLE_CUDAGRAPH=0` on
prefill nodes. It's set before `prefill_env_vars`, so a config can still
override it.
- **Example configs:** the GLM-5.3 P/D examples
(`examples/advanced/glm-5.3/swe.toml`, `infer/pd.toml`,
`infer/pd-llmd.toml`) set it explicitly in their prefill env vars. The
setting then travels with the config to launchers that don't use these
templates (rl-k8s, fft#103).

## Why

vLLM 0.29 auto-enables breakable CUDA graphs for `GlmMoeDsaForCausalLM`.
On prefill ranks, which these templates pin to `all2all_backend =
"deepep_high_throughput"`, capture then includes the internode DeepEP
dispatch and every prefill engine dies at startup:

```
RuntimeError: DeepEP error: timeout (dispatch CPU)
torch.AcceleratorError: CUDA error: capturing stream has unjoined work
```

**Root cause (vLLM bug, present identically in v0.29.0 and v0.30.0).**
vLLM has a guard that disables CUDA graphs for `deepep_high_throughput`
("not CG compatible") in `CompilationConfig.set_splitting_ops_for_v1`,
but it sits below the early return taken when `mode != VLLM_COMPILE` —
and enabling breakable cudagraph sets exactly that
(`_maybe_enable_breakable_cudagraph()` sets `mode = NONE`, before
`set_splitting_ops_for_v1` runs). The guard never fires, so
`use_breakable_cg` still captures the HT dispatch. With the flag set,
the guard runs and sets `cudagraph_mode=NONE` — the state vLLM intends
for HT prefill. Decode (`deepep_low_latency`, `FULL_DECODE_ONLY`) is
unaffected and keeps breakable.

**Interim.** This is a workaround for the guard-skip, not the final fix.
Upstream has the same defect filed for a different guard (vllm#53030,
fix in flight vllm#53061 — it hoists only that guard, not this one).
Drop these settings once the DeepEP-HT guard is hoisted, or when HT is
retired for `deepep_v2` (vllm#46887).

## Test plan

- [x] `infer/pd.toml` and `infer/pd-llmd.toml` validate as
`InferenceConfig` with the new key
(`prefill_env_vars["VLLM_USE_BREAKABLE_CUDAGRAPH"] == "0"`). `swe.toml`
gets the same one-line addition to its prefill env map; its full local
validation needs the `r2e-gym` taskset package installed.
- [x] GLM-5.3 10-node P/D (EP16 prefill + EP16 decode, DeepEP) on H200
via FFT/telus, image `commit-cef7100c7-amd64` (vLLM 0.29.0):
  - Without the setting, all 16 prefill ranks hit the error above.
- With `VLLM_USE_BREAKABLE_CUDAGRAPH=0` on prefill, all 16 reach
`Application startup complete`, and a chat request through the PD router
returns correctly with successful NIXL KV transfers (ENG-6348).
- This was set through the FFT chart's prefill env, not these templates.
The templates only need the same `export`.
2026-09-30 14:09:19 -06:00
Konstantin DunasandGitHub 15f4704092 feat(dashboard): show cancelled and failed subagents in the semantic timeline (#3721) 2026-09-30 19:55:47 +02:00
Konstantin DunasandGitHub 8f4ae42fb8 fix(dashboard): detect index rewrite on resume in index_rows (#3732) 2026-09-30 19:26:30 +02:00
d5f29c072a feat: dashboard global filter and train overview tiles (#3725)
## Summary

- **Overview keeps its scroll position across re-renders.** Every new
eval episode (and every new metric key on a training run) rebuilt
`#overview-body` and snapped it to the top, which made analysing
anything below the fold on a live eval impossible. `renderMetricsBody`
now restores `scrollTop` after the rebuild.
- **One filter shared by the overview, the traces table and the trace
viewer.** The filter menu (status, kind, env, outcome) is a single
`<template>` cloned into the three toolbars over one `state.filter`; a
change in any copy applies in all, and the traces tab reloads when it
opens with a filter set elsewhere. On the overview the env / kind pair
narrows the sections and summary tiles; for an eval run the outcome pair
(`ok` / `error`, replacing the per-pane `include errors` toggle) picks
the episodes the distributions read. The server's `errors_only` episode
filter becomes a three-way `ok` parameter.
- **Live rollouts obey the filter.** Live rows arrive by their own poll
and were spliced into the traces table and the viewer's list whatever
the filter said, so `live + eval` still listed the in-flight train
rollouts. They now pass the same kind / env / outcome check as finished
episodes (an outcome filter hides them, since theirs is still open), and
the "N live" count follows.
- **Eval overview is multi-env.** With no env filter every env renders,
one block after another, each headed by its env name and set off by a
rule; the composition panes hold one model per pane instead of two
globals.
- **Train overview leads with a step bar and summary tiles, like the
eval pane.** One cell per step (click opens that step's batch in the
traces tab) with `done/total (share)` beside the bar; a run without
`max_steps` reads `N/∞` over cells that grow instead of a bar that
always looks full. The tiles keep to results: the reward of each train
env and the avg@k of each eval env, each with its change from the first
logged value beside the number (green when it moved the right way), the
error / truncation / timeout rate of the shown scope, and the step time.
An SFT run shows loss, val loss, eval scores, total samples and tokens,
throughput and MFU. Panes default to 300 × 170px (four per row on a
14-inch laptop), a saved pane size still wins. Tiles are the eval pane's
`tileHtml` / `blockBarHtml`, share its hover cards, and wrap for runs
with many envs.
- **Flat, per-env sections with readable panel names.** The overview
reads top to bottom: no collapsible `details`, no collapse / expand
buttons (the Metrics tab keeps its folding sections), one train section
per env with the cross-env aggregate left to the Metrics tab. Panels are
named in caps for reading (`MEAN REWARD`, `MEAN TURNS`, `ERROR RATE`,
`AVG@4`, `GRAD NORM`, `KV CACHE USAGE`, ...) with an `i` mark beside the
title whose hover card says how the value is computed and shows the raw
key; the latest value reads larger in the corner. Pane order stays keyed
by the raw title, and the Metrics tab keeps every key as logged.
- **Eval sections show `avg@k` alone as the score**: it is the mean
reward over the same traces `reward/mean` averages, so the reward panes
only repeated it.
- **SFT sections**: `val loss` / `val perplexity` appear only once a
validation value is logged (the server's `has_validation` meta field
goes); stability adds `max vio` (expert load imbalance) when an MoE
model logs it; performance drops the step and checkpoint time panes.
- Smoke test asserts the step bar, tiles, info marks and the mounted
filter menus; the dashboard skill documents the new overview and the
shared filter.

## Verification

Ran a multi-env RL run (`configs/debug/multi-env/rl.toml`: two
reverse-text train sources + an online eval with a base eval at step 0,
10 steps), a 20-step SFT run (`examples/basic/reverse-text/sft.toml`
with validation and an online eval) and a two-source gsm8k eval against
Prime Inference, served all three from this branch's dashboard, and
drove it with playwright (no console errors):

- Before: scrolling the eval overview to 600px and re-rendering (what a
landed episode triggers) reset `scrollTop` to 0. After: it stays at 600.
- Setting `env = gsm8k-b` in the overview's filter narrows the overview
to that env, and the traces tab then lists only `gsm8k-b` rows with the
same badge; `error`-only narrows the table through the new `ok` param.
- Live rows: with two synthetic live rows (train + eval) injected, `live
+ eval` lists only the eval one, an env filter keeps only its env's, and
an outcome filter hides both.
- Train overview: `10/10 (100%)` bar; tiles `reverse-text-a reward 0.781
▲ +0.606`, `reverse-text avg@1 0.849 ▲ +0.737` (base eval at step 0),
`truncation rate 2% ▼ -72%`; clicking step cell 2 opens the traces tab
in step mode at step 2; with `env = reverse-text-a` only that env's
train section (plus stability / inference / performance) and tiles
remain. A synthetic 20-env run wraps its 25 tiles over four rows with no
horizontal overflow.
- SFT overview: `loss 3.196 ▼ -1.415` (lower is better reads green),
samples 2.2K and tokens 2.6M match the trainer's counters (32 × 4096 ×
20 steps), throughput 19.6K tok/s, MFU 31%.

### Eval overview, two envs (filter unset)

![eval overview multi
env](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/eval-overview-multi-env.png)

### Eval overview narrowed to one env from the same filter

![eval overview
filtered](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/eval-overview-filtered.png)

### The traces tab picks the filter up (env + badge)

![traces filter
shared](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/traces-filter-shared.png)

### Train overview: step bar, summary tiles with base deltas, flat
per-env sections

![train
overview](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/train-overview.png)

### Info mark on a panel

![train overview
info](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/train-overview-info.png)

### Train overview narrowed to one env

![train overview
filtered](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/train-overview-filtered.png)

### Open-ended run (no `max_steps`) and a synthetic 20-env run

![open
ended](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/train-open-ended.png)

![many
envs](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/train-many-envs.png)

### SFT overview (20-step reverse-text SFT with an online eval)

![sft
overview](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/ce5b8925bf9e5c2fb59f8f69ecf6f6b7dcaf4d92/sft-overview.png)

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches episode listing/filter query params and a large front-end
state refactor; incorrect filter wiring could hide episodes or desync
overview vs traces, but changes are UI/read-path focused with no auth or
training logic changes.
> 
> **Overview**
> Introduces a **single run filter** (status, kind, env, outcome) cloned
from one template into the overview, traces table, and trace
viewer—replacing separate env pickers and an “errors only” checkbox.
Episode APIs now take **`ok`** (`true` / `false` / unset) instead of
**`errors_only`**, and live rollout rows honor the same filter.
> 
> **Eval overview** shows **every filtered env** as stacked blocks (not
one env at a time); distributions respect the **ok/error** outcome
toggles. **Training/SFT overview** adds a **clickable step bar**,
**summary tiles** with delta-from-first-logged-value, **readable panel
titles** with **`i` tooltips** (raw metric keys on hover), flat per-env
sections, and **scroll position preserved** on live re-renders. SFT
panel layout tweaks (val metrics when logged, optional MoE `max_vio`,
trimmed performance panes); run meta drops **`has_validation`**.
> 
> Docs and smoke tests updated for the shared filter and new overview
chrome.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6bb87a7a0fd6e94922154649307167a41645913d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 18:58:49 -07:00
330f174761 feat: unify how source groups pass defaults (#3714)
## Summary

- Add `SourceGroupConfig`, the one base of every source group:
`[orchestrator.train]` (`TrainConfig`), `[orchestrator.eval]` and the
SFT `[eval]` block (`ScheduledEvalConfig`), and the top level of `uv run
eval` (`EvalConfig`). It has one rule: every field that a group and its
source type both declare is a default. Each source inherits the fields
that the group sets, merged under its own with `vf.merge_defaults`:
nested blocks merge key by key, a source's own values win, and a block
whose `type`/`id` differs is the source's alone.
- Remove the four earlier mechanisms: the group `env` merge, the shallow
group `select` merge, and the after-validators that copied `sampling`,
`group_size` (eval) and `interval` onto sources. Adding a shared field
is now one field on the group.
- Move `group_size` and `algo` from `OrchestratorConfig` into the train
group, so train sources inherit them from their group like eval sources
do. `TrainSourceConfig.algo` defaults to `grpo` instead of `None`, which
removes the `algo is not None` guards.
  ```toml
  [orchestrator.train]
  group_size = 16

  [orchestrator.train.algo]
  type = "echo"
  ```
- Let each train source use its own `group_size` over the group's
(source > group, like every default). The runtime already dispatches and
finalizes each group at its env's size. The config checks now require
`batch_size` to be divisible by every train source's group size, and
`concurrency.max_inflight`/`initial_inflight` to cover the largest one;
before, they checked only the group default. The platform run records
the largest source group size as `rollouts_per_example`.
- Migrate the shipped configs (47 TOMLs plus the k8s orchestrator
example), the docs and the `configs` skill (which now also describes the
group-default rule). Every rewritten TOML parses to exactly the old data
with the two keys moved.
- Pin `deps/verifiers` to its main, which merged
PrimeIntellect-ai/verifiers#2709 (`vf.merge_defaults` replaces
`vf.merge_env_defaults`). Raise the `verifiers` minimum to
`0.3.2.dev158`, its first release, in both `pyproject.toml` files, so
the slim `prime-rl-configs` install gets it.

## Breaking

- `orchestrator.group_size` moves to `orchestrator.train.group_size`
(`--orchestrator.train.group-size`). A standalone orchestrator config
moves `group_size` into `[train]`.
- `[orchestrator.algo]` moves to `[orchestrator.train.algo]`
(`--orchestrator.train.algo.*`).
- A source `algo` that sets params without a `type` now keeps the
group's algorithm with those params changed. Before, it meant `grpo`
with those params. A source that sets a `type` still runs its own
algorithm.
- A source's `select.include`/`exclude` now merges with the group's
block key by key (e.g. a group `include.idx` and a source
`include.names` both apply). Before, the source's block replaced the
group's. Lists still replace.
- Nested dicts in a group `sampling` block (e.g. `extra_body`) now merge
with a source's instead of being replaced.

## Verification

- Resolved every shipped config on `origin/main` and on this branch, and
compared what each source ends up with (`name`, `group_size`, `algo`,
`sampling`, `select`, `interval`, `env`): 77 configs, 95 sources, 0
differences. (9 configs need taskset packages that are not installed in
the test env, on both sides.)
- `uv run rl @ <config> --dry-run` on `configs/debug/algo/echo.toml`,
`configs/debug/algo/mixed_grpo_opd.toml`,
`configs/debug/multi-env/rl.toml` and
`examples/basic/reverse-text/rl.toml`: each source resolves the group's
`group_size` and `algo` (or its own `opd`), and the resolved
orchestrator config has no top-level `algo`/`group_size`.
- The slim-install check, run locally: the `prime-rl-configs` wheel
installed outside the workspace resolves `verifiers 0.3.2.dev158`, the
workflow's import script passes, and a train group's `group_size`,
`sampling` and `env` defaults reach its source through
`vf.merge_defaults`.
- `uv run pytest tests/unit/test_configs.py tests/unit/eval
tests/unit/orchestrator tests/unit/test_dashboard_timeline.py`: 303
passed (2 vLLM-only tests deselected). New tests: sources inherit unset
group fields for each kind of default (blocks, a `-r` alias, `interval`)
and round-trip; train sources with group sizes 16 and 8 resolve, and a
batch size or in-flight cap that does not fit both is rejected; each
group field's default equals its source field's.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking config paths and merge semantics can silently change resolved
training/eval settings; batch and concurrency validation is stricter
when sources use different group sizes.
> 
> **Overview**
> Introduces **`SourceGroupConfig`** so train/eval source groups share
one inheritance rule: any field declared on both the group and its
sources (`env`, `sampling`, `select`, `group_size`, `algo`, `interval`,
…) becomes a default merged into each source via `inherit_defaults` /
`vf.merge_defaults`, replacing the old separate env/select merges and
post-validators that copied fields onto sources.
> 
> **Breaking config moves:** `orchestrator.group_size` and
`[orchestrator.algo]` move under **`[orchestrator.train]`** (same for
standalone orchestrator TOMLs: `[train]`). Shipped configs, docs, and
the configs skill are updated accordingly. Per-env **`group_size`**
overrides are first-class; validation now requires `batch_size`
divisible by **every** train source’s group size and concurrency limits
≥ the **largest** group size. Platform monitoring reports the max source
`group_size` as rollouts per example.
> 
> **Semantics changes:** Source `algo` blocks without a new `type`
inherit the group algorithm with partial overrides (not implicit
`grpo`). Group/source **`select`** and nested **`sampling`** dicts
key-merge instead of wholesale replace where applicable. **`verifiers`**
minimum bumped to `0.3.2.dev158` for `merge_defaults`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
536cc3e1190f8f9fc06419af9dffb1eda331168f. 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-09-29 18:31:38 -07:00
HubertandGitHub 91f58bd9d9 fix: shard single-row gate weights along columns for Muon (#3723)
Qwen shared-expert gates can have weight shape `[1, hidden_size]`.
Default FSDP row sharding gives some ranks empty local tensors, which is
incompatible with the equal-shard layout needed by the distributed Muon
update.

Shard 2D single-row parameters along dimension 1 when their width is
divisible by the parameter-sharding degree, obtained directly from
`parallel_dims.get_mesh("dp_shard_cp").size()`. Other parameters retain
the existing fused-parameter placement callback or default placement.
FSDP still uses the HSDP mesh; the divisibility check excludes
replication ranks. The placement rule applies during model setup
regardless of optimizer selection.

There is no additional optimizer-setup validation. Non-divisible layouts
retain the existing placement and failure behavior in Muon.

Validation performed locally:
- Two-rank CPU/Gloo DTensor reproduction with PyTorch 2.8.0: `[1,128]` /
`[0,128]` under `Shard(0)` versus equal `[1,64]` shards under the
placement callback, with exact reconstruction.
- Isolated placement checks across shard degrees 1/2/4/8/16,
non-divisible widths, 1D/3D parameters and fallback delegation.
- Ruff lint/format and `git diff --check` passed. Local diagnostic
scripts are not added to the repository. These checks do not exercise a
full FSDP + Muon GPU update on current main.

Remaining merge blocker: the NIXL weight sender currently assumes
dimension-0 shard offsets. Its handling of column-sharded gates must be
fixed or the incompatible transport/layout combination rejected before
merge. Checkpoint-layout compatibility also needs review.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Alters FSDP/DTensor layout for a narrow class of MoE gate weights;
downstream weight sync or checkpoint code that assumes row-wise sharding
may need matching updates.
> 
> **Overview**
> **FSDP setup** now uses a custom `shard_placement_fn` instead of
passing the fused-parameter callback directly. For **2D weights with a
single row** (e.g. Qwen shared-expert gates shaped `[1, hidden_size]`),
parameters are sharded along **column dimension 1** when the hidden
width is divisible by the **`dp_shard_cp`** mesh size, so every rank
holds an equal local shard for **Muon’s all-to-all**. All other
parameters still use the existing fused `shard_fused_on_dim1` placement
or PyTorch’s default.
> 
> The change pulls in `Shard` from `torch.distributed.tensor` and reads
shard degree from `parallel_dims.get_mesh("dp_shard_cp").size()`
(parameter sharding only, not HSDP replication).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
159c63d852ad37cdeb9e49ed9439fb2cfba47a2c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-30 01:00:37 +02:00
samsjaandGitHub 7f9de649aa fix(utils): throttle BetterStack heartbeat pings (#3715)
## Problem

Since #3664, eval runs beat the Better Stack heartbeat on every landed
episode. `Heartbeat` only coalesced *concurrent* requests (at most one
in flight), so once a ping returned, the very next landed episode fired
a new one. A busy eval lands many episodes per second and blows past
Better Stack's heartbeat rate limit:

```
WARNING BetterStack heartbeat failed with status code: 429
```

The trainer/sft/orchestrator beat once per batch and stay under the
limit only because of step duration.

## Changes

- `Heartbeat` now rate-limits itself: at most one ping every
`min_interval` seconds (default 30), counted from when a ping *starts*,
so a failed ping (429, network error) throttles retries too instead of
retry-storming on every landed episode.
- New `heartbeat.min_interval` config field (default 30, `> 0`
enforced); `Heartbeat` is constructed from the `HeartbeatConfig` object
directly at all four sites (eval runner, orchestrator, rl/sft trainers).
- Beats that arrive within the interval (or while a ping is in flight)
are dropped without an HTTP request. `beat()` stays non-blocking and
event-driven: no startup ping, and the heartbeat still goes stale when
episodes stop landing.

Better Stack monitors only need pings well within their period + grace,
so pinging at most every 30s loses nothing. Size `min_interval` under
the monitor's period if it is unusually short.

## Verification

- `uv run ruff check` and `uv run ruff format --check` pass on the
touched files.
- Throttle behavior checked with a mocked `requests.get` and fake clock:
first beat pings immediately; in-flight and within-interval beats are
dropped; a beat after the interval pings; a failed 429 ping is not
retried within the interval.
- `uv run pytest tests/unit/test_configs.py tests/unit/eval
tests/unit/utils`: failure set identical before/after the change on this
tree — all 67 pre-existing failures are `ModuleNotFoundError`s for
optional taskset packages in a non-GPU sync.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Observability-only change with a safe default interval; no impact on
training, auth, or data paths beyond fewer external heartbeat HTTP
calls.
> 
> **Overview**
> Fixes Better Stack **HTTP 429** errors when eval runs call `beat()` on
every landed episode while only coalescing concurrent pings.
> 
> **`Heartbeat`** now takes full **`HeartbeatConfig`** (not just the
URL) and enforces **`min_interval`** (default **30s**): surplus `beat()`
calls are dropped with no HTTP request; interval is measured from when a
ping *starts*, so failed pings also throttle retries. In-flight
coalescing is unchanged; `_pending` is cleared in a `finally` block.
> 
> New config field **`heartbeat.min_interval`** (`> 0`, default 30) with
eval config docs updated. Eval runner, orchestrator, and RL/SFT trainers
construct `Heartbeat(config.heartbeat)`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b32a69252b8e393e933952e53e30ea7a9b78d67c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-29 12:38:49 -07:00
88f5e6def1 feat: bump vllm-router to 0.2.2 (#3718)
## Summary

- Bump `vllm-router` from 0.2.1 to
[0.2.2](https://github.com/PrimeIntellect-ai/router/releases/tag/v0.2.2)
(amd64 and arm64 release wheels).
- The new router picks up PrimeIntellect-ai/router#58. The default
health-check interval drops from 60s to 20s, and every health-check
cycle refreshes `/v1/models`. Workers that are still loading at startup
no longer stay under `unknown` and miss model-filtered traffic for
minutes.

## Verification

- `uv lock` resolves with `vllm-router v0.2.1 -> v0.2.2`.
- Installed router reports version `0.2.2` and
`RouterArgs.health_check_interval_secs == 20`.
- Ran 5 steps of `configs/basic/reverse-text/rl.toml` single-node on
SLURM (H200) through the router: 5/5 steps, 0% rollout errors, no
tracebacks.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the disaggregated inference routing dependency only, but the
new router changes health-check timing and worker/model discovery
behavior on the critical vLLM serving path.
> 
> **Overview**
> Upgrades the pinned **`vllm-router`** wheels from **0.2.1** to
**0.2.2** for Linux **x86_64** and **aarch64** in `pyproject.toml`, with
matching **`uv.lock`** updates (version, download URLs, and wheel
hashes).
> 
> Installs that use the **`disagg`** extra (and related GPU/disagg
resolution paths) will pull the new router release instead of 0.2.1. No
in-repo application code changes—only dependency resolution.
> 
> The **0.2.2** router (PrimeIntellect-ai/router#58) shortens the
default health-check interval (**60s → 20s**), refreshes
**`/v1/models`** on each health cycle, and avoids workers staying
**`unknown`** while still loading at startup (so model-filtered traffic
is not skipped for long periods).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f8087add142c2f5a8b27b669902335c60d186cc1. 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-09-29 10:04:06 -07:00
JannikStandGitHub 9eacd477f1 fix(docs): reword bare '<=' in scaling.md to avoid MDX parse error (#3713)
## What
A bare `<= 8` in the Expert Parallelism prose of `docs/scaling.md` (line
97) is parsed by MDX as the start of an HTML tag, failing compilation
with:

> `Unexpected character '=' (U+003D) before name, expected a character
that can start a name, such as a letter, '$', or '_'`

This breaks the Mintlify build of the page imported into **public-docs
PR #219** — the preview deploy 404s `/prime-rl/scaling`, so merging #219
before this fix would publish the broken page.

## Change
Reworded `and is <= 8` → `and is at most 8` (one line). Rewording was
chosen over an inline-expression escape (`{'<='}`) because it is robust
in both MDX pipelines and reads naturally in the sentence. Audited the
rest of the file for bare `<`/`>`/`{`/`}` outside code spans: the only
other occurrences are a `>` blockquote (line 185) and an inline `>`
(line 152), both valid MDX; every remaining `<`/`{`/`}` sits inside
backtick code spans.

## Verification
- Compiled with `@mdx-js/mdx@3` (same compiler family Mintlify pins):
  - pre-fix file: `MDX FAIL: Unexpected character '=' ...`
  - fixed file: `MDX OK`
- Rendered meaning is identical to the original sentence.

Blocks #219 (public-docs) — merge this first, then re-run the #219
preview build.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation-only wording change with no runtime or config behavior
impact.
> 
> **Overview**
> Fixes **Mintlify/MDX compilation** for the Expert Parallelism section
in `docs/scaling.md` by rephrasing the EP auto-resolution rule so prose
no longer contains a bare **`<= 8`**, which MDX treats as the start of
an HTML tag and fails to parse.
> 
> The sentence now says the chosen EP degree **is at most 8** instead of
**`is <= 8`**; meaning is unchanged. This unblocks the public-docs
preview for `/prime-rl/scaling` (merge before dependent doc PRs).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fda404ad8bea01b8afbd24b16f32c38d98846d65. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-29 08:04:05 +02:00
JannikStandGitHub 40d130d8f1 feature: prime monitor for SFT trainer (#3614)
## Motivation

Hosted SFT runs (the dedicated FFT path) currently report nothing to the
platform: `SFTConfig.monitors` was the base `MonitorsConfig` (wandb/file
only), so a hosted SFT trainer has no platform run — no metrics, no
billing surface, no "view on platform" link. RL runs get all of this
through `PrimeTrainMonitor` (wired in the RL orchestrator); this PR
gives the SFT trainer the same platform integration.

## What it adds

- **Config**: `SFTConfig.monitors` is now `TrainMonitorsConfig`, so
`[monitors.prime]` (and `--monitors.prime`) is a valid SFT config block.
`monitors.prime.name` defaults to `run.name`, mirroring the
orchestrator's and eval config's name inheritance.
- **Monitor**: `PrimeTrainMonitor.init` learns the SFT registration
shape — base model, no environments (SFT trains on a dataset),
`TrainingSpec(max_steps, batch_size, seq_len)` from the data block, no
rollouts per example, full resolved config dumped to the platform run
record. The RL registration path is unchanged.
- **Trainer** (`trainer/sft/train.py`): passes `monitors.prime` to
`monitors.setup` and calls `monitors.finalize()` after training,
matching the RL trainer's call sites. The existing per-step metric
logging (train loss/perplexity, `optim/lr`, grad norm, throughput,
progress, time) and `[val]` losses now fan out to the platform unchanged
— the platform's existing internal RFT endpoints work as-is.
- **Launcher** (`entrypoints/sft.py`): `build_online_eval_config`
converts the trainer's `TrainMonitorsConfig` into `EvalMonitorsConfig`
for the online-eval process (the platform monitor switches to the
evaluation flavor under the same name). Without this, an `[eval]` +
`[monitors.prime]` run would fail `SFTOnlineEvalConfig` validation.
- **Docs**: platform-monitoring section covers `sft`; SFT launch section
links to it.

Env surface mirrors RL exactly: the monitor reads `$RUN_ID` (attach to
the launcher-pre-created platform run), `$PRIME_API_BASE` and
`$PRIME_API_KEY` — the values the fft chart injects into trainer pods —
and `PRIME_RUNS_MODE=disabled` stays the opt-out. No trainer-side usage
POST is needed: RL's per-step `PI_USAGE_*` billing posts were removed in
#3275; usage/GPU-hours for hosted runs is derived platform-side from the
run record, which the SFT monitor now registers (config dump includes
the deployment topology).

## Tests

- `uv run pytest tests/unit/train/sft/test_prime_monitor.py` — 6 passed
(mocked `prime_runs.init`: registration kwargs for SFT, name
inheritance, W&B project passthrough, `monitors.setup` fan-out of
metrics + finalize, online-eval monitors conversion). This file is
torch-free and runs on macOS.
- `uv run pytest tests/unit/test_configs.py` — identical result to a
clean `origin/main` baseline (67 pre-existing failures on this macOS env
from missing GPU/harness packages — env-dependent, unrelated to this
change; diff of failing tests verified identical).
- `uv run sft @ <minimal sft.toml> --dry-run --monitors.prime` —
resolves; `monitors.prime.name` inherits `run.name` in the resolved
config dump.
- `uv run ruff check` / `ruff format --check` — clean.

Note: the fft validator service picks this schema change up
automatically once a GHCR image is built from a commit containing this
PR (per-image schema venvs install `prime-rl-configs` from the image's
commit). No validator-side change needed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches platform run lifecycle and cross-process shared state on the
run directory; training continues if dashboard record persistence fails,
but incorrect merging could break platform links for SFT+online-eval
runs.
> 
> **Overview**
> Adds **`--monitors.prime` / `[monitors.prime]`** to SFT so hosted runs
register on Prime Lab, stream trainer metrics (including validation),
and call **`monitors.finalize()`** on exit—same flag shape as RL, with
**no rollout episode uploads**.
> 
> **Config wiring:** `SFTConfig.monitors` is **`TrainMonitorsConfig`**;
online eval uses **`EvalMonitorsConfig`** plus
**`build_online_eval_monitors`** so the launcher maps the trainer’s
platform block to **`PrimeEvalMonitorConfig`** for the eval subprocess.
**`monitors.prime.name`** defaults to **`run.name`**. SFT online eval
shares the trainer’s **`run_dir`**; the dashboard platform JSON is
updated via **locked merge**, not separate dirs.
> 
> **`PrimeTrainMonitor`:** For **`SFTConfig`**, registration sends
dataset **`TrainingSpec`** (`max_steps`, `batch_size`, `seq_len`), empty
environments, and the resolved config dump. Docs clarify **best-effort**
finalize (SIGKILL/OOM may skip crash reporting).
> 
> **Concurrency:** Platform **`run.json`** writes use **PID-suffixed
temp files**, a **persistent flock lock** with bounded timeout,
**`update_platform_record` / `_merge_platform_record`**, and
**`asyncio.to_thread`** so eval + trainer don’t clobber each other’s
dashboard link. Lock/storage failures are **logged and skipped**, not
fatal.
> 
> New unit tests cover SFT registration, monitor fan-out, eval monitor
conversion, record merge/lock behavior.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bc33cb262d141c2d788acc5694aec85aea7b9ad4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-29 07:10:43 +02:00
Scott CabrinhaandGitHub 7027f65e5f fix(docker): pin the NIXL wheel build backend (#3720)
## Problem

Image builds on `main` have failed since #3667 merged. Every
`build_image.yaml` run since 2026-09-28 dies in the
`INCLUDE_NIXL_FROM_SOURCE` step, so no amd64/arm64 image is published.
The failing command is the step's own linkage check — the wheel builds
and installs fine:

```
ldd .../.nixl_cu13.mesonpy.libs/plugins/libplugin_UCX.so | grep -q /opt/ucx/lib/libucp.so
```

## Cause

The NIXL wheel build is not reproducible: NIXL's `[build-system]
requires` is an unpinned list, so pip's build isolation resolves the
newest backends at build time.

`meson-python 0.22.0` (uploaded 2026-09-26 08:33Z — after the
from-source images were built 09-25 01:53Z/02:11Z and validated on FFT,
before the first failing main build 09-28 02:35Z) added "support for
removing build RPATH entries added by Meson" plus RPATH/relocation
fixes. NIXL links UCX with bare `-L/opt/ucx/lib -lucp -lucs -luct` and
sets no `install_rpath`, so Meson's build-tree RPATH (the
`RUNPATH=/opt/ucx/lib` the step's comment and the FFT pods' runtime
check rely on) was the only thing making the installed libraries resolve
the image's UCX. 0.22.0 drops it, the check fails, and the registry
image would not resolve `/opt/ucx` at runtime either.

Evidence: identical step text passes on the 09-25 branch builds and
fails on every build from 09-28; the wheels differ by ~3 KB
(rpath/metadata, not content); `origin/main`'s step is unchanged, so the
failure persists.

## Fix

Constrain `meson-python==0.21.1` for the NIXL wheel via `pip wheel
--build-constraint` — the backend the from-source images were validated
with. Same pin in `scripts/install_nixl_from_source.sh`, whose SLURM
path builds the same wheel and drifts the same way.

Also make the linkage check diagnostic: it now prints `readelf -d`
RUNPATH and the `ldd` output before exiting, instead of `grep -q`
failing with no output (the failure above was silent).

## Notes

- Verified without a full image build: the step's shell, joined the way
Docker joins continuations, passes `sh -n` and `bash -n`; the check's
failure path prints diagnostics and exits 1; the skip path
(`INCLUDE_NIXL_FROM_SOURCE=0`) is unchanged.
- Verified with a real build: [run
36518545933](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/36518545933)
(amd64, `fix/nixl-build-constraints` @ 5e3cc4982) passed, image
`commit-5e3cc4982-amd64` pushed. The NIXL step ran
(`INCLUDE_NIXL_FROM_SOURCE=1`) and the linkage check passed; the wheel
is exactly the size of the wheels from the 2026-09-25 builds (3 467 198
bytes, vs 3 470 315 for the failing 0.22.0 build).
- The rest of NIXL's build-system set (`pybind11`, `patchelf`, `pyyaml`,
`build`, `setuptools`) stays unpinned; only the backend whose behaviour
broke is pinned. The constraint file is the lever if we want these
wheels fully reproducible.
- Durable alternative to the pin: set the RPATH explicitly at link time
(`-Wl,-rpath=/opt/ucx/lib` via Meson link args, or `patchelf
--add-rpath` on the installed libraries) so the artifact does not depend
on backend RPATH policy. Not included: it cannot be validated without a
full image build.
2026-09-28 22:47:13 -06:00
eligottsandGitHub d51d0bb84c Delegate prompt metadata to vLLM 0.30 (#3710) 2026-09-28 21:29:41 -07:00
112 changed files with 2455 additions and 1092 deletions
+15 -2
View File
@@ -144,6 +144,11 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
# (the PyPI wheel) first, so the fix would silently not apply. Libraries carry
# RUNPATH=/opt/ucx/lib, so no LD_LIBRARY_PATH is needed at runtime.
# Opt out via `--build-arg INCLUDE_NIXL_FROM_SOURCE=0`.
#
# NIXL's [build-system] requires are unpinned, so pip's build isolation picks up
# new backends as they are released. meson-python 0.22.0 stopped keeping Meson's
# build RPATH in wheel libraries, which dropped RUNPATH=/opt/ucx/lib and failed
# the linkage check below on every build. Pin the validated backend.
ARG INCLUDE_NIXL_FROM_SOURCE=1
ARG NIXL_VERSION=0.10.1
RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
@@ -151,11 +156,19 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
&& git clone --depth 1 --branch ${NIXL_VERSION} https://github.com/ai-dynamo/nixl.git /tmp/nixl \
&& cd /tmp/nixl \
&& uv run --no-project --with tomlkit python contrib/tomlutil.py --wheel-name nixl-cu13 pyproject.toml \
&& printf 'meson-python==0.21.1\n' > /tmp/nixl-build-constraints.txt \
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/tmp/nixl-whl \
--build-constraint /tmp/nixl-build-constraints.txt \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /tmp/nixl-whl/nixl_cu13-*.whl \
&& ldd /app/.venv/lib/python3.12/site-packages/.nixl_cu13.mesonpy.libs/plugins/libplugin_UCX.so | grep -q /opt/ucx/lib/libucp.so \
&& rm -rf /tmp/nixl /tmp/nixl-whl; \
&& PLUGIN=/app/.venv/lib/python3.12/site-packages/.nixl_cu13.mesonpy.libs/plugins/libplugin_UCX.so \
&& if ! ldd "$PLUGIN" | grep -q /opt/ucx/lib/libucp.so; then \
echo "ERROR: $PLUGIN does not link /opt/ucx/lib. RUNPATH and ldd output:" >&2; \
readelf -d "$PLUGIN" | grep -E 'RUNPATH|RPATH' >&2 || true; \
ldd "$PLUGIN" >&2; \
exit 1; \
fi \
&& rm -rf /tmp/nixl /tmp/nixl-whl /tmp/nixl-build-constraints.txt; \
fi
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
+1 -3
View File
@@ -53,15 +53,13 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
| 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 / 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 | ✅ |
| 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 | ✅ | ✅ |
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
| GLM-4 · GLM-4.5 MoE · INTELLECT-3 (`glm4_moe`) | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5-Air`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | yes | ✅ | ✅ |
| GPT-OSS (`gpt_oss`) | `unsloth/gpt-oss-20b-BF16`, … | yes | ✅ | ✅ |
| Other HF causal LMs | Qwen3 dense, Mistral, … (`impl = "hf"`) | varies | ❌ | ✅ |
## Setup
+5 -3
View File
@@ -63,17 +63,19 @@ type = "adamw"
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 32
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
initial_inflight = 1536
max_inflight = 1536
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
+2
View File
@@ -27,6 +27,8 @@ lr = 1e-5
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 8
[orchestrator.train.sampling]
+3 -1
View File
@@ -16,9 +16,11 @@ name = "hendrycks-sanity"
[orchestrator]
batch_size = 128
group_size = 8
seq_len = 8192
[orchestrator.train]
group_size = 8
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset.id = "math-env"
+2
View File
@@ -17,6 +17,8 @@ name = "reverse-text"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.train.sampling]
+2
View File
@@ -35,6 +35,8 @@ target_modules = [
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.train.sampling]
+2
View File
@@ -19,6 +19,8 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 8
[[orchestrator.train.source]]
@@ -17,6 +17,8 @@ lr = 1e-5
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
@@ -17,6 +17,8 @@ rank = 8
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
@@ -14,6 +14,8 @@ rank = 8
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
@@ -20,6 +20,8 @@ impl = "custom"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
@@ -22,15 +22,17 @@ name = "ci-rl-opd"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.algo]
[orchestrator.train.algo]
type = "opd"
[orchestrator.algo.teacher]
[orchestrator.train.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
@@ -22,16 +22,18 @@ name = "ci-rl-sft"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.algo]
[orchestrator.train.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
[orchestrator.train.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
@@ -20,6 +20,8 @@ lr = 3e-6
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
@@ -17,6 +17,8 @@ lr = 3e-6
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
@@ -16,6 +16,8 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
+3 -1
View File
@@ -15,9 +15,11 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
group_size = 8
seq_len = 8192
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
max_inflight = 128
+2
View File
@@ -16,6 +16,8 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
+2
View File
@@ -16,6 +16,8 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
+2
View File
@@ -16,6 +16,8 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 512
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
@@ -15,6 +15,8 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
+1 -1
View File
@@ -16,7 +16,7 @@ Minimal end-to-end configs for the algorithms against bundled verifiers envs, us
The policy inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local frozen model (used by `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed_grpo_opd.toml`) is **not** auto-launched — start it manually on GPU 1.
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for `opd`, `[orchestrator.algo.sampling.source]` for `sft` — with `name` + `base_url`. `opsd` declares none (it self-distills against the live policy). prime-rl never hosts them; only the trainable policy's server is managed by the `rl` entrypoint.
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.train.algo.teacher]` for `opd`, `[orchestrator.train.algo.sampling.source]` for `sft` — with `name` + `base_url`. `opsd` declares none (it self-distills against the live policy). prime-rl never hosts them; only the trainable policy's server is managed by the `rl` entrypoint.
## Start the local frozen model
+4 -2
View File
@@ -14,14 +14,16 @@ name = "debug-echo"
[orchestrator]
batch_size = 32
[orchestrator.train]
group_size = 4
# alphabet-sort's feedback arrives as user messages, so train the user role
# instead of echo's tool default.
[orchestrator.algo]
[orchestrator.train.algo]
type = "echo"
[orchestrator.algo.roles.user]
[orchestrator.train.algo.roles.user]
alpha = 0.1
[[orchestrator.train.source]]
+3 -1
View File
@@ -10,9 +10,11 @@ name = "debug-rl"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[orchestrator.renderer]
+3 -1
View File
@@ -10,9 +10,11 @@ name = "debug-max-rl"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.algo]
[orchestrator.train.algo]
type = "max_rl"
[orchestrator.renderer]
+3 -1
View File
@@ -20,9 +20,11 @@ name = "debug-mixed-grpo-opd"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[orchestrator.renderer]
+4 -2
View File
@@ -17,12 +17,14 @@ name = "debug-opd"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.algo]
[orchestrator.train.algo]
type = "opd"
[orchestrator.algo.teacher]
[orchestrator.train.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
+4 -2
View File
@@ -17,12 +17,14 @@ name = "debug-opd-lora"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.algo]
[orchestrator.train.algo]
type = "opd"
[orchestrator.algo.teacher]
[orchestrator.train.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
+3 -1
View File
@@ -10,9 +10,11 @@ name = "debug-rae"
[orchestrator]
batch_size = 32
[orchestrator.train]
group_size = 1
[orchestrator.algo]
[orchestrator.train.algo]
type = "rae"
[orchestrator.renderer]
+3 -1
View File
@@ -16,10 +16,12 @@ name = "debug-self-distill"
[orchestrator]
batch_size = 32
[orchestrator.train]
group_size = 1
# reverse-text's demo lives in the "answer" column.
[orchestrator.algo]
[orchestrator.train.algo]
type = "opsd"
demo_key = "answer"
+4 -2
View File
@@ -17,13 +17,15 @@ name = "debug-sft"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 4
[orchestrator.algo]
[orchestrator.train.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
[orchestrator.train.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
+4 -2
View File
@@ -17,13 +17,15 @@ name = "debug-sft-lora"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 4
[orchestrator.algo]
[orchestrator.train.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
[orchestrator.train.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
+5 -3
View File
@@ -88,13 +88,15 @@ type = "sign_sgd"
[orchestrator]
batch_size = 128
group_size = 8
max_off_policy_steps = 32
[orchestrator.algo]
[orchestrator.train]
group_size = 8
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
+4 -2
View File
@@ -9,5 +9,7 @@ group_size = 4
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
env.agent.retries.max_retries = 2
env.agent.retries.include = ["ProviderError", "SandboxError"]
env.agent.retries.rules = [
{type = "ProviderError", max_retries = 2},
{type = "SandboxError", max_retries = 2},
]
+2
View File
@@ -9,6 +9,8 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.renderer]
+1 -1
+1 -1
+21 -3
View File
@@ -28,7 +28,7 @@ impl = "custom" # or "hf" to force the HF path
| 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 / 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`, … | ✅ | ❌ |
@@ -49,12 +49,30 @@ Dense linear precision and routed-expert precision are configured independently.
- `type = "fp8"` — DeepGEMM FP8 blockwise linears (requires SM90+).
- `type = "mxfp8"` — torchao MXFP8 linears (requires SM100). `recipe` is `mxfp8_rceil` or `mxfp8_rceil_wgrad_with_hp`.
`[trainer.model.moe.compute]` selects routed-expert grouped GEMMs independently:
`[trainer.model.moe.compute]` selects routed-expert compute independently:
- `type = "bf16"` (default)
- `type = "bf16"` (default), with `backend = "torch"` (default) or `"sonicmoe"`.
- `type = "deepgemm_fp8"` (requires DeepGEMM and SM90+)
- `type = "mxfp8"` (requires `prime-kernels`, torchao, and SM100)
SonicMoE uses the upstream `sonic-moe` package (`uv sync --extra sonic-moe`) for fused BF16 expert computation. The supported model is Qwen3 MoE with the `gate_up` model fusion enabled. Backend selection requires fused gate/up weights, standard SwiGLU, and bias-free experts; incompatible expert structures raise an error during setup. It uses the same router and local, torch EP, or DeepEP dispatch as other compute backends:
```toml
[trainer.model]
name = "Qwen/Qwen3-30B-A3B"
ep = 2
[trainer.model.fusions]
enabled = ["gate_up"]
[trainer.model.moe.compute]
type = "bf16"
backend = "sonicmoe"
[trainer.model.moe.dispatch]
type = "torch"
```
```toml
[trainer.model.quantization]
type = "mxfp8"
+24 -22
View File
@@ -30,7 +30,7 @@ This page covers the math and the configurable algorithmic components: the algor
## The Algorithm Abstraction
A training algorithm in `prime-rl` is configured under `[orchestrator.algo]`, where **`type` names the algorithm** (`grpo`, `opd`, `sft`, …) and the class defaults are its vetted setting. It has two parts:
A training algorithm in `prime-rl` is configured under `[orchestrator.train.algo]`, where **`type` names the algorithm** (`grpo`, `opd`, `sft`, …) and the class defaults are its vetted setting. It has two parts:
1. **Sampling** (`algo.sampling`) — how train rollouts are produced: which model generates them. `source` is a [model reference](#model-references): `"policy"` (the live policy, the default) or an inline frozen hosted model. Group sizing stays on the env config (`group_size`).
2. **The per-token training signal** — credit assignment and loss routing, fused; the algorithm's own parameters sit directly on `algo`. One mapping from a finalized rollout to per-token *(loss component, weight)* pairs — the credit a token gets and the loss that consumes it are two coordinates of the same output. Group-relative algorithms compute credit on the orchestrator and ship per-token advantage streams; reference-KL algorithms query a reference model at batch-ship time (bounded concurrency) and ship its prefill logprobs for the trainer to evaluate against the live policy. The `type` determines which loss component consumes the action tokens (`rl` / `ce` / `ref_kl`) and what happens to env-provided observation tokens in multi-turn rollouts (masked out by default; `echo` trains on them with weighted CE).
@@ -42,17 +42,17 @@ The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, r
`prime-rl` hosts exactly one model: the trainable policy (`[orchestrator.model]`). Every other model an algorithm uses is an external OpenAI-compatible endpoint, declared *inline on the component that uses it*. A model reference is either the string `"policy"` (the live policy) or a frozen hosted model (`name` + `base_url`):
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "opd"
[orchestrator.algo.teacher] # opd's teacher: the frozen model it scores against
[orchestrator.train.algo.teacher] # opd's teacher: the frozen model it scores against
name = "Qwen/Qwen3-32B"
base_url = "http://localhost:8001/v1"
```
Model *roles* are algorithm-local vocabulary — each algorithm names its reference on the field where the model is actually used, and there is no shared `teacher` slot. `opd` declares a `teacher` field (the frozen model whose reverse KL the policy distills toward); `sft`'s teacher *is* its `sampling.source` (the frozen model it imitates); `opsd` self-distills against the live policy and names no model at all. No role exists outside the algorithm that declares it: the dispatcher, sink, and trainer branch on liveness alone, never on what an algorithm calls a model.
So for `opd` set `[orchestrator.algo.teacher]`; for `sft` set `[orchestrator.algo.sampling.source]`; `opsd` needs neither. `opd`'s teacher must be a frozen endpoint — it is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero); `opsd`'s teacher *is* the live policy by definition (self-distillation conditioned on a demonstration), so it exposes no reference to configure.
So for `opd` set `[orchestrator.train.algo.teacher]`; for `sft` set `[orchestrator.train.algo.sampling.source]`; `opsd` needs neither. `opd`'s teacher must be a frozen endpoint — it is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero); `opsd`'s teacher *is* the live policy by definition (self-distillation conditioned on a demonstration), so it exposes no reference to configure.
Liveness is a property of the reference, not of any role: rollouts sampled from `"policy"` get version-salted prefix caches, carry sampling logprobs for importance ratios, and age off-policy as weights update; rollouts and scores from frozen models get a stable prefix cache and never go stale. Frozen models are externally hosted (`base_url` is required) — `prime-rl` never launches or updates them, and each env's algorithm builds its own client pool to the endpoints it declares.
@@ -61,7 +61,7 @@ Liveness is a property of the reference, not of any role: rollouts sampled from
The `algo.type` names the algorithm, and each type's class defaults are its vetted setting — picking a type with no other keys IS the algorithm:
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo" # the default
```
@@ -83,13 +83,13 @@ Every key beyond `type` is visibly your own assembly — there is no preset laye
```toml
# echo on tool AND user feedback tokens, each at its own weight.
# Setting any role replaces the whole table.
[orchestrator.algo]
[orchestrator.train.algo]
type = "echo"
[orchestrator.algo.roles.tool]
[orchestrator.train.algo.roles.tool]
alpha = 0.25
[orchestrator.algo.roles.user]
[orchestrator.train.algo.roles.user]
alpha = 0.05
```
@@ -98,10 +98,10 @@ A new algorithm is a named class in code, not a config that points at an import
Echo also takes an optional user-supplied token filter that narrows the role selection per rollout — e.g. dropping warning lines from tool output, or tokens the sampler found unlikely:
```toml
[orchestrator.algo.filter]
[orchestrator.train.algo.filter]
import_path = "my_module.drop_warnings"
[orchestrator.algo.filter.kwargs]
[orchestrator.train.algo.filter.kwargs]
patterns = ["WARNING"]
```
@@ -116,14 +116,14 @@ Component compatibility is validated at config time: frozen-model sampling can o
### Per-Env Algorithms
Both components resolve per environment. Each env inherits `[orchestrator.algo]` unless it sets its own, so a single run can mix algorithms across envs — e.g. GRPO on math, ECHO on a terminal env:
Both components resolve per environment. Each env inherits `[orchestrator.train.algo]` like any other group default: an env that sets only some params keeps the group's algorithm with those params changed, and an env that sets a different `type` runs its own algorithm. So a single run can mix algorithms across envs — e.g. GRPO on math, ECHO on a terminal env:
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[[orchestrator.train.source]]
name = "math" # inherits the top-level grpo
name = "math" # inherits the group's grpo
env.taskset.id = "math"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
@@ -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.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 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:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
@@ -159,7 +159,7 @@ Algorithms operate on native verifier artifacts and annotate their message graph
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.
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.algo.advantage`.
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`.
## Async / Off-Policy Training
@@ -323,10 +323,10 @@ This is intentionally simple — it does the right thing for most envs. Write a
A **length penalty** (`length_penalty` on the `grpo`-family algorithms) can be layered on top to discourage rambling. The `linear` penalty subtracts a single `pass_rate`-scaled penalty from each reward before the GRPO baseline, combining output tokens (`num_output_tokens_weight`), input / context tokens (`num_input_tokens_weight`), and turns (`num_turns_weight`) — each normalized by the group's own max for that quantity, with `num_input_tokens_weight` and `num_turns_weight` defaulting to `0.1`.
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
```
@@ -362,7 +362,7 @@ For example, if three solvers receive rewards `[1, 1, 0]` on one proposed proble
Configure which roles are compared within a single proposed problem with `episode_agents`. For `proposer-solver`, that role is `solver`:
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "hierarchical_grpo"
episode_agents = ["solver"]
@@ -388,7 +388,7 @@ Group-relative baselines assume the group is exchangeable attempts by one agent.
`rae` implements SPIRAL's role-conditioned advantage estimation ([arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): each agent keeps an exponential-moving-average baseline of its own rewards, and every trace's advantage is its reward minus its agent's baseline — measured against the *pre-update* baseline (the unbiased order), then folded in at `decay` (SPIRAL's α, default 0.95). The algorithm instance is per-env, so baselines are keyed per (env, agent) — the paper's per (game, role). Advantages are not normalized, and `group_size` is free (RAE needs no sibling rollouts; `group_size = 1` is fine). Baselines live in orchestrator memory and re-warm from 0 over ~`1/(1 − decay)` traces per agent after a restart.
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "rae"
decay = 0.95
@@ -411,8 +411,8 @@ There is no config hook that points at user code — a new credit-assignment sch
# src/prime_rl/orchestrator/algo/my_algo.py
import torch
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.orchestrator.algo.routing import assign_advantages
from prime_rl.orchestrator.train.algo.base import Algorithm
from prime_rl.orchestrator.train.algo.routing import assign_advantages
class MyAlgorithm(Algorithm):
@@ -436,7 +436,7 @@ Curriculum admission and metrics can inspect the resulting graph-native streams
- `opsd` — SDFT: prepend an expert demonstration as a leading system message (`template`, with a `{demonstration}` placeholder) and score the sample under that demo-conditioned context. The sample is scored verbatim (`hint_block + token_ids`, slicing the hint's logprobs back off), so the join is BPE-clean and it's robust to tool/multimodal prompts and any number of turns. The scoring reference *is* the live policy — self-distillation names no teacher. opsd builds its own renderer to tokenize the hint block: the tokenizer is always the live policy's (not configurable — there is no separate model), and only the `renderer` family is settable (defaults to `"auto"`, resolved from the policy tokenizer; set it to match a non-auto policy renderer). The demonstration is read from the example's `info[demo_key]`, falling back to a top-level rollout field of the same name (e.g. `answer`).
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type = "opsd"
demo_key = "demonstration"
```
@@ -549,6 +549,8 @@ Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `glm-5`, `glm-4.5`
name = "auto" # detect from tokenizer; pass an explicit name for fine-tunes
```
A renderer outside the `renderers` package loads as a custom renderer: `name = "custom"` with `import_path = "my_module.Class"` (or `path/to/file.py:Class`), see [Custom renderers](training.md#dataset-format).
For the full design rationale (failure modes ruled out, empirical token-identity comparison against `apply_chat_template`, when to write a hand-coded renderer), see [the renderers writeup on the Prime Intellect blog](https://www.primeintellect.ai/blog/renderers) — the canonical reference.
### Discontinuous Trajectories
+19 -9
View File
@@ -171,23 +171,33 @@ env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — takes an `env` block that each of its sources inherits. A source's own `env` values win. The block holds only the knobs that every env and taskset has: `retries`, `timeout`, `max_concurrent_agents`, `interception`, and `taskset.task` and `taskset.system_prompt`. Ids and agents stay on each source:
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — holds defaults for its sources. Every field that a group and its sources both have is a default: `env`, `sampling`, `select` and `group_size`, plus `algo` on the train group and `interval` on the eval groups of a training run. Each source inherits the fields that its group sets. One rule applies to all of them: nested blocks merge key by key, a source's own values win, and a block whose `type` (e.g. of `algo`) differs from the group's is the source's alone.
```toml
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
type = "grpo"
[[orchestrator.train.source]]
env.taskset.id = "math"
group_size = 32 # this source's own value wins over the group's 16
[orchestrator.eval.env]
retries.max_retries = 3
retries.include = ["ProviderError", "SandboxError"]
retries.rules = [
{type = "ProviderError", max_retries = 3},
{type = "SandboxError", max_retries = 3},
]
timeout.episode = 7200
```
Each source also takes a `select` block that picks which tasks of its taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit`, in that order. A group's `select` block works like its `env` block: every source inherits it field by field, and a source's own fields win. A source's `include` or `exclude` replaces the group's whole block. To evaluate 128 tasks of each taskset:
```toml
[orchestrator.eval.select]
[orchestrator.eval.select] # evaluate 128 tasks of each taskset
limit = 128
```
`ratio` is a training-source field: it defaults to `1` (equal weight per env), and values are relative weights normalized to probabilities across envs. Eval sources of a training run carry `interval` instead, the step interval at which they fire (inherited from the group-level `interval` when unset); a standalone eval has neither.
The group `env` block holds only the knobs that every env and taskset has: `retries`, `timeout`, `max_concurrent_agents`, `interception`, and `taskset.task` and `taskset.system_prompt`. Ids and agents stay on each source. `select` picks which tasks of a source's taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit`, in that order.
`ratio` is a training-source field: it defaults to `1` (equal weight per env), and values are relative weights normalized to probabilities across envs. Eval sources of a training run carry `interval` instead, the step interval at which they fire; a standalone eval has neither.
Everything environment lives under the `env` block (verifiers' `[env]` shape): `env.taskset` configures the v1 taskset, and each agent is a field on the env — `env.agent.harness` selects how the single-agent env's tasks are run, and per-run caps are per-agent (`env.agent.max_turns`, `env.agent.timeout`, `env.agent.max_output_tokens`). A multi-agent env declares its own seats (`env.<role>.*`).
+1 -1
View File
@@ -94,7 +94,7 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
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` 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 <= 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
`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:
```toml
[trainer.model]
+37 -9
View File
@@ -59,9 +59,9 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|---|---|
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.constant_trainer_batch_size` | Keep trainer batches constant when samples have no training signal, such as zero advantage on all tokens. Enabled by default. Disable it for faster collection with variable trainer batch sizes. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `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.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[orchestrator.train.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[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). |
@@ -86,7 +86,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
### Algorithms
The RL entrypoint supports several training algorithms, switched via `[orchestrator.algo]`'s `type` (see [Algorithms](algorithms.md#the-algorithm-abstraction) for the full reference, model references, and per-algorithm customization):
The RL entrypoint supports several training algorithms, switched via `[orchestrator.train.algo]`'s `type` (see [Algorithms](algorithms.md#the-algorithm-abstraction) for the full reference, model references, and per-algorithm customization):
| `algo.type` | Frozen model | Use case |
|---|---|---|
@@ -101,7 +101,7 @@ The RL entrypoint supports several training algorithms, switched via `[orchestra
A new algorithm is a named class in code, not a config — see [Algorithms § Authoring an Algorithm](algorithms.md#authoring-an-algorithm).
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for `opd` (the frozen model scored against), `[orchestrator.algo.sampling.source]` for `sft` (the model it samples from) — each with `name` + `base_url`. `opsd` declares no frozen model: it self-distills against the live policy. The `rl` entrypoint only manages policy inference — start frozen-model servers yourself and point `base_url` at them:
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.train.algo.teacher]` for `opd` (the frozen model scored against), `[orchestrator.train.algo.sampling.source]` for `sft` (the model it samples from) — each with `name` + `base_url`. `opsd` declares no frozen model: it self-distills against the live policy. The `rl` entrypoint only manages policy inference — start frozen-model servers yourself and point `base_url` at them:
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
@@ -150,9 +150,15 @@ Two accepted layouts:
- **Prompt-completion**: a HF dataset with `prompt` and `completion` columns ([TRL format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion)). The trainer masks out the prompt and computes loss only over the completion.
- **Messages**: a HF dataset with a single `messages` column containing a list of chat turns. The trainer interprets the whole conversation as one sample, applies role-based loss masking, and trains over all assistant turns.
If both columns are present, `messages` takes precedence.
If both columns are present, `messages` takes precedence. A dataset that stores these under other names maps them in `[data.columns]`; the trainer renames the columns at load time:
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column (OpenAI function-calling format) or `tool_defs` ([`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) rollout format). Each row's value can be either a list of dicts or a JSON-encoded string of a list — both are accepted, and `tool_defs` rows are auto-converted to OAI shape before being passed into the renderer.
```toml
[data.columns]
messages = "conversation"
tools = "schemas"
```
**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:
@@ -162,10 +168,27 @@ name = "qwen3"
enable_thinking = false
```
A `reasoning_effort` column in the dataset sets the renderer's `reasoning_effort` field per row, on top of the `[renderer]` config. The column requires a typed renderer that has that field (for example `gpt-oss`, `qwen3.8`, `deepseek-v4`); rows with a null value use the configured renderer unchanged. This lets one run mix reasoning efforts, with the `[renderer]` value as the default for rows that do not set one.
Dataset columns can set renderer template controls per row, on top of the `[renderer]` config. `[data.columns.renderer]` maps renderer fields to columns and defaults to `reasoning_effort = "reasoning_effort"`, so a `reasoning_effort` column sets that field on renderers that have it (for example `gpt-oss`, `qwen3.8`, `deepseek-v4`). Rows with a null value use the configured renderer unchanged. This lets one run mix reasoning efforts, with the `[renderer]` value as the default for rows that do not set one:
```toml
# The renderer field is reasoning_effort; this dataset stores it in an effort column.
[data.columns.renderer]
reasoning_effort = "effort"
```
If a model needs another template control, add it to that model's renderer config in `renderers` (for example a new field on the relevant `*RendererConfig`) and consume it in the renderer implementation.
**Custom renderers.** A renderer can also live outside the `renderers` package. Set `name = "custom"` and point `import_path` at the class, as `my_module.Class` or `path/to/file.py:Class`; relative file paths resolve against the launch directory. The class sets `config_class` to its own `BaseRendererConfig` subclass, which validates the remaining `[renderer]` keys and declares its template controls:
```toml
[renderer]
name = "custom"
import_path = "my_renderers.glm53_no_thinking.NoThinkingGLM53Renderer"
clear_thinking = true
```
The same config selects the renderer for RL under `[orchestrator.renderer]`. The [`renderers` README](https://github.com/PrimeIntellect-ai/renderers#custom-renderers) shows the class behind this example.
**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).
@@ -182,6 +205,8 @@ uv run sft @ examples/basic/reverse-text/sft.toml --monitors.wandb
Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manages this for you — see [Scaling § SFT and Torchrun](scaling.md#sft-and-torchrun) for non-default layouts; multi-node SFT goes through [SLURM](scaling.md#slurm)).
`--monitors.prime` streams the run to the Prime Intellect platform — see [Platform Monitoring](#platform-monitoring).
### Online Evals
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `select` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
@@ -383,6 +408,7 @@ Register a run on the Prime Intellect platform (Prime Lab) and stream training m
```bash
uv run rl @ rl.toml --monitors.prime
uv run sft @ sft.toml --monitors.prime # same flag on the SFT trainer
```
Or set it in TOML:
@@ -392,7 +418,9 @@ Or set it in TOML:
name = "my-experiment"
```
The monitor is a thin layer over the [`prime-runs`](https://github.com/PrimeIntellect-ai/prime/tree/main/packages/prime-runs) SDK (installed as `prime-runs[train]`): it registers the run, streams per-step metrics, uploads every 10th step's episodes (full conversations with rewards and advantages) to the run's sample viewer, and closes the run out. A process that exits without finishing is reported as crashed. Uploaded episodes are keyed to the platform run by the SDK; the orchestrator's own run id (the launcher's `PRL_RUN_ID`) stays on W&B and in the local records.
The monitor is a thin layer over the [`prime-runs`](https://github.com/PrimeIntellect-ai/prime/tree/main/packages/prime-runs) SDK (installed as `prime-runs[train]`): it registers the run, streams per-step metrics, uploads every 10th step's episodes (full conversations with rewards and advantages) to the run's sample viewer, and closes the run out. Finalization is best-effort SDK delivery: a process that exits without finishing is reported crashed when the SDK's atexit hook runs, but an abrupt kill (SIGKILL, OOM, node loss) skips the report and a lost finalize is not retried — the platform owns the terminal state of attached (`RUN_ID`) and managed runs. Uploaded episodes are keyed to the platform run by the SDK; the orchestrator's own run id (the launcher's `PRL_RUN_ID`) stays on W&B and in the local records.
On `sft` the monitor registers the run with the dataset-batched training fields (`max_steps`, `batch_size`, `seq_len`) and streams the trainer's per-step metrics and validation losses; SFT has no rollouts, so no episodes are uploaded.
Requires `PRIME_API_KEY` (`prime login` or the env var) and a team (`PRIME_TEAM_ID`, or the team selected with `prime login`) enabled for external runs. A configured monitor must work: a missing key or a team outside the allowlist fails the launch. `PRIME_RUNS_MODE=disabled` keeps the monitor configured but opens no platform run; `RUN_ID=<id>` attaches to an external run a launcher already created instead of registering a new one. Currently internal-only.
@@ -400,6 +428,6 @@ Requires `PRIME_API_KEY` (`prime login` or the env var) and a team (`PRIME_TEAM_
- **Start small.** Run `examples/basic/reverse-text/rl.toml` end-to-end on 2 GPUs before scaling. If the smoke run finishes cleanly, your install is good.
- **Batch size ≥ 64.** Smaller batches give noisy gradient estimates and the trainer's overhead-per-step dominates throughput. 64 is the practical floor; 128–512 is the range for quick ablations; production RL often runs at 1024+.
- **Group size ≥ 8.** Bigger groups (`orchestrator.group_size`) make it more likely that a task produces a mix of high- and low-reward rollouts, which is what gives the trainer a usable signal — if all rollouts in a group succeed or all fail, the within-group advantage collapses to zero and the trainer learns nothing from that task. Bigger groups also tighten advantage normalization. 8 is the floor; 16–32 is common.
- **Group size ≥ 8.** Bigger groups (`orchestrator.train.group_size`) make it more likely that a task produces a mix of high- and low-reward rollouts, which is what gives the trainer a usable signal — if all rollouts in a group succeed or all fail, the within-group advantage collapses to zero and the trainer learns nothing from that task. Bigger groups also tighten advantage normalization. 8 is the floor; 16–32 is common.
- **Runs never share a directory.** Every launch writes to its own run directory `<output_dir>/<run_name>`, auto-named `<envs>--<model>--<short-id>` by default. Name runs you want to find again or resume with `--run.name <name>`; re-using a name blocks unless you resume or pass `--clean`.
- **Use `--dry-run` before SLURM.** Validators (e.g. CP needs flash-attention) fail fast in dry-run and slow in queue.
+5 -3
View File
@@ -68,9 +68,11 @@ type = "muon"
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 32
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
initial_inflight = 256
max_inflight = 512
@@ -79,10 +81,10 @@ max_inflight = 512
name = "glm-4.5"
thinking_retention = "all"
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
@@ -83,13 +83,15 @@ type = "sign_sgd"
# --- Orchestrator ---
[orchestrator]
group_size = 16
max_off_policy_steps = 32
[orchestrator.algo]
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
+5 -3
View File
@@ -79,13 +79,15 @@ type = "muon"
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 32
[orchestrator.algo]
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
+5 -3
View File
@@ -69,9 +69,11 @@ type = "muon"
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 32
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
initial_inflight = 256
max_inflight = 512
@@ -80,10 +82,10 @@ max_inflight = 512
name = "glm-4.5"
thinking_retention = "all"
[orchestrator.algo]
[orchestrator.train.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
@@ -24,6 +24,9 @@ decode_nodes_per_replica = 8
num_decode_replicas = 1
[deployment.prefill_env_vars]
# vLLM >= 0.29 auto-enables breakable CUDA graphs for GLM-5 (GlmMoeDsaForCausalLM); capturing
# the DeepEP high-throughput prefill dispatch then fails ("DeepEP error: timeout (dispatch CPU)").
"VLLM_USE_BREAKABLE_CUDAGRAPH" = "0"
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
+5
View File
@@ -6,6 +6,11 @@ prefill_nodes_per_replica = 4
decode_nodes_per_replica = 2
gpus_per_node = 8
[deployment.prefill_env_vars]
# vLLM >= 0.29 auto-enables breakable CUDA graphs for GLM-5 (GlmMoeDsaForCausalLM); capturing
# the DeepEP high-throughput prefill dispatch then fails ("DeepEP error: timeout (dispatch CPU)").
"VLLM_USE_BREAKABLE_CUDAGRAPH" = "0"
[slurm]
job_name = "glm5"
partition = "cluster"
+6 -1
View File
@@ -41,6 +41,9 @@ num_decode_replicas = 1
# skip warmup for faster start in cost of some jit overhead early
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
[inference.deployment.prefill_env_vars]
# vLLM >= 0.29 auto-enables breakable CUDA graphs for GLM-5 (GlmMoeDsaForCausalLM); capturing
# the DeepEP high-throughput prefill dispatch then fails ("DeepEP error: timeout (dispatch CPU)").
"VLLM_USE_BREAKABLE_CUDAGRAPH" = "0"
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
@@ -109,9 +112,11 @@ weight_decay = 0.0
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
initial_inflight = 256
max_inflight = 512
+2
View File
@@ -45,6 +45,8 @@ weight_decay = 0.01
[orchestrator]
batch_size = 2048
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
+18
View File
@@ -7,6 +7,7 @@ RL on the 30B-A3B MoE across three domains: math, SWE, and agentic tool use. The
| [`math.toml`](math.toml) | `i3_math` | `aime2025` (every 25 steps) | `subprocess` — runs locally, no sandbox | 2 train + 2 infer nodes |
| [`swe.toml`](swe.toml) | `r2e-gym` (`bash` harness) | `swebench-verified` (every 25 steps) | sandbox (Prime Intellect by default) | 2 train + 2 infer nodes |
| [`tool.toml`](tool.toml) | `general-agent` (colocated tools) | — | `modal` | 1 train + 1 infer node |
| [`sft/h200/`](sft/h200) | SFT on `PrimeIntellect/INTELLECT-3-SFT-10K` (math) | — | — | 2 train nodes |
`tool.toml` is the odd one out: 400 steps, `group_size = 16`, checkpoints every 50 steps with `keep_last = 1`, and inference at `dp = 2` / `tp = 4`. `math.toml` and `swe.toml` run 512-task batches with checkpoints every 100 steps.
@@ -105,3 +106,20 @@ uv run python tools/convert_dcp_to_bf16.py /shared/outputs/qwen30b/qwen30b-math/
```
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
## SFT
The SFT configs live under [`sft/h200/`](sft/h200). They are tuned for two 8-GPU H200 nodes and train only (no inference nodes). Combine the base config with a data overlay:
```bash
uv run sft @ examples/advanced/qwen3-30b-a3b/sft/h200/base.toml @ examples/advanced/qwen3-30b-a3b/sft/h200/math-10k.toml \
--output-dir /shared/outputs/qwen30b \
--run.name qwen30b-sft-math
```
This starts an SFT run with the following setup:
- The model is `Qwen/Qwen3-30B-A3B-Instruct-2507`, trained with the custom MoE implementation, expert parallelism (`ep = 8`), full activation checkpointing with offloading, and AdamW.
- The data is `PrimeIntellect/INTELLECT-3-SFT-10K` (math split), at a 32k sequence length with a batch of 16 samples per step.
For a fake-data dry run, add [`fake.toml`](sft/h200/fake.toml) instead of the data overlay. `base.toml` sets `[slurm] partition = "all"` and `HF_HOME = "/home/huggingface"`. Change both to match your cluster. For longer contexts, raise `data.seq_len` and set `model.cp` to split each sequence across GPUs. You can monitor the SFT run with the same dashboard.
+3 -1
View File
@@ -42,9 +42,11 @@ lr = 1e-6
[orchestrator]
batch_size = 512
group_size = 8
max_off_policy_steps = 8
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
initial_inflight = 1024
@@ -0,0 +1,35 @@
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
[model.ac]
freq = 1
[model.ac_offloading]
max_inflight_activations = 5
[optim]
type = "adamw"
lr = 1e-5
weight_decay = 0.01
[scheduler]
type = "linear"
warmup_steps = 50
decay_steps = 0
[deployment]
type = "multi_node"
num_train_nodes = 2
[slurm]
job_name = "qwen30b-sft"
partition = "all"
@@ -0,0 +1,8 @@
[model.debug]
force_balanced_routing = true
[data]
type = "fake"
batch_size = 16
micro_batch_size = 1
seq_len = 32768
@@ -0,0 +1,7 @@
[data]
type = "sft"
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
splits = ["math"]
batch_size = 16
micro_batch_size = 1
seq_len = 32768
+3 -1
View File
@@ -43,9 +43,11 @@ lr = 1e-6
[orchestrator]
batch_size = 512
group_size = 8
max_off_policy_steps = 16
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
initial_inflight = 1024
+3 -1
View File
@@ -32,9 +32,11 @@ freq = 1
[orchestrator]
batch_size = 512
group_size = 16
max_off_policy_steps = 32
[orchestrator.train]
group_size = 16
[[orchestrator.train.source]]
env.taskset.id = "general-agent"
env.taskset.min_tier = 1
+2
View File
@@ -26,6 +26,8 @@ lr = 1e-5
[orchestrator]
batch_size = 256
[orchestrator.train]
group_size = 16
[orchestrator.train.sampling]
+3 -1
View File
@@ -13,9 +13,11 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
group_size = 8
seq_len = 8192
[orchestrator.train]
group_size = 8
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset.id = "math-env"
+2
View File
@@ -10,6 +10,8 @@ name = "reverse-text"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.train.sampling]
+2
View File
@@ -31,6 +31,8 @@ target_modules = [
[orchestrator]
batch_size = 512
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
+2
View File
@@ -16,6 +16,8 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 512
[orchestrator.train]
group_size = 16
[[orchestrator.train.source]]
+2
View File
@@ -13,6 +13,8 @@ num_infer_gpus = 1
[orchestrator]
batch_size = 32
[orchestrator.train]
group_size = 8
[orchestrator.train.sampling]
+3 -1
View File
@@ -1,7 +1,6 @@
max_steps = 20
seq_len = 2048
batch_size = 128
group_size = 16
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -10,6 +9,9 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
project = "reverse-text"
name = "reverse-text"
[train]
group_size = 16
[train.sampling]
max_completion_tokens = 128
+1 -1
View File
@@ -10,7 +10,7 @@ dependencies = [
"renderers>=0.1.11",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.3.2.dev152",
"verifiers>=0.3.2.dev158",
]
[build-system]
@@ -4,7 +4,7 @@ from pathlib import Path
import verifiers.v1 as vf
from pydantic import AliasChoices, Field, model_validator
from prime_rl.configs.monitors import EvalMonitorsConfig, MonitorsConfig
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
@@ -28,11 +28,12 @@ class ServedEvalConfig(EvalSourcesConfig):
rate limiting."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat for the run: one ping per landed episode — the first
"""BetterStack heartbeat for the run: pinged by landed episodes — the first
landed episode is the first beat, so the run's boot never shows up as a
stale-prone silence. When episodes stop landing, the pings stop and the heartbeat
goes stale on Better Stack after its grace period. Size that period + grace above
the longest legitimate gap between episodes."""
stale-prone silence. Pings are throttled to at most one every
``heartbeat.min_interval`` seconds. When episodes stop landing, the pings stop
and the heartbeat goes stale on Better Stack after its grace period. Size that
period + grace above the longest legitimate gap between episodes."""
@property
def env_addresses(self) -> dict[tuple[str, str], str | None]:
@@ -157,8 +158,14 @@ class SFTOnlineEvalConfig(ScheduledEvalConfig, ServedEvalConfig):
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
monitors: EvalMonitorsConfig = EvalMonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``).
``EvalMonitorsConfig``, not the base ``MonitorsConfig``: the launcher
converts the trainer's ``[monitors.prime]`` into a
``PrimeEvalMonitorConfig`` for the online-eval process, and the base
type would drop (or forbid) the prime block at the eval.json
dump/re-parse boundary."""
@model_validator(mode="after")
def auto_setup_broadcasts_dir(self):
@@ -1,9 +1,10 @@
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from typing import Annotated, Any, Literal, TypeAlias, get_args
import verifiers.v1 as vf
from pydantic import Field, SerializeAsAny, ValidationError, model_validator
from pydantic import AliasChoices, BaseModel, Field, SerializeAsAny, TypeAdapter, ValidationError, model_validator
from pydantic.fields import FieldInfo
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.algorithm import (
@@ -194,49 +195,32 @@ class EnvConfig(BaseConfig):
return self
def merge_group_defaults(data: Any) -> Any:
"""Shared ``mode="before"`` body for source groups: layer the group's ``env`` and
``select`` blocks under those of each raw source. A source's own values win; a
source's ``include`` or ``exclude`` replaces the group's whole block."""
if not isinstance(data, dict):
return data
sources = data.get("source") or []
if data.get("env") is not None:
try:
shared = vf.SharedEnvConfig.model_validate(data["env"])
except ValidationError:
shared = None # the ``env`` field reports the errors once, not once per source
if shared is not None:
sources = [
{**source, "env": vf.merge_env_defaults(shared, source.get("env"))}
if isinstance(source, dict)
else source
for source in sources
]
if data.get("select") is not None:
group = select_fields(data["select"], vf.SelectCLIConfig)
if group is not None:
sources = [
{**source, "select": group | own}
if isinstance(source, dict)
and (own := select_fields(source.get("select"), vf.SelectConfig)) is not None
else source
for source in sources
]
if sources:
data["source"] = sources
return data
def inherit_defaults(defaults: dict[str, Any], source: dict) -> dict:
"""Fill in one raw source with its group's ``defaults`` (field name to validated
group value). A config block such as ``sampling`` is filled in key by key with
``vf.merge_defaults``; a plain value such as ``group_size`` is used only when the
source leaves it unset. The source's own values always win, and a block that the
source passes as an already-built config is kept as is."""
merged = dict(source)
for name, value in defaults.items():
own = source.get(name)
if isinstance(value, BaseModel):
if own is None or isinstance(own, dict):
merged[name] = vf.merge_defaults(value, own)
elif name not in source:
merged[name] = value
return merged
def select_fields(raw: Any, select_type: type[vf.SelectConfig]) -> dict | None:
"""The fields a raw ``select`` block sets, under their canonical names; None when
the block is invalid, which leaves it to report its own errors."""
if raw is None:
return {}
try:
return select_type.model_validate(raw).model_dump(exclude_unset=True)
except ValidationError:
return None
def raw_field(data: dict, name: str, field: FieldInfo) -> tuple[bool, Any]:
"""Whether raw ``data`` sets field ``name``, under its name or an alias (``-r``
arrives as ``r``), and the value it sets."""
alias = field.validation_alias
keys = [name, *(alias.choices if isinstance(alias, AliasChoices) else [alias] if alias else [])]
for key in keys:
if isinstance(key, str) and key in data:
return True, data[key]
return False, None
class StandardSamplerConfig(BaseConfig):
@@ -318,13 +302,14 @@ class TrainSourceConfig(EnvConfig):
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
group_size: int = Field(1, ge=1)
"""Rollouts generated per example for GRPO group-relative advantages.
Inherits from ``orchestrator.group_size`` when unset."""
"""Rollouts generated per example for GRPO group-relative advantages. Overrides the
train group's ``group_size`` for this env, so envs can use different sizes."""
algo: AlgoConfig | None = None
"""Training algorithm for this env. Inherits from the top-level
``orchestrator.algo`` when unset; set ``type`` (and its params) to give
this env its own algorithm."""
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm for this env: sampling plus the per-token training signal
(credit assignment and loss routing, fused — its ``type`` names the algorithm).
Setting only some params keeps the group's algorithm; a different ``type`` is
this env's own algorithm."""
curriculum: CurriculumConfig | None = None
"""User-authored task sampler and admission gates. The default cycles
@@ -343,41 +328,68 @@ class OnlineEvalSourceConfig(EvalSourceConfig):
"""An eval source of a training run: evaluated on a step interval."""
interval: int = Field(100, ge=1)
"""Per-env eval interval. If unset, inherits from the group-level eval interval."""
"""Step interval at which to evaluate this env."""
class TrainConfig(BaseConfig):
source: list[TrainSourceConfig] = Field(default_factory=list)
"""Training sources."""
class SourceGroupConfig(BaseConfig):
"""A list of sources plus defaults for them.
Any field that both the group and its source type declare (``env``, ``sampling``,
``select``, ``group_size``, ...) is a default. Before validation, each source gets
the group's value for every such field that the group sets:
- a field the source sets itself keeps the source's value;
- a nested block is filled in key by key (``vf.merge_defaults``);
- a block with a different ``type``/``id`` (e.g. another ``algo``) is the source's
alone.
A field the group leaves unset is not passed on, so each group field must default
to the same value as the source field it feeds."""
env: vf.SharedEnvConfig = vf.SharedEnvConfig()
"""Env knobs that every training source inherits: the fields every env and taskset
has, such as ``retries`` and ``timeout``. A source's own ``env`` values win."""
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
select: vf.SelectConfig = vf.SelectConfig()
"""Task selection that every training source inherits. Each field a source sets on
its own ``select`` wins over this one."""
"""Env knobs that every source inherits: the fields every env and taskset has, such
as ``retries`` and ``timeout``."""
@model_validator(mode="before")
@classmethod
def resolve_group_defaults(cls, data):
return merge_group_defaults(data)
def inherit_group_defaults(cls, data: Any) -> Any:
"""Pass the group's set defaults down into each raw source."""
if not isinstance(data, dict) or not isinstance(data.get("source"), list):
return data
(source_type,) = get_args(cls.model_fields["source"].annotation)
defaults: dict[str, Any] = {}
for name, field in cls.model_fields.items():
if name == "source" or name not in source_type.model_fields:
continue
is_set, raw = raw_field(data, name, field)
if not is_set:
continue
try:
defaults[name] = TypeAdapter(field.rebuild_annotation()).validate_python(raw)
except ValidationError:
continue # the group field reports its own errors once, not once per source
data["source"] = [
inherit_defaults(defaults, source) if isinstance(source, dict) else source for source in data["source"]
]
return data
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
is configured per env, defaulting to elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.source:
if "sampling" not in env.model_fields_set:
env.sampling = TrainSamplingConfig(**group_sampling)
else:
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
env.sampling = TrainSamplingConfig(**merged)
return self
class TrainConfig(SourceGroupConfig):
source: list[TrainSourceConfig] = Field(default_factory=list)
"""Training sources."""
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Sampling that every training source inherits."""
select: vf.SelectConfig = vf.SelectConfig()
"""Task selection that every training source inherits."""
group_size: int = Field(1, ge=1)
"""Rollouts generated per example that every training source inherits unless it
sets its own. ``batch_size`` must be divisible by every source's group size."""
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm that every training source inherits. Defaults to ``grpo``."""
@model_validator(mode="after")
def validate_unique_env_names(self):
@@ -390,46 +402,21 @@ class TrainConfig(BaseConfig):
return self
class EvalSourcesConfig(BaseConfig):
"""Eval sources and the group-level defaults they inherit."""
class EvalSourcesConfig(SourceGroupConfig):
"""Eval sources and the defaults they inherit."""
source: list[EvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources."""
env: vf.SharedEnvConfig = vf.SharedEnvConfig()
"""Env knobs that every eval source inherits: the fields every env and taskset
has, such as ``retries`` and ``timeout``. A source's own ``env`` values win."""
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
"""Shared eval sampling configuration; can differ from training sampling."""
"""Sampling that every eval source inherits; can differ from training sampling."""
select: vf.SelectConfig = vf.SelectConfig()
"""Task selection that every eval source inherits, e.g. ``limit = 128`` to evaluate
128 tasks of each taskset. Each field a source sets on its own ``select`` wins over
this one."""
128 tasks of each taskset."""
group_size: int = Field(1, ge=1)
"""Default rollouts per example. Can be overridden per env."""
@model_validator(mode="before")
@classmethod
def resolve_group_defaults(cls, data):
return merge_group_defaults(data)
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling and group_size (the
worker ``pool`` is configured per env, default elastic)."""
group_sampling = self.sampling.model_dump()
for source in self.source:
if "sampling" not in source.model_fields_set:
source.sampling = EvalSamplingConfig(**group_sampling)
else:
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
source.sampling = EvalSamplingConfig(**merged)
if "group_size" not in source.model_fields_set:
source.group_size = self.group_size
return self
"""Rollouts per example that every eval source inherits."""
@model_validator(mode="after")
def validate_non_empty_sources(self):
@@ -458,7 +445,7 @@ class ScheduledEvalConfig(EvalSourcesConfig):
"""Evaluation sources, each with its own step interval."""
interval: int = Field(100, ge=1)
"""Step interval at which to evaluate the model."""
"""Step interval that every eval source inherits."""
skip_first_step: bool = False
"""If True, skip the startup eval that otherwise runs before any
@@ -469,14 +456,6 @@ class ScheduledEvalConfig(EvalSourcesConfig):
crash that left in-flight evals unfinished). By default, assumes a clean
exit where all evals already completed."""
@model_validator(mode="after")
def resolve_env_intervals(self):
"""Per-env intervals inherit the group-level interval."""
for source in self.source:
if "interval" not in source.model_fields_set:
source.interval = self.interval
return self
@property
def intervals(self) -> dict[str, int]:
"""Step interval per eval env, by resolved name."""
@@ -580,12 +559,6 @@ TRAIN_TOP_K_BOUND = 512
class OrchestratorConfig(BaseConfig):
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
assignment and loss routing, fused — its ``type`` names the algorithm).
Defaults to ``grpo``. Override per source via ``[[orchestrator.train.source]]``'s
``algo``."""
model: ModelConfig = ModelConfig()
"""The model being trained: its model fields plus the client of the live
vLLM deployment (``[orchestrator.model] name = ...`` with
@@ -649,9 +622,6 @@ class OrchestratorConfig(BaseConfig):
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight concurrency control (``[orchestrator.concurrency]``)."""
group_size: int = Field(1, ge=1)
"""Output sequences returned per example during training."""
seq_len: int = 2048
"""Training sequence length. Shorter samples are padded; longer samples are truncated."""
@@ -688,20 +658,10 @@ class OrchestratorConfig(BaseConfig):
self.monitors.prime.name = self.monitors.wandb.name
return self
@model_validator(mode="after")
def inherit_env_algorithms(self):
"""Envs without their own algorithm inherit the top-level one.
Declared before any validator that reads ``algo``."""
for env_cfg in self.train.source:
if env_cfg.algo is None:
env_cfg.algo = self.algo.model_copy(deep=True)
return self
@model_validator(mode="after")
def validate_env_algorithms(self):
"""Let each algorithm reject environments it cannot score correctly."""
for env_cfg in self.train.source:
assert env_cfg.algo is not None # resolved by inherit_env_algorithms
env_cfg.algo.validate_env(env_cfg.env)
return self
@@ -712,9 +672,9 @@ class OrchestratorConfig(BaseConfig):
Owned here: every truncating config gets a top-k bound (bounds the sampling
masks); opd/opsd is rejected (full-vocab prefill refs would mix
normalizations). Frozen-source envs sample externally and are exempt."""
policy_samplings = [
env.sampling for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy"
] or ([self.train.sampling] if not self.train.source else [])
policy_samplings = [env.sampling for env in self.train.source if env.algo.sampling.source == "policy"] or (
[self.train.sampling] if not self.train.source else []
)
truncating = [sampling for sampling in policy_samplings if sampling.truncates_distribution()]
if not truncating:
return self
@@ -744,7 +704,7 @@ class OrchestratorConfig(BaseConfig):
for sampling in unbounded:
sampling.top_k = TRAIN_TOP_K_BOUND
algos = [env.algo for env in self.train.source if env.algo is not None] or [self.algo]
algos = [env.algo for env in self.train.source] or [self.train.algo]
if any(algo.type in ("opd", "opsd") for algo in algos):
raise ValueError(
"opd/opsd is not supported with truncated train sampling: reference logprobs are full-vocab "
@@ -757,7 +717,7 @@ class OrchestratorConfig(BaseConfig):
@property
def any_policy_sourced(self) -> bool:
"""True when at least one train env samples rollouts from the live policy."""
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.source)
return any(env.algo.sampling.source == "policy" for env in self.train.source)
@model_validator(mode="after")
def validate_renderer_auto_resolves(self):
@@ -804,18 +764,18 @@ class OrchestratorConfig(BaseConfig):
if not has_rollout_batch and not has_token_batch:
self.batch_size = 128
if self.batch_size is not None and self.batch_size % self.group_size != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
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):
raise ValueError(
f"Batch size {self.batch_size} must be divisible by every train source's group_size {sorted(set(group_sizes))}"
)
for field in ("max_inflight", "initial_inflight"):
value = getattr(self.concurrency, field)
if value is not None and value < self.group_size:
raise ValueError(f"concurrency.{field} must be at least the number of rollouts per example")
# Propagate the top-level ``group_size`` into each train env that didn't set its own.
for env_cfg in self.train.source:
if "group_size" not in env_cfg.model_fields_set:
env_cfg.group_size = self.group_size
if value is not None and value < max(group_sizes):
raise ValueError(
f"concurrency.{field} must be at least the largest train group_size ({max(group_sizes)})"
)
return self
@@ -825,7 +785,6 @@ class OrchestratorConfig(BaseConfig):
for env in self.train.source:
# Policy-sourced rollouts hit our vLLM server; frozen-sourced
# rollouts may hit external OAI endpoints that reject these knobs.
assert env.algo is not None
if env.algo.sampling.source == "policy":
env.sampling.extra_body.setdefault("top_k", -1)
env.sampling.extra_body.setdefault("min_p", 0.0)
@@ -835,9 +794,7 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def validate_policy_top_k_consistency(self):
"""Require one top-k capture mode across the live policy server."""
policy_sources = [
env for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy"
]
policy_sources = [env for env in self.train.source if env.algo.sampling.source == "policy"]
enabled = [env for env in policy_sources if env.sampling.top_k is not None]
disabled = [env for env in policy_sources if env.sampling.top_k is None]
if enabled and disabled:
@@ -618,9 +618,7 @@ class RLConfig(BaseConfig):
on, vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0``,
so eval sampling against the same server must set both."""
policy_samplings = [
env.sampling
for env in self.orchestrator.train.source
if env.algo is not None and env.algo.sampling.source == "policy"
env.sampling for env in self.orchestrator.train.source if env.algo.sampling.source == "policy"
] or ([self.orchestrator.train.sampling] if not self.orchestrator.train.source else [])
if not any(sampling.truncates_distribution() for sampling in policy_samplings):
return self
@@ -10,7 +10,7 @@ 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.monitors import MonitorsConfig
from prime_rl.configs.monitors import TrainMonitorsConfig
from prime_rl.configs.shared import (
EnvVars,
HeartbeatConfig,
@@ -85,6 +85,25 @@ class LossMaskConfig(BaseConfig):
"""Tool messages contribute to the loss."""
class SFTColumnsConfig(BaseConfig):
"""Dataset columns the trainer reads. Set a field to read a column under another name."""
messages: str = "messages"
"""Column with the whole chat as a list of OpenAI chat messages."""
prompt: str = "prompt"
"""Column with the prompt as a list of OpenAI chat messages, read with ``completion`` when a row has no messages."""
completion: str = "completion"
"""Column with the completion as a list of OpenAI chat messages."""
tools: str = "tools"
"""Column with the tool schemas in OpenAI function-calling format."""
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."""
class SFTDataConfig(BaseDataConfig):
type: Literal["sft"] = "sft"
@@ -112,6 +131,9 @@ class SFTDataConfig(BaseDataConfig):
seed: int = 0
"""Random seed for shuffling. Re-shuffled per epoch by adding the epoch count to the seed."""
columns: SFTColumnsConfig = SFTColumnsConfig()
"""Columns that carry per-sample renderer arguments."""
# Configuring
loss_mask: LossMaskConfig = LossMaskConfig()
"""Which message types contribute to the loss."""
@@ -229,8 +251,8 @@ class SFTConfig(BaseConfig):
log: TrainerLogConfig = TrainerLogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
monitors: TrainMonitorsConfig = TrainMonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
run: RunConfig = Field(default_factory=RunConfig)
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
@@ -249,7 +271,8 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_run_identity(self):
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
default the run directory and W&B run name to it when not set explicitly."""
default the run directory, W&B run name and platform run name to it when not
set explicitly."""
if self.run.name is None:
dataset = str(getattr(self.data, "name", "")).split("/")[-1]
model = self.model.name.split("/")[-1]
@@ -259,6 +282,8 @@ class SFTConfig(BaseConfig):
self.run.dir = self.run.name
if self.monitors.wandb is not None and self.monitors.wandb.name is None:
self.monitors.wandb.name = self.run.name
if self.monitors.prime is not None and self.monitors.prime.name is None:
self.monitors.prime.name = self.run.name
return self
matmul_precision: Literal["highest", "high", "medium"] = "high"
@@ -222,6 +222,11 @@ class HeartbeatConfig(BaseConfig):
url: str
"""URL to send the heartbeat to."""
min_interval: float = Field(30.0, gt=0)
"""Minimum seconds between pings. Beats can arrive far more often (evals beat once
per landed episode); surplus beats are dropped to stay under Better Stack's heartbeat
rate limit. Size it well under the monitor's period."""
class MetricsServerConfig(BaseConfig):
port: int = Field(8000, ge=1, le=65535)
@@ -212,9 +212,11 @@ class MoEComputeConfigBase(BaseConfig):
class BF16MoEComputeConfig(MoEComputeConfigBase):
"""Run routed-expert grouped GEMMs in bfloat16."""
"""Run routed experts in bfloat16."""
type: Literal["bf16"] = "bf16"
backend: Literal["torch", "sonicmoe"] = "torch"
"""Expert compute implementation."""
class DeepGemmFP8MoEComputeConfig(MoEComputeConfigBase):
@@ -107,7 +107,8 @@ def propagate_shared_fields(data: Any) -> Any:
# [monitors.file] leaf. (Bare empty ``[monitors.file]`` block enablement is at the end.)
propagate("monitors.file.path", "trainer.monitors.file.path", "orchestrator.monitors.file.path")
# [monitors.prime] leaf → orchestrator only (the trainer has no platform integration).
# [monitors.prime] leaf → orchestrator only (the RL trainer has no platform
# integration; the SFT trainer does, but it parses SFTConfig directly).
propagate("monitors.prime.name", "orchestrator.monitors.prime.name")
# [tokenizer]. ``chat_template`` also flows to ``inference.vllm`` (vLLM's
+7 -3
View File
@@ -29,7 +29,7 @@ dependencies = [
"rich>=14.0.0",
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"verifiers[harbor]>=0.3.2.dev152",
"verifiers[harbor]>=0.3.2.dev158",
"renderers[multimodal]>=0.1.12.dev2",
"pybase64>=1.4.2",
"orjson>=3.10",
@@ -97,6 +97,7 @@ disagg = [
quack = [
"quack-kernels>=0.4.1 ; sys_platform == 'linux'",
]
sonic-moe = ["sonic-moe ; sys_platform == 'linux'"]
# 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 = [
@@ -107,6 +108,7 @@ all = [
"prime-rl[flash-attn]",
"prime-rl[disagg]",
"prime-rl[quack]",
"prime-rl[sonic-moe]",
"prime-rl[flash-attn-3]",
"prime-rl[flash-attn-cute]",
]
@@ -268,10 +270,12 @@ torchao = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
dion = { git = "https://github.com/samsja/dion.git", rev = "6f9242d" }
sonic-moe = { git = "https://github.com/S1ro1/sonic-moe", rev = "0bf06ac" }
quack-kernels = { git = "https://github.com/S1ro1/quack", rev = "f62009f" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ 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'" },
+7 -1
View File
@@ -94,7 +94,13 @@ export LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:
WHEEL_DIR="$PROJECT_DIR/deps"
mkdir -p "$WHEEL_DIR"
uv pip install pip 2>/dev/null
"$PYTHON" -m pip wheel . --no-deps --wheel-dir="$WHEEL_DIR"
# NIXL's [build-system] requires are unpinned; meson-python 0.22.0 stopped
# keeping Meson's build RPATH in wheel libraries, which drops the link to the
# UCX built above. Constrain the backend to the version these wheels were
# validated with (same pin as Dockerfile.cuda).
printf 'meson-python==0.21.1\n' > "$WORKSPACE/nixl-build-constraints.txt"
"$PYTHON" -m pip wheel . --no-deps --wheel-dir="$WHEEL_DIR" \
--build-constraint "$WORKSPACE/nixl-build-constraints.txt"
WHEEL=$(ls "$WHEEL_DIR"/nixl_cu13-"$NIXL_VERSION"-*.whl | head -1)
echo "=== NIXL wheel built at: $WHEEL ==="
+5 -3
View File
@@ -63,19 +63,21 @@ env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
Each source group (`[orchestrator.train]`, `[orchestrator.eval]`, the `sft` `[eval]` block, the top level of `eval`) holds defaults that its sources inherit: every field that the group and its sources both have (`env`, `sampling`, `select`, `group_size`, plus `algo` on train and `interval` on online eval). Blocks merge key by key, a source's own values win, and a block whose `type` differs is the source's alone.
Source lists are set in TOML. The CLI has no list-index paths (`--orchestrator.eval.source.0.env.taskset.id` does not parse); a whole list can be passed as JSON (`--orchestrator.eval.source '[{"env": {"taskset": {"id": "reverse-text"}}}]'`), which replaces the list wholesale.
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server). The `eval` entrypoint flattens it further: `[[source]]`, `[client]`, `[concurrency]`, `[select]`, `group_size` at the top level, plus the single-source shorthands `uv run eval <taskset-id> --env.<field> <value> -n N -s -r N -c N -m MODEL` (see the `eval` skill).
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.train.algo.type max_rl`) or a TOML overlay file.
**vLLM pass-through** — `[inference.vllm]` uses vLLM's own argument names (`model`, `tensor_parallel_size`, `data_parallel_size`, `max_model_len`, ...) and forwards *any* key to the vLLM server, typed by prime-rl or not: `[inference.vllm] max_num_seqs = 256`, or `--inference.vllm.max-num-seqs 256` on the CLI. CLI values are JSON-coerced, so dict-valued vLLM args work as `--inference.vllm.compilation-config '{"cudagraph_mode": "NONE"}'`. Non-vLLM knobs (router, deployment, weight broadcast, kv-cache offload, env vars) stay on `[inference]` itself.
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.train.algo] type = "max_rl"`). Omit `type` to keep the default variant.
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1`, `adv_tau = 1.0`, and `kl_tau = 1e-3`. Omit the section to use these defaults. Set `type = "icepop"` for ratio masking with `ratio_low = 0.2`, `ratio_high = 5.0`, and `adv_tau = 1.0`; IcePop has no separate KL term. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**Algorithms** — `[orchestrator.train.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.train.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Each train source inherits the group algorithm: a source `algo` with a different `type` is its own algorithm (`[orchestrator.train.source.algo] type = "opd"`), and params without a `type` keep the group's algorithm with those params changed. prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.train.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.train.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
+3 -2
View File
@@ -9,11 +9,12 @@ description: Find, start, use, and stop the local run dashboard for metrics, con
What is not obvious from the UI:
- Overview and Metrics read the same `monitors/file/metrics.jsonl`. **Overview** is the curated view (the sections of the W&B overview: train, eval, stability, inference, performance). **Metrics** is every key in the file, one pane per key, sectioned by parent path (`Flat`) or as a tree of sections along the key path (`Nested`), with a regex filter; time-keyed rows (`inference/`, `concurrency/`, `dispatcher/`) chart against wall time.
- Overview and Metrics read the same `monitors/file/metrics.jsonl`. **Overview** is the curated view: a step bar (click a cell for that step's batch), summary tiles (reward per train env and avg@k per eval env, each with the change from its first logged value in the corner; error / truncation / timeout rate; step time), then the sections of the W&B overview (train, eval, stability, inference, performance) with readable panel names (hover a panel's `i` for how it is computed and its raw key). **Metrics** is every key in the file, one pane per key, sectioned by parent path (`Flat`) or as a tree of sections along the key path (`Nested`), with a regex filter; time-keyed rows (`inference/`, `concurrency/`, `dispatcher/`) chart against wall time.
- The `filter` menu (status, kind, env, outcome) is one state shared by the overview, the traces tab and the trace viewer: an env or outcome set in one applies in all. On the overview it narrows the sections and tiles to that env / kind and, for an eval run, the distributions to that outcome (`ok` / `error`; errored episodes read red).
- Config and Logs default to `latest (attempt <n>)`; select an attempt to inspect an earlier launch. The Config view shows a copyable launch command.
- Trace viewer views: **Transcript**, **Timeline** (wall-clock Gantt of prefix branches), **Replay** (the branch as a terminal session; response text is paced evenly across the recorded model-call span and labelled inferred; default 8×; **Skip inference** collapses model calls but keeps tool delays; **T** toggles thinking, never advertise Ctrl+T) and **Semantic** (`semantic_parents` as a causal graph of model calls; width reflects peak agent concurrency; unplaceable fragments show as unlinked). Traces without semantic parents disable Semantic.
- Live rollouts appear in the traces table with a pulsing dot and a phase badge, and open in the viewer, which follows them (pinned to the newest turn until you scroll up; the request in flight's uncommitted messages render dimmed as `awaiting model`). They come from `monitors/file/traces/live/*.jsonl`, polled once a second.
- For an eval run the overview tab shows one env at a time (filter → env, `include errors`): a block progress bar (one cell per expected episode, from `monitors/file/plan.json`), summary tiles (avg@k, pass@k, error and truncation rate coloured >10% yellow / >50% red, turns / branches, episode time, tokens, cost), env metrics as dot plots or beeswarms (hover a dot for its episode, click to open it; hover the background for the quantiles), and usage / timing composition panes (icicle of the mean split over per-episode strips; `other` is wall time no phase accounts for; hover a part to dim the rest; 40 strips by default, `show all` for every one).
- For an eval run the overview tab shows every env the filter keeps, one block after another when there are several (the progress head names each): a block progress bar (one cell per expected episode, from `monitors/file/plan.json`), summary tiles (avg@k, pass@k, error and truncation rate coloured >10% yellow / >50% red, turns / branches, episode time, tokens, cost), env metrics as dot plots or beeswarms (hover a dot for its episode, click to open it; hover the background for the quantiles), and usage / timing composition panes (icicle of the mean split over per-episode strips; `other` is wall time no phase accounts for; hover a part to dim the rest; 40 strips by default, `show all` for every one).
- `view on platform` in the top bar links to the run on the Prime platform when `--monitors.prime` was on (`monitors/prime/run.json`); an eval's evaluation opens at epoch start, so the link is live from the first episode.
- An eval reads `completed` once its stream is sealed by a clean exit; a crashed or interrupted one reads `stopped` after its files go quiet.
+38 -14
View File
@@ -81,7 +81,7 @@ _summaries_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
_series_keys: dict[tuple[Path, str | None], tuple[int, set[str]]] = {}
"""Per stream and kind filter: how many summaries were scanned for series keys, and the keys."""
_annotations_cache: OrderedDict[Path, tuple[tuple, dict[str, dict], dict[Path, int]]] = OrderedDict()
_index_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
_index_cache: OrderedDict[Path, tuple[int, bytes, list[dict]]] = OrderedDict()
_rows_cache: OrderedDict[Path, tuple] = OrderedDict() # key, rows, entered, by_trace, consumed, last row
_tokenizer_cache: dict[str, object] = {}
_piece_cache: dict[tuple[str, int], str] = {}
@@ -351,7 +351,6 @@ def run_meta(run_dir: Path) -> dict:
"platform": platform,
"model": model_name(config),
"dataset": (config.get("data") or {}).get("name"),
"has_validation": run_type == "sft" and config.get("val") is not None,
"env": eval_env(config),
"total_episodes": eval_total_episodes(config),
"eval_totals": eval_totals(config),
@@ -1016,8 +1015,15 @@ def timeline_lane(
starts = [span["started_at"] for span in spans if span.get("started_at") is not None]
ends = [span["ended_at"] for span in spans if span.get("ended_at") is not None]
started = started_at if started_at is not None else min(starts or ends, default=None)
terminal = next(
(span["status"] for span in lifecycle if span["status"] in {"cancelled", "failed", "timeout"}),
None,
)
status = (
("completed" if all(span["status"] == "completed" for span in lifecycle + activities) else "running")
(
terminal
or ("completed" if all(span["status"] == "completed" for span in lifecycle + activities) else "running")
)
if branch
else timeline_status(trace)
)
@@ -1208,6 +1214,13 @@ def semantic_context_lanes(
ordered_components = sorted(components, key=lambda component: (component_start(component), component))
cross_edges = [edge for edge in edges if component_for[edge["source_node"]] != component_for[edge["target_node"]]]
# subagent_failed (child -> parent) marks its source; subagent_cancel (parent -> child) its target.
context_outcome = {}
for edge in cross_edges:
if edge["type"] == "subagent_failed":
context_outcome[component_for[edge["source_node"]]] = "failed"
elif edge["type"] == "subagent_cancel":
context_outcome[component_for[edge["target_node"]]] = "cancelled"
created_components = {
component_for[edge["target_node"]]
for edge in cross_edges
@@ -1277,6 +1290,10 @@ def semantic_context_lanes(
default=None,
)
completed = bool(trace.get("is_completed"))
# A cancelled/failed context is done even if the trace as a whole is not.
outcome = context_outcome.get(component)
status = outcome or ("completed" if completed else "running")
ended_at = end if (outcome is not None or completed) else None
label = f"{agent_label} · context {context_index}"
lifecycle = (
[
@@ -1285,8 +1302,8 @@ def semantic_context_lanes(
"label": label,
"track": "lifecycle",
"started_at": start,
"ended_at": end if completed else None,
"status": "completed" if completed else "running",
"ended_at": ended_at,
"status": status,
}
]
if start != float("inf")
@@ -1305,6 +1322,8 @@ def semantic_context_lanes(
"agent": agent_label,
"index": context_index,
}
if outcome is not None:
lane["context"]["outcome"] = outcome
if component in unlinked_components:
lane["context"]["unlinked"] = True
if component in attempt_by_component:
@@ -1447,9 +1466,14 @@ def index_rows(path: Path) -> list[dict] | None:
size = path.stat().st_size
with _lock:
cached = _lru_get(_index_cache, path)
# A resume rewrites/truncates the index (dropped errored rows, then re-grows it),
# so the bytes before the old EOF change: reusing the cache append-only would splice
# stale rows in. Detect it via file_checkpoint, exactly like line_offsets().
if cached and (cached[0] > size or (cached[0] and file_checkpoint(path, cached[0]) != cached[1])):
cached = None
if cached and cached[0] == size:
return cached[1]
rows, read_from = (list(cached[1]), cached[0]) if cached and cached[0] < size else ([], 0)
return cached[2]
rows, read_from = (list(cached[2]), cached[0]) if cached else ([], 0)
with path.open("rb") as f:
f.seek(read_from)
for raw in f:
@@ -1461,7 +1485,7 @@ def index_rows(path: Path) -> list[dict] | None:
break
read_from += len(raw)
with _lock:
_lru_put(_index_cache, path, (read_from, rows))
_lru_put(_index_cache, path, (read_from, file_checkpoint(path, read_from), rows))
return rows
@@ -1522,7 +1546,7 @@ def row_filter(
kind: str | None = None,
env: str | None = None,
episode: str | None = None,
errors_only: bool = False,
ok: bool | None = None,
start: float | None = None,
end: float | None = None,
):
@@ -1539,7 +1563,7 @@ def row_filter(
return False
if episode is not None and row.get("id") != episode:
return False
if errors_only and row.get("ok"):
if ok is not None and bool(row.get("ok")) != ok:
return False
arrival = row.get("arrival") or 0
return not ((start is not None and arrival < start) or (end is not None and arrival >= end))
@@ -1567,7 +1591,7 @@ def list_stream_episodes(
kind: str | None = None,
env: str | None = None,
episode: str | None = None,
errors_only: bool = False,
ok: bool | None = None,
sort: str = "arrival",
order: str = "desc",
offset: int = Query(default=0, ge=0),
@@ -1594,7 +1618,7 @@ def list_stream_episodes(
if upto is not None:
rows = rows[:upto]
envs, kinds = index_facets(run_dir)
keep = row_filter(step=step, kind=kind, env=env, episode=episode, errors_only=errors_only, start=start, end=end)
keep = row_filter(step=step, kind=kind, env=env, episode=episode, ok=ok, start=start, end=end)
if sort == "arrival":
# the index is already in arrival order: walk it from the right end and stop
# once the page is full, so the common view costs a page rather than a run
@@ -1629,7 +1653,7 @@ def episode_histogram(
step: int | None = None,
kind: str | None = None,
env: str | None = None,
errors_only: bool = False,
ok: bool | None = None,
bars: int = Query(default=80, ge=8, le=500),
) -> dict:
"""Episodes finishing per time bin, over the same filters as the table — the
@@ -1637,7 +1661,7 @@ def episode_histogram(
the episodes and the bin is the roundest interval that keeps the bar count sane,
so a run of any length reads the same."""
run_dir = get_run_dir(run)
rows = filter_rows(episode_rows(run_dir), step=step, kind=kind, env=env, errors_only=errors_only)
rows = filter_rows(episode_rows(run_dir), step=step, kind=kind, env=env, ok=ok)
arrivals = sorted(row["arrival"] for row in rows if isinstance(row.get("arrival"), (int, float)))
if not arrivals:
return {"bins": [], "bin": 60, "start": None, "end": None, "total": 0}
File diff suppressed because it is too large Load Diff
+37 -67
View File
@@ -41,25 +41,10 @@
<main>
<section id="tab-overview">
<div class="controls">
<div id="overview-filter-wrap" class="dd-wrap" hidden>
<button id="overview-filter-btn" class="btn dd-btn" title="filter">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
</button>
<div class="dd-menu dd-filters" id="overview-filter-menu" hidden>
<div class="dd-sec">filter</div>
<label class="dd-row" id="overview-env-row"><span class="t-label">env</span>
<select id="overview-env"></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="overview-errors"><span class="dot"></span>include errors</label>
</div>
</div>
<div id="overview-filter-wrap" class="dd-wrap flt-wrap"></div>
<input id="overview-search" class="search" type="search" placeholder="regex filter, e.g. reward or ^inference/">
<label class="ctl">smooth <input id="overview-smooth" type="range" min="1" max="50" value="1"><span id="overview-smooth-val">off</span></label>
<span id="overview-status" class="muted"></span>
<div class="spacer"></div>
<button id="overview-collapse" class="btn">collapse</button>
<button id="overview-expand" class="btn">expand</button>
</div>
<div id="overview-body"></div>
<div id="swarm-tip" hidden></div>
@@ -111,32 +96,7 @@
<button data-mode="stream" class="active" title="every episode, newest first">Stream</button>
<button data-mode="step" title="the cohort shipped at one step">Step</button>
</div>
<div id="trace-filter-wrap" class="dd-wrap">
<button id="trace-filter-btn" class="btn dd-btn" title="filter">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
<span id="trace-filter-count" class="badge" hidden></span>
</button>
<div class="dd-menu dd-filters" id="trace-filter-menu" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row"><span class="t-label">status</span>
<div class="seg toggle-seg" id="trace-status-filter">
<button data-status="live" class="on" title="live rollouts, streamed by their env servers">live</button>
<button data-status="done" class="on" title="episodes in the finished stream">completed</button>
</div>
</div>
<div class="dd-row"><span class="t-label">kind</span>
<div class="seg toggle-seg" id="trace-kinds">
<button data-kind="train" class="on">train</button>
<button data-kind="eval" class="on">eval</button>
</div>
</div>
<label class="dd-row"><span class="t-label">env</span>
<select id="trace-env"><option value="">all envs</option></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<div id="trace-filter-wrap" class="dd-wrap flt-wrap"></div>
<select id="trace-sort" title="sort" data-label="sort">
<option value="arrival:desc">arrival ↓</option>
<option value="arrival:asc">arrival ↑</option>
@@ -221,31 +181,7 @@
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
</div>
<div class="tm-head tm-ctlrow">
<div id="tm-filter-wrap" class="dd-wrap">
<button id="tm-filter-btn" class="btn dd-btn" title="filter">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
</button>
<div class="dd-menu dd-filters" id="tm-filter-menu" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row"><span class="t-label">status</span>
<div class="seg toggle-seg" id="tm-status-filter">
<button data-status="live" class="on" title="live rollouts, streamed by their env servers">live</button>
<button data-status="done" class="on" title="episodes in the finished stream">completed</button>
</div>
</div>
<div class="dd-row"><span class="t-label">kind</span>
<div class="seg toggle-seg" id="tm-kinds">
<button data-kind="train" class="on">train</button>
<button data-kind="eval" class="on">eval</button>
</div>
</div>
<label class="dd-row"><span class="t-label">env</span>
<select id="tm-env"><option value="">all envs</option></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<div id="tm-filter-wrap" class="dd-wrap flt-wrap"></div>
<select id="tm-sort" title="sort" data-label="sort">
<option value="arrival:desc">arrival ↓</option>
<option value="arrival:asc">arrival ↑</option>
@@ -325,6 +261,40 @@
</aside>
</div>
<!-- one filter over every view: the overview, the traces table and the trace viewer
each host a copy, and a change in any of them shows up in all -->
<template id="filter-tpl">
<button class="btn dd-btn flt-btn" title="filter">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
<span class="badge flt-count" hidden></span>
</button>
<div class="dd-menu dd-filters" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row flt-status-row"><span class="t-label">status</span>
<div class="seg toggle-seg flt-status">
<button data-status="live" class="on" title="live rollouts, streamed by their env servers">live</button>
<button data-status="done" class="on" title="episodes in the finished stream">completed</button>
</div>
</div>
<div class="dd-row"><span class="t-label">kind</span>
<div class="seg toggle-seg flt-kinds">
<button data-kind="train" class="on">train</button>
<button data-kind="eval" class="on">eval</button>
</div>
</div>
<label class="dd-row"><span class="t-label">env</span>
<select class="flt-env"><option value="">all envs</option></select>
</label>
<div class="dd-row"><span class="t-label">outcome</span>
<div class="seg toggle-seg flt-outcome">
<button data-outcome="ok" class="on" title="episodes that finished without an error">ok</button>
<button data-outcome="error" class="on" title="episodes that errored">error</button>
</div>
</div>
</div>
</template>
<script src="/static/vendor/uPlot.iife.min.js"></script>
<script src="/static/app.js"></script>
</body>
+44 -9
View File
@@ -333,7 +333,7 @@ details.section > summary {
details.section > summary:hover { color: var(--grey-6); border-color: var(--grey-3); }
details.section .sec-chev { margin-left: auto; transition: transform 0.12s; font-size: 10px; color: var(--grey-4); }
details.section[open] .sec-chev { transform: rotate(90deg); }
.chart-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(var(--pane-min, 260px), 1fr)); gap: 12px; }
.chart-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(var(--pane-min, 300px), 1fr)); gap: 12px; }
/* eval runs: running-average stat cards instead of x/y chart panes */
.stat-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; }
.stat-card { background: var(--grey-2); border: 1px solid var(--hairline); padding: 12px 14px; min-width: 0; }
@@ -349,13 +349,17 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
}
.stat-value { font-size: 20px; color: var(--grey-6); margin: 6px 0 0; }
/* eval progress: one cell per expected episode */
.eval-progress { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; }
/* the tab already leaves 12px under its toolbar: 4px more reads as 16px, matching the gap below */
.eval-progress { display: flex; flex-direction: column; gap: 8px; margin: 4px 0 16px; }
.ep-head { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
.ep-row { display: flex; align-items: center; gap: 12px; }
.ep-row .ep-blocks { flex: 1; }
.ep-pct { font-size: 13px; color: var(--grey-6); min-width: 4ch; text-align: right; }
.ep-head .name { font-size: 14px; color: var(--grey-6); }
.ep-pct { font-size: 16px; font-weight: 500; color: var(--grey-6); white-space: nowrap; }
.ep-head .name { font-size: 16px; font-weight: 600; color: var(--grey-6); }
.ep-blocks { display: flex; gap: 2px; height: 28px; }
/* no horizon: fixed cells that wrap, so the bar grows rather than fills */
.ep-row .ep-blocks.open { flex: 0 1 auto; flex-wrap: wrap; height: auto; }
.ep-blocks.open .ep-cell { flex: 0 0 14px; height: 14px; }
.ep-cell { flex: 1; min-width: 0; background: var(--grey-2); border: 1px solid var(--hairline); }
.ep-cell.done { background: var(--accent); border-color: var(--accent); cursor: pointer; }
.ep-cell.done.err { background: var(--negative); border-color: var(--negative); }
@@ -366,7 +370,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
/* distributions: a beeswarm per metric, a faint boxplot behind it, stats on hover */
#tab-overview { position: relative; }
.swarm-card .chart-head { cursor: default; }
.swarm-host { height: var(--pane-h, 150px); margin-top: 6px; }
.swarm-host { height: var(--pane-h, 170px); margin-top: 6px; }
.swarm { display: block; }
.swarm .sw-bg { fill: transparent; }
.swarm circle { fill: var(--accent); fill-opacity: 0.7; cursor: pointer; }
@@ -398,14 +402,40 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
.tm-line.timeout { fill: var(--timeout); }
.comp-pane [data-part].dim { opacity: 0.2; }
.comp-pane .tm-node.dim { opacity: 0.35; }
/* the summary is one row whatever the count: the tiles share the width equally */
.sum-grid { margin-bottom: 4px; display: grid; grid-template-columns: none; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); gap: 12px; }
/* the summary tiles share the width equally and wrap only once they would squeeze */
.sum-grid { margin-bottom: 4px; display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; }
.sum-tile { cursor: default; padding: 14px 16px; min-height: 96px; display: flex; flex-direction: column; justify-content: center; }
.sum-tile .stat-label, .sum-tile .stat-value { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.sum-tile .stat-label { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
/* the headline may break before its change mark when the tile is narrow */
.sum-tile .stat-value { overflow-wrap: anywhere; }
.sum-tile .stat-value { font-size: clamp(16px, 1.7vw, 24px); margin-top: 8px; }
.sum-tile.rate-warn .stat-value { color: #ffd166; }
.sum-tile.rate-bad .stat-value { color: var(--negative); }
.sum-tile.rate-timeout .stat-value { color: var(--timeout); }
/* the change from the base value sits beside the headline */
.tile-delta { display: inline-block; margin-left: 8px; font-size: 11px; color: var(--grey-4); white-space: nowrap; }
.tile-delta.good { color: var(--positive); }
.tile-delta.bad { color: var(--negative); }
/* the overview's panels wear readable names, set like the tile labels; the mark opens how each is computed */
#overview-body .chart-card .chart-title { flex: 0 1 auto; text-transform: uppercase; letter-spacing: var(--track-caps); }
.chart-info {
flex-shrink: 0;
width: 13px;
height: 13px;
border: 1px solid var(--grey-3);
border-radius: 50%;
font: 500 9px var(--font-mono);
line-height: 12px;
text-align: center;
color: var(--grey-4);
cursor: help;
align-self: center;
}
.chart-info:hover { color: var(--grey-6); border-color: var(--grey-5); }
#swarm-tip .tip-note { max-width: 320px; white-space: normal; color: var(--grey-5); margin-bottom: 4px; }
#swarm-tip .tip-key { color: var(--grey-4); font-size: 10px; margin-top: 4px; }
/* several eval envs follow one another, a rule between them */
.eval-env + .eval-env { border-top: 2px solid var(--grey-3); padding-top: 22px; margin-top: 10px; }
.tm-note { font-size: 10px; margin-top: 4px; }
.tm-more { color: var(--grey-5); cursor: pointer; text-decoration: underline dotted; text-underline-offset: 3px; }
.tm-more:hover { color: var(--grey-6); }
@@ -456,7 +486,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
text-overflow: ellipsis;
flex: 1;
}
.chart-last { font-size: 12px; font-weight: 500; color: var(--grey-6); }
.chart-last { margin-left: auto; font-size: 15px; font-weight: 600; color: var(--grey-6); }
.chart-empty {
height: 120px;
display: flex;
@@ -893,6 +923,8 @@ mark.hit {
}
.tl-edge-key i.subagent-call { border-color: var(--infra); }
.tl-edge-key i.subagent-return { border-color: var(--risk); }
.tl-edge-key i.subagent-cancel { border-color: var(--negative); border-top-style: dashed; }
.tl-edge-key i.subagent-failed { border-color: var(--negative); }
.tl-edge-key i.compaction-attempt { border-color: var(--chart-2); border-top-style: dotted; }
.tl-edge-key i.compaction { border-color: var(--chart-2); border-top-style: dashed; }
.tl-edge-key i.custom { border-color: var(--accent); border-top-style: dotted; }
@@ -943,6 +975,7 @@ mark.hit {
.tl-state { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
.tl-state.completed { color: var(--positive); }
.tl-state.failed { color: var(--negative); }
.tl-state.cancelled { color: var(--negative); }
.tl-state.timeout { color: var(--timeout); }
.tl-state.running { color: var(--infra); }
.tl-tooltip {
@@ -1014,6 +1047,8 @@ mark.hit {
.sg-edge.continuation { opacity: 0.34; }
.sg-edge.subagent-call { stroke: var(--infra); stroke-width: 2.2; opacity: 0.9; }
.sg-edge.subagent-return { stroke: var(--risk); stroke-width: 2.2; opacity: 0.9; }
.sg-edge.subagent-cancel { stroke: var(--negative); stroke-width: 2.2; opacity: 0.9; stroke-dasharray: 5 3; }
.sg-edge.subagent-failed { stroke: var(--negative); stroke-width: 2.2; opacity: 0.9; }
.sg-edge.compaction-attempt { stroke: var(--chart-2); stroke-dasharray: 2 4; opacity: 0.66; }
.sg-edge.compaction { stroke: var(--chart-2); stroke-dasharray: 5 4; opacity: 0.9; }
.sg-edge.custom { stroke: var(--accent); stroke-dasharray: 2 4; opacity: 0.9; }
+1 -3
View File
@@ -243,9 +243,7 @@ def rl_local(config: RLConfig):
frozen_endpoints: list[str] = []
for env in config.orchestrator.train.source:
algo = env.algo
assert algo is not None, "TrainSourceConfig.algo must be resolved before launch (inherit_env_algorithms)"
for ref in (algo.sampling.source, getattr(algo, "teacher", None)):
for ref in (env.algo.sampling.source, getattr(env.algo, "teacher", None)):
if isinstance(ref, FrozenModelConfig):
frozen_endpoints.append(f"{ref.name} ({ref.base_url})")
if frozen_endpoints:
+17 -1
View File
@@ -9,6 +9,7 @@ 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
from prime_rl.configs.orchestrator import OnlineEvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.shared import LogConfig
@@ -72,6 +73,16 @@ def resolve_resume_step(config: SFTConfig) -> int | None:
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
def build_online_eval_monitors(monitors: TrainMonitorsConfig) -> EvalMonitorsConfig:
"""The online-eval process's monitors: same W&B and file config as the trainer's,
with the platform monitor switched to the evaluation flavor under the same name."""
return EvalMonitorsConfig(
wandb=monitors.wandb,
file=monitors.file,
prime=PrimeEvalMonitorConfig(name=monitors.prime.name) if monitors.prime is not None else None,
)
def build_online_eval_config(config: SFTConfig) -> SFTOnlineEvalConfig:
"""The online-eval process's config: the resolved ``[eval]`` block with the run-level
fields filled from the SFT config. The launcher spawns the env servers itself; the
@@ -85,9 +96,14 @@ def build_online_eval_config(config: SFTConfig) -> SFTOnlineEvalConfig:
broadcasts_dir=get_broadcast_dir(config.run_dir),
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
# Same run dir as the trainer: the dashboard reads the eval's
# file-monitor artifacts from the run directory, so a separate
# output dir would hide them. The train-vs-eval record collision
# is resolved by record merging in prime_rl.monitors.prime, not
# by directory separation.
output_dir=config.run_dir,
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
monitors=config.monitors,
monitors=build_online_eval_monitors(config.monitors),
)
return SFTOnlineEvalConfig(**{**eval_config.model_dump(exclude=set(run_fields)), **run_fields})
+1
View File
@@ -47,6 +47,7 @@ class OnlineEval:
await monitors.setup(
producer="online-eval",
wandb=config.monitors.wandb,
prime=config.monitors.prime,
file=config.monitors.file,
output_dir=config.output_dir,
run_config=config,
+1 -1
View File
@@ -84,7 +84,7 @@ class EvalRunner:
# sit inside the ping stream as an abnormally long silence and flip a healthy
# run stale. Until then the heartbeat has simply never been pinged.
if config.heartbeat is not None:
self.heart = Heartbeat(config.heartbeat.url)
self.heart = Heartbeat(config.heartbeat)
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
+11 -67
View File
@@ -4,25 +4,19 @@ vLLM ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
prefix-cache salting, lora dispatch, multimodal content parts and features,
prompt logprobs, priority, ``data_parallel_rank`` header routing, server-side
``max_tokens`` defaulting and ``usage`` reporting. We subclass it for the bits
still missing from the upstream handler:
1. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as ``{data, shape, start, dtype}`` base64 raw-byte
objects (the form the PD router can merge and the renderers parse) instead
of upstream's single ``.npy`` base64 string.
2. Prompt metadata — return the effective engine prompt and authoritative
multimodal placeholder ranges after expansion. Drop this once upstream's
response includes these fields.
``max_tokens`` defaulting, ``usage`` reporting, and expanded prompt metadata.
We subclass it for the one bit still missing from the upstream handler: compact
``routed_experts`` export. When the engine emits routing decisions, surface them
as ``{data, shape, start, dtype}`` base64 raw-byte objects (the form the PD
router can merge and the renderers parse) instead of upstream's single ``.npy``
base64 string.
Everything else delegates to upstream so we track future vLLM changes for free.
"""
from __future__ import annotations
from collections.abc import AsyncGenerator, AsyncIterable
from contextvars import ContextVar
from collections.abc import AsyncGenerator
from typing import Any
from vllm.entrypoints.generate.base.protocol import RequestResponseMetadata
@@ -30,7 +24,6 @@ from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateRequest,
GenerateResponse,
GenerateResponseChoice,
PlaceholderRangeInfo,
)
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
@@ -47,27 +40,6 @@ class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
class PrimeRlGenerateResponse(GenerateResponse):
choices: list[PrimeRlGenerateResponseChoice]
prompt_token_ids: list[int] | None = None
mm_placeholders: dict[str, list[PlaceholderRangeInfo]] | None = None
_response_mm_placeholders: ContextVar[dict[str, list[PlaceholderRangeInfo]] | None] = ContextVar(
"response_mm_placeholders", default=None
)
def _extract_mm_placeholders(
engine_input: Any,
) -> dict[str, list[PlaceholderRangeInfo]] | None:
if not isinstance(engine_input, dict) or engine_input.get("type") != "multimodal":
return None
return {
modality: [
PlaceholderRangeInfo(offset=placeholder.offset, length=placeholder.length)
for placeholder in sorted(ranges, key=lambda placeholder: placeholder.offset)
]
for modality, ranges in engine_input["mm_placeholders"].items()
}
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
@@ -82,29 +54,8 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
return PrimeRlGenerateResponse(**{**response.model_dump(exclude={"choices"}), "choices": choices})
class _PromptTokenIdsCapture:
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
self._source = source
self.prompt_token_ids: list[int] | None = None
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
async for output in self._source:
self.prompt_token_ids = output.prompt_token_ids
yield output
class PrimeRlServingTokens(ServingTokens):
"""ServingTokens with Prime's remaining response and PD extensions."""
def _log_inputs(
self,
request_id: str,
inputs: Any,
params: Any,
lora_request: Any,
) -> None:
_response_mm_placeholders.set(_extract_mm_placeholders(inputs))
super()._log_inputs(request_id, inputs, params, lora_request)
"""ServingTokens with compact routed experts."""
async def serve_tokens_full_generator( # type: ignore[override]
self,
@@ -122,22 +73,15 @@ class PrimeRlServingTokens(ServingTokens):
)
result_generator = routed_experts
prompt_capture = _PromptTokenIdsCapture(result_generator)
response = await super().serve_tokens_full_generator(
request,
prompt_capture,
result_generator,
request_id,
model_name,
request_metadata,
)
if not isinstance(response, GenerateResponse):
return response
if routed_experts is not None:
if routed_experts is not None and isinstance(response, GenerateResponse):
response = routed_experts.post_process(response)
else:
response = PrimeRlGenerateResponse(**response.model_dump())
response.prompt_token_ids = prompt_capture.prompt_token_ids
response.mm_placeholders = _response_mm_placeholders.get()
return response
+145 -19
View File
@@ -1,17 +1,22 @@
from __future__ import annotations
import asyncio
import fcntl
import os
import time
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Callable, Iterator
import orjson
import prime_runs as pr
from prime_sandboxes import Config as PrimeConfig
from prime_rl.configs.monitors import PrimeEvalMonitorConfig, PrimeTrainMonitorConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_platform_run_path
from prime_rl.utils.utils import sanitize
@@ -28,12 +33,18 @@ FINISH_TIMEOUT = 60.0
def write_platform_record(output_dir: Path, record: dict[str, Any]) -> None:
"""Leave the run's platform identity in the run directory for the dashboard's
"view on platform" link (atomic replace: a reader never sees a torn file)."""
"view on platform" link (atomic replace: a reader never sees a torn file).
The tmp file is pid-suffixed: the trainer and the online-eval process
share the run directory, and two writers sharing one tmp path can tear
each other's staged file mid-write."""
path = get_platform_run_path(output_dir)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".json.tmp")
tmp.write_bytes(orjson.dumps(record, option=orjson.OPT_INDENT_2))
tmp.replace(path)
tmp = path.with_suffix(f".json.tmp.{os.getpid()}")
try:
tmp.write_bytes(orjson.dumps(record, option=orjson.OPT_INDENT_2))
tmp.replace(path)
finally:
tmp.unlink(missing_ok=True)
def read_platform_record(output_dir: Path) -> dict[str, Any] | None:
@@ -41,6 +52,73 @@ def read_platform_record(output_dir: Path) -> dict[str, Any] | None:
return orjson.loads(path.read_bytes()) if path.is_file() else None
# Bounded wait for the record lock: a blocking flock(LOCK_EX) would stall the
# async event-loop thread for as long as the other writer holds the lock.
RECORD_LOCK_TIMEOUT = 10.0
RECORD_LOCK_POLL = 0.05
@contextmanager
def _platform_record_lock(output_dir: Path) -> Iterator[None]:
"""Cross-process read-modify-write lock for the platform record: the
trainer and the online-eval process merge into the SAME run.json, and an
unlocked read-modify-write lets one clobber the other's snapshot. POSIX
flock on a sibling .lock file. The lock file is NEVER unlinked: a waiting
writer can still hold the unlinked inode's lock while a new writer
creates and locks a fresh file — two simultaneous "exclusive" locks and
a lost merge; a stable lock inode is the whole guarantee. Acquisition is
BOUNDED (`RECORD_LOCK_TIMEOUT`), retried with non-blocking flock so the
async event-loop thread never blocks; `TimeoutError` past the bound.
Storage errors that make locking impossible (e.g. ENOLCK) raise
immediately instead of retrying."""
path = get_platform_run_path(output_dir)
path.parent.mkdir(parents=True, exist_ok=True)
lock_path = path.with_suffix(path.suffix + ".lock")
with open(lock_path, "a+b") as lock_file:
deadline = time.monotonic() + RECORD_LOCK_TIMEOUT
while True:
try:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except BlockingIOError:
if time.monotonic() >= deadline:
raise TimeoutError(f"platform record lock at {lock_path} still held after {RECORD_LOCK_TIMEOUT}s")
time.sleep(RECORD_LOCK_POLL)
try:
yield
finally:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
def _merge_platform_record(
output_dir: Path,
merge: Callable[[dict[str, Any]], dict[str, Any]],
) -> None:
"""Best-effort locked read-modify-write of the platform record: run
`merge` on the current record under the record lock and atomically
replace the file. The record only backs the dashboard's "view on
platform" link, so a lock or storage failure (TimeoutError, ENOLCK, ...)
is logged and SKIPPED, never fatal to training; the dashboard just misses
the link for that run."""
try:
with _platform_record_lock(output_dir):
write_platform_record(output_dir, merge(read_platform_record(output_dir) or {}))
except OSError:
get_logger().warning(
f"Failed to persist the platform record at {get_platform_run_path(output_dir)} "
f"(lock or storage error); the dashboard's platform link may be missing. "
f"Training continues."
)
def update_platform_record(output_dir: Path, update: dict[str, Any]) -> None:
"""Best-effort locked read-modify-write of the platform record: `update`
overlays the current record (preserving keys it doesn't set). Use for
every writer that shares the file — a naive overwrite drops concurrent
writers' keys."""
_merge_platform_record(output_dir, lambda record: {**record, **update})
def _base_url() -> str | None:
"""$PRIME_API_BASE historically points at the RFT API root (``.../api/v1/rft``);
the SDK takes the platform base URL. Unset means the SDK resolves it."""
@@ -54,8 +132,12 @@ class PrimeTrainMonitor(Monitor):
The run handle owns what ``TrainRun`` used to do by hand: the RFT
lifecycle (register or attach, finalize), the per-step metrics POSTs, the
every-10th-step Parquet sample uploads (presign -> PUT -> confirm), and
the terminal status — a process that exits without finalizing is reported
crashed by the SDK's atexit hook, replacing the old ``_mark_failed`` one.
the terminal status. Delivery is BEST-EFFORT: the SDK's atexit hook
reports a process that exits without finalizing, but an abrupt kill
(SIGKILL, OOM, node loss) skips the hook and a lost finalize is not
retried here — the platform owns the terminal state of attached
($RUN_ID) and managed runs. `FINISH_TIMEOUT` bounds the queued-upload
drain, not the SDK's finalize HTTP retries.
``init``/``finish`` do network I/O and run in worker threads; the log
calls are queue puts onto the SDK's uploader thread, which owns retries
@@ -69,9 +151,25 @@ class PrimeTrainMonitor(Monitor):
init_kwargs: dict[str, Any]
if run_id := os.getenv("RUN_ID"):
# A managed launch pre-created the platform run and injected its id -
# attach instead of registering a duplicate. The backend owns the run's
# failure marking then; a clean finish() still marks it completed.
# attach instead of registering a duplicate. The platform owns the
# attached run's failure/completion marking; a clean finish() is
# delivered best-effort and does not by itself mark it completed.
init_kwargs = {"id": run_id}
elif isinstance(config, SFTConfig):
# SFT trains on a dataset, not on environments, and has no rollouts - the
# platform run is registered without both.
init_kwargs = dict(
name=self.config.name,
model=config.model.name,
environments=[],
training=pr.TrainingSpec(
max_steps=config.max_steps or 0,
batch_size=config.data.batch_size,
seq_len=config.data.seq_len,
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
),
config=config.model_dump(exclude_none=True, mode="json"),
)
elif config is not None:
init_kwargs = dict(
name=self.config.name,
@@ -80,7 +178,9 @@ class PrimeTrainMonitor(Monitor):
training=pr.TrainingSpec(
max_steps=config.max_steps or 0,
batch_size=config.batch_size,
rollouts_per_example=config.group_size,
rollouts_per_example=max(
(source.group_size for source in config.train.source), default=config.train.group_size
),
seq_len=config.seq_len,
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
),
@@ -107,7 +207,15 @@ class PrimeTrainMonitor(Monitor):
attached = " (attached via $RUN_ID)" if self.run.attached else ""
self.logger.info(f"Logging metrics and episodes to platform run {self.run.id} ({self.run.url}){attached}")
if output_dir is not None:
write_platform_record(output_dir, {"kind": "train", "id": self.run.id, "url": self.run.url})
# Merge, not overwrite: a concurrent eval process (SFT
# online evals share the trainer's run dir) may already
# have written its evaluations record. Off the event
# loop: the flock retry must not stall it.
await asyncio.to_thread(
update_platform_record,
output_dir,
{"kind": "train", "id": self.run.id, "url": self.run.url},
)
else:
self.logger.info(f"Platform run disabled ({pr.MODE_ENV}=disabled)")
@@ -170,7 +278,19 @@ class PrimeEvalMonitor(Monitor):
if self.mode == "online":
self.logger.info("Streaming eval epochs to the Prime platform")
if output_dir is not None:
write_platform_record(output_dir, {"kind": "eval", "run_id": self.run_id, "evaluations": {}})
# Merge, not overwrite: when the eval process shares the
# trainer's run dir (SFT online evals), the train record's
# platform link (kind/id/url) must survive; a standalone
# eval keeps the plain eval-shaped record. Locked RMW.
def _eval_init_update(record: dict[str, Any]) -> dict[str, Any]:
if record.get("kind") == "train":
record.setdefault("evaluations", {})
record["run_id"] = self.run_id
return record
return {"kind": "eval", "run_id": self.run_id, "evaluations": {}}
# Off the event loop: the flock retry must not stall it.
await asyncio.to_thread(_merge_platform_record, output_dir, _eval_init_update)
else:
self.logger.info(f"Platform evaluations disabled ({pr.MODE_ENV}=disabled)")
@@ -229,13 +349,19 @@ class PrimeEvalMonitor(Monitor):
attached = f" (attached via ${EVAL_ID_VAR})" if run.attached else ""
self.logger.info(f"Streaming {env_name} (Step {step}) evaluation - {run.url}{attached}")
if self.output_dir is not None:
record = read_platform_record(self.output_dir) or {
"kind": "eval",
"run_id": self.run_id,
"evaluations": {},
}
record["evaluations"][env_name] = {"step": step, "id": run.id, "url": run.url}
write_platform_record(self.output_dir, record)
def _eval_epoch_update(record: dict[str, Any]) -> dict[str, Any]:
record.setdefault("kind", "eval")
record.setdefault("run_id", self.run_id)
record.setdefault("evaluations", {})[env_name] = {
"step": step,
"id": run.id,
"url": run.url,
}
return record
# Off the event loop: the flock retry must not stall it.
await asyncio.to_thread(_merge_platform_record, self.output_dir, _eval_epoch_update)
return run
async def log_eval_plan(self, env_name: str, step: int, expected: int) -> None:
+1 -4
View File
@@ -159,9 +159,7 @@ class TrainEnv(Env):
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
# Truncated policy sampling must ship the sampling masks the trainer replays.
self.requires_sampling_masks = (
config.sampling.truncates_distribution()
and config.algo is not None
and config.algo.sampling.source == "policy"
config.sampling.truncates_distribution() and config.algo.sampling.source == "policy"
)
@@ -235,7 +233,6 @@ class TrainEnvs(Envs[TrainEnv]):
):
self._envs: dict[str, TrainEnv] = {}
for config in configs:
assert config.algo is not None, "TrainSourceConfig.algo must be resolved before env construction"
get_logger().info(f"Initializing {config.algo.type} algorithm for {config.resolved_name}")
env = TrainEnv(
config,
+1 -1
View File
@@ -224,7 +224,7 @@ class Orchestrator:
set_base_sandbox_labels([self.run_name])
if config.heartbeat is not None:
self.heart = Heartbeat(config.heartbeat.url)
self.heart = Heartbeat(config.heartbeat)
config_dir = get_config_dir(config.output_dir)
self.train_envs = TrainEnvs(
@@ -252,6 +252,9 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
PORT=$PREFILL_PORT
HEAD_HOST="${HOSTNAMES[$((REPLICA_BASE + SUB_REPLICA * NODES_PER_PREFILL_REPLICA))]}"
# vLLM >= 0.29 auto-enables breakable CUDA graphs; capturing the DeepEP
# high-throughput internode dispatch then fails ("timeout (dispatch CPU)").
export VLLM_USE_BREAKABLE_CUDAGRAPH=0
{% for key, value in prefill_env_vars.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
@@ -396,6 +396,9 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
PORT=$PREFILL_PORT
START_RANK=$((ROLE_RANK * INFERENCE_DP_LOCAL))
HEAD_HOST="${HOSTNAMES[$((REPLICA_BASE + SUB_REPLICA * NODES_PER_PREFILL_REPLICA))]}"
# vLLM >= 0.29 auto-enables breakable CUDA graphs; capturing the DeepEP
# high-throughput internode dispatch then fails ("timeout (dispatch CPU)").
export VLLM_USE_BREAKABLE_CUDAGRAPH=0
{% for key, value in prefill_env_vars.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
@@ -69,6 +69,9 @@ DEFAULT_SELECTIVE_SAVE_OPERATIONS = frozenset(
"prime_rl::fp8_blockwise_mm",
"prime_rl::grouped_fp8_gemm",
"prime_rl::sparse_mla",
"quack::gemm_act_out",
"quack::gemm_gated_out",
"quack::gemm_out",
}
)
# An operation target matches one qualified operator name, while a namespace
+11 -3
View File
@@ -19,6 +19,7 @@ from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
from torch.distributed.device_mesh import DeviceMesh
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
from torch.distributed.tensor import Shard
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, PretrainedConfig
from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.utils.import_utils import is_flash_attn_3_available
@@ -504,7 +505,16 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=DTYPE_MAP[config.reduce_dtype])
offload_policy: OffloadPolicy = CPUOffloadPolicy(pin_memory=True) if config.fsdp_cpu_offload else OffloadPolicy()
shard_placement_fn = get_fsdp_shard_placement_fn(model) if config.fusions.shard_fused_on_dim1 else None
fused_shard_placement_fn = get_fsdp_shard_placement_fn(model) if config.fusions.shard_fused_on_dim1 else None
hsdp_mesh = parallel_dims.get_mesh("hsdp")
shard_size = parallel_dims.get_mesh("dp_shard_cp").size()
def shard_placement_fn(parameter: nn.Parameter) -> Shard | None:
# Qwen's single-row shared-expert gates need equal shards for Muon's all-to-all.
if parameter.ndim == 2 and parameter.shape[0] == 1 and parameter.shape[1] % shard_size == 0:
return Shard(1)
return fused_shard_placement_fn(parameter) if fused_shard_placement_fn is not None else None
fsdp_config = {
"mp_policy": mp_policy,
"offload_policy": offload_policy,
@@ -512,8 +522,6 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
"shard_placement_fn": shard_placement_fn,
}
hsdp_mesh = parallel_dims.get_mesh("hsdp")
dp_mod_ep_mesh: DeviceMesh | None = None
if parallel_dims.ep_enabled:
dp_mod_ep_mesh_dim_names = []
@@ -0,0 +1,112 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from collections.abc import Callable
from functools import partial
from types import ModuleType
from typing import TYPE_CHECKING, Protocol
import torch
from torch.distributed.tensor import DTensor
if TYPE_CHECKING:
from prime_rl.trainer.models.layers.moe import GroupedExperts
class ExpertCompute(Protocol):
token_group_alignment: int
def validate(self, experts: "GroupedExperts") -> None: ...
def __call__(
self, experts: "GroupedExperts", x: torch.Tensor, num_tokens_per_expert: torch.Tensor
) -> torch.Tensor: ...
def broadcast_expert_bias(
bias: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
target_rows: int,
) -> torch.Tensor:
repeats = num_tokens_per_expert.to(torch.int64)
padding_rows = repeats.new_tensor(target_rows) - repeats.sum()
return torch.repeat_interleave(
torch.cat((bias, bias.new_zeros((1, bias.shape[1])))),
torch.cat((repeats, padding_rows.unsqueeze(0))),
dim=0,
output_size=target_rows,
)
class GroupedGemmExpertCompute:
def __init__(
self,
gemm: Callable[[torch.Tensor, torch.Tensor, torch.Tensor], torch.Tensor],
token_group_alignment: int = 8,
) -> None:
self.gemm = gemm
self.token_group_alignment = token_group_alignment
def validate(self, experts: "GroupedExperts") -> None:
"""The shared forward handles the experts' activation, biases, and weight layout."""
def __call__(self, experts: "GroupedExperts", x: torch.Tensor, num_tokens_per_expert: torch.Tensor) -> torch.Tensor:
assert x.dim() == 2
def to_local(tensor: torch.Tensor) -> torch.Tensor:
return tensor.to_local() if isinstance(tensor, DTensor) else tensor
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
x_bf16 = x.bfloat16()
if experts.gate_up_proj is None:
up_proj = to_local(experts.up_proj).transpose(-2, -1)
up = self.gemm(x_bf16, up_proj.bfloat16(), offsets)
gate = None
if experts.gate_proj is not None:
gate_proj = to_local(experts.gate_proj).transpose(-2, -1)
gate = self.gemm(x_bf16, gate_proj.bfloat16(), offsets)
else:
gate_up_proj = to_local(experts.gate_up_proj).transpose(-2, -1)
gate_up = self.gemm(x_bf16, gate_up_proj.bfloat16(), offsets)
gate, up = gate_up.chunk(2, dim=-1)
if experts.up_proj_bias is not None:
up_proj_bias = to_local(experts.up_proj_bias)
up = up + broadcast_expert_bias(up_proj_bias, num_tokens_per_expert, up.shape[0]).bfloat16()
if gate is not None and experts.gate_proj_bias is not None:
gate_proj_bias = to_local(experts.gate_proj_bias)
gate = gate + broadcast_expert_bias(gate_proj_bias, num_tokens_per_expert, gate.shape[0]).bfloat16()
hidden = experts.activation.apply(gate, up)
down_proj = to_local(experts.down_proj).transpose(-2, -1)
output = self.gemm(hidden, down_proj.bfloat16(), offsets)
if experts.down_proj_bias is not None:
down_proj_bias = to_local(experts.down_proj_bias)
output = output + broadcast_expert_bias(down_proj_bias, num_tokens_per_expert, output.shape[0]).bfloat16()
return output.type_as(x)
class BF16ExpertCompute(GroupedGemmExpertCompute):
def __init__(self) -> None:
super().__init__(torch._grouped_mm)
class DeepGemmFP8ExpertCompute(GroupedGemmExpertCompute):
def __init__(self) -> None:
from prime_rl.trainer.models.layers.fp8_grouped_gemm import grouped_fp8_gemm
super().__init__(grouped_fp8_gemm)
class MXFP8ExpertCompute(GroupedGemmExpertCompute):
def __init__(self, kernel: ModuleType, high_precision_wgrad: bool) -> None:
super().__init__(
partial(kernel.grouped_gemm, high_precision_wgrad=high_precision_wgrad),
token_group_alignment=kernel.TOKEN_GROUP_ALIGNMENT,
)
@@ -1,68 +0,0 @@
from dataclasses import dataclass
from types import ModuleType
from typing import Protocol
import torch
class GroupedGemm(Protocol):
token_group_alignment: int
def __call__(
self,
x: torch.Tensor,
weight_t: torch.Tensor,
*,
offs: torch.Tensor,
) -> torch.Tensor: ...
@dataclass(frozen=True)
class BF16GroupedGemm:
token_group_alignment: int = 8
def __call__(
self,
x: torch.Tensor,
weight_t: torch.Tensor,
*,
offs: torch.Tensor,
) -> torch.Tensor:
return torch._grouped_mm(x, weight_t, offs=offs)
@dataclass(frozen=True)
class DeepGemmFP8GroupedGemm:
token_group_alignment: int = 8
def __call__(
self,
x: torch.Tensor,
weight_t: torch.Tensor,
*,
offs: torch.Tensor,
) -> torch.Tensor:
from prime_rl.trainer.models.layers.fp8_grouped_gemm import grouped_fp8_gemm
return grouped_fp8_gemm(x, weight_t, offs)
@dataclass(frozen=True)
class MXFP8GroupedGemm:
kernel: ModuleType
high_precision_wgrad: bool
token_group_alignment: int
def __call__(
self,
x: torch.Tensor,
weight_t: torch.Tensor,
*,
offs: torch.Tensor,
) -> torch.Tensor:
return self.kernel.grouped_gemm(
x,
weight_t,
offs,
high_precision_wgrad=self.high_precision_wgrad,
)
@@ -5,11 +5,9 @@ from torch import nn
from torch.distributed.tensor import DTensor
from prime_rl.trainer.models.layers.activations import ClampedSwiglu
from prime_rl.trainer.models.layers.expert_compute import broadcast_expert_bias
from prime_rl.trainer.models.layers.lora.base import MultiLoRAModule, get_lora_num_tokens, get_multilora_scaling
from prime_rl.trainer.models.layers.moe import (
GroupedExperts,
broadcast_expert_bias,
)
from prime_rl.trainer.models.layers.moe import GroupedExperts
def _run_lora_grouped_mm(
+9 -59
View File
@@ -10,12 +10,11 @@ from typing import Literal
import torch
import torch.nn.functional as F
from torch import nn
from torch.distributed.tensor import DTensor
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher, TokenDispatcher
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
from prime_rl.trainer.models.layers.grouped_gemm import BF16GroupedGemm, GroupedGemm
from prime_rl.trainer.models.layers.expert_compute import BF16ExpertCompute, ExpertCompute
from prime_rl.trainer.models.layers.mlp import ExpertType, FeedForward
ScoreFuncType = Literal["softmax", "sigmoid", "topk_softmax"]
@@ -67,21 +66,6 @@ class MoEArgs:
ActivationDispatch[self.activation]
def broadcast_expert_bias(
bias: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
target_rows: int,
) -> torch.Tensor:
repeats = num_tokens_per_expert.to(torch.int64)
padding_rows = repeats.new_tensor(target_rows) - repeats.sum()
return torch.repeat_interleave(
torch.cat((bias, bias.new_zeros((1, bias.shape[1])))),
torch.cat((repeats, padding_rows.unsqueeze(0))),
dim=0,
output_size=target_rows,
)
class GroupedExperts(nn.Module):
supported_fusions = {"gate_up": fuse_gate_up_projections}
@@ -94,7 +78,7 @@ class GroupedExperts(nn.Module):
expert_type: ExpertType = "gated",
activation: ActivationType = "silu",
bias: bool = False,
grouped_gemm: GroupedGemm | None = None,
compute: ExpertCompute | None = None,
):
super().__init__()
self.num_experts = num_experts
@@ -109,59 +93,25 @@ class GroupedExperts(nn.Module):
self.up_proj_bias = nn.Parameter(torch.empty(num_experts, hidden_dim)) if bias else None
self.down_proj_bias = nn.Parameter(torch.empty(num_experts, dim)) if bias else None
self.grouped_gemm = grouped_gemm or BF16GroupedGemm()
self.activation = ActivationDispatch[activation]
if expert_type == "non_gated":
self.supported_fusions = {}
self.set_compute(compute or BF16ExpertCompute())
def set_compute(self, compute: ExpertCompute) -> None:
compute.validate(self)
self.compute = compute
@property
def token_group_alignment(self) -> int:
return self.grouped_gemm.token_group_alignment
def set_grouped_gemm(self, grouped_gemm: GroupedGemm) -> None:
self.grouped_gemm = grouped_gemm
return self.compute.token_group_alignment
def forward(
self,
x: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
) -> torch.Tensor:
assert x.dim() == 2
def to_local(tensor: torch.Tensor) -> torch.Tensor:
return tensor.to_local() if isinstance(tensor, DTensor) else tensor
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
x_bf16 = x.bfloat16()
if self.gate_up_proj is None:
up_proj = to_local(self.up_proj).transpose(-2, -1)
up = self.grouped_gemm(x_bf16, up_proj.bfloat16(), offs=offsets)
gate = None
if self.gate_proj is not None:
gate_proj = to_local(self.gate_proj).transpose(-2, -1)
gate = self.grouped_gemm(x_bf16, gate_proj.bfloat16(), offs=offsets)
else:
gate_up_proj = to_local(self.gate_up_proj).transpose(-2, -1)
gate_up = self.grouped_gemm(x_bf16, gate_up_proj.bfloat16(), offs=offsets)
gate, up = gate_up.chunk(2, dim=-1)
if self.up_proj_bias is not None:
up_proj_bias = to_local(self.up_proj_bias)
up = up + broadcast_expert_bias(up_proj_bias, num_tokens_per_expert, up.shape[0]).bfloat16()
if gate is not None and self.gate_proj_bias is not None:
gate_proj_bias = to_local(self.gate_proj_bias)
gate = gate + broadcast_expert_bias(gate_proj_bias, num_tokens_per_expert, gate.shape[0]).bfloat16()
hidden = self.activation.apply(gate, up)
down_proj = to_local(self.down_proj).transpose(-2, -1)
output = self.grouped_gemm(hidden, down_proj.bfloat16(), offs=offsets)
if self.down_proj_bias is not None:
down_proj_bias = to_local(self.down_proj_bias)
output = output + broadcast_expert_bias(down_proj_bias, num_tokens_per_expert, output.shape[0]).bfloat16()
return output.type_as(x)
return self.compute(self, x, num_tokens_per_expert)
def init_weights(self, init_std: float):
if self.gate_up_proj is None:
@@ -0,0 +1,55 @@
from typing import TYPE_CHECKING
import torch
from sonicmoe import moe_general_routing_inputs
from sonicmoe.enums import ActivationType
from torch.distributed.tensor import DTensor
from prime_rl.trainer.models.layers.activations import Silu
if TYPE_CHECKING:
from prime_rl.trainer.models.layers.moe import GroupedExperts
class SonicMoEExpertCompute:
token_group_alignment = 8
def validate(self, experts: "GroupedExperts") -> None:
if experts.gate_up_proj is None:
raise ValueError(
"SonicMoE requires gated experts with fused gate/up projections. Enable the gate_up fusion."
)
if experts.activation is not Silu:
raise ValueError(
"SonicMoE requires standard SwiGLU (silu); custom or clamped activations are not supported."
)
if any(bias is not None for bias in (experts.gate_proj_bias, experts.up_proj_bias, experts.down_proj_bias)):
raise ValueError("SonicMoE requires bias-free experts.")
def __call__(self, experts: "GroupedExperts", x: torch.Tensor, num_tokens_per_expert: torch.Tensor) -> torch.Tensor:
gate_up = experts.gate_up_proj
down = experts.down_proj
if isinstance(gate_up, DTensor):
gate_up = gate_up.to_local()
down = down.to_local()
token_indices = torch.arange(x.shape[0], dtype=torch.int32, device=x.device)
offsets = num_tokens_per_expert.cumsum(0, dtype=torch.int32)
expert_indices = torch.searchsorted(offsets, token_indices, right=True)
# Dispatch discards the trailing padding beyond the per-expert counts.
expert_indices = expert_indices.clamp_max(gate_up.shape[0] - 1).to(torch.int32)
output, _ = moe_general_routing_inputs(
x=x.bfloat16(),
router_scores=torch.ones(x.shape[0], dtype=torch.float32, device=x.device),
token_indices=token_indices,
expert_indices=expert_indices,
w1=gate_up.bfloat16().permute(1, 2, 0),
b1=None,
w2=down.bfloat16().permute(1, 2, 0),
b2=None,
E=gate_up.shape[0],
stream_id=0,
activation_type=ActivationType.SWIGLU,
concat_layout=True,
)
return output.type_as(x)
+23 -20
View File
@@ -19,11 +19,11 @@ from prime_rl.trainer.distributed.token_dispatcher import (
MXFP8TorchTokenDispatcher,
TorchTokenDispatcher,
)
from prime_rl.trainer.models.layers.grouped_gemm import (
BF16GroupedGemm,
DeepGemmFP8GroupedGemm,
GroupedGemm,
MXFP8GroupedGemm,
from prime_rl.trainer.models.layers.expert_compute import (
BF16ExpertCompute,
DeepGemmFP8ExpertCompute,
ExpertCompute,
MXFP8ExpertCompute,
)
from prime_rl.trainer.models.layers.moe import MoE
from prime_rl.trainer.parallel_dims import ParallelDims
@@ -31,10 +31,14 @@ from prime_rl.utils.logger import get_logger
from prime_rl.utils.vlm import get_language_model
def _resolve_grouped_gemm(config: ModelConfig) -> GroupedGemm:
def _resolve_expert_compute(config: ModelConfig) -> ExpertCompute:
compute = config.moe.compute
if isinstance(compute, BF16MoEComputeConfig):
return BF16GroupedGemm()
if compute.backend == "sonicmoe":
from prime_rl.trainer.models.layers.sonic_moe import SonicMoEExpertCompute
return SonicMoEExpertCompute()
return BF16ExpertCompute()
if isinstance(compute, DeepGemmFP8MoEComputeConfig):
if importlib.util.find_spec("deep_gemm") is None:
raise RuntimeError("DeepGEMM FP8 expert compute requires the deep-gemm package.")
@@ -43,15 +47,14 @@ def _resolve_grouped_gemm(config: ModelConfig) -> GroupedGemm:
raise RuntimeError(
f"DeepGEMM FP8 expert compute requires SM90 or newer, but this device is SM{capability[0]}{capability[1]}."
)
return DeepGemmFP8GroupedGemm()
return DeepGemmFP8ExpertCompute()
if isinstance(compute, MXFP8MoEComputeConfig):
import prime_kernels
kernel = prime_kernels.load("mxfp8_moe")
return MXFP8GroupedGemm(
return MXFP8ExpertCompute(
kernel=kernel,
high_precision_wgrad=compute.recipe == "mxfp8_rceil_wgrad_with_hp",
token_group_alignment=kernel.TOKEN_GROUP_ALIGNMENT,
)
raise TypeError(f"Unsupported MoE compute config: {type(compute).__name__}")
@@ -77,37 +80,37 @@ def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims:
if isinstance(module, MoE)
}
get_logger().debug(f"Selected model layers for MoE compute: {sorted(selected_layers)}")
bf16_grouped_gemm = BF16GroupedGemm()
selected_grouped_gemm = _resolve_grouped_gemm(config) if selected_moes else bf16_grouped_gemm
bf16_compute = BF16ExpertCompute()
selected_compute = _resolve_expert_compute(config) if selected_moes else bf16_compute
ep_mesh = parallel_dims.get_mesh("ep") if parallel_dims.ep_enabled else None
dispatch = config.moe.dispatch
for moe in moe_layers:
grouped_gemm = selected_grouped_gemm if moe in selected_moes else bf16_grouped_gemm
compute = selected_compute if moe in selected_moes else bf16_compute
if ep_mesh is not None and moe.experts.num_experts % parallel_dims.ep:
raise ValueError(
f"MoE expert count {moe.experts.num_experts} must be divisible by model.ep={parallel_dims.ep}."
)
moe.experts.set_grouped_gemm(grouped_gemm)
moe.experts.set_compute(compute)
if ep_mesh is None:
token_dispatcher = LocalTokenDispatcher(
num_experts=moe.experts.num_experts,
top_k=moe.router.top_k,
token_group_alignment=grouped_gemm.token_group_alignment,
token_group_alignment=compute.token_group_alignment,
)
elif isinstance(dispatch, TorchMoEDispatchConfig):
if dispatch.transport == "mxfp8" and isinstance(grouped_gemm, MXFP8GroupedGemm):
if dispatch.transport == "mxfp8" and isinstance(compute, MXFP8ExpertCompute):
token_dispatcher = MXFP8TorchTokenDispatcher(
num_experts=moe.experts.num_experts,
top_k=moe.router.top_k,
token_group_alignment=grouped_gemm.token_group_alignment,
token_group_alignment=compute.token_group_alignment,
group=ep_mesh.get_group(),
)
else:
token_dispatcher = TorchTokenDispatcher(
num_experts=moe.experts.num_experts,
top_k=moe.router.top_k,
token_group_alignment=grouped_gemm.token_group_alignment,
token_group_alignment=compute.token_group_alignment,
group=ep_mesh.get_group(),
)
elif isinstance(dispatch, DeepEPMoEDispatchConfig):
@@ -115,7 +118,7 @@ def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims:
token_dispatcher = DeepEPTokenDispatcher(
num_experts=moe.experts.num_experts,
token_group_alignment=grouped_gemm.token_group_alignment,
token_group_alignment=compute.token_group_alignment,
group=ep_mesh.get_group(),
num_sms=dispatch.num_sms,
token_chunk_size=dispatch.token_chunk_size,
@@ -128,6 +131,6 @@ def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims:
parallelize_module(moe.experts, device_mesh=ep_mesh, parallelize_plan=ExpertWeightParallel())
get_logger().info(
f"Configured {len(selected_moes)}/{len(moe_layers)} MoE layers with compute={config.moe.compute.type}, "
f"Configured {len(selected_moes)}/{len(moe_layers)} MoE layers with compute={type(selected_compute).__name__}, "
f"apply_to={config.moe.compute.apply_to}, fallback=bf16, dispatch={config.moe.dispatch.type}, ep={parallel_dims.ep}"
)

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