Compare commits

...
Author SHA1 Message Date
9fff742eae Allow eval.retrigger_on_resume with an in-memory weight broadcast (#4007)
## Problem

`eval.retrigger_on_resume` is rejected at config-validation time unless
`weight_broadcast.type == "filesystem"`:

```python
if self.eval.retrigger_on_resume:
    raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
```

With the default `nccl` transport the flag is therefore unusable, and
resuming an SFT run at an interval-aligned step silently skips that
step's evals: the trainer broadcasts the resume checkpoint at startup
and the evals process loads it, but nothing re-fires, so the next eval
is a full interval away and the step resumed from is never evaluated.

## Why the gate isn't needed

The in-memory path already meets the precondition the gate was
protecting. `OnlineEval.watch()` rendezvouses with the trainer's startup
broadcast before the re-fire, for every transport:

```python
startup_step = config.resume_step or 0
await self.receiver.sync_startup(startup_step, timeout=STARTUP_BROADCAST_TIMEOUT_S)
```

and `sync_startup` is transport-agnostic in
`transports/weights/base.py`:

```python
async def sync_startup(self, step: int, timeout: float) -> None:
    await asyncio.wait_for(self.wait_published(step), timeout=timeout)
    await self.receive(step)
```

So by the time `maybe_run_eval(step=config.resume_step)` runs, the
served weights are already the resume checkpoint's — and that call
passes `reload_weights=False`, so it never needs to re-read them from
disk, which is the only thing a filesystem broadcast would have added.

Cancellation is unchanged: the re-fired epoch gets the usual
`superseding_step` callback, so a newer broadcast supersedes it exactly
as for any other eval epoch.

NIXL remains rejected by the check immediately above. The RL
orchestrator already honours `retrigger_on_resume` with no transport
restriction, so this also removes an SFT/RL inconsistency.

## Change

Two-line deletion. No tests assert the removed error.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Config-validation-only change; removes an overly strict guard with no
runtime logic changes.
> 
> **Overview**
> **Allows `eval.retrigger_on_resume` with NCCL (in-memory) weight
broadcast for SFT online evals.**
> 
> SFT config validation no longer raises when `retrigger_on_resume` is
set alongside non-filesystem `weight_broadcast` (e.g. default `nccl`).
Resuming at an interval-aligned step can re-fire that step’s evals
without forcing `weight_broadcast.type = 'filesystem'`. **LoRA +
in-memory broadcast** and **NIXL** restrictions in the same block are
unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
acf86f21d9345e3677852baaefe690f73b938026. 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 (1M context) <noreply@anthropic.com>
2026-10-11 13:30:16 +01:00
HubertandGitHub 73140dec35 fix(trainer): keep Qwen3.5 CP context setup eager (#4011)
Qwen3.5 training with context parallelism can fail on the first forward
after #3925 places compilation inside activation checkpointing. FLA's CP
setup reads tensor-valued sequence boundaries and calls
`torch.searchsorted`; Inductor fails to specialize the resulting scalar:

```
GuardOnDataDependentSymNode:
Could not extract specialized integer from data-dependent expression (u0//4)
```

Wrap `build_cp_context` with `torch.compiler.disable`, alongside the
existing eager CP convolution wrapper. CP setup runs eagerly while the
surrounding block remains eligible for compilation. CP calculations,
model parameters and checkpointing settings are unchanged.

Validation ran on an allocated India H200 compute node with PyTorch
2.13.0+cu130 and FLA 0.5.2. A bounded CUDA/FSDP/checkpoint reproducer
used two sequence-boundary fixtures and logical CP size 4:

| Layout | Result | Maximum absolute
output/input-gradient/parameter-gradient difference vs eager |
| --- | --- | --- |
| Earlier outer compilation | Pass | 0 |
| Inner compilation introduced by #3925 | Same `(u0//4)` compiler
failure | — |
| Inner compilation with eager FLA CP metadata | Pass |
1.9073486328125e-6 |

This reproducer uses one CUDA/FSDP rank; it does not exercise real
four-rank CP collectives or a full Qwen training step. Full distributed
training validation remains outstanding. Ruff and `git diff --check`
passed for the patch. No test or experiment files are included in this
diff.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Narrow trainer workaround for a known torch.compile + FLA CP setup
issue; behavior matches eager CP setup with negligible numeric drift in
repro.
> 
> **Overview**
> Fixes Qwen3.5 **context-parallel (CP)** training failures when the
block is compiled inside activation checkpointing (#3925). Inductor
cannot specialize scalars from FLA’s `build_cp_context`
(`torch.searchsorted` on tensor sequence boundaries), which triggers
`GuardOnDataDependentSymNode`.
> 
> The change wraps **`build_cp_context`** with
**`torch.compiler.disable`** (same pattern as the existing eager CP
**`causal_conv1d`** wrapper) and calls **`build_cp_context_eager`** in
the forward path when CP is enabled. CP math, parameters, and
checkpointing are unchanged; only CP metadata setup runs outside the
compiled graph.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c192fc98cedc342e16af9307577f38fa77213b4e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 16:05:14 -07:00
0936378085 refactor(configs)!: one model.offload field for CPU offloading (#3988)
Replaces the three switches `model.fsdp_cpu_offload`,
`model.optim_cpu_offload` and `model.full_offload` with one field:

```toml
[model]
offload = "optimizer"   # default; also "full", "none"
```

This applies to both the RL trainer and SFT. The `fsdp` switch is not
migrated: the mode is removed outright (rationale below). The
`[model.full_offload] numa_bind` knob is dropped: no recipe, deployment,
template or doc sets it. Full offload now always pins each rank's CPUs
to its GPU's NUMA node. That was already the default. Ranks whose GPU
reports no NUMA node still skip binding with a warning. On hosts without
GPU sysfs topology (`/sys/bus/pci/devices/<bus>/numa_node`), binding is
no longer optional: full offload fails there instead of being switched
off.

Why: the three switches could only be used one at a time, enforced by
`cpu_offload_mutual_exclusion`. Because `optim_cpu_offload` defaulted to
`true`, enabling full offload also meant writing `optim_cpu_offload =
false`, otherwise validation failed (see the old
`configs/advanced/deepseek-v4-flash/sft.toml` comment). With one value
the conflicting combinations cannot be expressed, so that validator is
deleted. The default behaviour does not change: optimizer-state offload
stays on.

Why drop `fsdp`: the mode was the stock torch FSDP2 `CPUOffloadPolicy`
with no in-tree config, example, or test user; Muon rejected it and it
broke NCCL weight broadcast. It was kept only for long-context runs
whose fp32 masters/moments no longer fit on GPU (the reason it was
restored in #3052); the `full` mode added in #3234 keeps FP32 masters,
moments, and gradients in host RAM, covering that memory pressure
instead. Gone with it: the `CPUOffloadPolicy` selection in `setup_fsdp`,
CPU-side model init in `setup_model`/`load_dcp_from_hf`,
`_move_buffers_to_cuda`, and the fsdp leg of the Gloo special case.

Changes:
- `ModelConfig.offload: Literal["none", "optimizer", "full"] =
"optimizer"` replaces the three fields.
`OptimizerInBackwardOffloadConfig` (and with it `numa_bind`) and its
bool-normalizing `BeforeValidator` are gone.
- Validators in `TrainerConfig` and `SFTConfig`:
- full offload accepts only AdamW or SignSGD and disables clipping, now
reading `offload == "full"`;
- the `Muon optimizer does not support FSDP CPU offload` validators are
deleted with the mode.
- Runtime:
- `setup_optimizer(..., offload=...)` replaces `cpu_offload` +
`full_offload_config`, and its "both enabled" check is gone.
- `FullCPUOffloadOptimizer` drops its unused `offload_config` argument.
- `setup_full_cpu_optimizer_offload()` takes no arguments and always
binds.
- `model.py`: FSDP always uses the default `OffloadPolicy()`; CPU-side
model init in `setup_model`/`load_dcp_from_hf` and
`_move_buffers_to_cuda` are gone.
- Tomls: `glm-4.5-air/swe-budget.toml` and
`ci/integration/reverse-text-sft/full-offload-resume.toml` → `offload =
"full"`; `glm-5.3/sft/h200/16k-12-node.toml` → `offload = "none"`;
`glm-5.3/sft/h200/base.toml` → `offload = "optimizer"`. Also updated
`docs/scaling.md`, the `deepseek-v4-flash/sft.toml` comment, and
`skills/training/start-run/SKILL.md`, which documented the removed
fields.

Breaking: the old keys now fail with `extra_forbidden`, and `offload =
"fsdp"` fails the `Literal`. There is no shim.

Interaction with #3849 (one trainer-common config base): #3849 moves the
full-offload and Muon/FSDP validators from `TrainerConfig`/`SFTConfig`
onto `BaseTrainerConfig`. This PR edits the full-offload validator's
condition and deletes the Muon/FSDP one, so the conflict is textual
only: keep #3849's single copy of the full-offload validators with
`self.model.offload == "full"` and drop its Muon/FSDP copy. Whichever
lands second takes a small rebase.

Other open PRs that set or read the old keys need a rebase:
- tomls: #3883, #3879, #3766, #3765, #3729, #3629, #3627, #3616, #3544
- code: #3885 (`optim_cpu_offload`), #3739 (`full_offload` validators),
#3724, #3719, #3699, #3610, #3487 (`fsdp_cpu_offload` / `enable_gloo`)

Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/train/test_cpu_adam.py tests/unit/train/test_state_offload.py
-m "not gpu"`: 336 passed, 1 skipped (Qwen3-VL snapshot not cached on
this host), 4 deselected (GPU; this host has no GPU). The existing
offload config tests are updated to the new field. `test_load_configs`
covers the 4 edited tomls.
- `cli(TrainerConfig|SFTConfig, ...)`: `--model.offload full|none` and
the default (`optimizer`) resolve as expected; `optim_cpu_offload` and
`offload = "fsdp"` are rejected.
- `import prime_rl.trainer.rl.train, prime_rl.trainer.sft.train` works.
- `ruff check` and `ruff format --check` on the changed Python files:
clean.
- Not run: GPU or multi-node training with `offload = "full"`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking TOML/API surface touches distributed training memory paths
(FSDP offload, optimizer-in-backward, Gloo); behavior should match prior
modes when mapped correctly, but mis-migrated configs will fail at parse
time.
> 
> **Overview**
> **Breaking config change:** `model.fsdp_cpu_offload`,
`model.optim_cpu_offload`, and `model.full_offload` are replaced by a
single **`model.offload`** setting (`"optimizer"` default, or `"full"`,
`"fsdp"`, `"none"`). RL and SFT share the same field; example TOMLs and
scaling docs are updated accordingly.
> 
> The mutual-exclusion validator between the old flags is removed
because only one mode can be expressed. **`[model.full_offload]` /
`numa_bind` is dropped** — `"full"` always runs NUMA binding and CPU
optimizer thread setup via parameterless
`setup_full_cpu_optimizer_offload()`. Runtime paths (`setup_optimizer`,
FSDP CPU offload in `model.py`, Gloo when offload is `"full"` or
`"fsdp"`) key off the new enum; `FullCPUOffloadOptimizer` no longer
takes an offload config object.
> 
> Default training behavior is unchanged: optimizer-state CPU offload
remains the default (`"optimizer"`). Old TOML keys are not aliased and
should fail validation.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
35da73ad2f1a73533595a979a971b0cdd8d6e63f. 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: sami jaghouar <sami.jaghouar@gmail.com>
2026-10-10 15:39:30 -07:00
faresobeidandGitHub 41a8ed0190 feat(configs): one weight wait timeout, default 3600 s (#3980)
## What
- `weight_broadcast.timeout` default goes from 1200 s to 3600 s
(`configs/shared.py`).
- It now also bounds the orchestrator's wait for the trainer's startup
broadcast. `orchestrator.ckpt.wait_for_weights_timeout` and the
hardcoded `STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200` fallback are removed.
Configs that set the old field fail validation (`extra="forbid"`); no
in-repo config sets it.
- The `[weight_broadcast]` blocks in five recipes only repeated `type =
"nccl"` (already the `rl` default when inference is managed and LoRA is
off) and `timeout = 3600`. They are removed: glm-4.5-air
swe/swe-budget/search/terminal and nemotron-3-super swe. glm-5.3 keeps
its `timeout = 12000`.
- Orchestrator `ckpt` and `resume` docstrings: `resume` had two
docstrings and `ckpt` had none. The stray one now documents `ckpt`.

## Why
- Every large multi-node recipe raises the timeout: 3600 s in five
recipes, 12000 s in glm-5.3.
- Measured startups come close to 1200 s or pass it. GLM-4.5-Air TP8
cold start takes 465-623 s. GLM-5.3 and DeepSeek-V4 inference startup
with cudagraph capture took about 16 min.
- vLLM's own engine-ready timeout is already 4200 s
(`VLLM_ENGINE_READY_TIMEOUT_S`).
- The startup wait and the per-step waits had two knobs with the same
1200 s default. The startup one was under `ckpt`, but it applies without
`ckpt` too.
- Trade-off: a consumer that dies is detected after 60 min instead of
20.

## Overlap
- #3652 (mikasenghaas, draft) reformats the `wait_timeout = ...` line
that this PR removes. Whichever lands second has a one-line conflict.
- Rebased over #3983, which removed the neighbouring orchestrator
`ckpt.keep_last`/`keep_interval` fields. The orchestrator
`CheckpointConfig` now has only `interval`.

## Test plan
- Rebased onto origin/main 32c48f5d9. `pytest tests/unit/orchestrator
tests/unit/test_configs.py -m "not gpu"`: 335 passed. `test_configs`
validates every TOML under `configs/` and `examples/`.
- `ruff check` and `ruff format --check` on the changed files: clean.
- Resolved `RLConfig` of the 5 edited recipes, main vs this branch:
identical (apart from the checkout path in `template_path`).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes orchestrator startup behavior and timeout defaults for
trainer–inference weight sync; mis-tuned timeouts could delay failure
detection (up to 60 min) or still timeout on very slow large-model
startups.
> 
> **Overview**
> **Unifies weight-broadcast timing** so one knob
(`weight_broadcast.timeout`) covers both the trainer handshake and the
orchestrator’s wait for the trainer’s **startup** broadcast. The default
rises from **1200 s to 3600 s**, and docs note raising it for large
models on slow filesystems.
> 
> **Removes** `orchestrator.ckpt.wait_for_weights_timeout` and the
orchestrator’s `STARTUP_WEIGHT_WAIT_TIMEOUT_S` fallback; startup sync
now uses `config.weight_broadcast.timeout` in `sync_startup`.
**Orchestrator config** docstrings are fixed so `ckpt` is documented on
the right field.
> 
> **Five example/advanced recipes** drop redundant `[weight_broadcast]`
blocks that only repeated NCCL type and `timeout = 3600` (now defaults).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e318f1cb0b10a8a5507520f2c6b1176f9fbd0813. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:34:47 +01:00
faresobeidandGitHub 9cde4d74f5 fix(slurm): stop crashed multi-node RL jobs idling for an hour (#3979)
Multi-node RL jobs that crash currently sit idle for an hour.

On any non-zero exit (crash, OOM, SIGTERM, wall-time),
`multi_node_rl.sbatch.j2` ran an unconditional `sleep {{
cleanup_grace_period }}` (default 3600 s, #2670) before tearing down.
The sleep keeps the task alive so `--kill-on-bad-exit` does not reap
trainers that are mid-checkpoint. But it waits the full hour even when
no checkpoint is being written, so a crashed N-node job idles for 1 h.

Now the node waits only while the newest `checkpoints/step_*/trainer`
has no DCP `.metadata` yet, i.e. a trainer save is still in flight. It
polls every 10 s, with `cleanup_grace_period` as the cap, and tears down
as soon as that save finishes or there is none. Runs without `[ckpt]`
tear down immediately. The checkpoint dir follows `ckpt.output_dir` when
it is set. The default stays 3600 s; it is now only an upper bound.

Limitation: if the crash happens right before a save starts (step dir
not created yet), we no longer wait for that save. Only that save is
lost; the previous checkpoint is intact.

**Interaction with #3875 (requeue + step watchdog):** before this
change, every requeue of a crashed multi-node RL job first waited the
full grace period. Now it waits only for an in-flight checkpoint.
`.metadata` is the same completeness marker that #3906 uses for "latest
complete checkpoint". The SFT and inference templates do not use
`cleanup_grace_period` and are unchanged.

Test plan (all run):
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed.
- `rl @ examples/advanced/glm-4.5-air/swe.toml --dry-run`: the rendered
sbatch has the wait loop with the run's `checkpoints/` path and passes
`bash -n`. With `--no-ckpt` the loop is not rendered.
- Ran the rendered teardown snippet in bash against a temp checkpoint
dir:
  - empty dir: no wait;
  - newest step complete: no wait;
  - newest step in flight: waits until the cap;
  - older incomplete step but newest complete: no wait;
  - in-flight save that completes after 1 s: waits ~1 s.
- `ruff check` and `ruff format --check` on the changed Python files.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes multi-node job teardown timing and checkpoint detection logic;
incorrect polling could tear down early or delay allocation release, but
scope is limited to SLURM RL launcher scripts.
> 
> **Overview**
> Multi-node SLURM RL jobs no longer **sleep the full
`cleanup_grace_period` (default 1h) on every failure**. Teardown after a
non-zero exit now waits only while an **in-flight trainer checkpoint**
is detected.
> 
> The `multi_node_rl.sbatch.j2` teardown block is gated on both
`cleanup_grace_period` and a rendered **`ckpt_dir`** (from
`get_ckpt_dir` when `[ckpt]` is enabled). Instead of a fixed `sleep`, it
polls every 10s: if the newest `step_*/trainer` directory lacks DCP
**`.metadata`**, it keeps the task alive (preserving
`--kill-on-bad-exit` behavior for peer trainers); otherwise it tears
down immediately. **`cleanup_grace_period` is documented as an upper
bound**; runs without checkpoints skip the wait entirely.
> 
> `write_slurm_script` in `rl.py` passes `ckpt_dir` into the multi-node
template renders.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8168264718f38f6e2e9636ea7bc7098e91743ba3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:31:54 +01:00
faresobeidandGitHub 32c48f5d9a chore(configs)!: rename tasks_per_minute to dispatch_per_minute (#3991)
## What

Renames `tasks_per_minute` to `dispatch_per_minute` on `orchestrator`,
the `eval` entrypoint and the SFT online `[eval]` block. This uses the
same name and wording as #3652.

The old name was wrong. The dispatcher takes one rate-limiter token per
**episode** it starts (`Dispatcher.acquire`, called once per scheduled
episode), not one per task. With `group_size = 8`, `tasks_per_minute =
80` started only 10 tasks per minute. The docstrings now say what is
counted: at most N episodes start per minute, and a group counts
`group_size` times.

Breaking: configs that set `tasks_per_minute` now fail validation
(`extra="forbid"`). No shipped config, doc, test or skill sets it or
mentions it.

## Overlap
#3652 (draft, orchestrator as hook-wired components) makes the same
rename. This PR lands it on its own and does not depend on that
refactor.

## Test plan
- `pytest tests/unit/orchestrator tests/unit/eval
tests/unit/test_configs.py -m "not gpu"`: 357 passed.
- `ruff check` and `ruff format --check` on the changed files.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Breaking config field rename only; runtime rate limiting behavior is
unchanged aside from clearer documentation.
> 
> **Overview**
> **Breaking rename:** `tasks_per_minute` → `dispatch_per_minute` on
orchestrator config, eval/SFT online eval config (`ServedEvalConfig`),
and everywhere it is passed into `Dispatcher` (orchestrator + eval
runner).
> 
> The limit semantics are unchanged in code (still `AsyncLimiter` with
one token per scheduled episode in `Dispatcher.acquire`), but the name
and docstrings now match behavior: the cap is **episodes started per
minute**, and a rollout group with `group_size` N consumes N tokens.
Configs that still use `tasks_per_minute` will fail validation under
`extra="forbid"`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0436304d5e40baed76abfadaa5b989048e818b6a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:29:40 +01:00
faresobeidandGitHub 8b2eb329e1 chore(trainer)!: remove the model.index_cache override (#3984)
Removes `model.index_cache` (`IndexCacheConfig.topk_freq` and
`.topk_pattern`). The trainer still turns on IndexShare from the model's
own `indexer_types` schedule (`src/prime_rl/trainer/model.py`), as
before.

Why: the override changes the trainer only. No inference-side config
matches it, so setting it makes the trainer pick different top-k indices
than vLLM unless the user also passes the same vLLM `hf_overrides` by
hand. The setting appears in no config, example or test. The HF-level
`use_index_cache` / `index_topk_freq` / `index_topk_pattern` attributes
on `GlmMoeDsaConfig` stay, so a checkpoint's own `config.json` still
drives them.

Breaking: `[trainer.model.index_cache]` / `[model.index_cache]` now
fails validation.

Overlap with open PRs:
- #3833 rewrites the same `index_cache` lines in `model.py`
(`set_model_options(model_config, "index_cache", ...)`). Whichever lands
second drops or rebases that block; the conflict is small.
- #3879 is based on that code too.
- #3616 already leaves `trainer.model.index_cache` unset for the reason
above: a trainer frequency override replaces the checkpoint schedule and
requests weights the checkpoint does not have.

Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed.
- `pytest tests/unit/utils/test_weights.py` (includes
`GlmMoeDsaForCausalLM`): 7 passed.
- `ruff check` and `ruff format --check` on the changed Python files:
clean.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking config validation for anyone using `index_cache`, and it
changes sparse-attention index scheduling to follow the checkpoint
only—important for trainer/inference logprob alignment on DSA models.
> 
> **Overview**
> **Removes the trainer-only `[trainer.model.index_cache]` override**
(`topk_freq` / `topk_pattern`). Configs that still set it will fail
validation.
> 
> IndexShare for GLM-5.2-style DSA models is unchanged in behavior: when
the checkpoint’s `indexer_types` includes `"shared"` layers, the trainer
still sets `use_index_cache` on the HF config and logs the full/shared
layer counts. It no longer applies manual `index_topk_freq` /
`index_topk_pattern` or clears `indexer_types`, which could diverge from
vLLM rollouts.
> 
> Docs no longer mention manually overriding the schedule via
`[trainer.model.index_cache]`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bf75c92edd9982a776bff29601c1e8c4519aebeb. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:22:14 +01:00
faresobeidandGitHub be89bbdaa1 fix(inference): keep the routed-experts dtype vLLM picks from the model config (#3965)
vLLM 0.31's routed-experts capturer already returns uint8 or uint16,
chosen from the model's expert count (`uint8 if num_experts <= 256 else
uint16`). `serialize_routed_experts` cast every request back to uint8
whenever its ids happened to be below 256. On a >256-expert model
(NemotronH Super/Ultra: 512 experts), a request whose ids all fall below
256 therefore came out uint8 while the others were uint16. Packing two
such samples into one micro batch trips `assert routed_experts.dtype ==
sample.routed_experts.dtype` in `orchestrator/batch.py`. Multi-turn
traces hit the same mix: verifiers concatenates the per-turn arrays, and
NumPy widens the result.

`serialize_routed_experts` now keeps the capturer's dtype and asserts
that it is uint8 or uint16. Every request of a model then has the same
dtype. Models with 256 or fewer experts are unchanged (uint8).

Tests: the existing serialize test now passes a uint16 array with ids
below 256 and checks that it stays uint16. `tests/unit/orchestrator`,
`tests/unit/inference`, `tests/unit/utils`, `tests/unit/test_configs.py`
pass with `-m "not gpu"`; `ruff check` and `ruff format --check` are
clean.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Narrow inference serialization fix; ≤256-expert models stay uint8, and
behavior only changes where mixed dtypes previously caused orchestrator
batch asserts.
> 
> **Overview**
> **Fixes inconsistent routed-experts dtypes** that broke micro-batch
packing on models with more than 256 experts (e.g. NemotronH 512).
> 
> `serialize_routed_experts` no longer re-encodes expert indices to the
smallest integer width based on per-request max values. It keeps the
array dtype from vLLM’s capturer (`uint8` or `uint16` from model expert
count), with assertions that the input is 3-D and one of those two
types. The serialized payload’s `"dtype"` field reflects that array
unchanged.
> 
> Unit tests now decode using `encoded["dtype"]` and assert a `uint16`
capture with all ids &lt; 256 stays `uint16` through serialize/decode.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e4a8e9ea05cb4e960192cdb7929e2c2566ca9734. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:18:00 +01:00
faresobeidandGitHub a1e0edbb4f fix(rl): inherit inference.deployment.gpus_per_node from deployment (#3978)
Under `rl`, `inference.deployment.gpus_per_node` was never set from
`deployment.gpus_per_node`. `InferenceConfig.auto_setup_disaggregated`
sizes `data_parallel_size_local`, `data_parallel_size` and
`api_server_count` from the nested copy, which defaults to 8. The
launcher, sbatch `dp_per_node` and weight-broadcast world size use the
top-level copy. So a P/D run on nodes that do not have 8 GPUs got
mismatched engine counts.

Example: `examples/advanced/glm-5.3/swe.toml` with
`deployment.gpus_per_node = 4` resolved to `data_parallel_size_local =
8` and `api_server_count = 8`, while the template launched 4 engines per
node.

Changes:
- `propagate_shared_fields` now fills
`inference.deployment.gpus_per_node` from `deployment.gpus_per_node`. As
with the other shared fields, setting both to different values raises.
- `RLConfig.validate_shared_configs` requires the two to be equal. This
catches a nested-only override that leaves the top-level value at its
default.

## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 335 passed (includes the new
`test_disaggregated_inference_inherits_deployment_gpus_per_node`)
- Parsed all 78 tomls under `configs/` and `examples/` with every config
class on main and on this branch: same results, none fail
- glm-5.3 `swe.toml` with `deployment.gpus_per_node = 4` now resolves
`inference.deployment.gpus_per_node = 4`, `dp_local = 4`,
`api_server_count = 4`
- `ruff check` / `ruff format --check` on the changed files

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Mis-sized inference parallelism and launcher/engine counts on
multi-node disaggregated runs; the change is narrow config propagation
plus validation with low blast radius beyond P/D sizing.
> 
> **Overview**
> Fixes a config bug where **`deployment.gpus_per_node`** at the RL top
level did not flow into **`inference.deployment.gpus_per_node`**, so
disaggregated P/D runs could size **`data_parallel_size_local`**,
**`api_server_count`**, and related fields from the nested default (8)
while SLURM/launchers used the top-level value (e.g. 4).
> 
> **`propagate_shared_fields`** now copies top-level
**`deployment.gpus_per_node`** into
**`inference.deployment.gpus_per_node`** (with the same
shared-vs-sub-config conflict rules as other shared fields).
**`RLConfig.validate_shared_configs`** additionally requires the two
values to match when inference is enabled, catching nested-only
overrides that disagree with the top-level deployment.
> 
> A unit test asserts inheritance and that mismatched nested/top-level
**`gpus_per_node`** fails validation.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
863bbf67298b456c48418c7326c820cc930ca203. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:14:07 +01:00
faresobeidandGitHub 8493109b7d chore(inference): drop typed vLLM fields that only repeat vLLM defaults (#3986)
Drops seven typed `[inference.vllm]` fields: `seed`, `enforce_eager`,
`dtype`, `trust_remote_code`, `enable_dbo`, `max_loras`,
`all2all_backend`, and the `All2AllBackend` alias. Each one only
repeated vLLM 0.31's own default, and nothing in prime-rl reads it.
`VllmConfig` is `extra="allow"`, so all seven keys still pass through to
vLLM unchanged. The `VllmConfig` docstring says to type only fields that
prime-rl types, defaults or reads back; these were none of those.

`all2all_backend` also suggested control it doesn't have for P/D: the
sbatch templates set the per-role backend in `ROLE_EXTRA`
(`inference.sbatch.j2:261,276`, `multi_node_rl.sbatch.j2:405,419`). That
stays as is.

Behavior: I resolved the vLLM serve args (`to_namespace` →
`make_arg_parser().parse_args`) on main and on this branch for the
default config and for `--vllm.enforce-eager`, `--vllm.enforce-eager
true`, `--vllm.max-loras 2`, `--vllm.dtype bfloat16`, `--vllm.seed 7`,
`--vllm.all2all-backend deepep_low_latency`, `--vllm.enable-dbo true`,
`--vllm.trust-remote-code true`, `@
examples/advanced/glm-5.3/infer/pd.toml`. All seven values are
identical. The nested rl form `--inference.vllm.enforce-eager
--inference.vllm.max-loras 2` also resolves to `True, 2`. `"enable_dbo"
= true` in `examples/advanced/glm-5.3/swe.toml` sits under
`prefill_vllm_overrides` and is unaffected.

Differences:
- `--no-vllm.enforce-eager` (the negated bool flag) only exists for
typed fields. Use `--vllm.enforce-eager false`. All four removed bools
default to False, so this only matters when undoing a toml that set one
to true.
- `dtype` now accepts every value vLLM accepts (for example `half`)
instead of prime-rl's narrower Literal.

`skills/configs/SKILL.md` used `enforce_eager = true` as its TOML
boolean example. It now uses `enable_prefix_caching = true`, which is
still typed, so `--no-flag` applies to it.

## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/test_parsers.py -m "not gpu"`: 489 passed
- Parsed all 78 tomls under `configs/` and `examples/` with every config
class on main and on this branch: same results
- The resolved-args comparison above
- `ruff check` / `ruff format --check` on the changed file
2026-10-10 19:07:27 +01:00
faresobeidandGitHub c9ce5f3d30 chore(configs): drop dead orchestrator fields (#3983) 2026-10-10 19:04:40 +01:00
faresobeidandGitHub 9570bccc28 chore(configs): drop recipe lines that repeat defaults (#3982)
## What
Drop recipe lines that only repeat what the config already resolves to.
The resolved configs do not change, except for `skip_optimizer` (see
below).
- `[weight_broadcast] type = "nccl"`: `rl` already picks NCCL when
inference is managed and LoRA is off. Removed from minimax-m2.5 swe,
intellect-3.1 rl, and qwen3-30b-a3b swe/math. The block stays in
examples/extra/dynamo/rl.toml (no managed inference, so the default
there is filesystem) and in glm-5.3 (it also sets port and timeout).
- `ac.freq = 1` (the default) is removed from 8 recipes. The
`[*.model.ac]` table header stays, matching the GLM-4.5-Air recipes.
- `trainer.dist_timeout_seconds = 3600` / `dist_timeout_seconds = 3600`
(the default) is removed from 5 RL recipes and vlm/sft-moe.
- `inference.vllm.enable_return_routed_experts = true` is removed where
`trainer.enable_router_replay = true` already sets it (glm-4.5-air ×4,
nemotron-3-super).
- `[trainer.ckpt] skip_optimizer = true` is removed from glm-4.5-air
swe-budget/search/terminal and nemotron-3-super swe.
  - It only affects loading: on resume, it drops the AdamW/Muon state.
- It came from the #2862/#2915 ablation configs. None of these recipes
warm-starts from another run's checkpoint. They train from the HF model
and resume their own checkpoints, which include optimizer state.
- configs/ci/integration/reverse-text-sft/full-offload-resume.toml keeps
it on purpose: it tests that path.
- docs/scaling.md: the `fused_lm_head_token_chunk_size` default is 8192
(since #3302), not 1024.

## Not touched
- `fused_lm_head_token_chunk_size = 1024` pins (7 recipes) and `attn =
"flash_attention_3"` pins (10). Should they stay as memory/hardware
choices?
- `[ac_offloading] max_inflight_activations` lines (a separate PR
removes the field).
- The `[weight_broadcast]` blocks of the GLM-4.5-Air and nemotron
recipes (handled in the weight_broadcast.timeout PR, to avoid a
conflict).

## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed (validates every TOML under configs/ and examples/).
- Resolved configs of all 14 edited recipes, main vs this branch
(RLConfig/SFTConfig `model_dump`):
- identical, except `trainer.ckpt.skip_optimizer` True → False in the 4
recipes above;
- the checkout path in `template_path` also differs (main checkout vs
this worktree), which is not a recipe change.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Mostly documentation and deduplication; the only resolved-config
change is `skip_optimizer` false on four recipes that resume with full
optimizer state, which matches their intended training flow.
> 
> **Overview**
> Trims RL/SFT example and advanced recipe TOMLs by deleting settings
that already match framework defaults, so recipes only spell out
non-default choices.
> 
> Removed redundant **`[weight_broadcast] type = "nccl"`**,
**`trainer.model.ac` `freq = 1`**, **`dist_timeout_seconds = 3600`**,
and **`inference.vllm.enable_return_routed_experts`** where NCCL
broadcast, AC frequency, dist timeout, and routed-expert return are
implied (e.g. managed inference + **`enable_router_replay`**). Dropped
**`[trainer.ckpt] skip_optimizer = true`** from four GLM-4.5-Air and
Nemotron SWE/search/terminal recipes so resume loads optimizer state
from their own checkpoints instead of discarding it.
> 
> **`docs/scaling.md`** now documents
**`fused_lm_head_token_chunk_size`** default **8192** (was incorrectly
**1024**). Explicit pins like **`fused_lm_head_token_chunk_size =
1024`** in memory-tight recipes are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c87c43defc655e83c39559736ca874740327d266. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 18:38:11 +01:00
faresobeidandGitHub c5406f8d09 perf(examples): use cudnn_flashmla DSA backend in GLM-5.3 RL example (#3968)
Sets `dsa_backend = "cudnn_flashmla"` for the trainer in the GLM-5.3 RL
example (`examples/advanced/glm-5.3/swe.toml`). The SFT example already
uses it (#3829); the RL example still ran the TileLang forward and
backward.

Measured on 1x8 H200 with the trainer settings of `swe.toml` (131k seq,
cp 4, ep 8, fp8 + `deepgemm_fp8`, full AC + offload, compile). Random
init, 8 layers (3 dense + 5 MoE), fake data, 2 micro-batches per dp
rank, balanced routing:

| `dsa_backend` | step 2 / 3 | sparse attn fwd per call | sparse attn
bwd per call |
|---|---|---|---|
| `tilelang` | 16.6 s / 15.5 s | 35 ms | 190 ms |
| `cudnn_flashmla` | 12.8 s / 12.1 s | 12 ms | 53 ms |

- Entropy and mismatch KL are identical to 4 decimals.
- With a 4-layer run (5.7 s), one MoE layer costs 1.6 s instead of 2.07
s. Extrapolated to 78 layers at this shape: ~124 s vs ~160 s per step
(-22%).
- Kernel check at the CP shape (8k local queries vs 32k keys, cp rank 0
and 3, top-k 2048, sentinel slots): out / dq / dkv relative error vs
TileLang 5e-4 to 9e-4, LSE 7e-8.
- Needs the `flash-mla` extra, which the README's `uv sync --all-extras`
installs.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single example TOML knob with no production code changes; requires the
optional flash-mla dependency for the new backend.
> 
> **Overview**
> Aligns the GLM-5.3 RL example trainer config with the SFT example by
setting **`dsa_backend = "cudnn_flashmla"`** in
`examples/advanced/glm-5.3/swe.toml`, so sparse DSA attention uses the
cuDNN/FlashMLA path instead of the default TileLang forward/backward.
> 
> This is a **performance-only** example change for long-context RL
training (131k seq, CP/EP, fp8 MoE); behavior should match TileLang
within measured numerical tolerance when the `flash-mla` extra is
installed.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e2135c38262af40b51d866026cdfa3a83fb7c7b4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 18:29:07 +01:00
Florian BrandandGitHub 9b39a10949 refactor(sampling): share parameter resolution across eval and training (#3782)
Use Verifiers' shared sampling config and resolution path for evaluation
and rollout dispatch. Parameter names, provider options, source
defaults, and agent overrides follow the same rules in native Verifiers
and Prime-RL. Training retains its strict config for the distribution
the trainer replays.

## Sampling flow

```mermaid
flowchart TD
    T["Train source and agent config<br/>TrainSamplingConfig and replay bounds"] --> V["Validate live-policy sampling<br/>Source owns the distribution"]
    V --> S["Shared Verifiers SamplingConfig<br/>Normalize aliases and extra_body"]
    V --> A["AgentConfig.sampling<br/>Sparse overrides across config transport"]
    E["Eval source and agent config"] --> S
    E --> A
    S --> R["RunRequest to env server"]
    A --> M["Verifiers resolve_agent<br/>Shared merge_defaults"]
    R --> M
    M --> P["Provider request<br/>Non-null resolved parameters"]
    M --> C["Trace<br/>Complete resolved sampling"]
```

## Shared parameters

Verifiers normalizes `max_tokens` / `max_completion_tokens` and flattens
`extra_body` before merging each override layer. Source values replace
group defaults; agent values replace inherited sampling. An explicit
null clears an inherited parameter.

Within one sampling block, top-level values take precedence over
`extra_body`. A typed training `top_k=20`, or the automatic replay bound
of `512`, therefore takes precedence over `extra_body.top_k=-1`. With no
typed `top_k`, the disabled sentinel remains effective.

Prime-RL carries `vf.SamplingConfig` through dispatch and converts
`TrainSamplingConfig` once. Source defaults and agent overrides use
Verifiers' `merge_defaults`; duplicate eval schemas and
sampling-dictionary converters are removed. Request-specific cache salts
are copied onto the shared config.

Unresolved agent overrides remain sparse across env-server config
boundaries. `resolve_agent` materializes the sampling used for
generation, and traces record the complete resolved config. Provider
dialects and the renderer client omit nulls when constructing requests.

## Training ownership

Live-policy sources validate their sampling when the config loads.
Unsupported source parameters, including `frequency_penalty`, are
rejected before generation.

The source owns the distribution replayed by the trainer. Every agent in
a live-policy source, including non-trainable roles, may override only
`max_tokens`, `reasoning_effort`, and `chat_template_kwargs`.
Distribution parameters belong on the source, even when an agent would
repeat the same value. Policy logprobs remain enabled. Evaluation and
frozen-model sources retain general agent overrides.

This removes the post-rollout sampling comparison from `TrainSink`.

## Dependency

Pins Verifiers `2cb0a6d`, the merged commit for [Verifiers
#2762](https://github.com/PrimeIntellect-ai/verifiers/pull/2762), for
shared sampling normalization and resolution. This includes merging
per-call judge sampling overrides before constructing SDK requests,
preserving unrelated configured provider parameters. The lockfile
updates `prime-tunnel` to `0.1.14` to meet the merged dependency's
minimum.

Before publishing packages outside this source checkout, release that
Verifiers change and raise the `verifiers` minimum in both `prime-rl`
and `prime-rl-configs`. The current `>=0.3.2.dev158` package constraints
do not guarantee these semantics.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how sampling is resolved and validated for all rollouts;
mis-merged configs or rejected agent overrides could break existing
TOMLs, though unit tests cover the main inheritance and policy rules.
> 
> **Overview**
> **Unifies rollout sampling** on Verifiers' shared `SamplingConfig` and
merge rules instead of Prime-RL–specific eval schemas and
`to_sampling_args()` dict builders.
> 
> Eval sources and group defaults now use `vf.SamplingConfig`;
train/eval env wrappers carry a typed `SamplingConfig` through to the
env server (including per-request `cache_salt` via `model_copy`). Policy
train sources get **load-time validation**: the source owns distribution
parameters (`temperature`, `top_p`, etc.), while agents may only
override `max_tokens`, `reasoning_effort`, and
`chat_template_kwargs`—frozen-model and eval paths stay permissive.
`TrainSink` reads temperature from `env.config.sampling` instead of a
resolved args dict.
> 
> **Docs** describe alias normalization (`max_tokens` /
`max_completion_tokens`), `extra_body` merging, and live-policy override
limits. **Tests** cover inherited sampling merges and policy sampling
rejection cases. Lockfile bumps `prime-tunnel` to `0.1.14`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
671a5aa9857a39a4d44fa7902f1c89021b8fd380. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 00:30:12 -07:00
Florian BrandandGitHub f7e8ab6456 fix(eval): resume rollouts by task content and selected occurrence (#3808) 2026-10-09 15:47:46 -07:00
84e94bf05c perf(orchestrator): poll for new weight versions every 0.1s instead of 1s (#3952)
## Summary
- `WeightWatcher.poll_interval` default: 1.0s → 0.1s
- `WeightReceiver.wait_published` sleep: 0.2s → 0.1s

## Why
The trainer blocks in `WeightSender._wait_for_receiver_ready` until the
orchestrator notices `.sender_ready`. With a 1s poll, that adds 0–1s
(~0.5s avg) of idle trainer time on every step. NVIDIA flagged this
while benchmarking the ModelExpress broadcast (#3890).

A poll is one `glob("step_*")` on the broadcast dir (≤2 entries thanks
to `_clean`) plus a few `exists()` calls, so 10Hz is negligible.
Correctness relies on the marker handshake + `update_lock`, not on the
poll timing.

Caveat: these are sync FS calls on the orchestrator event loop. On a
very slow shared FS, that might show up in `EventLoopLagMonitor`. If it
does, we can move them to `asyncio.to_thread`.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Timing-only tuning on poll loops; no change to weight handshake logic,
though more frequent sync FS calls could add event-loop lag on very slow
filesystems.
> 
> **Overview**
> **Faster weight-version discovery** so the trainer spends less time
blocked waiting for the orchestrator to see `.sender_ready`.
> 
> The orchestrator `WeightWatcher` default `poll_interval` drops from
**1.0s to 0.1s**, cutting typical idle wait on each broadcast handshake
from ~0.5s toward ~0.05s. `WeightReceiver.wait_published` uses the same
**0.1s** sleep (was 0.2s) while waiting for the sender marker.
> 
> Handshake correctness is unchanged (markers + `update_lock`); cost is
slightly more frequent lightweight FS checks on the orchestrator event
loop.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5c825d0f126e16885eae77f4f6ebc2ddf306de59. 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-09 10:25:55 -07:00
IanandGitHub 37b48a996e security(ci): pin BuildKit builder to v0.33.1 and rotate registry buildcache (CVE-2026-93318) (#3889)
## security(ci): pin BuildKit builder to v0.33.1 and rotate the GHCR
registry buildcache (CVE-2026-93318)

### What changed (rebased onto current main)
`.github/workflows/build_image.yaml`:
1. **Builder pin** — `docker/setup-buildx-action@v4` now sets
`driver-opts: image=moby/buildkit:v0.33.1`. Without it the job starts
the rolling `moby/buildkit:buildx-stable-1` tag, and because these are
persistent self-hosted runners (`image-builder`,
`image-builder-arm-2204`), the builder version is not even guaranteed to
follow the tag — a stale local image can keep a pre-patch builder alive
indefinitely. The pin makes the builder version deterministic.
2. **Registry cache rotation** — both shared cache refs rotated:
- `:dependency-buildcache-<suffix>` ->
`:dependency-buildcache-v2-<suffix>`
- `:application-buildcache-<suffix>` ->
`:application-buildcache-v2-<suffix>`

### Why rotation (evidence)
- The registry-backed cache was introduced in d8f3d0101 (2026-08-16,
#3279) and has been written on nearly every run since — including all
runs before the patch was published.
- BuildKit v0.33.1 (the CVE fix) was released **2026-09-30T17:08Z**; the
rolling `moby/buildkit:buildx-stable-1` tag only moved to that digest at
**2026-09-30T17:32Z**. Every cache write before that timestamp came from
a builder older than v0.33.1, on runners that may also hold stale local
images.
- Per the CVE-2026-93318 playbook: stop importing a shared cache that
pre-fix builders wrote, rebuild from trusted inputs, and pin the patched
builder so every future write is attributable to a fixed version.

### Expected cost
The first run per platform suffix after merge does a cold build of the
dependency layer + application layer (no cache import). The old
`*-buildcache-*` tags can be deleted from the `prime-rl` GHCR package as
cleanup — they are cache-only refs, never deployed.

### Out of scope / notes
- `docker-push.yaml` (old Docker Hub publisher) no longer exists on main
— nothing to pin there.
- No GHA-scope (`type=gha`) caches exist in this repo's workflows
(verified by grep), so no Actions-cache cleanup applies.
- Build image runs are frequent and mostly manual dispatch; this PR
should merge before the next `main` image build.

### Security review requested
- Cache invalidation: confirm the `*-v2-*` refs fully replace the old
buildcache lineage.
- Published-image provenance: GHCR `prime-rl` images built before
2026-09-30T17:32Z were produced by a pre-patch builder; assess whether a
clean rebuild of the current release tags is warranted.
- No applicable CODEOWNERS entry exists in this repo; CI/build owner
please review.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> CI-only security remediation with intentional cache busting (slower
first builds); no application runtime code changes, but GHCR images
built before the fix may need a separate provenance/rebuild decision.
> 
> **Overview**
> Remediates **CVE-2026-93318** in the GHCR image build workflow by
making the BuildKit builder version fixed and breaking reuse of
artifacts produced before the patch.
> 
> **BuildKit pin:** `docker/setup-buildx-action` now sets `driver-opts`
to `moby/buildkit:v0.33.1` (digest-pinned) so self-hosted
`image-builder` runners do not keep serving a stale local
`buildx-stable-1` builder.
> 
> **Cache and deps lineage:** Shared registry cache refs move to
`dependency-buildcache-v2-*` and `application-buildcache-v2-*` so layers
written by pre-v0.33.1 builders are not imported. Dependency base tags
gain a `-v2-` epoch (`deps-${key}-v2-${suffix}`) so existing
`deps-${key}` images are not reused as the runtime base when only
Dockerfile/lock inputs are unchanged.
> 
> The first build per platform after merge is expected to be cold (no
old cache import); published runtime tags are unchanged—only CI
remediation naming and builder configuration.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0310e6d89608d9d34fd0c1a4c0e9a5c6ba5261bf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-09 08:22:03 -07:00
Konstantin DunasandGitHub 88faa6dc22 feat(sft): warn when renderer is not prefix stable (#3953)
Warn when SFT constructs a renderer that does not guarantee prefix
stability. The warning explains that each conversation is rendered once
into one training sample, that N assistant turns are not expanded into N
samples, and that earlier reasoning may be omitted by the template.
Cached renderers warn only on construction; stable renderers stay quiet.
Custom renderers without the capability are conservatively treated as
unknown.

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

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

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

## DeepSeek-V4 ablation

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

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

## Alternatives considered

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

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

---------

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

## What changes

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

## Result

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

## Not in this PR (follow-ups)

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

## Verification

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

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Lockfile and uv policy changes only; risk is mainly behavioral shifts
from Harbor 0.24.0 and updated verifiers Harbor adapter usage in
eval/training paths.
> 
> **Overview**
> Updates dependency resolution so **`harbor` 0.24.0** (via the
`verifiers[harbor]` pin) can install under uv’s rolling
**exclude-newer** policy by moving the bounded **`harbor` cutoff** from
`2026-08-11` to **`2026-10-08`** in `pyproject.toml`, mirrored in
`uv.lock`.
> 
> The lockfile refresh bumps **`harbor` 0.21.0 → 0.24.0**, records new
transitive deps **`jsonschema`** and **`semver`**, and aligns the
verifiers harbor extra specifier to **`==0.24.0`**. This pairs with the
verifiers main bump described in the PR (Harbor adapter alignment and
reward/verifier precedence behavior), even though those code changes
live outside this diff.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
69e62c1fc116896ce99c79dbfc454959c748cb47. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:18:33 -07:00
26681fc6c7 fix(models): pass contiguous router-replay experts to compiled layers (#3947)
On torch 2.13.0 with compile and router replay, some MoE layers silently
replay layer 0's routing instead of their own from the second training
step on. This PR calls `.contiguous()` on each layer's routed-experts
slice, which removes the bug.

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

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

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

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

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

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

## Verification

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

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

---------

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

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

---------

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

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

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

This also fixes what #3924 fixes.

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

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

<!-- CURSOR_SUMMARY -->
---

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

## Behavior change
None.

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

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

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

### Possible middle ground (not implemented)

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Launch-time env default only; behavior is overridable via config and
fixes known multi-rank Triton cache races, with a one-time cold-compile
cost on each node.
> 
> **Overview**
> **Sets a global launcher default** so every trainer, orchestrator, and
inference process gets `TRITON_CACHE_DIR=/tmp/triton-<uid>` via
`DEFAULT_COMMON_ENV_VARS`, avoiding concurrent Triton kernel writes
under `~/.triton` on a shared filesystem (hangs / `FileNotFoundError`
under multi-rank compile).
> 
> **Removes redundant `[env_vars]` overrides** from six GLM-4.5-Air RL
and GLM-5.3 / Qwen3-30B SFT example configs that previously pinned
Triton cache paths under `/tmp`; those runs now inherit the per-user
node-local default (still overridable through config `env_vars`).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f21642046ea59cab0b9460863560b4df825f29c0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
2026-10-08 11:59:17 +01:00
faresobeidandGitHub fec3acd8e7 chore(orchestrator): fold GenerationSource into TrainEnv (#3838)
## Summary
Fold `GenerationSource` into `TrainEnv`, its only owner. Move
`connect_frozen_client` from `algo/base.py` to `clients.py`, so `algo`
no longer imports `clients` lazily. Give `TrainEnv` `setup()`/`aclose()`
so orchestrator setup and teardown no longer reach into its parts.

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

## Behavior change
None.

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

<!-- CURSOR_SUMMARY -->
---

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

## Before

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

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

## After

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

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

<!-- CURSOR_SUMMARY -->
---

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

## Before

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

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

## After

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

## Why

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

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

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

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

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

## Changes

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dependency floor bump only; no application code changes and default
trace upload behavior stays the same.
> 
> **Overview**
> Raises the **`prime-runs[train]`** minimum from **`>=0.1.3`** to
**`>=0.1.4`** in `pyproject.toml` and pins **`prime-runs` 0.1.4** in
`uv.lock`.
> 
> This ensures installs pick up **Prime Traces opt-out** behavior
(`PRIME_TRACES_OPT_OUT`, `prime config set-traces-opt-out`, or
`prime_runs.init(traces_opt_out=True)`), which 0.1.3 silently ignored so
opted-out runs could still upload to Prime Traces. Default runs that do
not opt out are unchanged; `prime-rl` still depends on the **`[train]`**
extra for legacy sample encoding when opting out.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
06caa96109250b6b800d8e757de7133b4f152031. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 19:38:03 -07:00
f3827c4ed2 perf(trainer): avoid eager fallback of MoE blocks with an fp32 router and activation checkpointing (#3925)
With `moe_router_dtype="float32"` (the RL default) and activation
checkpointing on, every MoE block ran eager under `torch.compile`. Two
things combine to cause it:

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

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

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

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

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

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

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

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

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

</details>

## Alternative considered

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

## North star: fullgraph fp32 router support

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

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

---------

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

## Before

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

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

## After

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

---------

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

## Verification

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes sparse-attention forward/backward kernels and gradient
numerics (LSE/index flattening); `cudnn_flashmla` needs SM90+ and extra
deps, with SM100 paths noted as untested.
> 
> **Overview**
> Adds **`model.dsa_backend`** (`tilelang` default,
**`cudnn_flashmla`**) so GLM-5 DSA sparse MLA can use **FlashMLA sparse
prefill** forward and **cuDNN CuTe-DSL** backward instead of TileLang
for both directions. The trainer passes the setting through
`model_config` into `sparse_mla`, which now takes a `backend` argument;
autograd routes backward to the matching implementation and **normalizes
LSE to natural log** across paths (TileLang converts at the boundary).
> 
> Packaging adds **`nvidia-cudnn-frontend`** on the GPU extra, a
**`flash-mla`** optional extra (pinned x86_64 wheel), and lockfile
updates.
> 
> GLM-5.3 SFT examples: **`base.toml`** sets `dsa_backend =
"cudnn_flashmla"`; new **`16k-12-node.toml`** overlay documents 12-node
/ 16k training without CP or offloading; README expanded for both
setups.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0894aa8897544e3c2913b6a4274a3f9f7c6c9527. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 21:54:55 -07:00
minh hoangandGitHub 883b8f32c5 feat(docker): reuse dependency images for fast Docker source builds (#3828) 2026-10-04 22:47:39 -06:00
faresobeidandGitHub 407e8ba223 refactor(algo): declare action_loss_type once on the config; drop finalize_group (#3845)
Two small cleanups in `orchestrator/algo/`. Item 4 of the orchestrator
review.

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

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

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

GPU checks: none needed.

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

<!-- CURSOR_SUMMARY -->
---

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

Item 6 of the orchestrator review.

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

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

GPU checks: none needed.

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

## Why

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

## Breaking changes

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

## Validation

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

## How it works

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

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

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

## Notes

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

## Testing

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

## Why

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

## How

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

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

## Validation

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

## Breaking changes (all minor)

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

## Validation

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Import-path-only refactor with inlined helper code; no training,
packing, or NCCL broadcast logic changes, aside from downstream breakage
if anything still imports the removed modules.
> 
> **Overview**
> This PR reorganizes modules so orchestrator-only, test-only, and
single-use code no longer lives under `trainer/`. **Batch packing**
moves from `prime_rl.trainer.batch` to `prime_rl.orchestrator.batch`,
with `packing.py` and orchestrator unit tests updated to the new import
path.
> 
> **DeepSeek V4 eager reference** implementations move out of the
production package into
`tests/unit/train/models/deepseek_v4_eager_reference.py`; DSv4 GPU tests
import from there instead of
`prime_rl.trainer.models.deepseek_v4.eager_reference`.
> 
> **Layer counting for NCCL weight broadcast** drops the standalone
`trainer/conversion_utils.py` module: `get_max_layer_num` is defined
inline in `transports/weights/nccl.py`, its only caller. Behavior is
unchanged; callers must switch imports for batch and remove use of the
deleted trainer modules.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9287ae8ce22ba8731b80ebc1634ee0d5bbb25ea3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 13:42:11 -07:00
NeoandGitHub 0164aab72c perf(metrics): count attention FLOPs with the real head dim and report SFT MFU per step (#3755)
For discussion: this is the MFU accounting used in the Qwen3-235B
prime-rl vs torchtitan benchmarks (#3753, #3754), so that both stacks
report comparable numbers. Opening it as its own PR so we can decide
whether to adopt it as the trainer's metric.

## What changes

1. **Attention FLOPs use the real head dim.** `PerfCounter` counted
attention as `12 * layers * heads * (hidden_size / heads) * seq`. For
models whose `head_dim` is not `hidden_size / num_attention_heads` that
undercounts: Qwen3-235B-A22B has head_dim 128 but hidden/heads = 64. The
new term is torchtitan's `quadratic_attention_flops_per_token`: `6 *
layers * heads * (qk_head_dim + v_head_dim) * seq`, with the MLA qk/v
head dims when the config has them. Identical to the old value when
head_dim == hidden/heads.
2. **SFT throughput and MFU are per step over the full step wall time**,
including the optimizer step, as torchtitan reports with `log_freq=1`.
Before, they came from a 10-step sliding window over forward/backward
time only. The RL trainer is unchanged and still reports over
forward/backward time.

## Effect

- Qwen3-235B-A22B at seq 8192: 167.3 -> 205.1 GFLOP/token; at 16384:
280.8 GFLOP/token. Logged MFU on such models goes up accordingly, so
dashboards and the benchmark tables in
`benchmarks/results/BENCHMARKS.md` are not directly comparable across
this change.
- Two expected values in `tests/unit/train/test_perf.py` updated
(Qwen3-0.6B: head_dim 128 vs hidden/heads 64; the debug MoE likewise).

## Caveat worth discussing

Both formulas charge dense causal attention. On packed short documents
with varlen attention the executed attention FLOPs are far lower, so
absolute MFU is overstated for both stacks (roughly 2x at seq 16k on the
235B bench). Counting executed FLOPs from the packed sequence lengths
would be a separate change.
2026-10-03 13:26:42 -07:00
faresobeidandGitHub 243cfba0fb chore(trainer): remove torch full-offload backend, fold gradient offload managers (#3781)
Removes the full-offload `cpu_optimizer_backend = "torch"` path and
folds the two gradient offload managers in `trainer/optim/offload.py`
into one.

**Why:** there were two offload pipelines doing the same job. The native
backend covers the same optimizers (AdamW, SignSGD). `test_cpu_adam.py`
already checks native AdamW directly against fused torch AdamW. The
torch backend was only a debug/parity fallback (#3234).

**Changes**
- `GradientOffloadManager` is now the former
`BoundedGradientOffloadManager` (pageable FP32 accumulators, bounded
pinned transfer rings). The base methods it still used
(`optimizer_overlapped`, `gradient_scale`, `scale_`, `clip_grad_norm_`,
`load_cpu_chunk`) are moved into it. The base-only slab-pinned
accumulator/staging pipeline is deleted. `load_cpu_chunk` drops the
scale/assign/staging options that only the torch path used.
`release_chunk` is removed: on the native path it only cleared grads
that were already `None`.
- `FullCPUOffloadOptimizer`: removed the fused/foreach torch-AdamW step
(`_step_chunk`, `_prepare_fused_cpu_adamw`), the torch state warm-up
step, and all native/torch branching.
- `_create_cpu_master_weights`: removed the `pin_memory` option. FP32
masters are always pageable, as they already were on the native path.
- Removed `model.full_offload.cpu_optimizer_backend` from
`OptimizerInBackwardOffloadConfig`, plus its config test and the mention
in `skills/training/start-run/SKILL.md`.

Native AdamW and native SignSGD numerics and pipeline order are
unchanged.

**Breaking:** `model.full_offload.cpu_optimizer_backend` is removed. Any
value, including `"native"`, now fails config validation.

**Validation**
- `ruff check .` and `ruff format --check .`
- `pytest tests/unit/train/test_cpu_adam.py tests/unit/test_configs.py
tests/unit/train/test_state_offload.py -m "not gpu"`: 209 passed. This
includes the 3 `test_cpu_adam.py` tests (C++ extension built on CPU).
- Not run (no GPU on this machine). GPU checks still needed:
- `reverse-text-sft/full-offload-resume` integration test, including the
resume step
- one RL full-offload step each with AdamW and SignSGD: loss matches
main, and the `Offload pipeline` timing logs appear
  - synchronous `step()` path at validation and checkpoint boundaries

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Large refactor of full CPU optimizer offload (gradients, stepping,
checkpoint load) with a breaking config removal; native numerics are
claimed unchanged but GPU integration tests are still needed.
> 
> **Overview**
> Removes the debug **Torch** full-offload path and makes **native** CPU
AdamW/SignSGD the only implementation for `model.full_offload`.
> 
> **Breaking:** `model.full_offload.cpu_optimizer_backend` is gone
(including `"native"`). `[model.full_offload]` now only exposes options
like **`numa_bind`**.
> 
> The two gradient offload implementations are collapsed into a single
**`GradientOffloadManager`**: the old slab-pinned accumulator/staging
hook pipeline is deleted; the bounded pinned D2H/H2D ring with pageable
FP32 accumulators becomes the only manager.
**`FullCPUOffloadOptimizer`** no longer branches on backend—no fused
Torch `optimizer.step()` per chunk, no torch state warm-up, and
**`load_cpu_chunk`** is simplified.
> 
> FP32 CPU master weights are always **pageable** (`pin_memory` removed
from `_create_cpu_master_weights`). Docs and the config test for the
torch backend are updated accordingly.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
530cc3c380f44229c16374963a85ccf5bd0371bf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 12:58:04 -07:00
faresobeidandGitHub 9ff04f56bf refactor(inference): register all vLLM patches in the general plugin (#3780)
Register all vLLM monkeypatches in one place: the `vllm.general_plugins`
entry point (`apply_shared_vllm_patches`).

Before this PR, patches in `inference/patches.py` were applied from
three places: the plugin, import-time calls in
`inference/vllm/server.py`, and import-time calls in
`inference/vllm/worker/__init__.py`.
`monkey_patch_nano_v3_reasoning_parser` ran twice. Having three places
makes it hard to see which patches are active in which process.

## Design
- `apply_shared_vllm_patches` now applies every patch: the existing
ones, plus `tokenize_params_validation`,
`strip_routed_experts_from_chat`, `dp_coordinator_startup_timeout`
(moved from server.py) and `minimax_m2_for_lora` and the
`PRIME_NO_MOE_LORA`-gated `no_moe_lora` (moved from worker/__init__.py).
- `server.py` no longer applies patches at import time.
`worker/__init__.py` is now empty.
- Patch bodies are unchanged. No patch was removed. One docstring was
reworded because it said "import time".

In vLLM 0.30 the plugin runs once per process (guarded by
`plugins_loaded`), in every vLLM process type:
- API server main process: `make_arg_parser` ->
`AsyncEngineArgs.add_cli_args` -> `load_general_plugins()`. This happens
inside `server()` after `PRIME_NO_MOE_LORA` is set and before arg
validation, so `reasoning_parser = "nano_v3"` is registered in time.
`server()` is the first point that loads plugins (checked on CPU).
- Extra API server processes (`api_server_count > 1`):
`AsyncEngineArgs.from_cli_args` -> `EngineArgs.__post_init__` ->
`load_general_plugins()`. This runs before the app and
`OpenAIServingChat` are built.
- Engine core: `v1/engine/core.py`. Workers:
`WorkerWrapperBase.init_worker`, before `worker_extension_cls` is
resolved. The worker module used to apply its patches only at that later
point.

Every patch replaces methods or attributes on vLLM classes, so it has no
effect in process types that do not use that class. The difference is
that some patches now also run in more process types than before. For
example, server-only patches now also run in engine and worker
processes, and the MiniMax LoRA patch now also runs in the API server.
Nothing needed an exception.

`no_moe_lora` stays on the `PRIME_NO_MOE_LORA` env var. The plugin takes
no arguments and runs before any vLLM config exists. The env var set in
`server()` is the simplest way to reach the engine and worker processes.
A config path would need a new channel into the workers.

## Breaking changes
None intended. Accepted and resolved configs are unchanged. The only
behavior change: the `PRIME_NO_MOE_LORA=1/0` info log line in workers is
gone. If `VLLM_PLUGINS` is set and does not include `prime_rl`, vLLM
skips all patches, and that now includes the server and worker patches.
Nothing in the repo sets `VLLM_PLUGINS`.

Also removed: the dead `logger = get_logger()` in `server.py`. The next
line overwrites it. The inference entrypoint already calls
`setup_logger` before it imports `server.py`, and `get_logger()` sets up
the logger lazily on first use anywhere else.

## Validation
- CPU script (not committed). It loads the `vllm.general_plugins` entry
points through `vllm.plugins.load_general_plugins()` and checks that the
moved patches are applied: TokenizeParams, OpenAIServingChat,
DPCoordinator, MiniMaxM2MoE/`hf_to_vllm_mapper`, nano_v3 parser
registered. With `PRIME_NO_MOE_LORA=1`, FusedMoEConfig is patched. With
`0`, it is not.
- CPU check: importing `prime_rl.entrypoints.inference` and
`prime_rl.inference.vllm.server` does not load plugins. So in the API
process, the plugin first runs at `make_arg_parser` inside `server()`.
- `pytest tests/unit/inference
tests/unit/transports/test_nccl_broadcast.py -m "not gpu"`: 20 passed.
- `ruff check .` and `ruff format --check .` pass.
- Not run: GPU and integration tests (no GPU on this machine). GPU
checks needed before merging:
- Single API server `rl` run: a prompt with prompt + max_tokens >
max_model_len is accepted, and chat responses contain no
`routed_experts`.
  - `api_server_count > 1`.
- MiniMax-M2 LoRA, and non-expert LoRA (`no_moe_lora` reaches the
workers).
  - Multi-node DP coordinator startup timeout is 300s.
  - The server starts with `reasoning_parser = "nano_v3"`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches every vLLM process startup path and timing of patch
application; mis-timed plugin load or a broken entry point would
silently skip all patches, including ones that previously ran only in
the API server or workers.
> 
> **Overview**
> **Consolidates vLLM monkeypatches** so they all run from
`apply_shared_vllm_patches` (the `vllm.general_plugins` entry point)
instead of being split across `server.py` import time and
`worker/__init__.py`.
> 
> Patches moved into the plugin include tokenize validation, stripping
`routed_experts` from chat completions, DP coordinator startup timeout,
MiniMax M2 LoRA fixes, and the `PRIME_NO_MOE_LORA`-gated `no_moe_lora`
path. **`server.py` no longer applies patches at import** (and drops the
dead duplicate logger); **`worker/__init__.py` is cleared** so workers
rely on the plugin. `server()` still sets `PRIME_NO_MOE_LORA` before arg
parsing so the plugin can honor it when vLLM loads general plugins.
> 
> Patch logic is unchanged; the main behavioral shift is **where and
when** patches run (once per vLLM process via the plugin, including
process types that previously only got a subset). Worker info logs for
`PRIME_NO_MOE_LORA` are removed.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
dfaca8f493afeac2cf203f14e63bb1b0dbf43078. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 12:47:25 -07:00
afe37d1c7a feat(models): add native Qwen3.8 Flash Next (#3434)
Merged `main` at `e094f0860`. Main's expert parameters remain in the
transformer block's FSDP group; prefetching retains that behavior and
Qwen3.8's final hyper-connection mixer handling. Adds Qwen3.8 Flash Next
text training for `qwen4_exp` and `qwen4_exp_text`: hyper-connection
residual streams, Gated DeltaNet, indexed sparse attention, PLE N-gram
embeddings, and sigmoid-gated MoE, with HF checkpoint conversion.

## Head parallelism

PLE uses ordinary `nn.Embedding` parameters. `EmbeddingParallel`, an
external `RowwiseParallel` style, shards vocabulary rows across
`dp_shard_cp`, independently of EP. FSDP handles precision, replication,
and parameter lifetime on the complementary mesh. Packed token lengths
can differ across data ranks, so the style pads before collectives and
crops local outputs. The requested TODO marks the host synchronization
needed to size this padding.

When the head mesh has size one, the embedding follows ordinary FSDP and
no extra head dimension is created. The extra head axis is appended
after the existing world-mesh dimensions, preserving their indices.
Optimizer code is unchanged. Dion indexes each parameter's DTensor mesh,
not the root mesh; its momentum tensors retain the parameter placements.
Four-rank CPU/Gloo checks against main passed for six
DP/EP/CP/replication layouts, including momentum local shard sizes and
head-parallel state. Qwen3.5 and the shared MoE implementation are
unchanged; Qwen3.8's gated MoE lives in its own model package. Skills
and unrelated comments are unchanged.

## Required integration changes

- **Gradient clipping:** TorchTitan separates dense and EP gradients but
cannot combine the additional head mesh: its `aten.stack` raises “All
operands … must have the same mesh.” Resolve norms separately on each
DTensor mesh, then combine them into one global L2 norm and apply the
existing clipping formula. This is the same clipping mathematics; no
threshold, optimizer, `optimization_dtype`, or `reduce_dtype` changes.
The two-rank CPU/Gloo reproduction fails with the original helper and
matches the unsharded norm reference after mesh reductions. B300
gradient/update parity passed in SLURM 1440.
- **NCCL buffers:** a PLE-containing layer requires a 100.26 GiB
concatenation under the original protocol. Bound same-dtype groups to
512 MiB and send larger individual tensors without a concatenation copy.
Small groups retain the same collective count. Prior two-GPU A/B receive
medians were 0.365/0.367 ms at 128 MiB, 1.032/1.033 ms at 512 MiB, and
2.027/1.707 ms for a 1 GiB tensor plus small tensors (original/bounded;
SLURM 1347).
- **vLLM compatibility:** filter PLE checkpoint pieces with no overlap
on the local TP rank before vLLM's deferred loader buffers them. The
original loader still handles valid local pieces and malformed shards.
The generic reload machinery is unchanged. Real Qwen PLE reload values,
storage identity, and queue behavior passed on four GPUs (SLURM 1352).
- **Model setup:** register the config/model, freeze its sparse indexer,
wrap its final hyper-connection mixer with FSDP, and register its
indexed-attention operators with activation checkpointing. `vlm.py` only
supplies composite-config text-backbone lookup; this PR adds text
training, not a vision implementation.

## Validation

The merge with `e094f0860` was checked for unresolved conflicts and
whitespace errors; tests were not rerun. The results below remain from
their stated pre-merge commits/jobs.

SLURM **1442** completed successfully at cleanup commit `e50e42316`
(exit `0:0`, 3269 seconds including startup/shutdown). The prerequisite
four-B300 mesh/Muon-state/vLLM-reload check **1440** also passed.

- Official Qwen3.8 Flash Next checkpoint; 16 trainer B300 GPUs and TP8
inference.
- **20 math RL steps, batch 64**, group 4, `math-env` /
`PrimeIntellect/Hendrycks-Math` training split, debug algorithm, default
policy lag 8.
- **GPU memory utilization 0.85**, CUDA graphs and default vLLM
batching. Context 4096, completion limit 3072, thinking disabled;
SignSGD at `1e-6`, BF16 router projections on both sides, unchanged FP32
optimization/reduction defaults.
- GPU-resident PLE on vLLM 0.30 with explicit
`engram_config.cpu_offload=false`. NCCL transfers, no checkpoint saves
or filesystem weight transfer. `FLA_DISABLE_TENSOR_CACHE=1` is explicit
in the run environment; launcher defaults are unchanged.
- All 20 mean mismatch KL values are below **0.015**. Maximum
**0.001570820**; mean across steps **0.000701912**.
- Median warmed-up step **56.1s**, median broadcast **41.5s**.
- SLURM 1440 checked dense/EP/head norms, clipped gradients and
parameter updates against full-tensor references, plus uneven token
counts, replication/CP topologies, FSDP CPU offload, Muon momentum shard
sizes against main, and vLLM 0.30 PLE reloads. The original clipping
helper reproduced the mixed-mesh error; dense/EP-only norms matched the
original helper.
- Four config/checkpoint conversion cases, unchanged single-rank Muon
construction, Ruff and whitespace checks passed.
- Artifacts: `outputs/qwen38-validation/runs/qwen38-math20-main-gpu/`
(`validation-summary.json`, `mismatch-kl.md`, resolved configs and
logs); mesh log `outputs/qwen38-validation/rebased-head-1440.log`.

| Step | Mean mismatch KL |
| --- | ---: |
| 1 | 0.000282296 |
| 2 | 0.000228267 |
| 3 | 0.000326421 |
| 4 | 0.000275441 |
| 5 | 0.000435869 |
| 6 | 0.000398891 |
| 7 | 0.000725010 |
| 8 | 0.000521352 |
| 9 | 0.001052707 |
| 10 | 0.000689109 |
| 11 | 0.000823852 |
| 12 | 0.000369604 |
| 13 | 0.001008985 |
| 14 | 0.000577958 |
| 15 | 0.001168500 |
| 16 | 0.000841276 |
| 17 | 0.001036190 |
| 18 | 0.000672617 |
| 19 | 0.001570820 |
| 20 | 0.001033083 |


## Kernel dependency

[prime-kernels
#8](https://github.com/PrimeIntellect-ai/prime-kernels/pull/8) is merged
and released as
[v0.1.0-6f48176](https://github.com/PrimeIntellect-ai/prime-kernels/releases/tag/v0.1.0-6f48176).
Both x86_64 and aarch64 wheel URLs and SHA256 hashes are pinned in
`pyproject.toml` / `uv.lock`; the submodule matches release commit
`6f48176`. The release tree is identical to the `7bd1e89` source used in
the 20-step math run above, and the indexed-attention Python files in
both downloaded wheels match that source byte for byte.

The release wheel installed successfully with `uv sync --all-extras
--all-packages --frozen`; `uv lock --check` and `git diff --check`
passed. B300 validation of the installed x86_64 release wheel (SLURM
1468) passed forward/backward numerical comparisons, selection and tie
handling, fullgraph forward/backward compilation, and selective
activation checkpointing. The 20-step KL table above remains from SLURM
1442; it was not rerun for this wheel-only update.

The temporary Qwen overlap shim can be removed when pinned vLLM includes
the overlap check in `Qwen4ExpNGramEmbedding.load_weights`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Large new model and head-parallel embedding path, plus mesh-aware
gradient clipping and NCCL bucketing that can affect any run using these
parallelism modes or very large PLE layers.
> 
> **Overview**
> Adds a **native trainer implementation** for Qwen3.8 Flash Next
(`qwen4_exp` / `qwen4_exp_text`): hyper-connection residual streams,
Gated DeltaNet linear layers, **indexed sparse attention** (via
`prime_kernels`), PLE N-gram embeddings, and sigmoid-gated MoE, plus
HF↔Prime checkpoint conversion (including sharded `ngram_embedding`
weights).
> 
> **Distributed setup** introduces vocabulary-parallel
**`EmbeddingParallel`** for PLE embeddings on a new **head** mesh
(`dp_shard_mod_head`), FSDP on those tables, freezing of
`SparseAttentionIndexer`, and FSDP/prefetch handling for the final
**`hyper_connection_mixer`**. Activation checkpointing now saves
**`prime_kernels`** indexed-attention ops.
> 
> **Training/inference plumbing:** **`clip_grad_norm_`** computes norms
per DTensor mesh then combines them (replacing TorchTitan’s EP-only
helper). NCCL weight send/receive uses **`iter_tensor_buckets`**
(512 MiB) to avoid huge single concatenations. vLLM gets a **PLE shard
filter** patch so non-local TP pieces are skipped before load.
> 
> Configs/models are registered in AutoConfig/custom LM/VLM maps;
`qwen4_exp` is listed in the VLM registry for composite configs (text
training only in this PR). Unit test covers config and checkpoint
round-trip.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e50e423169964b8e8a800a610cf8e77d4c56053f. 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-10-03 21:45:27 +02:00
faresobeidandGitHub ecbf3e657f chore: remove fusions.raise_on_fail and dead ProgressTracker (#3778)
Removes two small things:

- `trainer.model.fusions.raise_on_fail`. A requested fusion that no
module supports now always logs a warning and is skipped. The default
fusions list (`["gate_up", "qkv"]`) is applied to every model, including
models that lack those modules, so warning is the right single behavior
instead of a flag.
- Dead `ProgressTracker` class in `prime_rl/utils/logger.py`, plus the
`_progress` branch in `build_log_entry` that only it could reach.
Nothing in the repo, `deps/verifiers`, or `deps/prime-envs` references
them. JSON logging itself is unchanged.

**Breaking changes**
- `[trainer.model.fusions] raise_on_fail` is no longer a config field;
configs that set it will fail validation.
- `apply_model_fusions` no longer takes `raise_on_fail` and never raises
for unsupported fusions.
- `prime_rl.utils.logger.ProgressTracker` is removed.

**Validation**
- `ruff check .` and `ruff format --check .`
- `pytest tests/unit/train/models/test_fusions.py
tests/unit/test_configs.py tests/unit/utils -m "not gpu"` (CPU only; no
GPU on this machine, so GPU/integration tests were not run)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Config that set `raise_on_fail` will fail validation; fusion behavior
only softens (warn/skip). Logger removal is dead code with no callers.
> 
> **Overview**
> Removes **`trainer.model.fusions.raise_on_fail`** and standardizes
runtime fusions: unsupported fusion names always **log a warning and are
skipped** instead of optionally failing startup.
**`apply_model_fusions`** drops the `raise_on_fail` argument and never
raises for missing module support; **`setup_model`** calls it without
that flag.
> 
> Also deletes unused **`ProgressTracker`** and the JSON **`_progress`**
handling in **`build_log_entry`**—standard JSON logging is unchanged.
> 
> Docs in **`advanced.md`** match the warn-and-skip behavior. Unit tests
now assert unsupported fusions return `{}` rather than raising.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ed70c99254a99460d4d582d001ce282ad2eb03b7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 12:40:44 -07:00
faresobeidandGitHub 23017482f9 chore(configs): remove configs/basic and unreferenced debug configs (#3777)
Removes `configs/basic/` and the debug configs
`configs/debug/concurrency.toml` and `configs/debug/multi-env/`.

**Why:** `configs/basic/*` are dev-size copies of `examples/basic/*`,
and they have already drifted from them. For example,
`configs/basic/reverse-text/rl.toml` no longer has the eval block. The
remaining differences are GPU count, batch size and group size, which
can all be set from the CLI. No test runs these configs;
`test_configs.py` only checks that they parse, using a glob. Nothing in
the repo references the two debug configs, so they have no owner and
will drift the same way.

**Changes**
- Deleted
`configs/basic/{alphabet-sort,hendrycks-sanity,reverse-text,wiki-search,wordle}`,
`configs/debug/concurrency.toml`, and `configs/debug/multi-env/`. Kept
`configs/debug/{algo,eval,fake}`.
- `README.md`: the 2-GPU check now uses
`examples/basic/reverse-text/rl.toml`. That example already defaults to
1 trainer GPU + 1 inference GPU.
- `configs/README.md` / `examples/README.md`: removed the `basic/` and
`multi-env/` entries and the "smoke-tested" claim.
- `examples/basic/{wiki-search,wordle,hendrycks-sanity}/README.md`:
added the 2-GPU overrides `--deployment.num-train-gpus 1
--deployment.num-infer-gpus 1 --orchestrator.batch-size 128`. Inference
DP adjusts to the GPU count automatically.

**Breaking:** commands like `uv run rl @ configs/basic/...` no longer
work. Use `examples/basic/...`, with the overrides above for 2 GPUs.

**Validation**
- `rl @ examples/basic/{wiki-search,wordle,hendrycks-sanity}/rl.toml
--deployment.num-train-gpus 1 --deployment.num-infer-gpus 1
--orchestrator.batch-size 128 --dry-run`: all three resolve. For wordle,
the resolved inference has `data_parallel_size = 1`.
- `pytest tests/unit/test_configs.py -m "not gpu"`: 199 passed.
- `ruff check .` and `ruff format --check .`: clean.
- No GPU runs; this machine has no GPU.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation and config path removal only; users must switch to
example configs and optional CLI flags for 2-GPU dev runs.
> 
> **Overview**
> Removes duplicate **`configs/basic/`** tutorial configs and two
unreferenced debug configs (**`concurrency.toml`**,
**`multi-env/rl.toml`**), so **`examples/basic/`** is the single source
for small end-to-end runs.
> 
> **Breaking:** `uv run rl @ configs/basic/...` no longer works. The
root README’s 2-GPU stack check now uses
**`examples/basic/reverse-text/rl.toml`**. **`configs/README.md`**
documents **`debug/algo`**, **`fake`**, and **`eval`** only.
> 
> For former 2-GPU **`basic`** setups, **`hendrycks-sanity`**,
**`wiki-search`**, and **`wordle`** READMEs document CLI overrides:
`--deployment.num-train-gpus 1 --deployment.num-infer-gpus 1
--orchestrator.batch-size 128`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4776cecdef44708f93c73075a5d57b5eb87a007f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 12:37:05 -07:00
faresobeidandGitHub 37bdd552f6 chore: remove KL penalty term from RL policy losses (#3810)
Removes the KL penalty/regularizer term from the RL policy losses.

## What changed
- `IPOLossConfig.kl_tau` removed
(`packages/prime-rl-configs/.../configs/trainer.py`); `IPOLoss` no
longer adds `kl_tau * log_ratio^2` (`src/prime_rl/trainer/rl/loss.py`).
- `ref_kl_loss_fn`: removed the hard-coded `1e-3 * log_ratio^2` drift
regularizer. The `ref_kl` component itself (reverse KL to the reference
model as the PG signal for OPD/OPSD) is unchanged.
- `mismatch_kl` metrics are unchanged.
- Docs (`docs/algorithms.md` IPO formula + knob table, IcePop wording)
and `skills/configs/SKILL.md` updated.
- `tests/unit/train/rl/test_loss.py`: the IPO/IcePop reference test no
longer uses `kl_tau`.

No config or example in the repo set `kl_tau`, so there are no TOML
changes.

## Breaking / behavior changes
- **Breaking:** TOMLs that set `[trainer.loss] kl_tau` now fail
validation (extra field). Delete the line. `kl_tau` defaulted to `0.0`,
so runs that did not set it behave the same.
- **Behavior change (OPD/OPSD):** the `ref_kl` loss no longer has its
fixed `1e-3` squared-log-ratio regularizer. Gradients for `opd`/`opsd`
runs change slightly.

## Conflicts
Draft #3776 (removes PPO/CISPO) also touches `loss.py`,
`configs/trainer.py`, and the IPO default line in
`skills/configs/SKILL.md` (which mentions `kl_tau`). Expect a small
textual conflict there; resolve by dropping `kl_tau` from that line.

## Tests
- `pytest tests/unit/train/rl tests/unit/test_configs.py -m "not gpu"`:
214 passed, 25 deselected (GPU tests, including `test_loss.py`, which
needs CUDA, were not run).
- `ruff check` + `ruff format --check`: clean.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core RL and on-policy distillation loss math; OPD/OPSD runs
will see different gradients, and TOMLs with `kl_tau` break at config
validation.
> 
> **Overview**
> Removes squared log-ratio **KL penalty terms** from RL training so
policy losses are pure importance-weighted policy gradients (plus
existing trust-region masking).
> 
> **IPO** drops `kl_tau` from `[trainer.loss]` and stops adding `kl_tau
* log_ratio²` in `IPOLoss`; configs that still set `kl_tau` will fail
validation. **OPD/OPSD** `ref_kl` keeps reverse-KL as the PG signal but
loses the fixed `1e-3 * log_ratio²` drift regularizer, so distillation
gradients change slightly. Docs (`docs/algorithms.md`,
`skills/configs/SKILL.md`) and unit tests are aligned; `mismatch_kl`
metrics are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6e2f6f96f9aee85f66bed5d525ecac3ec6d4fe5b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 20:29:23 +01:00
HubertandGitHub e094f0860f fix(monitors): omit training arrays from live trace records (#3763)
Live MoE trace deltas contain binary `routed_experts` and
`sampling_mask` payloads. `FileMonitor.log_live()` currently serializes
those bytes through `default=str`, expanding them into escaped text and
adding serialization work to live monitoring.

Filter these two fields from copied node dictionaries inline before
writing live records, and omit `routing_repairs` since the corresponding
arrays are absent from those records. The original deltas and training
payloads remain unchanged; message content, token IDs, calls, semantic
links, dispatch metadata and scalar updates remain available to the live
reader.

Validation ran separately from this PR: two regression-test cases passed
against the deployed runtime dependencies, covering live-file
reconstruction, routing repairs, unchanged training inputs, and both
completion and discard cleanup. Ruff and `git diff --check` passed. A
saved trace with 188 deltas reconstructed successfully through the
patched `FileMonitor`. This PR contains only the inline logging fix; it
does not claim to resolve every source of orchestrator event-loop lag.

Additional CPU replay measurement on a saved routing-heavy delta:
serialization took **1.43–1.51 s before vs 0.040–0.055 s after**,
approximately **31× faster** at the median; serialized JSON shrank from
**306.8 MB to 31.8 MB**. These are serialization measurements, not an
end-to-end training speed claim.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Scoped to live-monitor serialization; training data and episode
logging are unchanged.
> 
> **Overview**
> **Live trace JSONL writes no longer include MoE training payloads.**
> 
> `FileMonitor.log_live()` now builds a display-only copy of each delta
before `orjson` serialization: it drops top-level `routing_repairs` and
strips per-node `routed_experts` and `sampling_mask`. Dispatch metadata
on open deltas is unchanged (`dispatch` is still attached when `"open"`
is present).
> 
> Upstream deltas and training paths are untouched; this only shrinks
what lands under `traces/live/` and avoids turning large binary arrays
into escaped strings via `default=str`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ff8908b15dd2444474af8a4f3aaa04a1fa8e62ac. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 10:53:55 -07:00
samsjaandGitHub 93cfa84dcc refactor(trainer): move SignSGD into trainer/optim (#3764)
## What does this PR do?

Moves `sign_sgd.py` from `prime_rl/trainer/` into
`prime_rl/trainer/optim/` so all optimizer implementations live in one
place. Pure file move — git detects a 100% rename so history and blame
are preserved. No functional changes.

Updated the three import sites:
- `trainer/optim/__init__.py`
- `trainer/optim/offload.py`
- `tests/unit/train/test_cpu_adam.py`

No other references to `prime_rl.trainer.sign_sgd` exist; configs, docs,
and example TOMLs use the `sign_sgd` optimizer type value, which is
unchanged.

## Validation

- `ruff check` and `ruff format --check` pass
- `tests/unit/train/test_cpu_adam.py` — 3/3 passed
- sign_sgd-related tests in `tests/unit/test_configs.py` — 13/13 passed
- Sanity-checked `SignSGD` imports and a full optimizer step from the
new path

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Import-path-only refactor with no logic changes; low risk if all call
sites were updated (verified no remaining `prime_rl.trainer.sign_sgd`
references).
> 
> **Overview**
> **SignSGD** is relocated from `prime_rl/trainer/sign_sgd.py` into
`prime_rl/trainer/optim/sign_sgd.py` so it sits alongside the other
optimizer implementations. Behavior is unchanged; imports are updated in
`trainer/optim/__init__.py`, `trainer/optim/offload.py`, and
`tests/unit/train/test_cpu_adam.py` to use
`prime_rl.trainer.optim.sign_sgd`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
943a774d6ff8996476ef736a0f7ed8bb4d0df334. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-02 17:15:50 -07:00
Florian BrandandGitHub 43be755e39 feat(dashboard): add persistent trace URLs (#3759) 2026-10-02 16:54:17 -07:00
Florian BrandandGitHub 6c5e1ebc52 fix(dashboard): wrap trace viewer toolbar (#3760) 2026-10-02 16:54:09 -07:00
Florian BrandandGitHub ee9bfb34db fix(dashboard): group collapsible tool results with calls (#3761) 2026-10-02 16:54:01 -07:00
Konstantin DunasandGitHub 46e5082d9b chore: bump verifiers to 4fd5921 and prime-envs to d4fb80a (#3762) 2026-10-03 01:33:17 +02:00
samsjaandGitHub 28c627d73f feat(configs): auto-resolve moe_router_dtype (fp32 for RL, bf16 for SFT) (#3757)
`model.moe_router_dtype` gains an `auto` value, the new default,
resolved per trainer at config-validation time:

- **RL → `float32`** (unchanged): keeps matching the fp32-routed
checkpoints RL trains from (e.g. GLM-5.x via Megatron
`--moe-router-dtype fp32`).
- **SFT → `bfloat16`** (new default): the gate GEMM runs in the model
compute dtype and the router no longer gets its dedicated fp32 FSDP unit
or fp32 full-offload policy.

Explicit `float32` / `bfloat16` still win in both trainers. Because
resolution happens in the `SFTConfig` / `TrainerConfig` validators,
`setup_model`, `setup_fsdp`, and the full-offload dtype policy needed no
changes, and the resolved-config JSON dump records the concrete dtype
(resume/repro never sees `auto`).

### Testing
- `uv run pytest tests/unit/test_configs.py`: 208 passed (includes
`test_load_configs` over every checked-in config file).
- End-to-end via `cli`: GLM-5.3 SFT (`base + math-10k`) → `bfloat16`;
wordle RL, GLM-5.3 `swe.toml`, GLM-4.5-air RL → `float32`; explicit
`--model.moe-router-dtype float32` on an SFT config is kept.
- `ruff format --check` / `ruff check` clean.

### Behavior change
MoE SFT runs (GLM-5.3 SFT, Qwen3.6 VLM SFT, Qwen3-30B SFT examples) now
train with a bf16 router by default; pin `moe_router_dtype = "float32"`
to keep the old behavior. RL behavior is unchanged.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> MoE SFT runs change default router numerics and FSDP layout; RL stays
fp32. Pin `moe_router_dtype = "float32"` on SFT to preserve prior
behavior.
> 
> **Overview**
> Adds **`auto`** as the default for `model.moe_router_dtype`, resolved
at **config validation** in trainer-specific validators so dumps and
runtime never see `auto`.
> 
> **RL (`TrainerConfig`)** still ends up on **`float32`** routing
(unchanged behavior vs the old default). **SFT (`SFTConfig`)** now
defaults to **`bfloat16`** for the MoE gate GEMM, avoiding the dedicated
fp32 router/FSDP path unless you set `moe_router_dtype` explicitly.
> 
> Explicit **`bfloat16`** / **`float32`** overrides are unchanged. A
unit test locks in per-trainer resolution.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bbbfc02947c60ab8e81b0fad853667d1633341c8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-02 14:46:01 -07:00
NeoandGitHub d4a11f2379 perf(trainer): keep EP experts in the block's FSDP unit so MoE blocks compile with fullgraph (#3753)
## Why

Under expert parallelism the EP experts were their own FSDP unit nested
inside each transformer block. FSDP2 wraps its hooks in
`torch._dynamo.disable`, so dynamo graph-broke at the experts and the
MoE dispatch/combine glue and the activation-checkpointing policy ran
eagerly. On the Qwen3-235B SFT profile against torchtitan that was ~2.7
s/step of unfused elementwise and index kernels plus 3.4x the kernel
launches, and `compile.fullgraph=true` failed outright (job 1180).
torchtitan avoids this by sharding the experts over the EP-complement
mesh from the block's own `fully_shard` call.

## What

- The block's `shard_placement_fn` returns a `ShardPlacementResult` with
the `dp_shard_mod_ep` mesh for expert parameters. FSDP2 in torch 2.13
groups one unit's parameters by process group, so the experts still
all-gather and reduce-scatter over the EP-complement mesh, with no
nested unit and no hook inside the compiled block.
- The gradient divide factor is set on the block. With an fp32 reduce it
is the dense parameters' default divisor (`ReduceOp.AVG` over the shard
group), so dense numerics are unchanged; the experts keep dividing by
the full data-parallel size as before.
- Explicit EP prefetch lists drop the experts module.
- `compile.fullgraph=true` on a custom MoE model now requires
`moe_router_dtype="bfloat16"`: the fp32 router is still its own FSDP
unit inside the block. `setup_fsdp` raises early with that message. The
fp32-router default is unchanged.

## Benchmark

Qwen3-235B-A22B-Thinking-2507 SFT, 4 nodes x 8 B300, FSDP over 32 GPUs,
ep=8, seq 16384 (one packed sample per GPU per step), balanced routing,
AdamW fp32 states, full AC, 20 steps, steady state = steps 5..20, same
MFU formula in every row (280.8 GFLOP/token). Measured together with the
FA4 custom op (#3676 / the sibling `mario/optimize-fa4-custom-op` PR),
which fullgraph also needs on B300.

| run | s/step | MFU | tok/s/GPU | peak GiB |
|---|---|---|---|---|
| torchtitan 9e159aed7, fullgraph | 5.01 | 40.9% | 3273 | 144 |
| prime-rl before, graph breaks at the expert unit | 6.98 | 29.3% | 2347
| 140 |
| **prime-rl after, fullgraph** | **4.40** | 46.5% | 3726 | 141 |
| prime-rl before, real routing (job 1184) | 9.51 | 21.5% | 1724 | 142 |
| **prime-rl after, fullgraph, real routing (job 1461)** | **6.11** |
31.2% | 2681 | 141 |

Per-step losses match the previous runs on the same data order (balanced
and real routing). A rank-0 torch-profiler trace of the new step (4.46
s) vs the old one (7.26 s): eager MoE glue went from 2.95 s elementwise
+ 1.09 s index kernels to 0.62 s of inductor kernels, kernel launches
from 33.9k to 9.9k, and the per-op Python AC dispatch mode is gone. The
remaining step is GEMM 47%, the EP all-to-all 22% (still on the compute
stream, fully exposed), fused glue 14%, attention 7%. prime-rl is ahead
of torchtitan because torchtitan's compute stream idles 1.55 s waiting
on its 1.34 s all-to-all, while prime-rl's inline all-to-all takes 0.99
s.

Caveat: the MFU formula charges dense causal attention, but packed
documents make attention 0.2 to 0.3 s of the step in both stacks, so
absolute MFU is about 2x overstated for every row; the comparison is
unaffected. A 1-node Qwen3-30B-A3B fullgraph smoke run and
`tests/unit/train/models/test_moe.py` pass.

## Open

- fp32 router under fullgraph needs the router out of its own FSDP unit
(ignored params with a replicated fp32 gate and a manual grad
all-reduce, or a bf16 gate). Not decided here.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes distributed FSDP sharding and gradient divisors for EP MoE
blocks, which affects training numerics and performance paths;
misconfiguration now errors at setup instead of silent graph breaks.
> 
> **Overview**
> **MoE + expert parallelism (EP) no longer uses a nested FSDP unit on
`experts`**, so `torch.compile(fullgraph=True)` can capture whole
transformer blocks without dynamo breaking on FSDP hooks inside the
block.
> 
> Under EP, expert weights still shard on the EP-complement mesh via a
per-block `shard_placement_fn` that returns `ShardPlacementResult` for
expert parameters, while dense block params use the usual placement.
Gradient scaling moves to the **transformer block**
(`set_gradient_divide_factor`) instead of the removed experts submodule.
EP forward/backward **prefetch** lists drop explicit `experts` prefetch
and only add the fp32 **router** when it remains its own FSDP module.
> 
> **Config/docs:** `CompileConfig.fullgraph` documents that custom MoE +
fullgraph needs `moe_router_dtype="bfloat16"`. **`setup_fsdp` fails
fast** if `compile.fullgraph=true` is combined with the default fp32
router, since that router must stay a separate FSDP unit inside the
compiled block.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d2f76357ccc0d893e3e7db69848738d3bf29b688. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-02 14:45:39 -07:00
2b420a1df1 fix(trainer): run FA4 through a custom op so compile can trace attention (#3754)
Same change as #3676 on a `mario/optimize-*` branch, so the fullgraph
work lands as independent PRs; supersedes #3676.

## Why

FA4's `flash_attn_varlen_func` is a Python `autograd.Function` that
calls `torch._guards.active_fake_mode()`, which dynamo refuses to trace.
Under activation checkpointing each block is one checkpointed region, so
that graph break drops the whole block to eager for every FA4 model,
dense or MoE, and `compile.fullgraph=true` fails (job 1175).

## What

- Wrap FA4's varlen forward and backward in a
`prime_rl_attn::flash_attn_4_varlen` custom op with fake impls and
registered autograd, dispatched through `FlashAttention._funcs` like the
other versions.
- Add the `prime_rl_attn` namespace to the selective activation
checkpointing save list so attention is not recomputed in backward.

Needed, together with the sibling `mario/optimize-fsdp-expert-fold` PR,
for the Qwen3-235B result of 4.40 s/step vs torchtitan's 5.01 s at seq
16k on 4 nodes.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes the FA4 attention forward/backward path and autograd behavior;
incorrect custom-op wiring would affect training correctness, but scope
is limited to FA4 + compile/checkpointing.
> 
> **Overview**
> Flash Attention 4 varlen is no longer called via FA4’s untraceable
Python `autograd.Function`. Forward and backward are wrapped in
**`prime_rl_attn::flash_attn_4_varlen`** (and a matching backward op)
with fake kernels and registered autograd, and **`FlashAttention`**
version 4 now dispatches through **`flash_attn_4_varlen_op`**.
> 
> That avoids Dynamo graph breaks inside activation-checkpointed blocks
(which previously forced whole blocks to eager and broke
**`compile.fullgraph=true`**) and lets selective activation
checkpointing treat attention as an opaque op.
> 
> **`prime_rl_attn`** is added to the selective checkpoint **save**
namespace list so FA4 attention outputs can be saved instead of
recomputed on backward.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
37cdea5d1e3eddcd99fab64c54101cf1c5c96833. 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: sami jaghouar <sami.jaghouar@gmail.com>
2026-10-02 14:12:27 -07:00
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
1b929ec184 feat: depend on the prime CLI instead of prime-sandboxes (#3717)
## Summary

- Replace `prime-sandboxes>=0.3.2` with `prime>=0.8.0` in the core
dependencies. `prime` 0.8.0 drops its `verifiers==0.2.0` pin
([prime#940](https://github.com/PrimeIntellect-ai/prime/pull/940)).
`prime-sandboxes` now comes in transitively and stays locked at 0.3.2.
- Remove the separate `uv pip install 'prime>=0.7'` step and its
`verifiers` override from `Dockerfile.cuda`. `uv sync` now installs the
CLI into `/app/.venv` at the locked version.
- Remove the same replay step from the `PRIME_RL_REF` source overlay in
`scripts/docker-entrypoint.sh`.
- Remove `uv tool install prime` from `scripts/install.sh`. `uv sync`
installs the CLI into the project venv.
- Lock changes: add `prime` 0.8.0, `prime-evals` 0.2.4 and
`gitignore-parser` 0.1.13. Bump `prime-traces` 0.0.4 → 0.0.7.

## Verification

- `uv lock` resolves. `uv sync --all-packages --locked` succeeds.
- `uv run --no-sync prime --version` prints `Prime CLI version: 0.8.0`.
- `verifiers` still imports from the editable `deps/verifiers`.
`prime_rl.configs.orchestrator` imports.

I did not build the image.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how the Prime CLI and sandbox stack are installed in Docker
and dev venvs; wrong resolution could still break editable `verifiers`
imports, though the explicit override path is gone.
> 
> **Overview**
> **Switches the project’s direct dependency from `prime-sandboxes` to
the `prime` CLI (`>=0.8.0`)**, so the CLI is installed via `uv sync` at
the locked version instead of a separate install path. `prime-sandboxes`
remains available transitively through `prime`.
> 
> **Removes the Docker/runtime workaround** that ran `uv pip install
'prime>=0.7'` with a `verifiers` overrides file after sync (in
`Dockerfile.cuda` and `scripts/docker-entrypoint.sh`). That existed
because older CLI versions pinned `verifiers==0.2.0` and could replace
the editable `deps/verifiers` wheel; `prime` 0.8.0 drops that pin.
> 
> **Simplifies local setup** by dropping `uv tool install prime` from
`scripts/install.sh`—developers use `uv run prime` from the project
venv.
> 
> Lockfile updates add `prime` 0.8.0 and its new deps (`prime-evals`,
`gitignore-parser`) and bump `prime-traces` to 0.0.7.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
696ae027e29ff470d9f7d40a0d82e3797704f2a1. 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-28 19:39:40 -07:00
d72e7e8b1e feat: bump vllm to 0.30.0 (#3716)
## Summary

- Bump vLLM to
[v0.30.0](https://github.com/vllm-project/vllm/releases/tag/v0.30.0).
- Bump the `nvidia-cutlass-dsl` override to 4.7.1. vLLM 0.30.0 and its
quack-kernels 0.6.5 require it.
- Set `--enable-scale-out` on the inference server. vLLM 0.30.0 no
longer registers `/inference/v1/generate` on `vllm serve` without it,
and the orchestrator generates through that endpoint. Set
`inference.vllm.enable_scale_out = false` to opt out.
- Remove two DeepSeek V4 patches that upstream now covers:
- `monkey_patch_deepseek_v4_per_layer_rope`: fixed by
vllm-project/vllm#54815. The reference RoPE test now checks upstream
directly.
- `monkey_patch_deepseek_v4_bf16_o_proj`: upstream
`deep_gemm_fp8_o_proj` has a bf16 path since vllm-project/vllm#56228.

The other patches in `prime_rl/inference/patches.py` stay: their
upstream code is unchanged, or the upstream fix is not released yet.

## Relevant upstream changes

- vllm-project/vllm#54901: MRV2 compacts sampling masks on the GPU. This
fixes an about 2x RL step-time regression with `--return-sampling-mask`.
- vllm-project/vllm#53187: `/inference/v1/generate` returns prompt
metadata. This unblocks #3710.
- vllm-project/vllm#52957: pause and sleep no longer run 32 dummy
forwards per DP rank.
- vllm-project/vllm#56706: fixes stale QK-norm weights after a weight
refit.
- vllm-project/vllm#51485: sleep mode releases NCCL communicator memory.
- vllm-project/vllm#54646: MRV2 CUDA graph capture freezes gc (engine
init 28.9s → 8.2s on H200).
- vllm-project/vllm#54518: NIXL no longer asserts when it cleans up a
failed transfer twice.
- vllm-project/vllm#55548: rsLoRA scaling in MoE expert packing.

## Verification

Ran 5-step RL smoke runs on SLURM (H200) against this branch:

- `configs/basic/reverse-text/rl.toml`, single-node (1 trainer GPU + 1
inference GPU): 5/5 steps, no errors.
- `configs/basic/reverse-text/rl.toml`, multi-node (1 trainer node + 1
inference node): 5/5 steps, no errors.
- `examples/advanced/glm-4.5-air/swe.toml` (2 trainer nodes, 4 × TP8/EP
inference replicas, router replay), with `batch_size = 32`, `group_size
= 8`, and no eval, checkpoint, or wandb. Ran the same config on `main`
(vLLM 0.29.0) for comparison:

| | main (vLLM 0.29.0) | this branch (vLLM 0.30.0) |
|---|---|---|
| Steps completed | 5/5 | 5/5 |
| Tracebacks | 0 | 0 |
| Mismatch KL | 1e-4 – 2e-4 | 1e-4 – 2e-4 |
| Grad norm | 0.33 – 0.87 | 0.26 – 0.44 |
| Reward (steps 1–5) | 0.28, 0.31, 0.13, 0.34, 0.34 | 0.34, 0.34, 0.38,
0.25, 0.41 |
| Trainer peak memory | 110 – 112 GiB | 110 – 113 GiB |

Both runs have a few `scaleswe` harness-setup failures (`uv python find
--script` is unsupported by the sandbox image's uv). This is a verifiers
runtime issue and is independent of the vLLM version.

Unit tests: `tests/unit/inference` and `tests/unit/test_configs.py` pass
(212 tests).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Major inference-engine upgrade touches RL generation, router replay,
and DeepSeek V4 serving; remaining monkey patches and new scale-out
default can change runtime behavior across deployments.
> 
> **Overview**
> **Bumps the GPU inference stack from vLLM 0.29.0 to 0.30.0**,
including lockfile updates for CUTLASS DSL 4.7.1, quack-kernels 0.6.5,
FlashInfer 0.6.18.post1, and huggingface-hub 1.32.0 on Linux.
> 
> **Inference defaults:** vLLM args now turn on **`enable_scale_out`**
when not overridden, so `/inference/v1/generate` stays available for the
orchestrator under 0.30 (opt out with `inference.vllm.enable_scale_out =
false`).
> 
> **Patch cleanup:** Removes
**`monkey_patch_deepseek_v4_per_layer_rope`** and
**`monkey_patch_deepseek_v4_bf16_o_proj`** because upstream 0.30 covers
those paths; DeepSeek V4 RoPE unit tests assert against stock
`build_deepseek_v4_rope` instead of the old monkey patches.
> 
> **Docs:** Router-replay text no longer pins “vLLM 0.29”; it states
standard deployments use the V2 runner.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3c6229d9b08a7f32f74d5cab1dfd1fbb83c43482. 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-28 18:45:39 -07:00
2662c9ace1 feat: select taskset tasks per train and eval source (#3703)
## Summary

- Give every train and eval source a `select` block (`EnvConfig.select`,
a `vf.SelectConfig`): `include`/`exclude` by task `idx`, `ids`, `keys`
or `names`, then `shuffle`, `skip` and `limit`. The orchestrator loads
each source's tasks with `vf.load_taskset(...).select(source.select)`.
prime-rl no longer shuffles or slices tasksets itself, so it picks the
same tasks as `vf-eval` for the same selection.
  ```toml
  [[orchestrator.train.source]]
  env.taskset.id = "gsm8k"
  select.exclude.idx = [":100"]   # hold out the first 100 tasks

  [[orchestrator.eval.source]]
  env.taskset.id = "gsm8k"
  select.include.idx = [":100"]
  ```
- Every source group (`[orchestrator.train]`, `[orchestrator.eval]`, SFT
`[eval]`, the top level of `uv run eval`) takes a shared `select` block.
The same before-validator that layers the group `env` block layers it
under each source, field by field, and a field that the source sets
wins. A source's `include` or `exclude` replaces the group's whole
block. A source `select` that does not validate keeps its own block, so
its error surfaces. For example, this evaluates 128 tasks of each
taskset:
  ```toml
  [orchestrator.eval.select]
  limit = 128
  ```
- Only `uv run eval` has the `-n`/`-s` short flags
(`select.limit`/`select.shuffle`), through `vf.SelectCLIConfig`. The
`rl`, `orchestrator` and `sft` CLIs have several `select` blocks, so
they get no short flags.
- The dashboard derives the expected episode count from `select.limit`,
per source and for vf-shaped configs.
- Migrate the configs, examples and docs from `num_examples` to
`select.limit`. Group-level blocks use `[... .select]` tables.
- Update the eval docs and skill: resume no longer checks the config
(#3690), and a resume matches landed episodes to the new `select` by
`task.key`.
- Update the `configs` skill (`[select]`, `-s`). Update the eval skill:
the `select` shorthands, and common patterns (a random subset, tasks by
position or name, dropping broken tasks, contiguous and random
train/test splits via `include`/`exclude` and `skip`).
- Pin `deps/verifiers` to its main, which merged
PrimeIntellect-ai/verifiers#2695 (`Taskset.select`, `vf.SelectConfig`).
Raise the `verifiers` minimum to `0.3.2.dev152`, its first release, in
both `pyproject.toml` files, so the slim `prime-rl-configs` install gets
it.

Companion PRs: PrimeIntellect-ai/verifiers#2695 (merged),
PrimeIntellect-ai/prime-envs#852 (independent; `compile_statements`
stops calling `head()`).

## Breaking

- `EnvConfig.shuffle` is removed. Use `select.shuffle`.
- `EvalSourceConfig.num_examples` and the group-level `num_examples` are
removed. Use `select.limit` on the source or on the eval block.
- The shuffle seed changes from 42 to verifiers' default 0
(`select.seed`). Existing `shuffle = true` configs pick other tasks, so
eval numbers before and after this change are not comparable.
- Default task keys change for tasksets that never set `idx` (see
verifiers#2695). An interrupted eval of such a taskset cannot resume
across this change.

## Verification

- The slim-install CI check, run locally: the `prime-rl-configs` wheel
installed outside the workspace resolves `verifiers 0.3.2.dev152`, and
the workflow's import script passes.
- `uv run pytest tests/unit/test_configs.py tests/unit/eval
tests/unit/orchestrator tests/unit/test_dashboard_timeline.py`: 296
passed (2 vLLM-only tests deselected; `vllm` is not installed on the
test box). `test_load_configs` loads every migrated TOML.
- Real configs and CLI calls against a local mock OpenAI server (no
inference spend). The mock counted the model calls, and the selected
task `idx` matched an independent oracle:
- `uv run eval @ configs/debug/eval/single-turn.toml`: tasks 0–7 × 2, 16
calls.
- `uv run eval @ configs/debug/eval/resume.toml`: first run 16 calls.
`--resume --select.limit 10` restored 16 episodes and ran only tasks 8–9
(4 calls). `--resume --select.include.idx 0:5` kept the landed episodes
of tasks 0–4 and made no model calls.
- `uv run eval gsm8k -n 4 -s --select.exclude.idx '[0]'`: the oracle's 4
tasks, 4 calls.
- A two-source TOML that splits gsm8k into `[:50]` and the rest under a
group `select` default: both sources match the oracle, 5 calls.
- Config checks: train and eval group `select` defaults reach every
source, a source's own fields win, and the resolved `OrchestratorConfig`
re-validates to the same values. `uv run rl -h`, `orchestrator -h` and
`sft -h` list no `-n`/`-s`; `uv run eval -h` does.
- `uv run rl --dry-run` on `configs/debug/algo/grpo.toml`,
`examples/basic/reverse-text/rl.toml` and
`configs/debug/multi-env/rl.toml`, and `uv run sft --dry-run` on
`examples/basic/reverse-text/sft.toml`: group eval limits (128, 64, 32)
resolve onto each source, a per-source `select.limit = 256` is kept, and
train sources default to all tasks.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking config renames and verifiers-driven
selection/shuffle/task-key semantics affect every train/eval run and
eval resume comparability across the upgrade, though runtime logic is
largely delegated to verifiers.
> 
> **Overview**
> Replaces **`num_examples`** and per-source **`shuffle`** with
verifiers' **`select`** block on every train/eval source (and
group-level `[select]` / `[orchestrator.eval.select]` /
`[eval.select]`). **`select.limit`** caps how many tasks run;
**`include`/`exclude`**, **`shuffle`**, **`skip`**, and **`seed`**
follow verifiers' ordering so prime-rl matches **`vf-eval`** for the
same selection.
> 
> The orchestrator now loads tasks with
**`vf.load_taskset(...).select(source.select)`** instead of client-side
shuffle (seed 42) and **`islice`**. Group config merging layers shared
**`select`** onto each source like **`env`**. **`uv run eval`** maps
**`-n`/`-s`** to **`select.limit`/`select.shuffle`**; eval resume no
longer validates config against the interrupted run—landed episodes are
matched by **`task.key`** to the new **`select`**.
> 
> All example/debug/CI TOMLs, docs, and skills are migrated.
**`verifiers`** minimum is raised to **`0.3.2.dev152`**. The dashboard
expects **`select.limit`** when estimating episode counts.
> 
> **Breaking:** rename configs from **`num_examples`** →
**`select.limit`**, **`shuffle`** → **`select.shuffle`**; default
shuffle seed and task keys may differ from pre-change runs
(resume/comparability implications).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f30798a0a6d20e3a474cb58a6dd48a8a85eb6ace. 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-28 15:39:41 -07:00
NeoandGitHub cde3bcd546 Add new chunked loss impl based on torchtitan (#3673)
Port of torchtitan based chunked loss, which greatly imporves perf on
hopper for smaller models:

<html>
<head>

</head>
<body>
<html>
<head>

</head>
<body>

Model | Old chunked head | New chunked head | Gain
-- | -- | -- | --
Qwen3-30B-A3B, 8×H200, no AC, chunk 1024 | 6.71s | 6.20s | −7.6% step
time (+8.2% throughput)
Qwen3-235B-A22B, 4×8 H200, full AC, chunk 2048 | 14.09s | 14.00s | −0.6%
step time


</body>
</html>


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core LM-head autograd and SFT loss computation; RL/temperature
paths are mostly untouched but shared head code affects all training
modes using injected heads.
> 
> **Overview**
> Adds a **torchtitan-style chunked summed cross-entropy** path on the
fused LM head when `labels` are passed **without** `temperature`, so SFT
no longer fakes unit temperature and negates logprobs (or materializes
full logits on the vanilla path).
> 
> **`FusedOutputLinear`** now branches: no temperature →
`_ChunkedCrossEntropySumFn` returns scalar `loss` and folds
softmax-minus-one-hot grads into hidden/weight during forward (one token
chunk’s full-vocab logits at a time; backward only scales by the
upstream scalar). With temperature, behavior stays on the existing
logprob/entropy path.
> 
> **Vanilla and Gemma** heads mirror the same contract
(`cross_entropy_sum` or Gemma’s chunked logprob sum). SFT **`train.py`**
is unified to masked `IGNORE_INDEX` labels and `out["loss"]`. Config
docs now describe SFT fused-head behavior instead of claiming it is
disabled.
> 
> New unit tests check loss and gradients across fused/vanilla/Gemma
heads and chunk sizes, plus that temperature still uses logprobs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c4d2601e4cc55d6a921d80a33d19eb2e1407a230. 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 00:33:18 +02:00
Xuan-Phi NguyenandGitHub f962e9c104 feat(rl): add PPO and CISPO loss options (#3697)
## Motivation

The trainer exposes IPO and IcePop but has no built-in PPO or CISPO loss
for controlled math-RL comparisons. PPO clips the token importance-ratio
surrogate; CISPO clips a **detached** importance weight multiplying the
current log probability, so an out-of-band ratio still has a policy
gradient. Both need to operate on the trainer's existing eligible-token
masks and optional per-token weights.

## Design

- Add `PPOLossConfig` / `PPOLoss` with a sign-aware clipped surrogate
(`ratio_low=.8`, `ratio_high=1.2` by default). A separate
`max_importance_ratio=1e4` bounds the otherwise unbounded side while
preserving its capped gradient; metrics report clipped and capped
fractions.
- Add `CISPOLossConfig` / `CISPOLoss`:
`-stop_gradient(clip(p_trainer/p_inference, low, high)) * advantage *
log p_trainer` on eligible tokens. The default lower bound `0` disables
lower clipping; the default upper bound is `5`. Metrics report the
clipped fraction.
- Register both as explicit `trainer.loss.type` choices. Existing loss
defaults and model precision fields are unchanged. #3696 is merged into
main and supplies the stable ratio arithmetic used by the new losses.

## Validation completed

- On the pre-restack head, the GPU loss and config suite had **213
passed**, covering PPO/CISPO values, advantage signs, clipping
gradients, masks, and config validation. Focused rerun after metric
cleanup: **4 passed**. Ruff check/format and SLURM dry run passed.
- At the current #3697 head, 192 config tests, a CPU PPO/CISPO
forward/backward smoke check, and Ruff check/format passed. Four focused
PPO/CISPO GPU tensor tests passed on GPU 7 of
`prime-nebius-puku-h200-gpu-059`, covering clipping, gradients, extreme
ratios, and masks. No full model test was run.
- One-node CISPO smoke job `1575` completed two optimizer updates with
finite loss, entropy, and mismatch KL; orchestrator reward was `0.3125`
then `0.4062` on 32 trainable traces per step, with no episode errors.
It was intentionally stopped after that validation: [W&B
run](https://wandb.ai/primeintellect/qwen30b-math/runs/0c0bb28ed7734551b600cbe52253d7f5).

## Ongoing experiment and private TOML provenance

CISPO job on math qwen3-30b-3a is pending validation. The long-run
reward and stability outcome remains pending.
2026-09-28 13:34:56 -07:00
eligottsandGitHub 771953ee01 Train from inline multimodal rollouts (#3320) 2026-09-28 12:59:05 -07:00
Xuan-Phi NguyenandGitHub e3dd67633d fix(rl): stabilize IPO, IcePop, and ref-KL loss masking (#3696)
## Motivation

Packed RL batches can contain masked tokens with invalid or extreme log
probabilities. IPO, IcePop, and ref-KL previously formed importance
ratios before removing those tokens, so a nominally excluded token could
still produce `0 * inf` or `0 * NaN`. Accepted rare actions could also
overflow `exp(log p_trainer - log p_inference)`, including in
mismatch-KL diagnostics.

## Design

- Select eligible tokens before ratio and KL arithmetic; IcePop and
ref-KL also select accepted tokens before exponentiating their policy
terms.
- Compute IPO's absolute probability-difference gate using `exp(max(log
p, log q)) * -expm1(min(log p, log q) - max(log p, log q))`, retaining
the same `eps` decision with better behavior for nearby small
probabilities.
- Add `IPOLossConfig.max_importance_ratio` (default `1e4`) and cap
accepted IPO/ref-KL forward weights while retaining the capped
policy-gradient coefficient. Bound squared-log-ratio terms and mismatch
diagnostics so they remain finite for extreme finite log ratios.
- Keep masked/unmasked diagnostics, namespace ref-KL metrics, and treat
the shared mismatch-KL helper as internal; leave model precision
settings unchanged.

## Validation completed

- GPU loss tests: **17 passed**, including extreme-ratio forward and
gradient cases. Expanded config suite: **205 passed**. Ruff check and
format passed.
- The stacked CISPO and IPOv2 two-update smoke runs both completed with
finite trainer metrics and no episode errors:
[CISPO](https://wandb.ai/primeintellect/qwen30b-math/runs/0c0bb28ed7734551b600cbe52253d7f5),
[IPOv2](https://wandb.ai/primeintellect/qwen30b-math/runs/3ab7fbd7805d4ebca1d7ff2d1dc0cc84).
These validate this fix in downstream training paths; there was no
standalone PR1 training run.

## Ongoing experiments and config provenance

The 300-step CISPO and IPOv2 runs use this fix through stacked commits.
[IPOv2](https://wandb.ai/primeintellect/qwen30b-math/runs/9045de5680a44a1d9a9f6bd84e9c30f2)
is running; the CISPO job is queued for an 8-GPU node. Long-run outcomes
are pending.

The actual run TOMLs at
`docs/study/examples/qwen3-30b-a3b/math16k_slurm.toml`,
`math_cispo.toml`, and `math_ipov2.toml` are **local and uncommitted**.
Relative to the checked-in [advanced math
example](https://github.com/PrimeIntellect-ai/prime-rl/blob/f87fd0eb3372cded4cf6cfb20e41189796354eae/examples/advanced/qwen3-30b-a3b/math.toml),
the shared local base uses one 8-H200 node (2 trainer, 6 inference GPUs)
instead of two trainer plus two inference nodes; 16,384 sequence tokens
and 15,000 completion tokens instead of 32,768 each; EP 2 + Ulysses CP 2
instead of EP 8; batch size 32, zero allowed off-policy steps, and 64
inflight episodes instead of batch size 512, eight off-policy steps, and
1,024 initial inflight episodes (group size 8 is shared); and vLLM TP 2
/ DP 3 instead of TP 8. It runs 300 steps without the example's AIME
eval source. The model, math taskset, AdamW learning rate (`1e-6`), and
W&B project are shared. The private overlays select CISPO
(`ratio_high=5`) or IPOv2 (`eps=.3`, `ratio_cap=5`, entropy floor `.15`)
and point SLURM at this worktree.
2026-09-28 12:24:58 -07:00
Mika SenghaasandGitHub 0a437ae340 fix: bump verifiers and prime-envs for timeouts (#3709)
## Summary

- Bump Verifiers to
[`c35ebd32`](https://github.com/PrimeIntellect-ai/verifiers/commit/c35ebd320126ee17f6a570a4f3fb8ef0fe0b0ae1).
This includes [the merged timeout
fix](https://github.com/PrimeIntellect-ai/verifiers/pull/2697): an unset
agent rollout timeout no longer falls back to four hours.
- Bump prime-envs to
[`565e8a74`](https://github.com/PrimeIntellect-ai/prime-envs/commit/565e8a74c001b25706d7c958f36d7bb0cd504ddc).
Its Lean helper now works with Verifiers' taskset API.

## Breaking

- An unset agent rollout timeout now inherits the task timeout, or has
no separate limit. Set a positive `env.<agent>.timeout.rollout` to
retain a stage limit.
- `env.<agent>.timeout.rollout = 0` is rejected. Remove the field to
request no separate stage limit.

## Verification

- `uv lock --check --offline` passed with the updated submodules.
- A focused UV smoke test confirmed that an unset agent timeout resolves
to no limit, a positive override resolves as given, and zero fails
validation.
- `git diff --check` passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Behavior change to rollout timeout defaults affects how long agent
stages can run; misconfigured envs may run longer or fail validation
until configs are updated.
> 
> **Overview**
> Updates **Verifiers** and **prime-envs** dependency pins to pick up
upstream fixes and API alignment.
> 
> The Verifiers bump fixes agent rollout timeout resolution: an
**unset** `env.<agent>.timeout.rollout` no longer silently defaults to
four hours—it now follows the task timeout or has no separate stage cap.
**`env.<agent>.timeout.rollout = 0` is now invalid**; omit the field
instead of using zero to mean “no separate limit.” Configs that relied
on the old default or zero need an explicit positive rollout timeout if
they still want a stage limit.
> 
> The **prime-envs** bump updates its Lean helper for Verifiers’ taskset
API.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
dead789c54f98ce0e57ab3fe47f9e819a9b802eb. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-28 12:02:31 -07:00
9a55a0899c [ENG-6355] feat(docker): in-place PRIME_RL_REF source overlay for chart pods (#3686)
## Summary

Reworks the entrypoint's `PRIME_RL_REF` runtime source override so the
prime-rl-fft chart can run a branch on hosted FFT without building an
image for it. Inert unless `PRIME_RL_REF` is set; the default `docker
run` / chart path is unchanged.

The hook already existed (#2850) but was tuned for long-lived
containers: it cloned the full repo (~700 MB of `.git`) and `cp -a`'d
the 20 GB baked venv into a per-ref dir before syncing. As a per-pod
startup step that is unusable. Kubernetes `command:` also replaces the
image ENTRYPOINT, so the fft chart never ran this script at all; the
companion chart PR (PrimeIntellect-ai/fft#101) routes every prime-rl
container through it with a dispatcher-pinned sha.

## Changes

- **Shallow fetch by ref.** Fresh `git init` + `fetch --depth 1 origin
<ref>` + `checkout FETCH_HEAD`, then `submodule update --init
--recursive --depth 1` for the same four public submodules
`build_image.yaml` inits. GitHub serves branches, tags and full shas
alike; abbreviated shas are not fetchable and the comment says so. The
checkout is always fresh: a container is, and the fetch is seconds.
- **Sync into the baked venv instead of copying it.**
`UV_PROJECT_ENVIRONMENT=/app/.venv uv sync --inexact --locked ...` from
the checkout, with the same extras list as `Dockerfile.cuda`. uv
re-points the first-party editables at the checkout and reinstalls only
third-party pins that differ; flash-attn, deep-ep, mamba-ssm and friends
stay as baked. The chart's `uv run --no-sync <entrypoint>` commands
resolve the project from the new cwd.
- **Heavy-pin preflight.** Before syncing, compare the checkout's
`uv.lock` against `/app/uv.lock` for torch, torchvision, torchaudio,
triton, vllm, vllm-router, flash-attn, flash-attn-3, flashinfer-python,
tilelang, deep-ep, deep-gemm, mamba-ssm, nixl, prime-kernels and
quack-kernels. Any difference exits with a message to build an image
instead. The validator in fft runs the same check at dispatch
(PrimeIntellect-ai/fft#102); this is the backstop.
- **Pretend versions like the image build.** The shallow submodule
clones carry no tags, so hatch-vcs stamped verifiers/renderers
`0.0.1.dev1` and every `verifiers>=…` floor in the tree was unmet.
Resolve the same versions the Dockerfile does
(`docker-editable-pretend-versions.sh`), bake them into
`fallback-version` and drop the submodules' git metadata so the fallback
applies. (setuptools-scm's per-dist env vars turned out not to be
honored by hatch-vcs.)
- **Replay the image's prime CLI install, with its verifiers pin
overridden.** `Dockerfile.cuda` installs `prime>=0.7` after its lockfile
sync, which pulls prime-traces / prime-sandboxes / openai past the
lock's pins; the `--locked` sync here rolled them back and `prime env
install` could no longer import. The CLI also pins `verifiers==0.2.0`,
which replaces the editable with the PyPI wheel and breaks prime-rl's
own imports (see below). The replayed install passes `--overrides` with
a one-line file containing `verifiers`. **Workaround, marked
`FIXME(prime#940)` in the script:** remove the override once the prime
CLI drops verifiers as a dependency (PrimeIntellect-ai/prime#940),
together with the matching override in `Dockerfile.cuda` (#3705).
- **Git URL rewrite via `GIT_CONFIG_*` env** instead of `git config
--global`, so pods whose `HOME` is not writable by their uid still clone
the ssh-listed submodules.
- **`PRIME_RL_SOURCE_COMMIT`** is exported and logged so runs record
what actually ran.

## Found along the way: published images ship a broken verifiers

Since #3635 (2026-09-22) the Dockerfile's `uv pip install 'prime>=0.7'`
step replaces the submodule verifiers (0.3.x) with the PyPI
`verifiers==0.2.0` wheel that every prime release since 0.6.30 pins. On
the pristine image and on main-built `v0.9.1.dev128`, `uv run --no-sync
orchestrator --help` and `env-server --help` fail at import
(`verifiers.v1` has no `SingleAgentEnvConfig`; no
`set_base_sandbox_labels`). Runs that install a Hub env at pod start
survive by accident, because that install pulls verifiers 0.3.x back in;
baked-env runs like the nightly FFT configs do not, and nightly FFT has
failed daily since 9/24. The same override fixes the Dockerfile in
#3705.

## Verified on telus (namespace `minh-dev`, image built from this branch
at 478481593, later revisions of the script fetched into the same image)

Overlaying main tip `b94487324`, which adds `get_global_moe_stats` to
the trainer model module, a marker the baked source lacks:

| Check | Result |
|---|---|
| depth-1 fetch + four submodules | 9 s |
| container start → pod command, including the CLI install | ~35 s; ~60
s with a Hub env install |
| `prime_rl`, `verifiers`, `renderers` import from the checkout; marker
present in the overlay, absent in `/app/src` | pass, as root and as uid
1000 (`HOME` on an emptyDir, like the chart's env-servers) |
| vllm / torch / flash-attn versions and site-packages mtimes untouched
| pass |
| editables report `verifiers 0.3.2.dev137`, `renderers 0.1.12.dev2` |
pass |
| `prime --version`, `prime env install --help`, `uv run --no-sync prime
env install primeintellect/wordle` | pass; the install swaps the baked
`wordle` for the Hub's and leaves verifiers alone |
| `uv run --no-sync orchestrator --help`, `env-server --help` | pass
(they fail on the pristine image, see above) |
| `uv pip check` | 7 incompatibilities, down from the image's 107: six
are the image's own lockfile inconsistencies (mamba-ssm/tilelang,
torch/cudnn, vllm/transformers, openai-agents/openai and
python-multipart, flash-attn-4/tvm), the seventh is the intentional
`prime requires verifiers==0.2.0` |
| ref whose lock pins vllm 0.28.0 vs the image's 0.29.0 | refused in 9
s, before any sync, naming `flashinfer-python, vllm` |
| a `PRIME_CLI_SPEC` knob tried in one revision | removed: a
caller-supplied env var must not choose what gets installed into a
hosted pod |

Not exercised: a GPU workload through the overlay (the pods were
CPU-only), and the chart path end to end (needs fft#101 deployed).

## Related

- fft: chart `source` values (PrimeIntellect-ai/fft#101) and validator
`source.ref` resolution with the same lockfile preflight
(PrimeIntellect-ai/fft#102).
- platform `sourceRef` on the dedicated run dispatch and `prime train
--ref` / `--pr` follow.
- Dockerfile fix for the verifiers clobbering: #3705.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how chart/FFT pods bootstrap Python when `PRIME_RL_REF` is set
by mutating `/app/.venv` at startup; mis-synced lockfiles or override
logic could break training entrypoints, though heavy-pin preflight and
the default no-ref path limit blast radius.
> 
> **Overview**
> When **`PRIME_RL_REF`** is set, the Docker entrypoint no longer does a
full repo clone and a 20 GB venv copy into `/tmp`. It
**shallow-fetches** the ref (depth‑1 + four submodules), exports
**`PRIME_RL_SOURCE_COMMIT`**, and **`uv sync`s the checkout into the
baked `/app/.venv`** so editables point at the overlay while heavy GPU
wheels stay untouched.
> 
> Startup adds **guardrails and parity with the image build**: compare
checkout vs image **`uv.lock`** for torch/vllm/flash-attn-style packages
and **exit early** if they drift; apply
**`docker-editable-pretend-versions.sh`** so shallow submodules satisfy
`verifiers`/`renderers` floors; **reinstall `prime>=0.7`** with a
**`verifiers` pip override** so the CLI does not clobber editables.
GitHub SSH URLs are rewritten via **`GIT_CONFIG_*`** (writable without a
global git config), and the process **`cd`s into the checkout** instead
of swapping **`VIRTUAL_ENV`** to a per-ref venv.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b2fddf150dcaadfbe66cc7945ac34dac649d2fc6. 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-28 10:29:40 -07:00
Andrew KirillovandGitHub 666297d09c Require prime-sandboxes>=0.3.2 (#3682)
Raises the pyproject floor to `prime-sandboxes>=0.3.2` and refreshes the
lock accordingly (resolves 0.3.2, wheel/sdist hashes cross-checked
against PyPI).

## Why

The hosted-eval stress runner bootstraps this repo with `uv sync
--no-dev --frozen`, so the 429-retry fixes in prime-sandboxes 0.3.2
(status-aware backoff on platform API and gateway retries) only reach
eval rollouts through this lock. 0.3.0 satisfied the old `>=0.3.0` floor
indefinitely - `lock-check` enforces consistency, not freshness - so the
behavioral fix could not arrive without either this bump or a new
automation mechanism.

The floor raise (rather than a lock-only refresh) encodes the actual
requirement: the runtime depends on the 429-retry semantics, and any
future lock regeneration can no longer backslide below 0.3.2. Precedent
for this shape: #3571 (`chore: require prime-runs 0.1.3`).

## What changed

- `pyproject.toml`: `prime-sandboxes>=0.3.0` -> `>=0.3.2`
- `uv.lock`: the matching specifier line; the prime-sandboxes resolution
entries already point at 0.3.2

## Validation

- `uv lock --check` passes (581 packages)
- `uv sync --no-dev --frozen` resolves prime-sandboxes 0.3.2
- `uv run pytest tests/unit/eval -v`: 9 passed
- Regenerated with uv 0.12.19 (older uv reorders unrelated lock tables)

Linear: ENG-5966 (eval-based stress testing).
2026-09-28 09:08:05 -07:00
Scott CabrinhaandGitHub 202f108f33 fix(docker): build NIXL from source by default; isolate the prime CLI install (#3667)
## What

- **NIXL from source (default on).** `Dockerfile.cuda` builds NIXL
0.10.1 against the baked `/opt/ucx` (UCX 1.19.1) by default. The wheel
is renamed to `nixl-cu13` before building, and the build asserts the UCX
plugin links `/opt/ucx/lib/libucp.so`.
`scripts/install_nixl_from_source.sh` gets the same rename for the SLURM
path.
- **prime CLI as an isolated uv tool.** It's installed into
`/app/.tools` instead of `uv pip install`-ing it into `/app/.venv`, with
the executable linked into `/app/.venv/bin`. The build asserts the
workspace `verifiers` is still the one installed.

## Why

**NIXL.** The PyPI `nixl-cu13` wheel bundles its own UCX, which
segfaults on the prefill→decode KV transfer (#2883). The existing
`INCLUDE_NIXL_FROM_SOURCE` option was:
1. **Off by default, never enabled in CI.** Every published image ships
the PyPI wheel. On SLURM, research works around this with a
`pre_run_command` reinstall after each `uv sync`.
2. **Broken when enabled.** NIXL 0.10.1's pyproject names the package
`nixl-cu12`, so the `nixl_cu13-*.whl` glob matched nothing.
3. **A no-op even when installed.** The `nixl` shim imports `nixl_cu13`
before `nixl_cu12`, so the source build sat unused. Upstream's
`contrib/build-wheel.sh` renames via `contrib/tomlutil.py --wheel-name
nixl-cu<major>`, and this PR does the same.

The plugin has `RUNPATH=/opt/ucx/lib`, so it doesn't depend on
`LD_LIBRARY_PATH`.

**prime CLI (regression from #3635).** Every `prime` 0.7.x on PyPI pins
`verifiers==0.2.0`. Running `uv pip install 'prime>=0.7'` into the app
venv resolves against it and replaces:
- workspace `verifiers` (0.3.2.dev) → 0.2.0
- `openai` 2.54 → 3.15
- workspace `prime-pydantic-config` → the PyPI one
- `prime-sandboxes` / `prime-traces` → newer versions

As a result, `prime_rl.configs.orchestrator` fails to import (`module
'verifiers.v1' has no attribute 'SingleAgentEnvConfig'`), and every
component crashes at startup. This affects every image built since
#3635.

## Test plan

- [x] Image `commit-0039ddc20-amd64` (NIXL fix only): the build passed,
and inference pods on telus confirmed the UCX plugin links `/opt/ucx`
1.19.1. The run then crashed on the `verifiers` downgrade above.
- [x] On `commit-a1822f7a0-amd64` (pre-#3635): `uv tool install
'prime>=0.7'` gives a working CLI 0.7.5, and `uv run --no-sync prime env
install primeintellect/reverse-text` installs into `/app/.venv`.
`verifiers` still has `SingleAgentEnvConfig`, and `openai` stays at
2.54.0.
- [x] Earlier, a GLM-5.3 10-node P/D run on FFT/telus with the same NIXL
build (installed in-pod): a chat request through the PD router
succeeded, with 1 NIXL KV transfer of 5.65 MB / 18.8 ms and no segfault
(ENG-6348).
- [x] Image `commit-cef7100c7-amd64` (both fixes, newest main): build
passed, including the new workspace-verifiers assertion. The GLM-5.3
10-node P/D run on telus used it with no in-pod bootstrap: the NIXL UCX
plugin links `/opt/ucx` 1.19.1, all components import cleanly, the
PD-router chat request returned correctly, and NIXL KV transfers
succeeded. Prefill also needed `VLLM_USE_BREAKABLE_CUDAGRAPH=0` on vLLM
0.29; that is separate, in #3669.

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

---------

Signed-off-by: Scott Cabrinha <scott.cabrinha@primeintellect.ai>
2026-09-27 19:35:41 -07:00
minh hoangandGitHub 96fa737c35 fix(docker): keep the editable verifiers when installing the prime CLI (#3705)
## Summary

Published prime-rl images since #3635 (2026-09-22) ship the PyPI
`verifiers==0.2.0` wheel instead of the submodule editable, and the
orchestrator and env-server entrypoints fail at import as a result. This
installs the prime CLI with its verifiers requirement overridden so the
editable stays, and asserts that at build time.

## What's wrong

`Dockerfile.cuda` installs the prime CLI after the lockfile sync (`uv
pip install 'prime>=0.7'`). Every prime release since 0.6.30 (prime#879,
2026-08-31) pins `verifiers==0.2.0`, so that install uninstalls the
editable verifiers (0.3.x, pretend version `0.3.2.dev137`) and replaces
it with the 0.2.0 wheel. Observed on a pristine `v0.9.1.dev128` pod on
telus:

```
$ uv run --no-sync orchestrator --help
  File ".../prime_rl/configs/orchestrator.py", line 160, in EnvConfig
    env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
AttributeError: module 'verifiers.v1' has no attribute 'SingleAgentEnvConfig'

$ uv run --no-sync env-server --help
  File ".../prime_rl/entrypoints/env_server.py", line 9, in <module>
    from verifiers.v1.runtimes import set_base_sandbox_labels
ImportError: cannot import name 'set_base_sandbox_labels' from 'verifiers.v1.runtimes'
```

`uv pip check` on the image reports 107 incompatibilities, all `...
requires verifiers>=0.3.1, but 0.2.0 is installed`.

Runs that install a Hub env at pod start survive by accident: `prime env
install` pulls an env that requires `verifiers>=0.3.1`, which drags
verifiers 0.3.x from PyPI back in before the orchestrator imports it.
Runs on baked envs get no such repair. The nightly FFT configs are all
baked envs, and nightly FFT has failed every day since 9/24.

An older CLI is not an option: the last release without the pin (0.6.29)
needs a prime-sandboxes API that 0.3.0 removed, and prime-rl itself
requires `prime-sandboxes>=0.3.0`.

## Fix

- Install the CLI with `--overrides` on a one-line file containing
`verifiers`, so its `verifiers==0.2.0` requirement is ignored and the
editable is left alone. Everything else the CLI needs (prime-traces,
prime-sandboxes, openai, …) still installs as before.
- Assert in the same `RUN` that `verifiers` imports from
`/app/deps/verifiers`, so a regression fails the build rather than the
orchestrator.
- **This is a workaround, marked `FIXME(prime#940)` in the Dockerfile.**
The real fix is the prime CLI dropping verifiers as a dependency,
PrimeIntellect-ai/prime#940. Once that ships, remove the overrides file
and the `--overrides` flag here and in `scripts/docker-entrypoint.sh` on
#3686, which replays this step with the same override for the runtime
source overlay. Keep the import assertion.

## Verified

- The override was exercised on telus pods against the
`v0.9.1.dev127-4-gba81f7c5b-feat-runtime-source-overlay` image (whose
entrypoint runs the identical command after re-syncing the editables):
verifiers stays at `0.3.2.dev137` from `deps/verifiers`, `prime
--version` and `uv run --no-sync prime env install
primeintellect/wordle` work, `orchestrator --help` and `env-server
--help` start, `uv pip check` drops from 107 incompatibilities to 7 (six
pre-existing lockfile inconsistencies plus the intentional `prime
requires verifiers==0.2.0`). A full hosted run (reverse-text, 20 steps)
completed on that venv.
- This Dockerfile change itself: image build dispatched from this
branch, result below.

Build from this branch: dispatched, result pending.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes Docker venv composition for a dependency that prime-rl
entrypoints rely on; mitigated by a build-time import-path assertion,
but image builds and baked-env runs depend on the override staying
correct.
> 
> **Overview**
> Published CUDA images broke **orchestrator** and **env-server**
because installing `prime>=0.7` after `uv sync` pulled PyPI
`verifiers==0.2.0` over the repo’s editable under `deps/verifiers`
(0.3.x APIs).
> 
> The **prime CLI install step** in `Dockerfile.cuda` now writes a
one-line `uv pip install --overrides` file (`verifiers`) so the CLI’s
pinned verifiers requirement is ignored while other CLI deps still
install. A **build-time assert** checks `verifiers` resolves under
`/app/deps/verifiers`. Comments mark this as a temporary
**FIXME(prime#940)** until the CLI drops verifiers; the entrypoint
overlay in `scripts/docker-entrypoint.sh` is called out as needing the
same cleanup later.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
22c9bfd1c9907da4662665f225ca10c3cdf6a930. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-27 16:53:54 -07:00
35aa06fbfa feat(eval): allow any config override on resume (#3690)
## Summary

`uv run eval --resume` used to compare the resolved config against the
interrupted attempt's `eval.json`. It refused any change outside a short
allowlist, which left out the solver `model`, everything under
`source.*.env` (including where each judge is served) and
`tasks_per_minute`. So a paused eval couldn't move to a new endpoint
serving the same weights under another name, such as a self-hosted
router becoming a hosted API. The only way out was `--clean`.

This PR removes that validation (`RESUMABLE`, `config_diff`,
`check_config`, `previous_config`), so any field can be overridden on
resume. It's up to whoever resumes to keep the measurement consistent.
The resolved config is still written beside each attempt's episodes
(`stamp_config`), so every attempt records what it ran with.
`docs/eval.md` still says a resume that changes the model, sampling or
env stops with the differing paths. That's no longer true and needs a
follow-up.

## Test plan

- Removed the tests for the deleted functions. `pytest tests/unit/eval`
passes (7 tests).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Resume can now mix previously landed episodes with a different model,
sampling, or env configuration, which can invalidate eval comparability
if operators override carelessly.
> 
> **Overview**
> **`uv run eval --resume` no longer compares the new resolved config to
the interrupted attempt's stamped `eval.json`.** The allowlist-based
guard (`RESUMABLE`, `config_diff`, `check_config`, `previous_config`) is
removed, so fields like model, sampling, env/judge endpoints, and source
layout can all change when resuming instead of forcing `--clean`.
> 
> Resume still loads landed episodes from the trace stream and stamps
the current config per attempt via `stamp_config`; only the validation
step in `Eval.run` is dropped. Module docs now state that **any config
may be overridden** and consistency is the operator's responsibility.
> 
> Unit tests for config checking and `previous_config` lookup were
removed; remaining resume tests (`plan`, `take_landed`, trigger
integration) are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
06482534d862782e1a844ea9f8d5c3f5c37310ac. 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-27 14:43:05 -07:00
718635b2ca feat: treat timed-out rollouts as their own outcome (#3702)
## Summary

Companion to PrimeIntellect-ai/verifiers#2693, which stops a rollout
whose stage deadline expires as `<stage>_timeout` with
`Trace.is_timeout` set (scored, not errored).

- Training keeps main's semantics: the dispatcher records a `Timeout`
error on a timed-out train trace, so it stays out of the batch and
counts under `has_error`. Eval keeps the timeout as a scored outcome.
- Metrics: `is_timeout` joins the trace rates
(`<scope>/{all,effective}/<agent>/is_timeout/mean`) next to
`is_truncated`; `EpisodeMetrics.is_timeout` over the full cohort feeds
the console summary lines (`... | Truncation 0.0% | Timeout 100.0%`) for
train, online eval and standalone eval.
- W&B overview and dashboard metric sections plot
`all/<agent>/is_timeout/mean`.
- Trace index rows carry `timeout` (the episode's `is_timeout` or any
trace's); the dashboard series expose it.
- Dashboard: yellow (`--timeout`) marks for timed-out episodes on the
overview tile (`timeout rate`), episode cells, swarm points,
timing/token strips, episode table rows (with a `timed out (<stop>)`
title), trace tabs and the timeline state; the trace meta panel shows
`is_timeout`.
- Dispatcher: a timed-out eval trace with zero turns stays a timeout
instead of being promoted to an `EmptyTrajectory` error; it is scored
and counted under `is_timeout`.
- Bumps `deps/verifiers` to verifiers `main` with #2693 merged.

## Breaking

- In evals, a rollout that hits its `timeout.rollout` (or
setup/finalize/scoring) budget no longer counts under `has_error`: it
lands `ok` with `stop_condition = "<stage>_timeout"`, is scored, and
enters the `effective` subset like a truncated rollout does. Training is
unchanged: a timed-out rollout is still an error (now typed `Timeout`,
with `is_timeout` set alongside).

## Verification

Ran off this branch with the verifiers companion on `PYTHONPATH`:

```
uv run eval gsm8k -n 4 -r 1 -c 4 -m alibaba/qwen3.5-flash --env.agent.harness.id null --env.agent.runtime.type subprocess --env.agent.timeout.rollout 2
```

Before the dispatcher change: `Error 100.0% | Truncation 0.0% | Timeout
0.0%`, every trace re-labelled `EmptyTrajectory`. After: `Error 0.0% |
Truncation 0.0% | Timeout 100.0%`, metrics `is_timeout/mean = 1.0`,
`stop_condition/agent_timeout = 1.0`, index rows `ok=true,
stop_condition=agent_timeout, timeout=true`. A control run with the
default budget lands `agent_completed`, `timeout=false`, `Timeout 0.0%`.

Dashboard driven headlessly with playwright against both runs: `timeout
rate` tile `100%` in `rgb(255, 209, 102)`, every episode cell/row class
`timeout`, rows titled `timed out (agent_timeout)`, trace meta
`is_timeout true` / `ok true`; the control run shows `0%` and no marks;
no page errors.

`tests/unit/orchestrator`, `tests/unit/eval` and
`tests/unit/test_dashboard_timeline.py` pass.


## Screenshots

Eval with `--env.agent.timeout.rollout 2`: the overview tile and episode
cells read yellow, the traces table marks each row's edge yellow, and
the trace viewer lists the timed-out episodes with `is_timeout true` /
`ok true`.


![overview](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/assets/is-timeout/timeout-2s-overview.png)

![traces](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/assets/is-timeout/timeout-2s-traces-table.png)
![trace
viewer](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/assets/is-timeout/timeout-2s-traces.png)

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Eval cohort semantics change (timeouts move off `has_error` onto
`is_timeout`), and the dispatcher path that promotes empty trajectories
to errors now explicitly exempts timed-out eval traces—worth validating
against downstream dashboards and monitors that assumed timeouts were
errors.
> 
> **Overview**
> Rollouts that hit a stage deadline (`<stage>_timeout`) are now a
**distinct outcome** from errors and truncation, with **`is_timeout`**
tracked alongside **`is_truncated`** in orchestrator metrics, console
summaries, W&B/dashboard metric panels, and docs.
> 
> **Training vs eval:** On **train**, the dispatcher still drops
timed-out traces from the batch by attaching a **`Timeout`** error and
marking the trace **`ok=false`** (same exclusion as before, now typed).
On **eval**, timeouts stay **`ok`** and scored; zero-turn timeout traces
are no longer relabeled as **`EmptyTrajectory`** errors.
> 
> **Observability:** Trace index rows and eval series expose
**`timeout`**; the dashboard uses yellow styling for timeout rate,
episode cells, swarm dots, tables, timeline state, and trace meta
**`is_timeout`**. Eval success logs and standalone eval runner output
add a **Timeout** percentage next to truncation/error.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
83c0ce4c920aa0fb55eea97c251db18ec763053f. 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-27 13:12:08 -07:00
f557d7593f feat: shared env block for train and eval sources (#3695)
## Summary

- **Group `env` block**: `[orchestrator.train]`, `[orchestrator.eval]`,
the `[eval]` block of `sft`, and the top level of `uv run eval` each
take an `env` block. Every source of the group inherits it through
`vf.merge_env_defaults`, and a source's own `env` values win.
- **Only shared knobs**: the block is typed as `vf.SharedEnvConfig`. It
takes `retries`, `timeout`, `max_concurrent_agents`, `interception`,
`taskset.task`, and `taskset.system_prompt`. Env ids, taskset ids, and
agent roles stay on each source and are rejected in the group block. So
one group can mix single-agent and multi-agent envs.
- **Eval shorthands**: `<taskset-id>` and `--env.<field>` keep their
single-source meaning. Next to a TOML that defines `[[source]]` blocks,
`--env.<field>` now sets the shared block instead of erroring, e.g. `uv
run eval @ sources.toml --env.retries.max-retries 3`.
- Pin `deps/verifiers` to the merged
[verifiers#2690](https://github.com/PrimeIntellect-ai/verifiers/pull/2690),
which adds `SharedEnvConfig` and `merge_env_defaults`. Raise the
`verifiers` minimum to `0.3.2.dev143`, its first release, in both
`pyproject.toml` files, so the slim `prime-rl-configs` install gets it.
- Update `docs/eval.md` and `docs/configuration.md`.

## Verification

- Composed `configs/basic/reverse-text/rl.toml` with an overlay that has
two train and two eval sources. Each group's `env` block sets
`retries.max_retries`, `retries.include`, `timeout.episode`,
`max_concurrent_agents`, and `taskset.system_prompt`. One source per
group overrides `retries.include` and `timeout.episode`. The other
source got every group value. The overriding source kept its two values
and inherited the rest. The same held after re-validating the resolved
`OrchestratorConfig` dump.
- Repeated the check with the same blocks in a `uv run eval` TOML, plus
a `proposer-solver` source. The multi-agent source inherited the shared
values and kept its `proposer` settings. The resolved `eval.json`
re-validates to the same dump.
- `--env.retries.max-retries 5 --env.retries.include A B` next to that
TOML reached every source, except that the overriding source kept its
own `include`.
- A group block with `id`, `agent.*`, `taskset.id`, or a misspelled
field fails with one error at `env.*`.
- `uv run eval gsm8k --env.agent.harness.id bash --env.taskset.split
test` still configures the single source.
- `pytest tests/unit/eval tests/unit/test_configs.py`: 202 passed.
- Built the `prime-rl-configs` wheel and installed it in a clean venv,
as the slim-install job does. It resolved `verifiers 0.3.2.dev143`, and
the configs imported with no heavy deps.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how train/eval env configs are merged at parse time, so
misconfigured shared blocks or invalid shared-only fields could affect
every source in a group; scope is config/CLI rather than training logic
itself.
> 
> **Overview**
> Adds a **group-level `[env]` block** on orchestrator train/eval source
groups (and standalone eval) so shared knobs—retries, timeouts,
concurrency caps, interception, shared taskset fields—apply to every
source, with per-source `env` still winning on conflict. Config
validation layers defaults through `merge_group_env` and verifiers’
`SharedEnvConfig` / `merge_env_defaults`.
> 
> **Eval CLI behavior** changes for multi-source TOMLs: `--env.*` now
targets the shared block instead of being rejected (single-source
`<taskset-id>` shorthands are unchanged and still cannot mix with
`[[source]]` TOMLs). Docs and unit tests cover the new TOML shape and
shorthand routing.
> 
> Pins **verifiers** to `>=0.3.2.dev143` in the root and
`prime-rl-configs` packages (lockfile updated).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8aef01e0cdd6baaf1275e06f33bf0091c548913a. 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-27 13:02:01 -07:00
f87fd0eb33 fix(examples): set group_size=8 in GRPO recipes (#3693)
## Summary

- Set `orchestrator.group_size = 8` in the INTELLECT-3.1 and Qwen3
math/SWE standalone RL examples.
- Prevent GRPO's default group size of 1 from giving every rollout a
zero group-relative advantage.
- Keep existing explicit group sizes, including GLM base configs used by
overlays.

## Verification

- Parsed each changed TOML through `RLConfig.model_validate`; all three
resolve to group size 8 for every train source.
- `git diff --check` passed.

Co-authored-by: Konstantin Dunas <git@hallerite.com>
2026-09-27 00:27:04 -07:00
Mika SenghaasandGitHub 12001f3167 fix: update eval dependency pins (#3694)
## Summary

- Pin verifiers to `6a82e5d`, which includes the [Bash/Null certifi
fix](https://github.com/PrimeIntellect-ai/verifiers/pull/2614) and the
[nano-rlm certifi
pin](https://github.com/PrimeIntellect-ai/verifiers/pull/2688).
- Pin prime-envs to `647ff7a`, which includes the [GPQA judge
fix](https://github.com/PrimeIntellect-ai/prime-envs/pull/845), [DeepSWE
missing-test
scoring](https://github.com/PrimeIntellect-ai/prime-envs/pull/847), and
[Apex Compose host
images](https://github.com/PrimeIntellect-ai/prime-envs/pull/842).
- Refresh `uv.lock`. Exclude `tau2-bench` from the shared workspace
because its new Tau2 dependency requires LiteLLM below 1.82.7, while
Harbor requires 1.92.0 or newer.

## Breaking

- `uv sync --all-packages` no longer installs `tau2-bench`. Install and
run it in a separate environment until its Tau2 and Harbor LiteLLM
requirements can share one lock.

## Verification

- `uv lock --check` and `uv sync --all-packages --all-extras --locked
--dry-run --quiet` passed.
- The five-source Intellect 4 GLM-5.3 eval composition resolved with the
intended model, max reasoning effort, harnesses, group sizes, and
rollout timeouts.
- `uv run --no-sync eval @ configs/debug/eval/multi-env.toml --dry-run`
passed.
- `uv run --no-sync rl @ configs/basic/wordle/rl.toml --dry-run` passed.
- A one-task `pi-terminal-bench-2` financial-document rollout on
`internal/glm-5.3-fast` completed with reward 1.0, 55 turns, and 0.0%
error.
- `git diff --check` passed.

Apex remains excluded from prime-rl's shared workspace because it pins a
separate verifiers git revision. Its new Compose host images still need
an Intellect 4 rollout check before Apex rejoins that suite.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking for anyone relying on `uv sync --all-packages` to install
`tau2-bench`; they must use a separate environment until LiteLLM
constraints align.
> 
> **Overview**
> **`tau2-bench` is removed from the shared `uv` workspace** so `uv sync
--all-packages` can keep Harbor’s **`litellm>=1.92.0`** without fighting
Tau tasksets’ **`litellm<1.82.7`**. The workspace **`exclude`** list now
includes `deps/prime-envs/environments/tool_use/tau2_bench`, and the
comment documents that split (alongside the existing Apex / tau2_synth /
tau3 exclusions).
> 
> **`uv.lock` is refreshed** accordingly: `tau2-bench` and the git
**`tau2`** package drop out of the lock, along with their former
transitive stack (e.g. gymnasium, matplotlib, langfuse, redis). Several
editable prime-envs packages show **patch version bumps** in the lock
(Lean/math envs, `gpqa`, `lean-common`, etc.) as part of the same
dependency refresh.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5f1504314e8e97d8e8bae5ebc49381cc30822106. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-26 22:43:55 -07:00
1cf683267d chore: drop CLAUDE.md in favor of native AGENTS.md (#3691)
## Summary

- Delete `CLAUDE.md`. It only imported `@AGENTS.md`, and Claude Code
reads `AGENTS.md` natively since v2.1.277
([docs](https://code.claude.com/docs/en/memory.md#agents-md)).
- Update the skills line in `AGENTS.md` to name both the
`.claude/skills` (Claude Code) and `.agents/skills` (Codex) symlinks.
Neither tool reads the other's skills folder, so both symlinks stay.

## Breaking

- Claude Code sessions older than v2.1.277 read only `CLAUDE.md`, so
they no longer load the repo instructions. On Bedrock or with telemetry
disabled, the minimum is v2.1.281. Migration: update Claude Code.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation-only agent config changes with no runtime or application
code impact; the only caveat is older Claude Code versions losing loaded
instructions.
> 
> **Overview**
> Removes **`CLAUDE.md`**, which only re-exported **`AGENTS.md`** via
`@AGENTS.md`, so agent instructions live in a single file now that
Claude Code reads **`AGENTS.md`** natively.
> 
> The **Skills** section in **`AGENTS.md`** now documents both symlink
targets: **`.claude/skills/`** for Claude Code and **`.agents/skills/`**
for Codex, since each tool only loads its own folder.
> 
> **Breaking:** Claude Code builds before native **`AGENTS.md`** support
(v2.1.277+, v2.1.281+ on Bedrock/telemetry-off) no longer pick up repo
instructions unless upgraded.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
205ca092421609d40c938a16c78a75051c67ec2e. 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-26 18:59:04 -07:00
Xuan-Phi NguyenandGitHub b944873248 fix(trainer): measure MoE violation per EP group and microstep (#3684)
## Summary

`max_vio` is intended to capture the largest expert routing violation
for each training microbatch across an entire EP group. The metric uses
expert token counts, not the number of tokens allocated to an EP rank.
For each microbatch, we take the maximum across MoE layers and EP
groups; `max_vio/mean` and `max_vio/max` then summarize those microbatch
maxima within the logged optimizer step.

### Why the old numbers depended on topology

The router records selections for every expert on each rank before
dispatch, but the original `get_load_balance_stats` computed violation
from that rank's **local** counts. With CP, each rank sees only a
sequence shard. At fixed EP, changing CP or DP changes the local token
population and the number of rank readings. SFT averaged layer
violations locally, took a world maximum, and averaged it over gradient
accumulation; RL's `/mean`, `/median`, `/std`, and `/max` summarized all
local layer/rank/microbatch readings. Those reductions did not describe
one EP group's routed traffic, so equal EP degrees could report
substantially different values.

### What changed

- Sum per-expert token counts and routing-confidence sums within the EP
group **before** computing per-layer violation and confidence. Reset
both buffers after reading them. Remove the unused `reset_stats` and
`try_to_avoid_padding_experts` switches while keeping their previous
default behavior.
- In RL and SFT, read routing statistics after **each microbatch**
through the shared `get_global_moe_stats` helper. Take the maximum
violation across layers, then across the `dp_cp` mesh. This preserves a
short-lived imbalance instead of pooling counts across microbatches.
- Aggregate those per-microbatch global maxima into `max_vio/mean` and
`max_vio/max` for each optimizer step. RL also retains the other
distribution statistics supplied by `Tensors.compute_stats`; SFT now
publishes `/max` alongside `/mean`.
- Clear SFT validation routing buffers before the next training step.

### Validation: same EP, more trainer replicas

These RL runs used Qwen3-30B-A3B-Thinking-2507, EP=4, CP=1, sequence
length 32,768, group size 8, and learning rate 1e-6. The experiment
configs were temporary; the tracked `math.toml` is restored and
`math2.toml` is not included in this PR.

| Run | Topology | `orchestrator.batch_size` | Average `max_vio/mean` |
Average `max_vio/max` |
| --- | --- | ---: | ---: | ---: |
|
[math1-v1](https://wandb.ai/primeintellect/qwen30b-math/runs/a2da2577b6c54320bc1d997022b0ebe7)
| 8 GPUs total: 4 train + 4 inference; one EP group, `dp_replicate=1` |
16 | 6.7774 | 7.7035 |
|
[math2-v1](https://wandb.ai/primeintellect/qwen30b-math/runs/d69f377a0cb5425b99b455e6c8101118)
| 16 GPUs total: 8 train + 8 inference; two EP groups, `dp_replicate=2`
| 32 | 6.8707 | 7.7897 |

Values are arithmetic averages of the logged metrics over the **shared
steps 1–99**, read from W&B. The two-group run is 1.38% higher on
`/mean` and 1.12% higher on `/max`. Its rollouts are different, so this
is a comparability check, not a paired-input equality test. This
comparison does not exercise CP. The shared-helper refactor followed
these runs and preserves their reduction arithmetic.

Relative to the original `examples/advanced/qwen3-30b-a3b/math.toml`,
the experiments used:

- **Math1:** single-node deployment with 4 train and 4 inference GPUs
instead of 2 train and 2 inference nodes; EP 4 instead of 8;
`orchestrator.batch_size` 16 instead of 512; inference TP 4 instead of
8.
- **Math2:** 1 train and 1 inference node instead of 2 each; EP 4
instead of 8; `dp_replicate=2`; `orchestrator.batch_size=32` instead of
512; inference TP 4 and DP 2 instead of TP 8. Its Slurm job name was
`math2-qwen30b` instead of `math-qwen30b`.
- **Both:** added `max_steps=400`, `orchestrator.group_size=8`, Slurm
partition `all`, and a run-specific `VLLM_CACHE_ROOT`; changed
`orchestrator.concurrency.initial_inflight` from 1024 to 64 and added
`max_inflight=128`. Other settings followed the original config.

### Remaining topology effects

At fixed EP, equal violation readings are not guaranteed. For
fixed-length packed SFT, the per-microbatch token population in one EP
group is `micro_batch_size × (EP / CP) × seq_len`. Increasing CP makes
that population smaller, and the relative count imbalance noisier,
unless `micro_batch_size` scales with CP. Increasing trainer nodes at
fixed EP creates more EP groups (`trainer_world_size / EP`); taking the
maximum over more groups tends to raise both logged `/mean` and `/max`
slightly through an order-statistics effect. With fixed CP and global
SFT batch size, adding DP ranks also reduces gradient accumulation steps
and the number of microbatch samples in each logged step.

For a stricter fixed-EP comparison, keep tokens per microbatch per EP
group constant (`micro_batch_size` proportional to CP) and scale the
global batch size with trainer world size. For example, double batch
size when trainer world size doubles, whether the added ranks come from
DP or CP. RL can still vary with actual sequence lengths and rollout
contents.

Checks: `uv run --no-sync pytest tests/unit/train/models/test_moe.py -q`
(15 passed), `ruff check`, `ruff format --check`, and `git diff --check`
passed for the PR changes.
2026-09-26 10:11:07 -07:00
c28afbbae2 fix: keep workstation blackwell on fa2 in auto-attn (#3681)
## Summary

- Gate `attn='auto'` → FA4 on SM10x/SM11x (`major in (10, 11)`) instead
of `major >= 10`. FA4's own interface uses the same families for its
native tcgen05/TMEM Blackwell path.
- B200/GB200 (SM100) and B300/GB300 (SM103) keep FA4, so the goal of
#3655 stays intact. Hopper keeps FA3.
- Workstation Blackwell (SM12x, e.g. RTX PRO 6000) resolves to FA2
again. #3655 sent it to FA4 as a side effect.
- Update the `attn` comment in `docs/scaling.md`.

| GPU | CC | `attn: auto` |
|---|---|---|
| H100/H200 | SM90 | FA3 |
| B200/GB200 | SM100 | FA4 |
| B300/GB300 | SM103 | FA4 |
| RTX PRO 6000 | SM120 | FA2 (main: FA4) |

## Verification

5 steps of `configs/ci/integration/reverse-text/start.toml` on 2x RTX
PRO 6000 (SM120), same venv (vllm 0.29):

**Before (main `b963ceda3`)**: `Auto-resolved attn='auto' to
'flash_attention_4' (SM120)`
```
Step 1 | Mismatch KL 0.2967 | Grad. Norm nan
Step 2 | Loss nan | Entropy nan | Mismatch KL nan | Grad. Norm nan   (run then stalls: NaN weights reach inference)
```

**After (this branch)**: `Auto-resolved attn='auto' to
'flash_attention_2' (SM120)`
```
Step 1 | Mismatch KL 0.0008 | Grad. Norm 0.8843 | Reward 0.19
Step 3 | Mismatch KL 0.0012 | Grad. Norm 0.8779 | Reward 0.15
Step 5 | Mismatch KL 0.0013 | Grad. Norm 1.6303 | Reward 0.46
Training finished!
```

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Small, targeted change to GPU-architecture gating at model setup;
lowers risk on SM12x by avoiding an incompatible FA4 path rather than
altering auth or data handling.
> 
> **Overview**
> **`attn='auto'` no longer picks Flash Attention 4 on every SM10+
GPU.** Resolution now uses FA4 only when the compute capability major is
**10 or 11** (datacenter Blackwell, e.g. B200/B300), keeps **FA3 on
Hopper (SM90)**, and uses **FA2 for everything else**—including
workstation Blackwell (**SM12x**, e.g. RTX PRO 6000), which lack the
tcgen05/TMEM path FA4 expects.
> 
> The **`resolve_auto_attn`** docstring and the **`attn`** comment in
**`docs/scaling.md`** are updated to match this split so docs and
runtime behavior stay aligned.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ab27534ec84dba23a2043dc65235e6b7ea57b41c. 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-25 15:58:24 -07:00
b963ceda3c perf(deepseek_v4): dynamic sparse attention slot count, no recompiles, per-query tile skipping (#3644)
The DSv4 sparse attention kernels compiled one kernel per gather width,
and HCA's width tracks the longest
document in the packed row, so every new width stalled training while
TileLang compiled. The kernels now
compile once per process and skip slot tiles no query can reach.

- `topk` was a compile key, so each new gather width recompiled; kernels
now take `Indices` as a free view
  `(B, S, G, n_tiles, tile)` with only `n_tiles = K / tile` dynamic.
- The tile size stays fixed so in-tile offsets stay provable; a fully
dynamic `topk` slowed the backward 24-29%.
- Each query loops only over tiles up to its last valid slot; the
skipped tiles are fully masked, so this is exact.

End to end, DeepSeek V4 Flash SFT on 8 B300 nodes (full model, 256k,
cp8/ep8, bf16, 20 steps, fresh compile
caches per arm). Real data packs 4-9 documents per row; fake data is one
document per row.

| data | arm | median step, 6-20 | total, steps 2-20 | MFU |
|---|---|---|---|---|
| real (scaleswe) | main | 19.20 s | 440.1 s | 46.7% |
| real (scaleswe) | this PR | 17.81 s (-7.2%) | 346.8 s (-21%) | 53.6% |
| fake | main | 16.87 s | | 57.5% |
| fake | this PR | 16.76 s (-0.7%) | | 57.8% |

On real data, main recompiles mid-run and spends 27-30 s on 8 of 19
steps; this PR compiles 28 TileLang
kernels in step 1 versus 356 for main, and losses match to 1e-4.

![Before/after timeline of a recompile
step](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/78da67f7cc8f89dec8032ea322ce488d5181b8c8/benchmarks/fp8_grouped_gemm/dsv4_attn_dynamism_stall.png)

Rank 0, step 5 of a traced 8-step run on a 6-layer one-node proxy with
real data
([config](https://github.com/PrimeIntellect-ai/prime-rl/blob/b339e8eafed9f39d832a5da0d2eae9a5a91b0b7a/benchmarks/fp8_grouped_gemm/sft_1n_scaleswe.toml)),
aligned at the step start.
On main the GPU idles 5.6 s and 4.2 s inside the sparse attention
forward and backward while TileLang compiles
new widths (cache file times: 4-7 compiles in 6 of the 7 steps after
step 1, versus none for this PR).
The untraced full-model numbers above are the timing claim.

Before:
[main@33e02a7](https://github.com/PrimeIntellect-ai/prime-rl/commit/33e02a7a183002aca0864c5afc1c2f5a50e48e37).
After: [real-data
config](https://github.com/PrimeIntellect-ai/prime-rl/blob/b339e8eafed9f39d832a5da0d2eae9a5a91b0b7a/benchmarks/fp8_grouped_gemm/sft_scaleswe.toml),
[fake-data
config](https://github.com/PrimeIntellect-ai/prime-rl/blob/b339e8eafed9f39d832a5da0d2eae9a5a91b0b7a/benchmarks/fp8_grouped_gemm/sft.toml).
Both real-data arms carry #3544's tool-call fix (`c7ba105d5`), which the
dataset needs.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 11:10:03 -07:00
samsjaandGitHub 3cc565eecb feat(eval): add a BetterStack heartbeat to eval runs (#3664)
## Summary

The trainer, sft, and orchestrator already beat a Better Stack
heartbeat; evals (and the sft online-eval, which shares the
`EvalRunner`) were invisible to it. This gives the eval its own
`heartbeat` config: one ping per landed episode.

There is deliberately no startup ping: the first landed episode is the
first beat. The gap between run start and the first episode (pool boot,
env servers, the first episode's full duration) would otherwise sit
inside the ping stream as an abnormally long silence that flips a
healthy run stale. Until the first beat, the heartbeat has simply never
been pinged.

When episodes stop landing, the pings stop and Better Stack flips the
heartbeat stale after its grace period. Size that period + grace above
the longest legitimate gap between episodes. The `Heartbeat` never runs
more than one ping in flight (a `beat()` while one is pending is
dropped), so continuous landings cost at most ~one request per
round-trip.

The orchestrator keeps its existing per-batch heartbeat; nothing there
changes.

## Usage

```toml
[heartbeat]
url = "https://uptime.betterstack.com/api/v1/heartbeat/<token>"
```

Set it on the `eval` config (also available to the sft online-eval via
its `[eval]` block).

## Validation

- `ruff check` + `ruff format` clean.
- `uv run pytest tests/unit/test_configs.py
tests/unit/eval/test_cli.py`: identical to the unmodified tree (67
pre-existing failures in this env from missing verifiers hub plugins;
126 pass).
- Live 30-minute run against a real Better Stack heartbeat URL using the
exact `Heartbeat` class: 60 pings at a 30s cadence, all HTTP 200 (RTT
126-344ms); silence after stop, as the dashboard's staleness window
expects.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Optional observability hook with no change to eval logic, auth, or
data paths when `heartbeat` is unset.
> 
> **Overview**
> Eval and SFT online-eval (shared `EvalRunner`) can now opt into Better
Stack uptime monitoring via an optional **`heartbeat`** block on
**`ServedEvalConfig`**, matching trainer/orchestrator/SFT.
> 
> When configured, **`EvalRunner`** creates a **`Heartbeat`** at setup
and pings **once per successfully landed episode**—not on dispatch
failures or cancellations, and **not at startup**. The first beat is the
first landing so long boot/first-episode gaps do not look like stale
silence in Better Stack; if episodes stop (dead inference, hang, or
clean exit), pings stop and the monitor goes stale after grace.
> 
> Configure with `[heartbeat] url = "..."` on the eval config (or SFT
`[eval]`); size Better Stack period + grace above the longest gap
between landed episodes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
75add6ed9027ef8b2f2aab2a63c945db38633655. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-25 10:59:31 -07:00
samsjaandGitHub f52f6a69df add sft example glm5 (#3666)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Documentation and example TOML only; no changes to training, auth, or
runtime code paths.
> 
> **Overview**
> Adds **supervised fine-tuning (SFT)** to the GLM-5.3 advanced example
alongside the existing RL/inference guides.
> 
> New TOML overlays under `sft/h200/` target **8-GPU H200 nodes** (8
training nodes, `cp`/`ep` = 8, 131k `seq_len`): **`base.toml`** wires
`zai-org/GLM-5.3-BF16`, custom MoE training settings, `sign_sgd`, and
Slurm; **`math-10k.toml`** points at
`PrimeIntellect/INTELLECT-3-SFT-10K` (math split); **`fake.toml`** swaps
in fake data for dry runs.
> 
> The README **SFT** section documents composing configs with `uv run
sft @ ...` and notes the existing dashboard can monitor SFT runs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
81d7877b4e06ec9f3865006f6b309ac0b0e95aff. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

## Layout

The SFT overlays live under `examples/advanced/glm-5.3/sft/h200/` — an
`h200/` subfolder marks them as tuned for 8-GPU H200 nodes, and the
files drop the `sft-` prefix since the parent folder already says SFT:

- `sft/h200/base.toml` — base SFT config: `zai-org/GLM-5.3-BF16` on 8
training nodes with the same large-scale knobs as RL (custom impl,
`cp`/`ep` = 8, 131k context, AC offloading, `sign_sgd`, SLURM job
`glm53-sft`).
- `sft/h200/math-10k.toml` — data overlay:
`PrimeIntellect/INTELLECT-3-SFT-10K` (math split).
- `sft/h200/fake.toml` — fake-data overlay with `force_balanced_routing`
for dry runs.

Launch:

```bash
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml
```

The README SFT section documents the command, the fake-data variant, and
the dashboard. Both compositions validate with `sft --dry-run`.
2026-09-25 10:58:54 -07:00
Mika SenghaasandGitHub 9cc215df69 chore: bump prime-envs to latest main (#3672)
## Summary
- Bump the `deps/prime-envs` submodule from `1213b7336` to `b677502a2`
(latest `main`). Pulls in:
-
[prime-envs#818](https://github.com/PrimeIntellect-ai/prime-envs/pull/818):
separate original OfficeQA from repaired PI-OfficeQA (new
`pi-officeqa-pro-v2` env).
-
[prime-envs#832](https://github.com/PrimeIntellect-ai/prime-envs/pull/832)
(+ [#835](https://github.com/PrimeIntellect-ai/prime-envs/pull/835),
[#836](https://github.com/PrimeIntellect-ai/prime-envs/pull/836)):
switch `swebench_pro` to SWE-bench Pro V2, constraining image repository
choices.
-
[prime-envs#824](https://github.com/PrimeIntellect-ai/prime-envs/pull/824):
SWE-Atlas Harbor environments (new `swe-atlas-qna`, `swe-atlas-rf`,
`swe-atlas-tw` envs).
-
[prime-envs#811](https://github.com/PrimeIntellect-ai/prime-envs/pull/811):
PI-DeepSWE while preserving original DeepSWE (new `pi-deepswe` env).
-
[prime-envs#801](https://github.com/PrimeIntellect-ai/prime-envs/pull/801):
APEX-Agents 1.1 with its reference harness and Harbor grading (new
`apex-agents` env).
-
[prime-envs#810](https://github.com/PrimeIntellect-ai/prime-envs/pull/810):
`pi-terminal-bench-2` with repaired QEMU task images.
-
[prime-envs#829](https://github.com/PrimeIntellect-ai/prime-envs/pull/829):
agentic Lean tasksets on a shared `lean-common` base (new cambench,
combibench, discover-and-prove, formalmath, kimina, matholympiadbench,
minif2f, numina, proofnet, proverbench, putnambench tasksets; removes
`deepseek-prover` and `goedel-pset`).
-
[prime-envs#838](https://github.com/PrimeIntellect-ai/prime-envs/pull/838):
raise Verifiers dev requirements to 0.3.2.dev137, matching our vendored
`deps/verifiers` pin.
- Relock `uv.lock`: new workspace members are auto-discovered via
`deps/prime-envs/environments/*/*`; `lean-common` joins as an editable
path source.
- Exclude `apex-agents` from the workspace: it pins `verifiers` as a git
rev (`328c0b1`), which conflicts with the editable workspace member —
same lock-conflict pattern as `tau2_synth` and `tau3_bench`.

## Validation
- `uv lock` and `uv lock --check` pass (581 packages resolved).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Large dependency-graph churn and benchmark harness upgrades (e.g.
SWE-bench Pro V2) can affect eval/training env selection, though changes
are confined to workspace packaging and the lockfile.
> 
> **Overview**
> Updates the monorepo lockfile and workspace rules after advancing
**`deps/prime-envs`**, so newly added Harbor/SWE/Lean/search env
packages resolve alongside the editable **`verifiers`** pin.
> 
> **`pyproject.toml`** documents why **`apex-agents`** is excluded from
the uv workspace (it pins **`verifiers`** to a git rev, same conflict
pattern as **`tau2_synth`** / **`tau3_bench`**) and adds that path to
**`tool.uv.workspace.exclude`**.
> 
> **`uv.lock`** registers many new auto-discovered workspace
members—including **`lean-common`**, agentic Lean tasksets (e.g.
**`cambench`**, **`proofnet`**, **`putnambench`**), PI variants
(**`pi-deepswe`**, **`pi-officeqa-pro-v2`**, **`pi-terminal-bench-2`**),
and **`swe-atlas-*`**—while dropping **`deepseek-prover`** and
**`goedel-pset`**. Several existing packages bump versions and tighten
**`verifiers`** requirements to **`>=0.3.2.dev137`** (notably
**`deep-swe`**, **`swebench-pro`**, and the migrated Lean envs).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5d592eccccbb09ad765d6663e12a91399a49e29b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-25 10:21:37 -07:00
NeoandGitHub 13c82f0551 Mario/increase moe mfu split size tensorize (#3665)
<html>
<head>

</head>
<body>

<p class="p1">This PR changes the split representation to use CPU
tensors.</p>

<h3><span class="s1"><b>Performance</b></span></h3>

<p class="p4">Benchmarked on Qwen3-30B-A3B with 8× H200, EP 8, balanced
routing, bf16, and no activation checkpointing.</p>



Version | Step time (3–30) | Tok/s/GPU | MFU (head_dim 128)
-- | -- | -- | --
main (job 1426) | 7.59s | ~8,635 | ~32.8%
CPU-tensor splits, this PR (job 1434) | 6.95s | ~9,430 | ~35.9%
torchtitan (job 1422) | 6.58s | ~9,960 | 37.8%




<p class="p1">Compared with <code>main</code>, this PR reduces step time
from <span class="s1"><b>7.59s to 6.95s</b></span> (~8.4% reduction),
increases throughput from <span class="s1"><b>~8,635 to ~9,430
tok/s/GPU</b></span> (~9.2% improvement), and raises MFU from <span
class="s1"><b>~32.8% to ~35.9%</b></span>.</p>

</body>
</html>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Logic for split sizes is unchanged; this only alters tensor
layout/device timing for a performance path in distributed MoE routing.
> 
> **Overview**
> Improves **MoE expert-parallel token dispatch** in
`TorchTokenDispatcher` by building `input_splits` and `output_splits`
together and moving them to **CPU once** before the all-to-all.
> 
> Instead of two separate GPU reductions, the change **stacks** the
per-rank token counts from local and grouped expert histograms, sums
them, and calls `.cpu()` up front so `all_to_all_single` can read split
sizes (via `.tolist()`) **without an extra device sync** on the hot
path. Dispatch/combine still use the same split semantics; only where
the tensors live and when they are transferred changes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e61d0bfdda7fe7ec7170b20eb60096d3552daa7a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-25 04:18:29 +02:00
7d25aaa0d2 docs: drop the standalone RL trainer entrypoint from the docs (#3634)
## Problem

`uv run trainer` calls `prime_rl.trainer.rl.train` directly, outside
torchrun, so the `env://` rendezvous has no
`RANK`/`WORLD_SIZE`/`MASTER_ADDR`/`MASTER_PORT` and the process dies
before any training starts:

```
ValueError: Error initializing torch.distributed using env:// rendezvous:
environment variable RANK expected, but not set
```

Every documented use of that entrypoint was therefore broken. Scott hit
it during onboarding on the README's own validation steps (#3633).

## Fix

Rather than defaulting the rendezvous env for a single-process group
(#3633), drop the standalone trainer from the docs — per the thread, it
isn't a path we want people on:

- **`README.md`** — removed "Validate your environment setup" step 4
(`uv run trainer @ configs/debug/fake/rl.toml`) and renumbered the
following steps. The remaining step 5 (`uv run rl @
configs/basic/reverse-text/rl.toml`) already exercises the trainer
end-to-end.
- **`docs/training.md`** — dropped the `uv run trainer` row from the
entrypoints table, and reworded the `uv run orchestrator` row that
pointed at a "separately-launched trainer".
- **`docs/scaling.md`** — the trainer-alone benchmark now launches under
torchrun, the way the `rl` launcher and
[`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py)
(what the CI benchmark matrix runs) already do.

Docs only — no code or config changes, and the `trainer` entrypoint
itself is untouched.

## Follow-up, not in this PR

`k8s/README.md`, `k8s/prime-rl/values.yaml` (the `trainer.command`
example), and the k8s section of `examples/basic/reverse-text/README.md`
still drive the trainer pod with `uv run trainer`, and hit the same
failure — the chart sets no rendezvous env on the trainer StatefulSet.
Fixing that means changing how the chart launches the trainer, not just
the prose, so it wants its own PR from someone who can run the
deployment.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation-only edits with no runtime or config changes.
> 
> **Overview**
> Documentation no longer recommends **`uv run trainer`**, which fails
on startup without torchrun/`RANK` because it invokes the RL trainer
outside distributed launch.
> 
> The README **environment validation** checklist drops the standalone
RL trainer step and **renumbers** the inference and full **`uv run rl`**
checks. **`docs/training.md`** removes the trainer row from the
entrypoints table and updates the **`uv run orchestrator`** note so it
no longer assumes a separately launched trainer. **`docs/scaling.md`**
changes the “RL trainer alone” benchmark to **`torchrun …
src/prime_rl/trainer/rl/train.py`**, matching how the **`rl`** launcher
and CI benchmarks run it.
> 
> The **`trainer`** CLI entrypoint is unchanged; this is prose-only.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
cb2aa3805b8e77dbb9e334961349c42a1c7462db. 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 <noreply@anthropic.com>
2026-09-24 16:05:26 -07:00
samsjaandGitHub 5a0c80e54a docs(readme): drop stale FA3 source-build step; flash_attn_3 comes from prebuilt wheels (#3648)
## Why

Section 3.1 of the README ("Optional: Install Flash Attention 3")
claimed FA3 "has no wheels prebuilt" and instructed a manual source
build from the `hopper` subdirectory. This is stale — **prime-rl already
installs FA3 as a prebuilt wheel from the lockfile**:

- `pyproject.toml` resolves `flash_attn_3 = { index =
"pytorch-cu130-test" }` → `https://download.pytorch.org/whl/test/cu130`
- `uv.lock` pins `flash-attn-3 == 3.0.0` from that index (real compiled
wheels: `flash_attn_3-3.0.0-cp39-abi3-manylinux_2_28_x86_64.whl`, ~402
MB, plus an aarch64 build)
- `uv sync --all-extras` (step 4 of the same install section) pulls it
in via the `flash-attn-3` extra — same as `Dockerfile.cuda` (`--extra
flash-attn-3`)
- This has been the case since at least May (the source was
`pytorch-cu128-test` before `70117046a` moved it to `cu130-test`)

Since step 4 already installs FA3, the section documents a step that
must not be followed: building from git would fight the lock (its "uv
sync will uninstall the package" warning was describing a self-inflicted
problem).

## What

- Remove section 3.1 entirely. Nothing is lost: `flash_attn_3` arrives
prebuilt with `uv sync --all-extras`, and the `flash_attention_3`
backend / `attn="auto"` picks it up on Hopper GPUs.

Docs-only change, no code touched.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> README-only edit with no runtime or dependency behavior changes.
> 
> **Overview**
> Removes **README Manual Setup subsection 3.1**, which told Hopper
users to build Flash Attention 3 from the Dao-AILab git source and
warned that **`uv sync` / `uv run` would uninstall** that manual
install.
> 
> That guidance is outdated for this repo: **`flash_attn_3` is already
pulled in via the lockfile and `uv sync --all-extras`** (optional extra
from the PyTorch test index), so the extra source-build step conflicted
with the pinned wheel and described a problem users only hit if they
bypassed the lock.
> 
> Docs-only; install flow in step 4 is unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
921c72d02f42ab0a58fe4b10cd8fb227f1a3543f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-24 16:05:09 -07:00
e48c943c48 fix(orchestrator): save final checkpoint before finalizing the run (#3642)
## Problem

`Orchestrator.start()` writes the orchestrator's own final checkpoint in
its `finally` block **after** `monitors.finalize()`. Finalize is what
tells the launcher the run is done: on the fft k8s path, the platform
marks the run COMPLETED and uninstalls the release. So the
orchestrator's final checkpoint races teardown.

## Fix

Save the final checkpoint first, then finalize. Clean and forced exits
both still save; only the order relative to `monitors.finalize()`
changes.

## Scope

This PR first also made the orchestrator wait for the trainer's final
checkpoint. Per review, waiting for both components is the launcher's
job, as the SLURM template already does with `.trainer.done` /
`.orchestrator.done`, so that part was dropped. The k8s launcher side is
platform#5817 + fft#92 (Linear ENG-6341): the platform marks a run
COMPLETED and tears it down only once both the trainer and the
orchestrator have finished.

With those in place, teardown already waits past the orchestrator's
finalize, so this change is **defense-in-depth** there. It still matters
for any launcher that tears down on finalize alone, and it makes the
orchestrator's own "I'm done" signal truthful.

## Testing

- `uv run pytest tests/unit -m "not gpu"` (as in `cpu_tests.yaml`,
x86_64, `--all-extras`): 616 passed, 1 skipped. CI CPU tests pass on
this head.
- Not exercised on k8s with an image built from this branch; the telus
runs for ENG-6341 used the stock prime-rl image. The GPU integration
tests (which run the orchestrator end to end from this branch) are the
coverage for the reordering.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 15:56:03 -06:00
e521297df6 perf(deepseek_v4): fused in-place interleaved RoPE for DeepSeek-V4, matching vLLM (#3645)
Eager interleaved RoPE was a large share of each DeepSeek-V4 attention
layer: every site widened the
tables with `repeat_interleave`, rotated a copy of the 64 rope channels,
and rebuilt the whole
512-channel head with `torch.cat`. All five RoPE sites (q, kv,
compressed kv, indexer q, and the
inverse rotation of the attention output) now run one out-of-place
Triton kernel, adapted from
Megatron-LM and bit for bit with vLLM's `rotary_embedding`, making the
end-to-end SFT step 13-14%
faster on B300.

- RoPE tables were built every forward in bf16. They are now one static
fp32 `[cos | sin]` cache in
  vLLM's layout, indexed by position inside the kernel.
- q was normed and rounded to bf16, then rotated and rounded again.
`dsv4_q_norm_rope` does both in
fp32 with one rounding: exact matches with vLLM rise from ~69% of rope
channels to 99.9997%.
- `dsv4_rope` is a functional custom op whose backward is the inverse
rotation. An in-place version
needs an `autograd.Function` wrapper, because `register_autograd`
rejects mutating ops.
- Passing fp32 tables through `PackedContext` failed multi-node: FSDP's
`cast_forward_inputs` cast
them to bf16. Hence the cache lives on one rotary module that every
attention layer shares.

DeepSeek V4 Flash SFT on 8 B300 nodes, full model, bf16, 256k tokens,
cp8/ep8, selective AC. Median step
over steps 6-20 of 20, which skips the sparse-attention recompiles both
real-data arms hit (removed by
#3644). tok/s/GPU is the 32,768 packed positions each GPU processes per
step, padding included, over that
median. Losses match `main` to 1.5e-3 on identical samples:

| Per step, 8 B300 nodes | Fake: main | Fake: this PR | Real: main |
Real: this PR |

|----------------------------------|------------|---------------|------------|---------------|
| Median step time | 16.896 s | 14.641 s | 19.203 s | 16.474 s |
| tok/s/GPU | 1939 | 2238 | 1706 | 1989 |
| MFU | 57.4% | 66.2% | 46.7% | 53.2% |
| Peak reserved GPU memory, rank 0 | 244.0 GiB | 246.6 GiB | 246.7 GiB |
247.0 GiB |

Fake data is one 256k document per row; real data is the scaleswe SFT
set, 4-9 documents per row.

![Before/after main-stream kernels in one DeepSeek-V4 layer's attention
block](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/1210bc4eaea568a0247d04d79ca425a21051ee6c/benchmarks/ds-v4-rope-profile-v2.png)

**Figure:** Kernels on rank 0's main GPU stream during layer 2's
forward, in the last of five
`torch.profiler` steps of a 1-node, 6-layer run (256k tokens, cp8/ep8,
bf16). Both arms start at the
layer's first kernel, and the dashed line marks the end of its attention
block at the MoE router. The two
~7 ms `torch.cat` blocks per layer, which rebuild the heads around q's
RoPE and around the inverse
rotation of the attention output, are gone, shortening the block from
94.1 ms to 72.3 ms. The bottom panel
sums each kernel category over the whole step: `torch.cat` -180 ms and
the RoPE path's elementwise ops and
copies -145 ms, against +7 ms for the fused kernels, for -307 ms of
main-stream kernel time. The profiled
run explains the mechanism; the unprofiled full-model runs in the table
are the timing claim.

Before: [`main`
33e02a7](https://github.com/PrimeIntellect-ai/prime-rl/commit/33e02a7a183002aca0864c5afc1c2f5a50e48e37).
After:
[`04f7b8a`](https://github.com/PrimeIntellect-ai/prime-rl/commit/04f7b8a94e7d6482843eb871e938ded9f71427fb),
the in-place version this PR began as, with the
[fake](https://github.com/PrimeIntellect-ai/prime-rl/blob/2c671d77ed8fe639a568976c832e4ed00995542f/benchmarks/fp8_grouped_gemm/sft.toml),

[real](https://github.com/PrimeIntellect-ai/prime-rl/blob/2c671d77ed8fe639a568976c832e4ed00995542f/benchmarks/fp8_grouped_gemm/sft_scaleswe.toml)
and
[profiling](https://github.com/PrimeIntellect-ai/prime-rl/blob/2c671d77ed8fe639a568976c832e4ed00995542f/benchmarks/fp8_grouped_gemm/sft_1n_256k.toml)
configs. Real-data runs add #3544's tool-call fix

([`c7ba105`](https://github.com/PrimeIntellect-ai/prime-rl/commit/c7ba105d58b1d825c3f411bcaf6bd6c85db57ddd))
to both arms.
The out-of-place rewrite was checked only in per-kernel benchmarks,
where it is net ~90 µs faster per
layer forward than in-place, and has not been re-run end to end.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 17:26:14 -04:00
Konstantin DunasandGitHub 1556db6ca7 chore: bump verifiers to latest main (#3663)
Advance the `deps/verifiers` submodule from `9e7ec2746` to `69cc0f948`,
the latest verifiers `main`, on top of prime-rl `origin/main`.

This picks up interrupted completion stream retries and the follow-up
refactor to tenacity. Dependency metadata is unchanged, so no lockfile
update is needed.

Validation: `uv lock --check --offline` passed. All four upstream
stream-retry regression cases passed with `uv run --no-sync pytest
--noconftest
deps/verifiers/tests/v1/test_e2e.py::test_chat_harness_preserves_streamed_reasoning
-q`. Shared integration fixtures were disabled because the local
environment lacks `prime_runs`. `git diff --check` passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Submodule pointer-only change with no prime-rl code or lockfile edits;
upstream behavior is limited to streaming/retry handling in verifiers
and was exercised by targeted tests.
> 
> **Overview**
> Updates the **`deps/verifiers`** git submodule from `9e7ec2746` to
**`69cc0f948`** (current verifiers `main`). There are **no changes to
prime-rl source or lockfiles**—only the pinned submodule commit moves.
> 
> The new verifiers revision adds **retries for interrupted completion
streams** and a follow-up refactor to use **tenacity** for that retry
logic. prime-rl still consumes verifiers the same way (CI initializes
the submodule; v1 config types extend `verifiers.v1`).
> 
> Validation noted in the PR: `uv lock --check --offline`, targeted
stream-retry e2e tests under `deps/verifiers/tests/v1/test_e2e.py`, and
`git diff --check`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c23df2e4bfaa88decca20bdb1a26d4fe5f9bd23c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-24 11:10:10 -07:00
Mika SenghaasandGitHub f984dee559 fix: pre-download data before trainer ranks (#3659)
## Summary

- pre-download Hub data in the SFT launcher, beside model predownload,
before trainer ranks start
- call data predownload only for SFT data, and skip generated fake data
in the launcher
- store the snapshot in the configured Hub cache and pass its local path
to the trainer
- log skipped local paths and download duration like model predownload
- add optional `data.revision` and honor it when loading data directly

## Verification

- before: research-prod debug job 1400 failed before its first step when
concurrent ranks received HTTP 429 from the Debug data tree API
- after: called the predownload utility with the pinned Debug data and
confirmed it resolved to the local snapshot
- ran Ruff lint and formatting checks on the changed Python files

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes SFT startup and mutates in-memory data config before
subprocesses start; low security impact but affects all real-data SFT
runs’ I/O behavior.
> 
> **Overview**
> **Pre-downloads Hugging Face SFT datasets in the launcher** (alongside
model pre-download) so a single process hits the Hub before
`torchrun`/SLURM ranks start, avoiding concurrent dataset API traffic
that caused HTTP 429 failures.
> 
> Adds `pre_download_data`, which no-ops for non-SFT/`fake` configs and
existing local paths, uses `snapshot_download` with optional
`HF_HUB_CACHE`, **rewrites `data.name` to the cached snapshot path**,
and logs timing like model pre-download. The launcher calls it for train
and validation data when not in `dry_run`.
> 
> Adds optional **`data.revision`** on `SFTDataConfig` and threads it
through `load_dataset` when data is loaded directly (revision is ignored
for local paths).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6aa6aa6e37a3e777bfd61ec835f02ee7f1a360cd. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-24 11:01:21 -07:00
Mika SenghaasandGitHub c1c1fe7e14 chore: update verifiers for buffered streams (#3656)
## Summary

- Advance the `deps/verifiers` submodule from `9cf0df2` to `9e7ec27`,
the last VF main commit before Matej's retry fix.
- Include buffered SSE keepalives and retry replay from
[verifiers#2650](https://github.com/PrimeIntellect-ai/verifiers/pull/2650),
the empty-tools fix from
[verifiers#2669](https://github.com/PrimeIntellect-ai/verifiers/pull/2669),
and Prime job-output recovery from
[verifiers#2670](https://github.com/PrimeIntellect-ai/verifiers/pull/2670).
- Include the nano-rlm default revision bump from
[verifiers#2672](https://github.com/PrimeIntellect-ai/verifiers/pull/2672).
- Keep Matej's stream-consumption retry PR
[verifiers#2654](https://github.com/PrimeIntellect-ai/verifiers/pull/2654)
out of this pin. VF main merged it during this load test.

## Breaking

- VF streams now send keepalives while they buffer a model turn. They
send the completed response after the turn commits. Consumers that need
live provider token deltas must connect to the provider directly.

## Verification

- `uv sync --all-extras --all-packages --locked` completed. Both eval
configs passed `uv run --no-sync eval @ ... --dry-run`.
- Served `poolside/Laguna-S-2.1-FP8` on eight H200 nodes. Each node ran
one ETP=8 replica behind the default vLLM router with a four-hour
request timeout.
- Ran AIME26/null and Terminal-Bench 2 `fix-git`/Bash together on VF
`1e0b660`, the direct parent of the pinned `9e7ec27`. The intervening VF
diff changes only the optional nano-rlm harness default. Neither tested
harness uses nano-rlm.
- Each eval had 2,000 rollouts, fixed 2,000 inflight concurrency, and a
900-second rollout cap. Bash used 20 maximum turns. No eval-side rate
limiter was set.

The table excludes sandbox-creation HTTP 429 rollouts. It counts the
configured 900-second cap as **no error**.

| Eval | No error | Other infrastructure errors | Stream errors |
| --- | ---: | ---: | ---: |
| AIME26/null | 1,770/1,772 | 2 | 0 |
| TB2 fix-git/Bash | 1,857/1,859 | 2 | 0 |
| Combined | 3,627/3,631 | 4 | 0 |

- AIME had 779 cap exits. Its other failures were one sandbox missing
`dockerImage` and one terminated sandbox. Its 996 model calls had no
recorded call error. Of its fully completed calls, 339 exceeded 600
seconds; the longest lasted 894 seconds.
- Fix-git had 37 cap exits. Its other failures were one sandbox missing
`dockerImage` and one sandbox setup `apt-get` I/O error. Its 27,874
model calls had no recorded call error. Six fully completed calls
exceeded 600 seconds.
- Found zero terminal stream-disconnect signatures in trace errors,
model-call errors, or eval and environment logs. Both eval commands
exited successfully.
2026-09-24 10:37:00 -07:00
samsjaandGitHub bdaafc35ab chore(deps): bump dion to 6f9242d (uneven FSDP shards) (#3658)
## Summary

Bumps the dion pin from `99e5f7e` to `6f9242d`, picking up samsja/dion#4
(merged into `sami/fix-ep`):

- **Uneven and empty FSDP shards in Muon**: local shards are padded to a
uniform peer-transfer size for the all-to-all and trimmed back
before/after orthogonalization, so the update is exactly the unpadded
Muon update. Previously the optimizer asserted the sharded dim is
divisible by the optimizer world size — full Muon failed on the first
step for matrices with e.g. 4 or 24 rows on a 64-rank FSDP group.
- **Partitioned-matrix fix**: per-row learning rates are now sliced with
chunk offsets matching DTensor's `Shard` (`torch.chunk`) layout;
`torch.tensor_split` disagrees with it at world size ≥ 3 and could
silently misassign or crash when a partition boundary fell inside an
uneven shard.
- Padding now uses `torch.nn.functional.pad` (no-op fast path when
shards are already uniform).

## Compatibility

- `Muon`'s constructor signature is unchanged; the call site in
`src/prime_rl/trainer/optim/__init__.py` is unaffected.
- The pinned tree is byte-identical to the dion branch validated with:
exact (`rtol=0, atol=0`) parity vs unsharded Muon across
uneven/empty/3D/partitioned shapes at world sizes 2 (NCCL) and 3 (gloo),
plus 170 pure-CPU padding round-trip cases.

## Changes

```
pyproject.toml | 2 +-
uv.lock        | 4 ++--
```

Note: `uv lock` in a fresh clone needs the `deps/` submodules
initialized **with tags** (`git submodule update --init`, then ensure
tags are fetched) — `verifiers` and `renderers` derive versions from git
tags via hatch-vcs, and a tagless shallow checkout resolves them as
`0.0.1.dev1`, which fails workspace resolution.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Pins a new git revision of the distributed Muon optimizer used on
Linux GPU training; behavior changes in FSDP edge cases but no in-repo
code edits.
> 
> **Overview**
> Updates the **dion** git pin from `99e5f7e` to `6f9242d` in
`pyproject.toml` and `uv.lock` only—no prime-rl source changes. Training
still wires **Muon** through `src/prime_rl/trainer/optim/__init__.py`
under the `gpu` extra.
> 
> The new revision pulls in upstream fixes for **FSDP-sharded Muon**:
uneven or empty local shards are padded for all-to-all peer transfer and
trimmed so updates match unsharded Muon (avoiding first-step failures
when matrix rows aren’t divisible by optimizer world size), and per-row
learning rates are sliced with **DTensor**-consistent chunk offsets
instead of `tensor_split` (which could misassign rates at world size ≥
3).
> 
> **Risk:** dependency-only bump, but it changes distributed optimizer
numerics/behavior on large FSDP runs where the old pin could assert or
silently wrong-rate parameters.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9ca26a11e000fb7ca8a374537af6a3858c1b1aed. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 22:40:17 -07:00
samsjaandGitHub 48aa99fbb5 feat(trainer): expose the torch.compile mode (reduce-overhead) in the compile config (#3657)
## Summary
`CompileConfig` only exposed `fullgraph`, so there was no way to opt
into `torch.compile`'s lower-overhead modes. This adds a `mode` field
that mirrors the `torch.compile` `mode` kwarg, and forwards it to each
layer's `.compile()` call in `apply_compile`.

- Accepts `reduce-overhead` (records CUDA graphs to cut kernel launch
overhead), `max-autotune`, `max-autotune-no-cudagraphs` (tune Triton
kernels, longer compile) and `lite`.
- `mode = None` (default) keeps the current behavior — layers compile
with PyTorch's default mode.
- CUDA-graph modes re-record on new input shapes, so runs with highly
variable shapes pay recompile churn.

## Usage

```toml
[trainer.model.compile]
mode = "reduce-overhead"
```

or on the CLI: `--trainer.model.compile.mode reduce-overhead`.
2026-09-23 22:39:07 -07:00
samsjaandGitHub 94dff2ca54 fix(trainer): b300 fallback to FA4 (#3655)
## Problem

Two GPU-capability gates in `src/prime_rl/trainer/model.py` matched
`(10, 0)` exactly, but B300/GB300 are **SM103** (compute capability
10.3, per https://developer.nvidia.com/cuda-gpus):

1. **`resolve_auto_attn`**: `attn: auto` on B300/GB300 resolved to
`flash_attention_2` instead of FA4, silently losing the Blackwell-native
attention kernels on every default-config B300 run.
2. **`apply_quantization` (MXFP8 gate)**: MXFP8 quantization raised
`requires SM100 (Blackwell)` on B300 even though Blackwell Ultra
supports it.

## Fix

Use `major >= 10` in both places, matching the existing Blackwell checks
in `fp8_utils.py` and `fp8_grouped_gemm.py`.

## Behavior after this PR

| GPU | CC | `attn: auto` | MXFP8 |
|---|---|---|---|
| H100/H200 | SM90 | FA3 (unchanged) | n/a |
| B200/GB200 | SM100 | FA4 (unchanged) | allowed (unchanged) |
| B300/GB300 | SM103 | **FA4 (was FA2)** | **allowed (was rejected)** |
| Other SM100+ parts | SM110+ | FA4 | allowed |

Note the previous code kept workstation Blackwell (SM120/121, e.g. RTX
PRO 6000) on FA2; with the simple `major >= 10` check those now
auto-resolve to FA4 too. If FA4 kernels aren't available on such a host,
set `attn` explicitly.

## Notes

- Verified SM103 device capability via NVIDIA's CUDA GPUs page; FA4 runs
on B300 with the pinned `flash-attn-4` rev (`0251105`), which is past
the SM103 JIT-compile-churn fixes reported in
Dao-AILab/flash-attention#2635/#2699.
- B300 runs can confirm the old behavior by grepping trainer logs for
`Auto-resolved attn='auto' to 'flash_attention_2' (SM103)`.
- No behavior change on Hopper or B200 hosts.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes GPU-specific attention backend auto-selection and MXFP8
eligibility at trainer setup; mis-gating could pick unsupported kernels
on some SM10x parts.
> 
> **Overview**
> **Fixes B300/GB300 (SM103) being treated as non-Blackwell** because
capability gates in `model.py` matched compute capability `(10, 0)`
exactly.
> 
> For **`attn: auto`**, `resolve_auto_attn` now picks **flash attention
4** when the device **major** compute capability is **≥ 10**, instead of
only SM100. SM103 runs get FA4 rather than silently falling back to FA2.
> 
> For **MXFP8** in `apply_quantization`, the same **`capability[0] <
10`** rule replaces the exact SM100 tuple check, and the error text now
refers to **Blackwell (SM100+)**.
> 
> Docstrings for auto attention resolution are updated to describe
**SM100+** (including SM103) rather than datacenter-only SM100 vs
workstation SM120 wording tied to the old `(10, 0)` branch.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fbd7387af8a54df4cb3829b29dcfbbc24c1a7d27. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 21:00:12 -07:00
Mika SenghaasandGitHub 4723b0ee5a fix: increase default router timeout to four hours (#3654) 2026-09-24 04:48:24 +02:00
Mika SenghaasandGitHub b695a0aeda fix(inference): align DeepSeek V4 request tool placement (#3646)
## Summary

- attach request-level tools to the first existing DeepSeek V4 system
message
- preserve vLLM's existing synthetic-system behavior when a request has
no system message
- cover both paths and ensure the caller's messages are not mutated

vLLM 0.29's Python DeepSeek V4 tokenizer prepends a synthetic tool-only
system message even when the request already has a system prompt. That
differs from DeepSeek's reference encoder, vLLM's Rust renderer, and
prime-rl's training renderer, producing a different token prefix at
inference time.

This is a temporary compatibility patch for
[vllm-project/vllm#51856](https://github.com/vllm-project/vllm/pull/51856)
(upstream commit `2909ad8f`). That fix is expected to ship in vLLM 0.31,
at which point this monkey patch can be removed.

## Tests

- `pytest tests/unit/inference/test_deepseek_v4_tokenizer_patch.py -q` —
2 passed
- `ruff check src/prime_rl/inference/patches.py
tests/unit/inference/test_deepseek_v4_tokenizer_patch.py`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Inference-only tokenizer shim with idempotent guards; behavior is
covered by reference-encoding unit tests and should be removable after a
vLLM upgrade.
> 
> **Overview**
> Adds a temporary vLLM monkey patch so **DeepSeek V4 inference prompts
match the reference encoder and training renderer** when requests
include tools plus an existing system message.
> 
> On vLLM 0.29, the Python tokenizer **prepends a synthetic system block
for request-level tools**, putting `## Tools` before the caller’s system
text. The patch wraps `get_deepseek_v4_tokenizer` and
**`apply_chat_template`**: if the conversation already has a system
role, it shallow-copies the conversation, **attaches `tools` to the
first system message**, clears top-level `tools` so vLLM does not insert
the extra system message, and leaves **no-system** requests on stock
behavior. It is registered in **`apply_shared_vllm_patches`** and is
meant to be removed once the vLLM pin includes upstream **#51856**
(~0.31).
> 
> Unit tests assert rendered prompts match **`encode_messages`**, that
only one `## Tools` section appears, and that **input `messages` are not
mutated**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1acca7c9d1c503d0d497f05638d50e687ec714c8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 15:14:15 -07:00
753cfb5a42 fix: mark dashboard episodes failed by ok, not by carried errors (#3649)
## Summary
- The dashboard marks an episode as failed only when `ok` is false.
Retry history no longer turns a successful episode red: the episode
table row, the rollout list item, the error-rate tile on the eval
overview, and the server's `errors_only` filter all read `ok` alone.
- Episode errors and trace errors render in different places, each
tagged with its scope. A failed episode's own errors sit above the agent
and branch selectors, since they belong to the whole episode. A failed
trace's errors sit at the top of that trace's transcript, only on its
tab, and the tab is red. A failure recorded on both the episode and its
trace shows once, as the trace's.
- Errors an ok episode or ok trace carries render as a collapsed
`recovered from N episode|trace errors in earlier attempts` list in the
same two places, each entry with its traceback. The table row and
rollout list item get a dotted left edge with the recovery count in
their tooltip.

## Why
Verifiers retries a whole episode when a retryable error such as
`SandboxError` ends an attempt, and on success it prepends the earlier
attempts' errors to the final record: `final.errors[:0] = history`, with
the comment "success is the `ok` stamp, never errors-emptiness". The
agent-level retry does the same on the trace. An episode that hit the
sandbox creation limiter once and then completed cleanly therefore lands
with `ok = true`, a full trace, and the limiter error in `errors`. The
dashboard treated `num_errors > 0` as failure, so such episodes showed a
red row, an error banner over a clean transcript, and inflated the error
rate, which is what a user saw after a run with `retries.include =
["SandboxError", ...]`. Episode errors also rendered inside the open
trace, so a multi-agent episode showed a red banner over a green agent's
transcript.

## Verification
A synthetic eval run was built from a real 4-episode gsm8k stream and
served by an isolated dashboard on this branch, driven headlessly with
Playwright:

| Line | Shape | Before | After |
|---|---|---|---|
| 1 | episode failed; trace `solver` failed with `SandboxError`, trace
`judge` ok | red row, `error` badge, both banners inside the solver
transcript, episode banner inside the judge transcript | red row; the
`episode error` banner above the tabs on both; the `trace error` banner
only in the solver transcript; `solver` tab red |
| 2 | episode ok after a retry; episode and trace carry `SandboxError`
as history | red row, `error` badge, red banner over the clean
transcript | plain `done` row with a dotted edge and a "recovered from 1
error" tooltip, no banner, collapsed "recovered from 1 trace error in
earlier attempts" list holding the SandboxError and its traceback |
| 3, 4 | plain ok | `done` | `done` |
| error-rate tile | 2 failures counted | 50% | 25% |
| `errors_only=true` | | lines 1 and 2 | line 1 |

No console errors in either state.

## Screenshots
Episode table: line 1 failed (red edge), line 2 recovered (dotted edge),
lines 3 and 4 plain.

![episode
table](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/table.png)

Line 2, recovered after a retry: no banner, the SandboxError in the
collapsed recovered list (expanded here), `ok = true`.

![recovered
episode](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/recovered.png)

Line 1, `solver` tab: the episode error above the selectors, the failed
trace's error at the top of its transcript, the tab red.

![failed episode, solver
tab](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/failed_solver.png)

Line 1, `judge` tab: the episode error stays above the selectors; the
judge's transcript carries no banner because that trace completed.

![failed episode, judge
tab](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/failed_judge.png)

Screenshots live on the `assets/dashboard-retry-errors` branch.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dashboard display and filtering only; no changes to training, eval
recording, or auth paths.
> 
> **Overview**
> Aligns the eval dashboard with Verifiers’ retry semantics: **success
is `ok`, not empty errors**. Episodes that recovered after retryable
failures no longer look failed or inflate error metrics.
> 
> **Failure detection** now keys off `ok` only—the episode table,
rollout list, swarm **error-rate** tile, and server **`errors_only`**
filter no longer treat `num_errors` on successful episodes as failures.
Recovered episodes get a **dotted “retried”** row style and tooltips
instead of red error styling.
> 
> **Error UI** splits episode vs trace scope: episode-level failures
render in a new **`#tm-episode-errors`** strip above agent/branch tabs;
trace failures stay at the top of that trace’s transcript, with failed
agent tabs highlighted. **`scopedErrors`** dedupes episode/trace
duplicates (trace wins) and separates **failed** errors from
**recovered** history on ok records, shown as collapsible “recovered
from N … errors” sections. **`resetTranscript`** clears the episode
error strip whenever the transcript is replaced.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c4f6e242745c085c4bac60388dfb8c775e7b65f4. 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-23 14:29:47 -07:00
Biswa PandaandGitHub 33e02a7a18 fix(trainer): preserve Nemotron Mamba parameter dtype (#3557)
## Summary

- Initialize Nemotron Mamba `A_log` and `D` parameters with the active
default dtype so FSDP units do not mix float32 and bfloat16 storage.
- Keep the existing float32 state-space computation by casting at use
time.
- Add a focused bfloat16 parameter-dtype regression test.

## Validation

- `ruff check src/prime_rl/trainer/models/nemotron_h/mamba.py
tests/unit/train/models/test_nemotron_h.py`
- Focused in-cluster GPU probe: `A_log=torch.bfloat16`,
`D=torch.bfloat16`
- One-step Nemotron 3.5 Super VLM + MATH + Dynamo run: optimizer
completed and policy v1 was applied over NCCL.
- Three-step Kubernetes run: all optimizer steps completed; policies v0
through v3 applied to Dynamo; Job succeeded.
- Trainer mismatch KL by step: `0.0274`, `0.0344`, `0.0309`.

W&B: https://wandb.ai/test232/nemotron35-vlm-rl/runs/jq06zl0l
2026-09-23 13:35:34 -07:00
94f359e8d6 feat: scope verifiers limiters by run id and bump verifiers to main (#3641)
## Summary
- Bump the verifiers submodule to main (`9cf0df22b`), which includes
PrimeIntellect-ai/verifiers#2657: creation limiters wait on backlog
instead of raising past 300s, and their bucket is scoped by
`$VF_RUN_ID`. `uv.lock` is regenerated; verifiers dropped its `lean`
extra.
- The env-server entrypoint sets `VF_RUN_ID` from `PRL_RUN_ID`, minting
a uuid only when neither is set. Its pool workers inherit it.
- The multi-node SFT SLURM script exports `PRL_RUN_ID` and
`PRL_RUN_NAME` unconditionally, as the RL script does. Only the W&B
shared-mode variables stay behind the wandb condition, now named
`wandb_shared` in the template.

## Why
With the bump, a run whose sandbox creation outpaces `creates_per_min`
throttles instead of failing every rollout past the 300s backlog.
Scoping the bucket by run id keeps one run's backlog from delaying
another.

The env server is the one prime-rl process that creates sandboxes, and
every launcher hands it `PRL_RUN_ID`: the `rl`, `sft`, and `eval`
entrypoints export it before spawning, and the SLURM scripts export it
at the top of the sbatch script, which `srun` propagates to the `uv run
env-server` tasks. Deriving `VF_RUN_ID` there covers every launch path
with one line. The SFT script previously exported the run id only for a
shared W&B run, so its online-eval env servers would otherwise each have
minted their own scope.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes run-id propagation for SLURM-launched env servers and sandbox
creation throttling behavior; mis-set env vars could affect multi-run
cluster behavior but not auth or data integrity.
> 
> **Overview**
> Aligns prime-rl with verifiers’ run-scoped sandbox **creation
limiters** (keyed on `$VF_RUN_ID`) so throttling and backlog are per run
instead of shared across jobs.
> 
> The **env-server** entrypoint now sets `VF_RUN_ID` from `PRL_RUN_ID`,
or mints a UUID when launched standalone, so pool workers inherit the
same scope on every launch path.
> 
> **Multi-node SFT** previously exported `PRL_RUN_ID` only when shared
Weights & Biases logging was enabled, which left online-eval env servers
without a consistent run id. The SLURM template now always exports
`PRL_RUN_ID` and `PRL_RUN_NAME` (matching RL), while W&B shared-mode env
vars are gated on a new `wandb_shared` flag passed from `sft.py`.
> 
> **Lockfile** metadata drops the removed `lean` extra from the bumped
verifiers dependency.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
364f0b58699ad556746116a1bf6208e37b5afc6b. 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-23 13:34:19 -07:00
Matej SirovatkaandGitHub cf400e7db9 perf: reduce DSV4 indexer stalls and overlap CP gathers (#3643)
Packed sequence lengths were causing repeated FP8-indexer autotuning
during training. Other DP groups then arrived late at the layer-4 FSDP
prefetch, making a normal ~1–3 ms parameter gather appear to take 1.78
s. Together with narrower checkpoint state, avoiding a query-layout
copy, and overlapping CP communication, the matched BF16 benchmark
improves from **22.741 s / 40.23% MFU** after #3638 to **18.999 s /
47.79% MFU**.

- Bucket the indexer's autotune key by compressed-key length, also
keying on head count and dimension. Exact key lengths still control
addressing and masks. An all-rank trace showed the last rank arriving
1.718 s late and completing the gather in 1.34 ms; it had been
benchmarking the first CSA indexer.
- Register the FP8 indexer as an opaque operation and make its final
int32 selection a mandatory checkpoint save. This preserves the top-k
replay requirement while retaining compact IDs and skipping indexer
scoring on replay.
- Apply query RoPE directly in the sparse kernel's `(batch, tokens,
heads, dim)` layout, removing the transpose/contiguous round trip in
attention and the indexer.
- Launch the main KV CP gather with PyTorch's asynchronous functional
collective before query/compressor computation, and wait just before
consuming KV. Its registered backward performs the corresponding sum
reduce-scatter. Compilation stays enabled; communication uses NCCL's
existing stream.

### SAC configuration

Exact configuration for the measured run:

```toml
[model.ac]
mode = "selective"
freq = 1
targets = [
  "prime_rl::dsv4_sparse_attn",
  "prime_rl_collectives::all_to_all_single_equal",
  "aten::sort.stable",
]
```

`prime_rl::fp8_indexer` is saved automatically by the mandatory policy
in both full and selective checkpointing. The qualified stable-sort
overload matters: `aten::sort` does not match `aten::sort.stable`.

### Measurements

| Variant | Mean step time | Logged tokens/s | Logged MFU |
| --- | ---: | ---: | ---: |
| PR #3638 only (job 653) | 22.741 s | 86,890 | 40.23% |
| Indexer tuning buckets, full AC (665) | 20.718 s | 95,043 | 44.01% |
| Buckets + sparse-attention/EP-count SAC (675) | 20.042 s | 97,636 |
45.21% |
| All changes + SAC above (691) | **18.999 s** | **103,210** |
**47.79%** |

This is a **1.197× step-time speedup** over #3638 alone and **1.055×**
over the prior SAC run. Peak rank-0 reserved memory is **232.5 GiB /
267.7 GiB**. All five losses are finite. These are short benchmark
results, not a long-run convergence measurement. Measurements use the
pinned job-492 environment; this branch is rebased onto current main,
whose touched modeling files were identical to that baseline.

### Validation

- CPU checkpoint-policy tests: 4 passed on the PR branch, including
mandatory indexer retention under custom SAC targets. Ruff lint and
formatting checks passed for all changed files.
- Existing FP8-indexer GPU correctness cases: 2 passed. Changing key
lengths 1060 → 1064 → 1073 reused one autotune entry (2.015 s initial
tuning, then 0.919 ms and 0.634 ms).
- Existing sparse/eager attention parity cases: 9 passed, covering CSA,
HCA, sliding attention, packed documents, and empty compression.
- Existing CP packing checks: 6 passed across CP2/CP4 and all three
attention types; rerun successfully after inlining the gather and wait
calls directly in attention forward.
- Two-rank async-collective probe: outputs and input/weight gradients
passed with full/selective checkpointing, eager execution and
`torch.compile(fullgraph=True)`.
- Compiled two-rank BF16 attention checks: all three attention types
passed under full/selective checkpointing against the blocking
implementation; maximum relative L2 difference across outputs and
gradients was 0.026%. The sliding cases ran in a separate process after
the combined test harness reached its compiled-variant limit.
- Query-layout microcheck: bitwise-equal outputs and input gradients in
BF16/FP32, including the production query shape.



<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes touch CP collectives, compile/custom-op boundaries, and SAC
correctness for non-replayable top-k; numerics are covered by existing
kernel and CP tests but production timing depends on NCCL stream overlap
behavior.
> 
> **Overview**
> This PR targets **DeepSeek V4 training step time** by cutting FP8
indexer autotune churn, overlapping context-parallel communication, and
tightening activation-checkpoint behavior around sparse indexing.
> 
> The **FP8 Lightning indexer** is registered as `prime_rl::fp8_indexer`
and added to the **mandatory** selective-activation-checkpoint save list
so replay keeps the final int32 top-k without re-running scoring. Triton
autotune now keys on **`next_power_of_2(S_k)`** plus head count and
dimension so packed batches with slightly different compressed-key
lengths reuse one tuned config.
> 
> In **attention**, queries stay in **`(batch, tokens, heads, dim)`**
through RoPE and into `dsv4_sparse_attn`, dropping the
transpose/contiguous path. Under CP, **KV all-gather** starts
asynchronously via `_c10d_functional.all_gather_into_tensor` before
query and compressor work, with **`wait_tensor`** immediately before KV
is consumed.
> 
> Tests assert mandatory checkpoint retention for the new op and extend
CP parity mocks for the async gather path.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6449f9212c3430c812b9623a1b5bd274e350b780. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 16:07:21 -04:00
samsjaandGitHub 8da21f16b8 feat(eval): make task dispatch rate configurable (#3602)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Optional config with default unchanged; reuses existing orchestrator
dispatch rate limiting with no auth or data-path changes.
> 
> **Overview**
> Eval runs can now cap how fast episodes are dispatched via a new
**`tasks_per_minute`** setting on **`ServedEvalConfig`** (shared by
standalone eval and SFT online eval). **`None`** keeps the previous
behavior with no rate limit; a positive value throttles dispatch through
the existing **`Dispatcher`** **`AsyncLimiter`**, intended to pace
sandbox provisioning during autoscaling.
> 
> The eval **`runner`** passes **`config.tasks_per_minute`** into the
dispatcher instead of hard-coding **`None`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
31f8041b908234dc4c45f128540af8e4daa6435b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 09:30:15 -07:00
ae37b35a34 fix(trainer): match vLLM's per-token FP8 activation quantization bit for bit (#3623)
RL compares trainer and inference logprobs token by token, so any
disagreement between the two FP8
quantizers is model-independent noise. The trainer's per-token
activation cast is now bit-identical to
vLLM's production CUDA op, `torch.ops._C.per_token_group_fp8_quant`.

- Three kernels in `fp8_utils.py` floor `amax` at `1e-10` and use
`tl.math.div_rn` for scale and quotient.
Triton's `/` lowers to multiply-by-reciprocal, one fp32 ULP off the
correctly rounded value.
- The weight kernel is untouched: vLLM's weight path is itself a
reciprocal-multiply and already matched.
- A new GPU test pins the equality against the CUDA op; the trainer
still imports vLLM nowhere.

Share of 128-wide groups whose scale is bitwise equal to vLLM's, and
share of elements whose fp8 byte
is, on four 4096x4096 bf16 activation tensors on an H200:

| tensor | scales: before | after | bytes: before | after |
|---|---|---|---|---|
| randn x0.02 | 42.8329% | 100.0000% | 98.1890% | 100.0000% |
| randn x1.0 | 41.0797% | 100.0000% | 99.8822% | 100.0000% |
| randn x30.0 | 43.6028% | 100.0000% | 99.8869% | 100.0000% |
| randn heavytail 16ch x50 | 42.7979% | 100.0000% | 99.8999% | 100.0000%
|

Every pre-fix mismatch was exactly one e4m3 step, so weights stay at
100% and dequantization error is
unchanged. Agreement with vLLM's Triton fallback drops to about 42% on
scales, which is forced since
vLLM's two backends are not bit-identical to each other and only the
CUDA op runs in production. Costs
3.1% of quant-kernel time at 4096x4096 and 8.7% at [8192, 7168].
Verified on sm90 with
`use_ue8m0=False`; sm100 takes a different vLLM kernel.

## Effect on training gradients

The old floor applied to the scale, not to `amax`, so any 128-wide group
with `amax < 0.0448` was
quantized against an inflated scale: its values were squeezed into a
corner of the e4m3 range
instead of spanning it, and everything below `1e-7` rounded to zero.
Forward activations sit above
that threshold; gradients do not, and both the input-gradient (dgrad)
and weight-gradient (wgrad)
paths cast `grad_output` through these kernels. The error is one-sided
toward zero, so it shrinks
gradients rather than adding noise.

Measured end to end: a 131k-context SWE RL run with an FP8 trainer on
pre-fix code logged
`optim/grad_norm` averaging 0.0079 over 100 steps, against 0.0465 and
0.0528 for otherwise
identical runs with a bf16 trainer. A rerun of that config on the fixed
kernels is at 0.0421 over
its first 17 steps, where the pre-fix run read 0.0094 and the bf16
reference 0.0468 over the same
window. Mismatch KL is blind to all of this, since it depends on the
forward alone: lr = 0 probes
read 0.0089 before the fix and 0.0091 after.

### Why the floor's location matters

Per 128-element group:

```
# before
amax  = max(|x|)
scale = max(amax / 448, 1e-4)      # floor on the SCALE
y     = x / scale

# after
amax  = max(max(|x|), 1e-10)       # floor on the AMAX
scale = div_rn(amax, 448)
y     = clamp(div_rn(x, scale), -448, 448)
```

A floor exists only to keep an all-zero group from dividing by zero. The
correct scale, `amax / 448`,
maps the group's largest element to exactly 448 and spans the full e4m3
range. Pinning the scale at
`1e-4` makes it too large whenever `amax < 0.0448`, and a scale that is
too large makes `y = x / scale`
too small, so the group occupies a corner of the range.

Take a gradient group with `amax = 1e-5`:

- correct scale is `1e-5 / 448 = 2.2e-8`, giving `y_max = 448`, the full
range
- old scale is `1e-4`, giving `y_max = 0.1`, a sliver of it
- e4m3's smallest subnormal is `2^-9 = 0.00195`, so any `|y|` below
about `0.001` rounds to zero
- that is every `|x|` below `1e-7`, which is 1% of this group's maximum
- at `amax = 1e-6` the same `1e-7` cutoff erases everything below 10% of
the maximum

Two properties make this worse than rounding noise. It is one-sided,
always toward zero, so it biases
the gradient short rather than jittering it. And it is non-uniform:
groups above `0.0448` are exact
while groups far below it are gutted, so the surviving gradient also
points in a different direction.
AdamW's per-parameter normalization absorbs much of the magnitude loss,
which is why a run carrying
this bug trains through it while looking healthy.

## Launch-config retune

This PR also reconfigures the kernel launch specs for perf (for H200).

Measuring the cost of correct rounding exposed a separate problem: these
kernels were already launched
at block sizes that spill registers. The per-channel cast used a `[128,
128]` fp32 tile, and
`div.rn.f32` needs more live temporaries than `div.full.f32`, which is
why correct rounding looked
expensive there. Retuning `BLOCK_M`, `BLOCK_N` and `num_warps` in five
host wrappers, with no kernel
body change, recovers more than correct rounding costs.

Measured on an H200 at this model's dimensions (hidden 4096, MoE
intermediate 2048, 8 local experts
with ragged routing), 102 configs against a noise-control arm:

| kernel | wins | regressions | noise | best delta |
|---|---|---|---|---|
| `grouped_per_channel` k-major | 24 | 0 | 2 | -54.1% |
| `grouped_per_channel` row-major | 21 | 0 | 5 | -35.3% |
| `per_token` transposed | 6 | 0 | 6 | -44.8% |
| `grouped_per_token` | 7 | 0 | 19 | -12.0% |
| `per_token` | 3 | 0 | 9 | -12.4% |

Ragged expert groups gain more than equal ones: at K=4096 with 4096
tokens per rank, the k-major
per-channel cast is -28.5% on an equal split and -54.1% under realistic
routing. A launch config cannot
change the arithmetic, so bit identity against the CUDA op is
unaffected.

## Verification

```
uv run --no-sync python -m pytest tests/unit/train/models/test_fp8_utils.py -q
```

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 11:14:43 -04:00
Matej SirovatkaandGitHub 77788ba020 fix: retain two reduce-scatter input buffers for FP32 MoE routers (#3638)
FP32 MoE routing uses a separate FSDP unit. Its post-backward hook can
request a reduce-scatter input buffer while the expert reduction is
still in flight; FSDP's default limit of one inserts a compute-stream
wait before attention backward can run.

Set `set_reduce_scatter_max_input_buffers(2)` on that router unit
immediately after sharding. FSDP resolves the shared buffer limit to the
maximum across its units, allowing the router to pack gradients while
the expert reduction completes. This adds two lines on top of main, with
no new configuration or numerical dtype changes. The tradeoff is
additional memory for in-flight reduction inputs.

### Measured timings

Same saved packed tokens and checkpoint, GLM-5.3 EP8/CP8 on 32 B300
GPUs, FP32 routing, full activation checkpointing, and activation
offloading enabled in both runs. Two warmup passes followed by one
profiled forward/backward; no optimizer update.

| Metric | One buffer | Two buffers |
| --- | ---: | ---: |
| Warm forward + backward, median across 32 ranks | 14.699 s | 12.649 s
|
| Profiled forward + backward, median across 32 ranks | 14.808 s |
12.717 s |
| Expert reduce-scatter overlap with main-stream compute, rank 0 | 11.1%
| 93.7% |
| Maximum reserved GPU memory across ranks/passes | 204.49 GiB | 205.29
GiB |

Warm forward/backward is **13.9% shorter**, equivalent to **16.2% higher
throughput**, at **0.80 GiB** more peak reserved memory in this run.

### Timeline of the stall

Actual CUDA kernel intervals for layer 77, rank 0. Each panel is aligned
independently to that layer's expert reduce-scatter launch. Blue is
other main-stream compute, green is attention backward, and orange is
expert gradient reduce-scatter.

![Measured one-buffer versus two-buffer reduce-scatter
overlap](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/1bebf826b530cb7c52d18d8cf92d562174a7efbe/reduce-scatter-overlap.png)

With one buffer, the router's post-backward hook queues a compute-stream
wait while the **4.5 GiB expert reduction** is in flight. This creates a
**40.7 ms main-stream compute gap**. The router's own reduction is only
**6 MiB / 0.66 ms**. Attention backward starts **48.87 ms** after the
expert reduction launch; with two buffers it starts at **8.15 ms**
instead. The layer's expert-reduction overlap rises from **7.3% to
96.3%**. These layer-specific percentages differ from the aggregate
values in the table.

These are single-run comparisons, not repeated statistical benchmarks.
The measured experiment set the cap at the root; this PR applies the
same effective shared cap through the router unit. Ruff and `git diff
--check` pass; this exact main-based patch has not had a new distributed
run.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Two-line FSDP scheduling tweak in MoE setup only; no numerical or API
changes, with modest extra peak memory for reduction buffers.
> 
> **Overview**
> When **FP32 MoE routers** are sharded as their own FSDP unit
(alongside expert-parallel expert shards), backward can stall: the
router’s post-backward reduce-scatter needs an input buffer while the
much larger expert gradient reduction is still using FSDP’s default
single buffer, forcing a **compute-stream wait** before attention
backward can proceed.
> 
> Right after `fully_shard` on `block_mlp.router`, the PR calls
**`set_reduce_scatter_max_input_buffers(2)`** so the router can queue
its small reduction without blocking on the in-flight expert
reduce-scatter. FSDP’s shared limit becomes the max across units—same
effective behavior as raising the cap at the root, but scoped to the
router shard path. **Tradeoff:** slightly more memory for in-flight
reduction inputs; no new config or dtype changes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
51a9e3daef8a53a254d7e7ff35d1ee3c8afce18c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 17:02:46 +02:00
Scott CabrinhaandGitHub ab85b3b369 fix(docker): install the Prime CLI into the image venv for hosted-run env bootstrap (#3635)
## Problem

Since #3585 removed the `prime` CLI as a prime-rl dependency ("Stop
installing the `prime` CLI with prime-rl. Run `uv tool install prime`
when the CLI is needed"), the published GHCR images ship no `prime`
executable. That breaks Hosted Training runs on these images at
bootstrap:

The platform's env-server and orchestrator pods prepend an
**authenticated** Hub env install to their pod command,

```
uv run --no-sync prime env install '<owner/name>' && ... && uv run --no-sync env-server @ config
```

because verifiers' own `ensure_installed` resolver fetches the Hub
**unauthenticated** and 404s on private environments — the pre-install
into the pod's venv is what makes v1 Hub tasksets resolvable at boot
(envs baked into the image never hit this path).

With the executable absent from `/app/.venv/bin`, every pod dies at
spawn and the run wedges at `CREATING`. Observed on
`ghcr.io/primeintellect-ai/prime-rl:v0.9.1.dev100` dispatching a run
with a Hub taskset:

```
error: Failed to spawn: `prime`
```

(the orchestrator's entire log is two lines: the no-checkpoints warning,
then that spawn failure).

## Fix

Install the CLI into the image venv at build time — **not** as a project
dependency, so #3585's "CLI as a separate tool" boundary stands for
library code; the image just ships the executable and its runtime deps
so the platform bootstrap can run.

- One `RUN` after the main `uv sync`, using the same uv cache mount as
the rest of the file.
- `prime>=0.7` — pure-Python CLI, few MB; most deps
(httpx/pydantic/etc.) are already in the venv.
- The runtime stage copies `/app` wholesale, and `PATH` already puts
`/app/.venv/bin` first, so `uv run --no-sync prime env install ...` and
direct `prime` calls both resolve.

## Alternatives considered

- Reverting #3585's dependency removal: rejected — keeps the boundary;
the image need, not the library, is what broke.
- Platform-side init container with a dedicated prime-cli image (cleaner
long-term: keeps the CLI out of the framework image entirely) — worth
tracking on the platform side; this PR is the minimal unblock for hosted
Hub-env runs today.

## Verification

- `VIRTUAL_ENV=<venv> uv pip install 'prime>=0.7'` smoke-tested locally
(CLI 0.7.0 boots).
- Placement reviewed against the builder stage: runs after the locked
sync chain, before the optional NIXL block; nothing downstream
overwrites the venv.
2026-09-22 19:06:08 -06:00
Mika SenghaasandGitHub de5cdb8bae fix: read serialized dashboard token counts (#3632)
## Summary

- pin Verifiers `main` at the merge of [Verifiers
#2652](https://github.com/PrimeIntellect-ai/verifiers/pull/2652),
including the computed fields from [Verifiers
#2651](https://github.com/PrimeIntellect-ai/verifiers/pull/2651)
- read serialized token counts directly from completed episode and live
trace records
- remove dashboard-specific token reconstruction and prompt-token
summation

The previous implementation summed every full prompt in a multi-turn
trace.
This counted the shared conversation once per request and inflated long
rollouts.

## Verification

Before this change, a two-turn trace with prompt usages of 100 and 150
tokens
reported 250 input tokens. After this change, the serialized record and
both
dashboard paths report 130 input tokens and 50 output tokens.

- tested the dashboard flow end to end
- `ruff check` and `py_compile` passed for both changed modules
2026-09-22 15:50:19 -07:00
samsjaandGitHub b636a8b7ec chore: bump prime-envs to latest main (#3630)
## Summary
- Bump the `deps/prime-envs` submodule from `1f1e050ab` to `1213b7336`
(latest `main`).
  - Pulls in:
-
[prime-envs#791](https://github.com/PrimeIntellect-ai/prime-envs/pull/791):
strip v0 remnants.
-
[prime-envs#795](https://github.com/PrimeIntellect-ai/prime-envs/pull/795):
restore solver network access for training environments.
-
[prime-envs#797](https://github.com/PrimeIntellect-ai/prime-envs/pull/797):
500-trace SWE cheating recall benchmark (new `trace-cheating-recall-500`
judge env).
-
[prime-envs#796](https://github.com/PrimeIntellect-ai/prime-envs/pull/796):
run MCP Atlas and Enterprise Ops Gym services in VMs.
-
[prime-envs#798](https://github.com/PrimeIntellect-ai/prime-envs/pull/798):
fair-use solver prompts for SWE and terminal training tasksets.
-
[prime-envs#805](https://github.com/PrimeIntellect-ai/prime-envs/pull/805):
keep env CI evals off the platform.
-
[prime-envs#770](https://github.com/PrimeIntellect-ai/prime-envs/pull/770):
OfficeQA Pro V2 (new `officeqa-pro-v2` env).
-
[prime-envs#808](https://github.com/PrimeIntellect-ai/prime-envs/pull/808):
complete TMax platform hosting and source references.
-
[prime-envs#814](https://github.com/PrimeIntellect-ai/prime-envs/pull/814):
ask before changing repository skills.
-
[prime-envs#815](https://github.com/PrimeIntellect-ai/prime-envs/pull/815):
support renamed Verifiers eval CLI in CI.
-
[prime-envs#822](https://github.com/PrimeIntellect-ai/prime-envs/pull/822):
remove obsolete Prime VM configuration.
- Relock `uv.lock`: new workspace members `officeqa-pro-v2` and
`trace-cheating-recall-500` (auto-discovered via
`deps/prime-envs/environments/*/*`); env package version bumps.

## Validation

- `uv sync --all-extras --all-packages --locked` passes.
- `uv run pytest tests/unit -m "not gpu"`: 616 passed, 1 skipped.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Training and evaluation behavior can shift (solver prompts, network
access, VM-hosted tool services, new benchmarks) because many SWE,
terminal, and tool-use env packages change together.
> 
> **Overview**
> Updates the **`deps/prime-envs`** submodule to the latest **`main`**
and refreshes **`uv.lock`** so the workspace picks up new and bumped
editable environment packages.
> 
> The lockfile adds two auto-discovered members—**`officeqa-pro-v2`**
(search) and **`trace-cheating-recall-500`** (judge)—and bumps patch
versions across many existing env packages (SWE stacks like
**`openswe`**, **`multiswe`**, **`swesmith-env`**; terminal **`tmax`** /
**`terminal-lego`**; tool-use **`mcp-atlas`** /
**`enterprise-ops-gym`**; plus assorted math, lean, long-context, and
reasoning envs).
> 
> Upstream **`prime-envs`** changes bundled with this bump include
stripping v0 remnants, restoring solver network access for training
envs, fair-use solver prompts for SWE/terminal tasksets, MCP Atlas and
Enterprise Ops Gym running services in VMs, TMax hosting completion,
CI/eval CLI fixes, and related housekeeping—not new logic in this repo
beyond the dependency pin and lock refresh.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
75422004f320992e134a1d188368f15637bf8193. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-22 13:19:08 -07:00
Mika SenghaasandGitHub 9aa8563eae fix(inference): extend startup readiness timeout (#3626)
## Summary
- increase the default inference readiness timeout from 30 minutes to 60
minutes
- keep the direct `check_health` default aligned with `ClientConfig`

Large models can exceed 30 minutes on a cold node while vLLM compiles
architecture-specific kernels and captures CUDA graphs. The previous
default can tear down an otherwise healthy launch just before readiness.

## Test plan
- `PYTHONPATH="$PWD/src:$PWD/packages/prime-rl-configs/src" pytest -q
tests/unit/orchestrator/test_clients.py` (10 passed)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Only increases startup wait defaults; no changes to auth, weight
updates, or runtime inference behavior once ready.
> 
> **Overview**
> Raises the default **inference pool startup wait** from 30 to **60
minutes** so cold starts (e.g. vLLM kernel compile and CUDA graph
capture on large models) are less likely to fail right before `/health`
succeeds.
> 
> The change updates `ClientConfig.wait_for_ready_timeout` in shared
config and the default `timeout` on `check_health`, keeping orchestrator
health polling aligned with the config default used by
`AdminPlane.wait_for_ready`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f9fdfe25be6d643d43e830121bf22b6a9bd036c1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-22 11:58:23 -07:00
Mika SenghaasandGitHub a44dc3572c feat(inference): configurable vLLM router request timeout (#3620)
## Summary

- Add `VllmRouterConfig.request_timeout_secs` (**default 1800 — the
router's own built-in default**, `ge=1`): the maximum lifetime of a
routed request, including streamed completions.
- Wire it through both router launch paths — the Python entrypoint
(`--request-timeout-secs`) and the `_launch_router.sh.j2` template. When
unset, the router behaves exactly as before.
- Long agentic rollouts set it explicitly, e.g. `request_timeout_secs =
3600` for one-hour SWE eval requests.

## Note on "no timeout"

The Rust router applies the value as its HTTP client's **total request
timeout unconditionally** (`server.rs`,
`.timeout(Duration::from_secs(...))`): plain `u64`, no disable sentinel,
and `0` would be an *immediate* timeout. So "no timeout" is not
expressible — a finite configurable value with the upstream default is
the right shape.

## Validation

- `VllmRouterConfig` default (`1800`) / set (`3600`) / `ge=1` rejection
all verified; both launch paths interpolate the same field (the template
already receives the `router` config object).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Operational tuning of router HTTP client timeouts only; no auth or
data-path changes, though misconfigured values could still cut off or
hang long requests.
> 
> **Overview**
> Adds **`request_timeout_secs`** on **`VllmRouterConfig`** (default
**1800s**, minimum 1) so the maximum lifetime of a routed
request—including streamed completions—can be set from inference config
instead of relying on implicit router defaults.
> 
> Both managed router launch paths now pass
**`--request-timeout-secs`**: the local **`start_router`** entrypoint
and the SLURM **`_launch_router.sh.j2`** template read
**`router.request_timeout_secs`**. Long agentic or eval rollouts can
raise the value (e.g. via config override) without patching launch
scripts.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
adf7321a3604f2fc784ab961688a281ab6002165. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 16:22:12 -07:00
Mika SenghaasandGitHub 32f4f40f9e feat(orchestrator): unified taskset shuffle for train and eval sources (#3622)
## Summary

- `EnvConfig.shuffle` (`bool`, default `False`): shuffle the source's
finite taskset **once at startup** with a fixed seed
(`TASKSET_SHUFFLE_SEED = 42`).
- Defined in one place — `EnvConfig`, the shared base — so both
`TrainSourceConfig` and `EvalSourceConfig` inherit it: one knob covers
RL train envs, RL/SFT online evals, and standalone evals. Train
curricula and eval example selection both consume the shuffled order.
- Infinite tasksets reject `shuffle` at startup with a clear error.
- The eval resume allowlist now overrides `source.*.shuffle` (fixed seed
⇒ deterministic across resume).

```toml
[[train.source]]           # or [[eval.source]]
shuffle = true
```

Mirrors the existing SFT-data convention (`shuffle: bool` + fixed seed).

## Validation

- `pytest tests/unit/orchestrator/ tests/unit/eval/
tests/unit/test_configs.py` — 288 passed, 1 skipped.
- Smoke: `TrainSourceConfig(..., shuffle=True)` and
`EvalSourceConfig(..., shuffle=True)` both parse; default is `False`;
resume allowlist updated.
- **Manual eval-selection run (real `Env.start()` path, gsm8k,
`num_examples = 50` of 1319 test tasks; only the env-server network
handshake stubbed — no GPU on the validating node):**
- `shuffle = false`, run 1 → `[0, 1, 2, ..., 49]` (natural source order)
- `shuffle = true`, run 1 → `[588, 1214, 57, 906, 1252, 618, 599, 289,
...]`
- `shuffle = true`, run 2 → identical to run 1 (same 50 tasks, same
order) ✔ reproduces
  - `shuffle = false`, run 2 → identical to run 1 ✔ off is stable
- off vs on selections differ (set overlap 2/50, as expected for a
random 50-of-1319 subset) ✔

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior is opt-in with a fixed seed and only affects task ordering at
startup; infinite tasksets are explicitly rejected.
> 
> **Overview**
> Adds a **`shuffle`** flag on shared **`EnvConfig`** (default
**`false`**) so train and eval sources can reorder a **finite** taskset
once at env startup instead of always taking tasks in source order.
> 
> When **`shuffle=true`**, the orchestrator materializes the taskset and
shuffles it with a fixed seed (**`TASKSET_SHUFFLE_SEED = 42`**), so the
same permutation holds for the whole run and eval example selection
stays reproducible. **Infinite** tasksets fail fast with a clear error.
> 
> Eval **resume** may override **`source.*.shuffle`** alongside other
rollout knobs. New unit tests cover default order, changed selection,
reproducibility, full-taskset selection, and the infinite-taskset
rejection.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8358483c1144ed331f575a5e857fabe390de50c8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 16:20:06 -07:00
Mika SenghaasandGitHub ef07764841 feat(sft): per-row reasoning_effort renderer override (#3621)
## Summary

- A `reasoning_effort` column in the dataset overrides the `[renderer]`
config's `reasoning_effort` field **per row**, so one SFT run can mix
reasoning efforts with the configured renderer serving as the default
for rows that do not set one (or set null).
- Requires a typed renderer config that has the field: `renderer.name =
"auto"` and field-less renderers raise a clear `ValueError`. Renderer
configs are frozen, so resolved configs are cached and rows resolving to
the same config share one renderer instance.
- Doc paragraph in `docs/training.md`; dataloader and sft-dataset tests
updated.

```toml
[renderer]
name = "glm-5.3"          # typed renderer; reasoning_effort = "max" is the row default
# dataset rows may carry reasoning_effort = "low" | "high" | "max" per row
```

## Validation

- `pytest tests/unit/train/sft/` — 47/47 pass.
- E2E with the real GLM-5.3 renderer: rendered prompts carry the per-row
effort preamble (`Reasoning Effort: Low` vs `Max`), invalid efforts
rejected by the config `Literal`, `None` rows fall back to the
configured renderer, and the resolver caches one renderer per distinct
config.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are confined to SFT tokenization/renderer selection with
explicit validation for auto or unsupported renderers; misconfiguration
fails at load time rather than silently wrong training.
> 
> **Overview**
> SFT can now **mix reasoning efforts in one run** via an optional
dataset **`reasoning_effort`** column that overrides the typed
`[renderer]` config per row; null/missing values keep the TOML default.
> 
> **`RendererResolver`** (in `data.py`) builds and **caches** renderers
from `renderer_config` + row overrides instead of a single shared
renderer. **`SFTDataset`** takes a per-example renderer callable;
**`setup_dataset`** / **`train.py`** pass **`renderer_config`** and the
VLM **processor** rather than constructing one renderer up front (train
and validation use the same path).
> 
> Docs in **`training.md`** describe the column, typed-renderer
requirement, and supported model families. Unit tests were updated to
pass `lambda _: renderer` into **`SFTDataset`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3408b9918dccf06d86ab732faa94a18f6233ca31. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 16:20:00 -07:00
7745c669d1 feat(monitors): attach eval runs to a platform-created evaluation (#3619)
## Summary

`PrimeEvalMonitor` attaches to an existing platform evaluation when
`$PRIME_RUNS_EVAL_ID` is set, instead of always registering a new one.
This mirrors how `PrimeTrainMonitor` already attaches to `$RUN_ID`.

Why: A hosted evaluation is created by the platform before its sandbox
starts: the platform owns billing, secrets, timeouts, cancellation and
the final "did every episode reach the platform" check, and it hands the
sandbox the evaluation's id, which the monitor reads from
`$PRIME_RUNS_EVAL_ID`. Today `uv run eval --monitors.prime` inside that
sandbox would call `pr.init(kind="eval", ...)` without an id, register a
second evaluation and leave the platform's one open forever.


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes platform eval registration lifecycle for hosted runs;
misconfiguration (multiple sources or multiple epochs) fails fast with
explicit errors.
> 
> **Overview**
> **Hosted eval sandboxes** can now stream to an evaluation the platform
already created instead of registering a duplicate that leaves the
platform run orphaned.
> 
> When **`PRIME_RUNS_EVAL_ID`** is set, `PrimeEvalMonitor` calls
`pr.init` with that **`id`** (same attach pattern as training’s
**`$RUN_ID`**). Init requires **exactly one** eval source, and
**`open`** rejects a second epoch so one injected id maps to one epoch.
Logs note attachment when **`run.attached`** is true.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b4af11c50eb8201cbaf1b9a903b245a1bb8ed76e. 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-21 15:23:56 -07:00
87c5456806 chore(deps): bump vLLM to 0.29.0 (#3617)
Bumps vLLM from 0.28.0 to 0.29.0 and reconciles prime-rl's runtime
monkeypatches with 0.29's reorganized entrypoint layout. Three patches
are now obsolete and removed, each backed by a merged upstream PR.

- Rebound the API server layer onto `vllm.entrypoints.launchers.*`: on
0.29 the old `openai.api_server` path is a deprecation shim, so without
this the custom routes and the `PrimeRlServingTokens` swap would
silently not install.
- Dropped `monkey_patch_fp32_lm_head`: vLLM does the fp32 lm_head
projection natively via `head_dtype`
([#48390](https://github.com/vllm-project/vllm/pull/48390), LoRA path
[#48525](https://github.com/vllm-project/vllm/pull/48525)), so
`enable_fp32_lm_head` now injects `hf_overrides = {"head_dtype":
"float32"}`.
- Dropped the `PrimeRlServingTokens.serve_tokens` `kv_transfer_params`
bridge: upstream threads the params into the engine itself as of
[#42644](https://github.com/vllm-project/vllm/pull/42644), which landed
after the 0.28.0 cut.
- Dropped `monkey_patch_qwen3_coder_param_newline_trim`: upstream
restored the single-newline trim in
[#48846](https://github.com/vllm-project/vllm/pull/48846), making the
patch a byte-for-byte no-op.
- #48390 and #48846 already shipped in 0.28.0, so 0.29's role is to make
`fp32_lm_head` *fatal* via the new positional `skip_gather`; only #42644
is genuinely unlocked by the bump.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 15:36:25 -04:00
12b4d4b050 chore: whitelist the Environments Hub index for uv installs (#3612)
## Summary

- Add an explicit `[[tool.uv.index]]` named `prime-hub` for
`https://hub.primeintellect.ai/primeintellect/simple/` with
`exclude-newer = false`. Hub wheels carry no upload time, so the repo's
7-day `exclude-newer` cooldown filtered all of them out.
- `uv pip install gsm8k --index prime-hub` and `uv add gsm8k --index
prime-hub` now resolve inside prime-rl. The index is `explicit`, so `uv
sync` never consults it and `uv lock --check` passes unchanged.

Only the named index inherits the setting: passing the same URL via
`--extra-index-url` still hits the cooldown (uv matches index config by
name). Other Hub owners need their own entry or `--no-config`.

Verified in a fresh checkout: `uv lock --check`, slim `uv sync`, then
install through `--extra-index-url` (rejected), `--index prime-hub`
(0.1.4 installed), and the per-environment install index (rejected).

Companion: PrimeIntellect-ai/prime#934 (`prime eval run` installs Hub
environments into a prime-rl sandbox; it uses `--no-config` so any owner
works).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dependency-index configuration only; narrows the exclude-newer bypass
to an explicit, opt-in first-party index without changing default sync
behavior.
> 
> **Overview**
> Adds a named **`prime-hub`** uv index pointing at the Environments Hub
with **`exclude-newer = false`**, so Hub wheels (which lack upload
timestamps) are no longer blocked by the repo-wide **7-day**
`exclude-newer` policy.
> 
> The index is **`explicit`**, so default **`uv sync`** / lock checks
stay unchanged; Hub packages resolve only when you opt in (e.g. **`uv
add gsm8k --index prime-hub`**). Passing the same URL via
**`--extra-index-url`** still applies the global cooldown because uv
matches index settings by configured name, not raw URL.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1ac034977bbf2a54ef2977314fc87a9d2f6b1b5f. 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-21 10:51:06 -07:00
JannikStandGitHub 64a0decfaa improvement(docker): bake the dashboard extra into the cuda image (#3613)
### What & why

The prime-rl-fft chart runs a standalone read-only dashboard pod per
release (prime-rl-fft #75) that serves prime-rl's run dashboard (`uv run
dashboard`, port 7788) off the run's shared PVC. The chart image does
not include the `dashboard` extra (fastapi/uvicorn), so the pod
previously installed it at start with `uv sync --inexact` — which hangs
on some clusters, leaves the Deployment permanently unready, and times
out the whole release's helm `--wait` readiness gate after 90m, killing
every trainer/inference/orchestrator pod regardless of their own health.
The dashboard was disabled by default as a stopgap (prime-rl-fft #86).

This bakes the `dashboard` extra directly into the cuda image so the
dashboard pod serves straight from the image with no runtime install.

### Changes
- `Dockerfile.cuda`: add `--extra dashboard` to both `uv sync` calls
(third-party deps layer + first-party source layer).

### Notes
- `fastapi` + `uvicorn` are a few MB next to the ~20 GB GPU venv;
negligible size impact.
- Both syncs use `--locked` and `uv.lock` already resolves the
`dashboard` extra — no lockfile changes.
- Follow-ups (fft chart repo, separate PRs): drop the pod-start `uv sync
--inexact` command and re-enable the dashboard by default; expose it to
the platform backend over the tailnet.

### Testing
- No runtime code touched; image CI builds the image from this branch.
- `uv lock --check` equivalent verified: lock already contains the
dashboard extra deps with markers.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Build-only Dockerfile change that adds two small locked deps to the
venv; no application or runtime behavior changes in this repo.
> 
> **Overview**
> **Bakes the `dashboard` optional extra (FastAPI + Uvicorn) into the
CUDA Docker image** so Helm FFT chart dashboard pods can run `uv run
dashboard` from the image without a startup `uv sync`.
> 
> Both dependency install steps in `Dockerfile.cuda` now pass `--extra
dashboard` alongside the existing GPU/flash-attn extras, with a short
comment tying this to the chart dashboard pod. Lockfile is unchanged;
syncs stay `--locked`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
78fecdd68099796469bc2cecce1ad10142d9a76c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 09:27:47 -07:00
samsjaandGitHub a1822f7a0a feat: default enable_ep_weight_filter to true (#3608)
## What

- Adds a typed `inference.vllm.enable_ep_weight_filter` field defaulting
to `true`, so every vLLM server prime-rl launches now passes
`--enable-ep-weight-filter` (previously this flag only appeared as an
explicit pass-through in the GLM-5.3 advanced examples).
- Drops the now-redundant explicit `enable_ep_weight_filter = true` from
the GLM-5.3 examples (`examples/advanced/glm-5.3/swe.toml`,
`examples/advanced/glm-5.3/infer/pd-llmd.toml`).
- Asserts the default lands on the server namespace.

## Why

Under expert parallelism, vLLM's weight filter skips non-local
per-expert tensors **before** reading them from disk: each rank reads
only its own expert shard instead of the full checkpoint (experts are
~85-90% of MoE weight bytes). This cuts load I/O and startup time,
especially on shared storage.

The default is safe elsewhere — vLLM only activates the filter when the
model is MoE, `enable_expert_parallel` is on, and EPLB is off. It is a
silent no-op for dense models, fused-expert checkpoints (GPT-OSS style),
and EPLB runs. The repo pins `vllm>=0.28.0`, which has the flag.

Set `inference.vllm.enable_ep_weight_filter = false` to restore the old
behavior.

Note: #3604 relocates these GLM-5.3 examples to `configs/advanced/` and
its copies still carry the explicit line — drop it when rebasing on this
PR.

## Test plan

- `uv run pytest tests/unit/test_parsers.py tests/unit/test_configs.py`
- Verified `to_namespace()` emits `enable_ep_weight_filter=True` for a
real GLM-5.3 config, and that `--vllm.enable-ep-weight-filter false`
overrides it.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior change is gated in vLLM to MoE + expert parallelism without
EPLB; dense models and other modes are no-ops, with an explicit config
escape hatch.
> 
> **Overview**
> **Expert-parallel MoE loads now opt into vLLM’s EP weight filter by
default**, via a typed `inference.vllm.enable_ep_weight_filter` field
(default `true`) that flows through `to_namespace()` to
`--enable-ep-weight-filter`. That lets each rank read only its local
expert shard at checkpoint load instead of full expert tensors, reducing
I/O and startup time when EP is on and EPLB is off.
> 
> The GLM-5.3 advanced TOML recipes **drop redundant**
`enable_ep_weight_filter = true` lines and rely on the default. A unit
test **asserts** the resolved server namespace includes
`enable_ep_weight_filter=True`. Set
`inference.vllm.enable_ep_weight_filter = false` to disable.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f26215dee423de2a19ec763106fd979183556cef. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 22:57:30 -07:00
samsjaandGitHub 8c2847721a chore(examples): glm-5.3 swe.toml base + swe-llmd.toml append, serve BF16 with vllm-side FP8 (#3607)
## What

Reworks the GLM-5.3 RL examples as a **base + append** pair instead of
two standalone configs, and moves both variants onto the shared
`GLM-5.3-BF16` checkpoint with vLLM-side online FP8 quantization:

- **`swe.toml`** — the base config, carrying all the params that used to
live only in `swe-llmd.toml` (r2e-gym train source under the `rlm`
harness, `deepgemm_fp8` trainer, `cp = 4` / `ep = 8`, 16 train + 16
disaggregated-P/D infer nodes) behind the default **`vllm-router`**.
Inference serves the same **`zai-org/GLM-5.3-BF16`** checkpoint the
trainer broadcasts; vLLM quantizes it to per-block FP8 online
(`quantization = "fp8_per_block"`) — no separate FP8 release checkpoint.
- **`swe-llmd.toml`** — now a small **append overlay**: llm-d router
(EPP scorer tuning), Mooncake KV offload, and run-identity swaps (run
name / W&B project / SLURM job / sandbox runtime label). Launch:

  ```bash
uv run rl @ examples/advanced/glm-5.3/swe.toml # vllm-router
uv run rl @ examples/advanced/glm-5.3/swe.toml @
examples/advanced/glm-5.3/swe-llmd.toml # llm-d + Mooncake
  ```

- **`README.md`** — documents the base/append split, the composed launch
command, and which FILL INs live where.

## Why

- Two nearly-identical 100+ line configs drifted apart; a base + `@`
overlay keeps the llm-d variant a true delta (router + KV offload) and
makes the router the only difference between runs.
- Serving `GLM-5.3-BF16` with online per-block FP8 matches the trainer's
broadcast target and removes the dependency on the official block-FP8
serving release for both variants.

## Validation

Both launch paths resolve and validate end-to-end with `rl --dry-run`
(resolved per-process configs + sbatch generation): the base launches
`vllm-router --policy sticky_least_loaded`; the composed run swaps in
the llm-d router (EPP + Envoy) and enables Mooncake KV offload. Overlay
list-replacement semantics verified — the composed run keeps exactly one
train source, with the runtime label swapped to `glm5-llmd`.

Infer pre-flight configs (`infer/pd.toml`, `infer/pd-llmd.toml`) are
untouched.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are limited to example TOMLs and documentation; no runtime or
library code paths are modified.
> 
> **Overview**
> Reorganizes the GLM-5.3 RL examples so **`swe.toml` is the full base
stack** (r2e-gym / `rlm`, FP8 trainer, P/D inference behind
**`vllm-router`**, serving **`GLM-5.3-BF16`** with online block FP8) and
**`swe-llmd.toml` is a thin overlay** for llm-d router scorer tuning,
Mooncake KV offload, and sandbox runtime labels.
> 
> Most settings that previously lived only in `swe-llmd.toml` move into
`swe.toml`; the llm-d file drops trainer/orchestrator/deployment
duplication. The README is updated to describe **base vs append**
launches (`rl @ swe.toml` vs `rl @ swe.toml @ swe-llmd.toml`), moves
“FILL IN” and Mooncake tuning notes to the right file, and states that
**neither RL file ships `[ckpt]`** by default (overlay to add
checkpoints). The old **`swe.toml` train-source-less / SWE-bench-eval
plane is replaced** by this composable layout—not removed entirely.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c9d87a57a24248945b3035d1cb87dee2f8f66a1a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 19:48:22 -07:00
samsjaandGitHub 9dbe8b5fa0 fix: select GLM-5.3 renderer in examples (#3606)
## Summary
- configure both GLM-5.3 example runs to use the matching `glm-5.3`
renderer

Requires the GLM-5.3 renderer pinned by #3605.
2026-09-18 16:03:56 -07:00
samsjaandGitHub 819993faac chore: bump renderers for GLM-5.3 (#3605)
## Summary
- pin `deps/renderers` to the GLM-5.3 renderer implementation

Depends on PrimeIntellect-ai/renderers#156.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> <sup>[Cursor Bugbot](https://cursor.com/bugbot) is generating a
summary for commit 8c41fdb84cd8bbfa5f2b2fc97887da57fbf3ba40. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 15:40:49 -07:00
Mika SenghaasandGitHub d57c59f16a fix: do not abort on consecutive empty train batches (#3595)
## Summary

- Remove the run-level aborts on consecutive empty train batches:
- The orchestrator raised after 10 consecutive no-sample train batches.
`MAX_CONSECUTIVE_EMPTY_BATCHES` and its counter are gone; an empty batch
now logs a warning and is skipped.
- The train sink raised after 10 batch-equivalents of finalized groups
that shipped no payload. The tally now only throttles the warning
(`_warn_zero_output`); there is no abort.
- Keep both warnings, so a run with no training signal stays visible in
the logs. A dead curriculum, an all-equal reward sweep, or an
infrastructure outage now stalls the run instead of killing it.
- Update the one `docs/algorithms.md` sentence that described the abort.
## Verification

- `uv run pytest tests/unit/orchestrator -q`: 82 passed, 1 skipped. The
8 failures are pre-existing `torch`/`vllm` import errors in a no-extras
env and fail the same way on `main`.
- `ruff check` / `ruff format --check` pass on both changed files.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior change is limited to error handling: runs no longer fail fast
on sustained empty training signal, which may hide config issues but
avoids killing jobs on benign stalls.
> 
> **Overview**
> **Removes run-killing guards** when training produces no shippable
data, so misconfigured curricula or transient all-zero-advantage groups
**stall with warnings** instead of crashing the orchestrator.
> 
> In **`orchestrator.py`**, the **10 consecutive empty-batch abort** is
gone: empty `TrainBatch` samples log *"skipping empty train batch"* and
return without advancing the step. **`train_sink.py`** keeps counting
zero-output finalized units but **`_warn_zero_output`** only emits
throttled warnings—no **`RuntimeError`** after 10 batch-equivalents.
> 
> **`docs/algorithms.md`** now says group-relative `group_size = 1`
empty batches are **skipped at runtime**, not aborted.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3160f47b861a2c9c6cb33fef4961336f9b6560e9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 11:22:15 -07:00
Matej SirovatkaandGitHub c4a78d1134 fix: specialize FP8 indexer quantization constants (#3594)
Compiled GLM-5.3 training fails on its first forward pass because `eps`,
`fp8_min`, and `fp8_max` reach the FP8 indexer quantization kernel as
runtime FP64 scalars. Their arithmetic promotes the quantization result
to FP64, and Triton rejects the resulting conversion with `Unsupported
conversion from f64 to f8E4M3FN with rounding mode rtne`.

Mark these three fixed scalar arguments as `tl.constexpr` so Triton
specializes them at compile time.

Validation: reproduced the failure on an 8-node H200 BF16 trainer with
`torch.compile`, activation checkpointing/offloading, full CPU offload,
and SignSGD. With this patch, the first forward/backward pass and
optimizer update completed, and the trainer began broadcasting policy
v1. The 20-step verification run is still in progress. `git diff
--check` passes.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single-line Triton signature change with no API or logic changes; only
affects compile-time specialization of fixed FP8 bounds.
> 
> **Overview**
> Fixes **compiled training crashes** on the first forward pass when the
FP8 indexer quantizes activations under `torch.compile`.
> 
> The Triton kernel `_per_token_group_quant_fp8` now treats **`eps`,
`fp8_min`, and `fp8_max` as `tl.constexpr`** instead of runtime
arguments. Previously those scalars promoted quant math to FP64, and
Triton failed converting the result to FP8 (`f64` → `f8E4M3FN`).
Specializing them at compile time keeps the quant path in types Triton
can lower correctly; callers still pass the same module-level `FP8_EPS`
/ `FP8_MIN` / `FP8_MAX` constants.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
02f155d8ffb8776346c320be42a6be1f1f5299e9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 13:12:13 +02:00
cacae615e6 chore(examples): rename GLM example folder to glm-5.3 (#3593)
The advanced GLM presets now train GLM-5.3, but the directory was still
named glm-5.2. Rename it and update every inbound link and the
"GLM-5/GLM-5.2" prose in the READMEs and docs.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation and example path updates only; no training, inference,
or runtime code changes.
> 
> **Overview**
> Renames the advanced GLM example from **`glm-5.2`** to **`glm-5.3`**
and updates every inbound link and launch snippet so docs match the
presets that target GLM-5.3.
> 
> **README**, **docs** (`advanced.md`, `configuration.md`,
`scaling.md`), and **examples/README** now point at
`examples/advanced/glm-5.3/` and describe **`GLM-5`/`GLM-5.3`** instead
of 5.2. The **glm-5.3** walkthrough updates `uv run rl` / `uv run
inference` paths; **`infer/pd-llmd.toml`** only fixes its launch comment
to the new path (config content such as `GLM-5.2-FP8` model IDs is
unchanged).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fb2d99039d8719ff2bcdf2ac1e2c7baaa6f49946. 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: Johannes Hagemann <johannes@Johanness-MacBook-Pro.local>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 00:22:35 -07:00
samsjaandGitHub a9005aba8e fix(examples): express GLM-5.2 SWE shared model as a [model] table (#3591)
## Summary
PR #3588 centralized the model id for
`examples/advanced/glm-5.2/swe.toml` as a top-level
string (`model = "zai-org/GLM-5.3-BF16"`), but `RLConfig.model` is a
`SharedModelConfig`
table, so no config class could parse the file and CPU tests on `main`
failed
(`test_load_configs[examples/advanced/glm-5.2/swe.toml]`).

- Express the shared model as a `[model]` table with `name =
"zai-org/GLM-5.3-BF16"`, which
propagates to `trainer.model.name`, `orchestrator.model.name`, and
`inference.vllm.model`
  (same intent as #3588).
- Update the `[inference.vllm]` comment: it now serves the shared BF16
checkpoint with online
  per-block FP8 quantization, not a separate block-FP8 release.

Fixes the CPU Tests failure on `main` introduced by #3588.
2026-09-17 23:55:47 -07:00
samsjaandGitHub 788b9fdd1a Update swe.toml (#3588)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Example config-only change with no application code; verify the stack
resolves the correct vLLM checkpoint now that `[inference.vllm]` no
longer sets a separate `zai-org/GLM-5.3` id.
> 
> **Overview**
> **Centralizes the Hugging Face model id** for the GLM-5.2 SWE advanced
example by adding a top-level `model = "zai-org/GLM-5.3-BF16"` and
dropping duplicate `name` / `model` entries under `[trainer.model]`,
`[inference.vllm]`, and `[orchestrator.model]`.
> 
> Inference still uses the same vLLM settings (BF16 dtype,
`fp8_per_block` quantization, GLM tool parser); only the redundant
per-section model strings are removed so one field drives training and
orchestration.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4520df470f2417d4333f48fb80f40a2ed820574e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
2026-09-17 22:38:22 -07:00
samsjaandGitHub abcf7c0acc docs(examples): update GLM SWE presets to 5.3 (#3587)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Documentation and example TOML checkpoint IDs only; no runtime or auth
logic changes.
> 
> **Overview**
> Updates the **GLM-5.2** advanced SWE example presets and README so
runs target **GLM-5.3**: trainers load **`zai-org/GLM-5.3-BF16`**, while
disaggregated vLLM inference serves the **`zai-org/GLM-5.3`** block-FP8
checkpoint (with short comments explaining the train/serve split).
> 
> **`swe.toml`** and **`swe-llmd.toml`** swap prior **`GLM-5` /
`GLM-5.1`** Hugging Face IDs on **`[inference.vllm]`**,
**`[trainer.model]`**, and **`[orchestrator.model]`**. The base
**`swe.toml`** plane also gains **`[orchestrator.renderer] name =
"glm-5.1"`** so it matches the llm-d stack’s rendering setup. Docs and
launch comments now describe **GLM-5.3** full-stack RL instead of 5.1;
inference-only table rows for **`infer/pd*.toml`** are unchanged in this
diff.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e02482573c596a0c7b575a710e8cf09e38ef4757. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 21:45:53 -07:00
samsjaandGitHub 26c967c6e3 Default IPO to eps 0.3 without KL (#3586)
## Summary

- make IPO use `eps = 0.3` by default
- disable the IPO KL regularizer by default with `kl_tau = 0.0`
- update the algorithm documentation to match

Explicit `[trainer.loss]` values continue to override these defaults.

## Test plan

- instantiated `IPOLossConfig` and the default `TrainerConfig.loss`,
confirming `eps == 0.3` and `kl_tau == 0.0`
- `ruff check packages/prime-rl-configs/src/prime_rl/configs/trainer.py`
2026-09-17 20:59:24 -07:00
Mika SenghaasandGitHub 7760531310 feat: update Prime sandbox SDK (#3585)
## Summary

- Replace the full Prime CLI dependency with `prime-sandboxes` 0.3.0.
- Preserve API key and team discovery from `prime login` through the
sandbox SDK config reader.
- Advance the verifiers submodule to merged
[PrimeIntellect-ai/verifiers#2626](https://github.com/PrimeIntellect-ai/verifiers/pull/2626).
- Document the Prime CLI as a separate tool for login and sandbox
cleanup commands.

## Breaking

- Remove the Prime runtime `vm` and `guaranteed` fields. Delete these
fields from configs. Prime now always creates a VM sandbox.
- Stop publishing ports from Prime service runtimes. Colocate the
service and consumer, or use Docker or Modal for the service runtime.
- Stop installing the `prime` CLI with prime-rl. Run `uv tool install
prime` when the CLI is needed.

## Verification

- `uv lock --check`
- `uv sync --all-packages`
- `uv run ruff check src/prime_rl/orchestrator/clients.py
src/prime_rl/monitors/prime.py`
- `uv run pytest tests/unit/orchestrator/test_clients.py
tests/unit/test_configs.py -q` (199 passed)
- Confirmed `prime_sandboxes.Config` detects the existing CLI login and
team with `PRIME_API_KEY` and `PRIME_TEAM_ID` unset and the `prime`
distribution absent.
- `env -u PRIME_API_KEY -u PRIME_TEAM_ID uv run eval gsm8k -n 1 -r 1 -c
1 --run.name cli-login-smoke --output-dir /tmp/prl-cli-login-smoke`
(reward 1.0, no errors)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how Prime credentials are loaded and sandbox SDK version;
misconfiguration could break Prime Inference headers or sandbox rollouts
until users install the CLI and log in separately.
> 
> **Overview**
> Swaps the **`prime`** PyPI dependency for **`prime-sandboxes>=0.3.0`**
and points API key / team resolution at `prime_sandboxes.Config` instead
of `prime_cli.core.config` in the orchestrator client helpers and Prime
monitors.
> 
> Advanced example READMEs now tell users to install the **`prime`** CLI
separately (`uv tool install prime` + `prime login`) rather than
assuming it ships with prime-rl. The lockfile drops the full **`prime`**
package and its transitive UI stack while bumping **`prime-sandboxes`**
to 0.3.0 (and related Prime packages where resolved).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9c37d34fc380e4c0a8d79159e8323c31fe605ff2. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 20:04:56 -07:00
Matej SirovatkaandGitHub ce65f38fc0 Replace trainer-side FP8 transfer with online inference quantization (#3581)
NCCL weight updates now always send HF checkpoint-format weights and use
vLLM's layerwise reload, letting inference apply its configured
quantization. Remove the trainer-side FP8 transfer switch from config
schemas, propagation, admin requests, and worker RPCs, along with its
unused kernel conversion and loading helpers and tests. No references to
the removed setting remain in tracked project files.

Update both GLM SWE configs to use their BF16 checkpoints, `dtype =
"bfloat16"`, and `quantization = "fp8_per_block"`; align the
orchestrator model names with those checkpoints. EPLB remains rejected
for RL weight updates because the remaining reload path has not been
validated with it.

Validation:
- 131 config and admin/Dynamo RPC unit tests passed, plus both changed
GLM config-loading tests (133 total).
- Full RL config smoke checks cover model-name alignment, NCCL settings
propagation, and EPLB rejection for both examples.
- Ruff lint/format, Python compilation, TOML parsing, and diff
whitespace checks passed.
- The broader config-file sweep was blocked by missing optional taskset
plugins. GPU weight reload was not exercised.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes the critical trainer→inference weight update path and removes
a large alternate loading implementation; misalignment between trainer
weights and vLLM quantization could cause silent drift until GPU reload
is exercised.
> 
> **Overview**
> **Removes trainer-side FP8 kernel-format NCCL weight transfer** in
favor of always broadcasting HuggingFace checkpoint-format tensors and
reloading them in vLLM with layerwise processing, so inference applies
its own quantization settings.
> 
> The `weight_broadcast.quantize_in_weight_transfer` flag is deleted
from shared/trainer/orchestrator schemas, RL propagation,
`/init_broadcaster` RPCs, Dynamo admin, and the NCCL broadcaster/worker
path. Related trainer conversion (`convert_layer_to_vllm_kernel`,
GLM-MoE-DSA kernel export, `quantize_to_vllm_kernel_format`) and
inference helpers (`load_weights_kernel`, EPLB expert remapping) are
removed along with their unit tests.
> 
> **Example GLM SWE configs** switch from `*-FP8` checkpoints to BF16
base weights with `dtype = "bfloat16"` and `quantization =
"fp8_per_block"` on the vLLM side; orchestrator model names match.
> 
> **EPLB** is no longer tied to quantized NCCL transfer—`enable_eplb`
now fails validation for any RL run with weight updates, since the
checkpoint reload path is not validated with EPLB.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
33bf980a95d5ee259f0f8d7b52a7e29b7d8e4a63. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 16:43:34 -07:00
Matej SirovatkaandGitHub 1c45dc4572 Add quantization type for inference configuration (#3580)
Restrict `VllmConfig.quantization` to `fp8_per_block` or `None` using a
consistently named `QuantizationType` alias beside the other vLLM type
alias. `None` continues to let vLLM infer quantization from the
checkpoint.

Update `configs/debug/concurrency.toml` to use `fp8_per_block` so it
validates against the typed field.

Validation: Ruff lint and formatting checks passed. A config smoke check
passed for imports, the default, acceptance of `fp8_per_block`,
rejection of `fp8`, and the updated concurrency config's vLLM section.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Tightening `quantization` to a single literal will reject any existing
TOML/CLI values other than `fp8_per_block`; only the debug config is
updated in this PR.
> 
> **Overview**
> Introduces a **`QuantizationType`** literal on
**`VllmConfig.quantization`**, restricting the inference config field to
**`"fp8_per_block"`** instead of an arbitrary string (still optional;
**`None`** lets vLLM infer from the checkpoint).
> 
> Updates the **debug concurrency** run to set **`quantization =
"fp8_per_block"`**, replacing the previous **`"fp8"`** value so online
quantization matches vLLM’s per-block FP8 mode (consistent with
block-wise FP8 / DeepGEMM expectations elsewhere in inference config).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2a65ad30df0866134dd3454f70033d602c40e2ab. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-09-17 16:17:49 -07:00
Mika SenghaasandGitHub 4a80d747db fix(dashboard): compress large HTTP responses (#3579)
Large run dashboards transfer every metrics chunk without compression,
making full-history loads expensive over remote connections. Enable the
existing GZip middleware for responses of at least 1,000 bytes, using
compression level 1 to limit CPU overhead.

Browsers negotiate gzip automatically. JSON payloads and pagination
offsets are unchanged, and server-sent events remain uncompressed. This
reduces network transfer size while adding compression CPU overhead; it
does not reduce the browser's JSON parsing or chart-rendering work.

Validation: Ruff lint/format and `git diff --check` passed. HTTP checks
verified gzip/identity payload equality, `Vary: Accept-Encoding`,
small-response bypass, and immediate uncompressed SSE delivery. A
headless Chromium smoke check verified that metrics load and charts
render without JavaScript errors after restarting the dashboard.

The initial metrics response reads up to 4 MiB of uncompressed JSONL for
quick initial chart rendering; subsequent responses read up to 16 MiB to
reduce sequential round trips. A short inline comment explains the
smaller initial response. The compressed size varies with the data. All
chart metrics remain available.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dashboard-only transport and read-size tuning; no auth or training
logic, with gzip negotiated via standard headers.
> 
> **Overview**
> Large dashboard API payloads (especially paginated **metrics JSONL**)
no longer go over the wire uncompressed. The FastAPI app now registers
**`GZipMiddleware`** with a **1,000-byte minimum** and **compression
level 1**, so browsers that send `Accept-Encoding: gzip` get smaller
transfers without heavy CPU; tiny responses and streaming endpoints like
SSE are unchanged in behavior.
> 
> **Metrics pagination** is adjusted alongside that: the per-chunk cap
rises from **4 MiB to 16 MiB** for follow-up requests (`offset > 0`),
cutting round trips on huge runs, while the **first** chunk at `offset
== 0` still reads **4 MiB** so initial charts can render quickly. The
API shape (`rows`, `offset`, `size`) is the same—only read sizes and
optional gzip on eligible responses change.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
57809813f385c93c54bf3243f8688060c8e1811a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 16:17:27 -07:00
8df2329a70 chore(trainer): update the reduce_scatter API and fix a ring attention edge case (#3570)
Drops a deprecated collective call in `ring_attn.py`.
`torch.distributed.reduce_scatter_tensor` is
deprecated in the pinned torch and emitted a `FutureWarning` on every
ring step:

```
FutureWarning: `torch.distributed.reduce_scatter_tensor` is deprecated. Please use `torch.distributed.reduce_scatter_single` instead.
```

It is now a thin wrapper delegating to `reduce_scatter_single` with an
identical signature, so the
swap is a pure rename.

While in there, a small edge-case cleanup in `ring_attention_backward`.
The gradient buffers were
allocated with `torch.empty_like`, which inherits the input's strides,
and on the
`heads_k_stride == num_kv_heads` branch they are passed straight to the
reduce-scatter. NCCL ignores
a destination's strides and fills its storage linearly, so a
non-contiguous `dk`/`dv` would silently
come back scrambled. `new_empty` always allocates contiguous.
Unreachable today, since
`heads_k_stride` is hardcoded to `1` with no config surface.

- `_ring_attention_backward_fake` has to move with it, or inductor bakes
the old strides into an
  `assert_size_stride` guard.
- `dq` is unaffected: flash kernels honor output strides, NCCL does not.
- Not every deprecated call site is covered.
`trainer/distributed/collectives.py:159,178` still use
`all_gather_into_tensor` and `reduce_scatter_tensor`, left as a
follow-up. The
`all_gather_into_tensor` warning still emitted on this path comes from
`AllGatherComm` in the
  `ring_flash_attn` package, not from our code.

## Verification

`tests/unit/train/models`: 181 passed, 5 skipped, unchanged. Checked
red-green with a local 2-rank
NCCL script (not committed, needs 2 GPUs), comparing contiguous against
head-major `k`/`v` with
bitwise-identical inputs.

Before, at `heads_k_stride = 4 == num_kv_heads`:

```
dk: bitwise_match=False max_abs_diff=1.27539 max_rel_diff=1.33811
dv: bitwise_match=False max_abs_diff=0.978516 max_rel_diff=0.97093
```

After:

```
dk: bitwise_match=True max_abs_diff=0 max_rel_diff=0
dv: bitwise_match=True max_abs_diff=0 max_rel_diff=0
```

`max_rel_diff` is normalized by the tensor's max magnitude. bf16 noise
on this shape is around
`4e-3`, so the pre-fix difference is structural rather than numerical.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 17:19:03 -04:00
samsjaandGitHub 487d8a76d1 feat(examples): add 4-node and 2-node GLM-4.5-Air scaleswe budget variants (#3548)
## Summary

Follow-up to #3546: the two budget variants and docs updates from that
PR were pushed after it was merged, so they never landed on main. This
PR carries them.

Adds two budget variants of the GLM-4.5-Air `scaleswe` example that keep
the single-node sign-SGD trainer setup (full optimizer offload +
skip-optimizer checkpointing) from before the Muon switch:

- `swe-budget.toml` + `swe-4-node.toml`: 1 train + 3 infer replicas (the
topology `swe.toml` used before #3546), batch size 256
- `swe-budget.toml` + `swe-2-node.toml`: 1 train + 1 infer replica at
batch size 64 (4 groups of 16) — train a 100B+ MoE on only two nodes

The variants are overlays rather than full copies: the shared recipe
(sign-SGD trainer, router replay, GRPO linear length penalty,
deployment/ckpt/broadcast/inference settings) lives in
`swe-budget.toml`, and each variant file only carries the deltas —
topology, batch size, per-variant SLURM job name / sandbox cleanup label
/ W&B run name, and the train/eval sources with their matching runtime
labels. Launch them composed, left-to-right:

```
uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml
```

Router replay, `max_off_policy_steps`, and the length-penalty weights
are the same as `swe.toml`. Each variant keeps its own SLURM job name,
sandbox cleanup label, and W&B run name so they can run side by side.

## Changes

- **`swe-budget.toml`** (new): shared base of the budget variants — the
single-node sign-SGD trainer recipe (cp=4 ulysses, full optimizer
offload, GLM-5.1 memory stack) plus the shared settings.
- **`swe-4-node.toml`** / **`swe-2-node.toml`**: now thin overlays over
`swe-budget.toml` — `num_infer_replicas` 3 / 1, batch size 256 / 64,
per-variant identity, and the sources with their labels.
- **`tests/unit/test_configs.py`**: `test_load_configs` retries files
that no config class parses standalone as overlays over each sibling
TOML — the documented `@ base.toml @ overlay.toml` composition.
- **Example README**: the table lists the budget variants as
`swe-budget.toml + <variant>` compositions; the launch section shows the
composed command.
- **`docs/scaling.md`** / **`docs/configuration.md`**: link the two-node
config ("train a 100B+ MoE on only two nodes"); scaling.md notes it is
an overlay on the shared base.

## Validation

- `uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @
examples/advanced/glm-4.5-air/swe-4-node.toml --dry-run`
- `uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @
examples/advanced/glm-4.5-air/swe-2-node.toml --dry-run`
- Config-level checks against the installed config package: the base
parses standalone; the composed configs resolve to configs identical to
the pre-split standalone files (compared resolved `model_dump()`, only
the auto-generated run name differs); the overlays alone fail validation
as intended (fail fast instead of silently launching a default-config
run).
2026-09-17 13:45:25 -07:00
d05fe6de95 feat: split dashboard overview and metrics tabs (#3578)
## Summary
- The dashboard's `Metrics` tab is now two tabs for every run type.
**Overview** is the curated view: the W&B overview sections for training
runs (train, eval, stability, inference, performance) and the episode
pane for eval runs (progress bar, summary tiles, swarms, usage and
timing). **Metrics** is every key in `metrics.jsonl`, one pane per key,
with a regex filter, smoothing and collapse/expand. The Overview/All
toggle is gone; the tabs replace it.
- Eval runs load `metrics.jsonl` next to their episode series, so the
time-keyed `inference/`, `concurrency/` and `dispatcher/` rows the
runner samples during the epoch chart on the Metrics tab the same way
they do for RL runs. Before, an eval run had no way to reach its raw
metric keys at all.
- The Metrics tab groups keys by path instead of by stat family. `Flat`
makes one section per parent path (`dispatcher/cancelled` holds `eval`,
`gsm8k`, `train`; `dispatcher` holds `mode`), sorted so a parent
precedes its children. `Nested` walks the key segments as a tree of
sections (`dispatcher` holds the `mode` pane and the nested `cancelled`,
`errored`, `inflight`, `off_policy`, `queued` sections).
- A section's pane grid keeps the 12px rhythm before the sections nested
under it; previously the nested section header sat flush against the
panes above.
- The two tabs share one metric store and one chart registry: the open
tab owns the charts and re-renders on switch, each tab keeps its own
search, and the smoothing window is shared. The dashboard skill, README,
`docs/eval.md`, `docs/training.md` and the browser smoke test (which now
also exercises the Metrics tab) are updated to match.

**Eval Overview**

<img width="1608" height="1045" alt="Screenshot 2026-09-17 at 1 00
24 PM"
src="https://github.com/user-attachments/assets/bd54ffa2-d18c-4379-acfb-7e3cb8982dcd"
/>

**Eval Metrics**

<img width="1608" height="1045" alt="Screenshot 2026-09-17 at 1 00
49 PM"
src="https://github.com/user-attachments/assets/53eca142-b7de-47db-baee-cd6561bf2e9f"
/>

**Train Overview**

<img width="1608" height="1045" alt="Screenshot 2026-09-17 at 1 01
04 PM"
src="https://github.com/user-attachments/assets/3860a4e4-ff1a-4502-9df6-88fff2174ce3"
/>

**Train Metrics**

<img width="1608" height="1045" alt="Screenshot 2026-09-17 at 1 01
16 PM"
src="https://github.com/user-attachments/assets/5e0a23b7-91ef-42f4-ab55-85aeadb7ee59"
/>

## Verification
Headless Chromium against the dashboard served from this branch, no
console errors on either tab:

- `uv run rl @ configs/ci/integration/reverse-text/start.toml
--max-steps 5`: Overview renders 23 curated panes including the
inference section; Metrics lists 1135 keys, 209 `inference/` families
and all five `concurrency/` gauges.
- `uv run eval gsm8k -n 16 -r 2` against a local `uv run inference`
server with adaptive concurrency: Overview renders the episode pane (32
episodes, 7 tiles); Metrics lists 870 keys, 213 `inference/` families
and the five `concurrency/` gauges.
- Flat and nested section structure checked for the `dispatcher/` and
`concurrency/` keys of the eval run as listed above.
- `tests/integration/dashboard_smoke.py` passes on both run dirs.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are confined to the local dashboard UI, static assets, docs,
and smoke tests; no server-side training or eval pipeline logic.
> 
> **Overview**
> The run dashboard replaces the single **Metrics** tab and its
Overview/All toggle with two tabs: **Overview** (default) for the
curated W&B-style layout—training sections or the eval episode pane—and
**Metrics** for every key in `metrics.jsonl`, with regex filter,
flat/nested path grouping, and shared smoothing.
> 
> Eval runs now stream **`metrics.jsonl` alongside the episode series**,
so time-keyed `inference/`, `concurrency/`, and similar rows appear on
Metrics instead of being unreachable. Chart rendering is refactored
around `CHART_VIEWS`: one metric store and chart registry, re-mounting
when switching tabs, per-tab search prefs, and eval-specific controls
moved to Overview.
> 
> Docs (`eval.md`, `training.md`, dashboard skill/README) and
**`dashboard_smoke.py`** are updated to expect six views and to exercise
both tabs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ce08f3f18f343a5c0b7b38585bb40a9409798117. 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-17 13:09:50 -07:00
Cooper MillerandGitHub a563a03d61 chore: require prime-runs 0.1.3 (#3571)
Require `prime-runs[train]>=0.1.3` and update the lockfile from 0.1.2 to
0.1.3. FFT image builds use `uv sync --locked`, so the PyPI release
alone leaves them on the previous SDK and its dual-upload behavior.

With the new SDK, training episodes upload only to Prime Traces when the
account has access; accounts without access retain legacy samples. Run
lifecycle and metrics continue through Platform. Only the SDK
requirement and its locked artifact change; pinned submodules and other
resolved packages are preserved.

Validation: `uv lock --check` passed; TOML and the resolved 0.1.3
requirement were verified; all 288 published SDK tests passed against
the locked prime-traces 0.0.3 dependency. A GPU training run was not
performed.

Rollout: rebuild and promote the FFT image after merge.
PrimeIntellect-ai/platform#5452 separately handles duplicate list
entries and displaying native traces inside the full run page.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> No in-repo logic changes, but the locked SDK upgrade alters how
training episodes are uploaded once images are rebuilt—worth validating
in staging before wide rollout.
> 
> **Overview**
> Raises the **`prime-runs[train]`** floor from **>=0.1.1** to
**>=0.1.3** in `pyproject.toml` and refreshes **`uv.lock`** so resolved
**`prime-runs`** moves from **0.1.2** to **0.1.3** (PyPI artifact hashes
only; no other dependency churn in this diff).
> 
> This matters because FFT training images install with **`uv sync
--locked`**, so the lockfile must advance for builds to pick up the new
SDK—not just the PyPI release. **`PrimeTrainMonitor`**
(`src/prime_rl/monitors/prime.py`) still calls the same **`prime_runs`**
APIs; behavior shifts come from **0.1.3** (e.g. trace-aware episode
uploads vs legacy samples for accounts without Traces access, while run
lifecycle/metrics stay on Platform).
> 
> After merge, **rebuild and promote the FFT image** so production
training runs the locked **0.1.3** SDK.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
21c2f421dfbf883bb9ca7eda4ed0a8cf10776fd7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 11:09:42 -07:00
Mika SenghaasandGitHub de08c72769 feat(inference): sticky least-loaded routing (#3563)
## Summary

Makes `sticky_least_loaded` the default routing algorithm on
`vllm-router` (ported from upstream into our fork in
https://github.com/PrimeIntellect-ai/router/pull/55). New session are
routed to the engine with _least active sessions_, any requests in an
active sessions are sticky-routed to maximize prefix cache hits. So this
is a mix of least loaded and consistent hashing which should be strictly
better for RL workloads.

- pin vllm-router v0.2.1 release wheels for x86_64 and aarch64
- make sticky_least_loaded the default vllm-router policy while
preserving explicit policy overrides
- release rollout sessions on success, failure, and cancellation for
managed routed inference, retaining discarded retry trace IDs
- call /finish_session without capability probing or 404/405 caching;
log individual failures at debug level and continue future cleanup
- document the new default and lifecycle behavior

## Context

- Router implementation:
https://github.com/PrimeIntellect-ai/router/pull/55
- Router release:
https://github.com/PrimeIntellect-ai/router/releases/tag/v0.2.1
- Side-by-side experiment:
https://github.com/PrimeIntellect-ai/prime-rl/pull/3553

## Verification

We ran matched 100-step GLM-4.5-Air ScaleSWE jobs on six H200 nodes (2
trainer + 4 TP=8 inference replicas), changing only the vllm-router
policy: [sticky
least-loaded](https://wandb.ai/primeintellect/routing/runs/b44ce2f5354a416bb37788a4db9d12c3)
versus [consistent
hashing](https://wandb.ai/primeintellect/routing/runs/de4b5c72f95c4c5ebbc7e9614690af52).
They reached trainer step 100 in 8h46m and 8h44m respectively, with
nearly identical mean step time (309s vs. 308s).

<img width="1239" height="762" alt="Screenshot 2026-09-17 at 10 11
13 AM"
src="https://github.com/user-attachments/assets/a3204c40-49b0-41f0-b1ae-9d85391f893d"
/>

| Metric | Sticky least-loaded | Consistent hashing | Difference |
| --- | ---: | ---: | ---: |
| Decode throughput | 13.85k tokens/s | 13.11k tokens/s | +5.6% |
| Prefill throughput | 702.6k tokens/s | 665.0k tokens/s | +5.7% |
| Decode-token imbalance (CV) | 1.2% | 6.8% | 82% lower |
| Running-request imbalance (CV) | 5.1% | 23.9% | 79% lower |
| KV-usage imbalance (CV) | 8.2% | 25.1% | 67% lower |


Sticky processed about 6% more tokens in essentially the same wall time.
The higher useful throughput and markedly lower engine imbalance,
without an end-to-end regression, make it the better default.

## Validation

- uv sync --all-extras --all-packages
- uv lock --check
- uv run pytest tests/unit/orchestrator tests/unit/test_configs.py -q
(276 passed, 1 skipped)
- uv run ruff check .
- verified the installed vllm-router CLI exposes sticky_least_loaded
- 10 focused local cleanup checks: successful and failed episodes,
cancellation, overload/stale/superseded drops, shutdown, max steps,
cancellation during cleanup, and continued cleanup after a 404

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes default multi-replica routing and adds best-effort session
cleanup on the rollout hot path; failures are logged but could leave
stale router session state on older routers.
> 
> **Overview**
> Switches the default **vllm-router** policy from `consistent_hash` to
**`sticky_least_loaded`**, pins **vllm-router v0.2.1**, and documents
that new `X-Session-ID` sessions land on the least-loaded replica while
later turns stay sticky for KV reuse.
> 
> For managed deployments where `admin_base_url` bypasses the router for
engine admin, the orchestrator now **releases router sessions when
rollouts finish**: after each successful env episode it calls
**`/finish_session`** per trace id via the client-facing router URL,
probes support once, and disables cleanup on 404/405 so external routers
are unaffected. Explicit `[inference.router] policy` overrides still
work.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
571b09581344e4ee420044aa8392ec97f9a4b538. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 10:55:15 -07:00
Mika SenghaasandGitHub 7f811c01a8 chore: bump verifiers to latest main (#3572)
## Summary

- Bump the `deps/verifiers` submodule from `5a69fb4d` (`feat: stream
served episodes turn by turn (#2512)`) to `28f08939` (latest `main`).
- Commits this pulls in:
- [vf#2616](https://github.com/PrimeIntellect-ai/verifiers/pull/2616)
(`ff3b8dc5`): fix(v1): recover the routed-experts row dropped at each
turn boundary — a reused sampled prefix node keeps a placeholder final
routing row until a later turn's prefill forwards it; it is now
repaired.
- [vf#2618](https://github.com/PrimeIntellect-ai/verifiers/pull/2618)
(`28f08939`): fix(serve): stream repaired routing rows — served
multi-turn episodes had the worker's #2616 repair but the delta stream
never delivered it, so the client kept placeholder routing rows; indexed
`routing_repairs` now reach the client assembly.
- Together they keep `routed_experts` training data correct for
multi-turn MoE episodes under env servers (the router-replay /
routed-experts data path).
- `uv.lock` is unchanged: verifiers is an editable path dependency and
the new commits touch no dependency metadata.

## Verification

- `git -C deps/verifiers merge-base --is-ancestor 5a69fb4d 28f08939` —
the new pin descends from the old one.
- `uv lock --check` — passes.
- `uv run pytest deps/verifiers/tests/v1/test_graph.py
deps/verifiers/tests/v1/test_serve_delta.py -q` — 18 passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the routed-experts data path for multi-turn MoE under env
servers; wrong routing rows would corrupt training data, but the change
is an upstream bugfix with targeted tests.
> 
> **Overview**
> Updates the **`deps/verifiers`** submodule from `5a69fb4d` to
**`28f08939`** (latest `main`). No other repo files change—**`uv.lock`**
stays the same because verifiers is an editable path dependency.
> 
> The new pin pulls in two upstream fixes for **multi-turn MoE
`routed_experts` / router-replay** when using env servers: **v1 graph
repair** for a routing row that was dropped at turn boundaries when a
sampled prefix node was reused, and **serve streaming** so those
repaired rows are included in the delta stream instead of leaving
placeholder routing on the client.
> 
> Together this keeps training data aligned with what the worker
actually computed for served multi-turn episodes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0fb3ab40ec5b917c2d0d548ac022fe6b5d08fce8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 10:54:59 -07:00
Mika SenghaasandGitHub 2d6dc64efd fix: log periodic gauges through the monitors (#3565)
## Summary
- The `PeriodicLogger` printed its pipeline view to the console and
called `wandb.log` directly, so the `dispatcher/*`, `concurrency/*`,
`watcher/*`, and `event_loop_lag/*` gauges only ever reached W&B. The
file monitor (and with it the local dashboard's `metrics.jsonl`) and the
Prime monitor never saw them; with W&B disabled the gauges existed only
as console log text.
- The periodic payload now fans out through `monitors.log(payload,
step=None)` like the inference-metrics collector, so every registered
monitor receives it as a time-keyed row and stamps its own time axis.
All W&B-specific logic is gone from the orchestrator and the eval runner
(`eval/runner.py`, which replaced the old evals process in #3471): the
W&B monitor already defines the `_timestamp` axis lazily per key prefix,
so the eager `wandb.define_metric` pre-registration and its
`metric_keys`/`wandb_enabled` plumbing are removed (the now-unused
`DispatcherMetrics.drain_keys` helper goes with it).
- Clean-exit teardown now stops the `PeriodicLogger` before
`monitors.finalize()`, next to the inference collector — both write
through the monitors, and a tick after finalize would land on a finished
W&B / Prime run. The eval runner already drained its loggers first
(`drain()` before `finalize()`); the orchestrator now matches.
- Overview panels, mirrored in the W&B saved view
(`monitors/wandb/overview.py`) and the local dashboard
(`dashboard/static/app.js`), which the overview code keeps in sync: the
inflight panel gains `concurrency/max_inflight` so in-flight episodes
read against the adaptive cap, and the token-rate panels drop their
per-engine tail series (`generation_tokens_total:rate/min`,
`prompt_tokens_total:rate/max`).

## Verification
1-step reverse-text runs (`uv run rl @
configs/ci/integration/reverse-text/start.toml --max-steps 1`, W&B off,
file monitor on), before on `main` vs. after on this branch:

- **before**: `monitors/file/metrics.jsonl` has 13 rows and zero
`concurrency/*` / `dispatcher/*` keys — only
train/eval/inference/loss/perf keys.
- **after**: periodic time-keyed rows (`"step": null`, `"producer":
"orch"`) carrying all `concurrency/*` gauges (`max_inflight`,
`turnover`, `capacity`, `signal`, `growth_multiplier`), 12
`dispatcher/*` keys, 4 `watcher/*` keys, and 7 `event_loop_lag/*` keys.
- **local dashboard overview** (headless browser check against both run
dirs): after, the `dispatcher/inflight/{train,eval}` +
`concurrency/max_inflight` panel renders with data (all charts mounted,
no console errors); before, the panel is absent (no keys, no panel).
- **teardown ordering** (after the finalize-order fix): the last
`metrics.jsonl` write lands strictly before `monitors.finalize()`
(03:54:38.66 vs. the `Finalized metrics` log line at 03:54:39), zero
rows written at or after finalize, clean exit, no `Failed to log`
warnings.
- Re-verified after rebasing onto `main` (picked up the eval-CLI
consolidation and the concurrency-taper commit) and again after the
teardown-order fix — all green.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes observability plumbing and shutdown ordering for background
loggers; behavior is well-scoped but affects all runs’ metrics export
and clean-exit teardown.
> 
> **Overview**
> **Periodic pipeline metrics** (dispatcher, concurrency, watcher, event
loop lag) no longer go only to W&B via direct `wandb.log`.
`PeriodicLogger` now emits each tick through `monitors.log(payload,
step=None)`, so file monitor, dashboard `metrics.jsonl`, Prime, and W&B
all get the same time-keyed rows.
> 
> The orchestrator and eval runner drop `metric_keys`, `wandb_enabled`,
and eager `wandb.define_metric` pre-registration; unused
`DispatcherMetrics.drain_keys` is removed. On clean exit, the
orchestrator **stops `PeriodicLogger` before `monitors.finalize()`**,
matching inference metrics teardown so nothing writes after the run is
closed.
> 
> **Overview charts** (W&B overview + local dashboard) add
`concurrency/max_inflight` to the inflight panel and simplify token-rate
panels to fleet sum only (no per-engine min/max tails).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
be479ea13c728ab82bacdd9f0773fc70dc0a3b41. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 10:02:47 -07:00
07ebe34570 fix(rl): launch env servers in multi-node RL runs (#3568)
Multi-node RL runs currently launch no environment servers. The
orchestrator waits 600 seconds
for an address file that nobody writes, then times out, and the trainer
sits in the weight
broadcast until its own timeout.

The flat-to-nested refactor in #3471 replaced `format_log_message`'s two
flat `train_env_names` /
`eval_env_names` parameters with a single `env_names: dict[str,
list[str]]` and updated all four
call sites in `rl.py`. Two of them really are `format_log_message` calls
and were correct. The
other two are `template.render(...)` calls feeding

[`multi_node_rl.sbatch.j2:542-559`](https://github.com/PrimeIntellect-ai/prime-rl/blob/d5ed9fb7e4233c6f4914af2652c3bda69bddb0c7/src/prime_rl/templates/multi_node_rl.sbatch.j2#L542-L559),
which still reads the flat names:

```diff
# src/prime_rl/entrypoints/rl.py:534,574 in c394c2e1b, write_slurm_script
-            train_env_names=train_env_names,
-            eval_env_names=eval_env_names,
+            env_names={"train": train_env_names, "eval": eval_env_names},
```

```jinja
{# multi_node_rl.sbatch.j2:542,550, unchanged by this PR #}
{%- if train_env_names or eval_env_names %}
{%- for name in train_env_names %}
```

Under Jinja's default `Undefined`, a name that was never passed is
indistinguishable from an
empty list: `{% if train_env_names or eval_env_names %}` is false either
way and nothing raises.
The generated script was therefore identical to one for a run that
legitimately has no env
servers. This reverts the two render calls to flat kwargs and leaves the
three
`format_log_message` calls on the nested dict.

- The failure is silent: the generated sbatch and the per-source env
JSON both look correct, and
the first symptom is `TimeoutError: env server never published its
address ... within 600.0s`.
- Single-node and SFT are unaffected. Single-node goes through
`rl_local`, which spawns env
servers as subprocesses; `sft.py` already spreads its env names as
`**eval_vars`, the flat form
  `multi_node_sft.sbatch.j2` wants.

## Verification

**Render level.** The pre-fix script is 13 lines shorter, and those 13
lines are the entire
env-server block:

```sh
uv run rl @ examples/basic/reverse-text/rl.toml --deployment.type multi_node --deployment.num-train-nodes 1 --deployment.num-infer-nodes 1 --slurm.partition all --max-steps 2 --run.name envserver-check --no-dashboard --dry-run
grep -c "uv run env-server" $PRL_OUTPUT_DIR/envserver-check/launcher/rl.sbatch
```

Before: `0`. After: `2`, one for the train source and one for the eval
source. Diffing the two
generated scripts shows nothing else moved (comment block elided):

```diff
@@ -331,0 +332,13 @@
+    mkdir -p $LOG_DIR/envs/train
+    uv run env-server @ $CONFIG_DIR/envs/train/reverse-text.json \
+        > $LOG_DIR/envs/train/reverse-text.log 2>&1 &
+    mkdir -p $LOG_DIR/envs/eval
+    uv run env-server @ $CONFIG_DIR/envs/eval/reverse-text-eval.json \
+        > $LOG_DIR/envs/eval/reverse-text-eval.log 2>&1 &
```

**Runtime.** Before, from one of the failing multi-node runs, the
orchestrator polls for a file
no process will write and gives up after 600s:

```
TimeoutError: env server never published its address to
<run>/configs/attempt_1/resolved/envs/train/reverse-text.address within 600.0s
```

After, a 2-node reverse-text run on Qwen3-0.6B spawns the server, which
publishes its address
46s later, and training completes:

```
14:48:47  <run>/logs/attempt_1/envs/train/reverse-text.log created
14:49:33  EnvServerPool up: address=tcp://127.0.0.1:42101 workers=1/inf multiplex=128
15:01:56  SUCCESS Step 2 | 1.2s | Loss 0.0038 | Entropy 0.6078 | Grad. Norm 0.7942
```

That log file is the cleanest discriminator: the shell redirect on the
`uv run env-server` line
creates it, so before the fix it never exists at all.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 13:02:37 -04:00
c1ac451e39 fix(trainer): declare contiguous outputs in the fp8 and ring attention fakes (#3567)
Three custom-op fake kernels declared output strides copied from their
inputs, while the real kernels return freshly allocated contiguous
buffers. `torch.compile` trusts the fake, bakes its strides into an
`assert_size_stride` guard, and the guard fires at runtime. This showed
up first in the fp8 MoE backward with activation checkpointing off,
where `ac=full` had been hiding the expert backward inside a recompute
region:

```
assert_size_stride(buf2, (32, 1408, 4096), (5767168, 1, 1408), 'torch.ops.prime_rl.grouped_fp8_gemm_backward.default')
AssertionError: expected size 1408==1408, stride 4096==1 at dim=1; expected size 4096==4096, stride 1==1408 at dim=2
```

All three fakes now declare metadata that is a pure function of their
inputs' shapes and dtypes, independent of the inputs' strides, of the
`needs_grad_*` flags, and of an unstated bf16 contract.

- `grouped_fp8_gemm_backward`, active: MoE passes a transposed weight;
real `(524288, 1024, 1)` vs fake `(524288, 1, 512)`.
- `ring_attn::attention`, active: rope leaves `q` non-contiguous, so
real `(1024, 128, 1)` vs fake `(128, 32768, 1)`, on every CP ring step.
- `fp8_blockwise_mm_backward` and the grouped GEMM's `grad_x`, latent:
masked only because production inputs are contiguous.
- The fp8 kernels' unobservable placeholder allocations are contiguous
too, which is what drops the flag-conditional stride.
- `ring_attn.py` needed no real-kernel change, since `torch.cat` is
already unconditionally contiguous.
- `_compute_grad_weight` downcasts to `weight.dtype`, not a hardcoded
bf16; a no-op today, as call sites pre-cast.
- Verified already correct, left alone: both fp8 forward fakes,
`attention_backward`, and the forward's `softmax_lse`.
- `compile=on, ac=off, fp8 MoE` now completes a full forward and
backward on the GLM-4.5-MoE path.

Noticed while auditing, not addressed: `gpt_oss` has its own ring
implementation that bypasses this op.

## Verification

An `opcheck` test for the four fp8 ops was added in `02f3f684b` and
removed again in `49ce67cff`: it needs an SM90+ GPU and `deep_gemm`, so
it would only ever skip on CI's `vm` runner. To re-run it on a Hopper or
Blackwell node:

```
git show 02f3f684b:tests/unit/train/models/test_fp8_fake_kernels.py > tests/unit/train/models/test_fp8_fake_kernels.py
DG_JIT_CACHE_DIR=<warm deepgemm cache> uv run pytest tests/unit/train/models/test_fp8_fake_kernels.py -v
```

`torch.library.opcheck` with `test_utils=["test_schema",
"test_faketensor"]` compares the real op's output shape, stride, and
dtype against the fake's. On 8x H200 that is 26 passed post-fix; against
the pre-fix sources it fails exactly the 9 cases where a grad is
requested and its corresponding input is non-contiguous and passes the
other 17, so it discriminates rather than failing everywhere. The
ring-attention fake was verified the same way under a two-rank
`torchrun` harness, not committed since a distributed GPU test would
also only skip on CI. `uv run pytest tests/unit/train/models` is green
on the same node: 177 passed, 5 skipped.

Verified end to end with a harness built from production code only
(`Glm4MoeForCausalLM`, `configure_moe_runtime` with
`DeepGemmFP8MoEComputeConfig`, `apply_compile`, `setup_fsdp`):
`compile=on, ac=off` completes forward and backward at `ep` 1, 2, and 4,
up to real GLM-4.5-Air dimensions on 8 H200s. Restoring the pre-fix fake
reproduces the original `assert_size_stride` traceback at the same
shapes, so the check is not inert.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 12:59:53 -04:00
rasdaniandGitHub d5ed9fb7e4 chore: ask before changing repository skills (#3564)
Require agents to suggest specific repository skill changes, explain the
benefit, and wait for user approval before editing. Existing explicit
requests or approvals remain sufficient; ordinary code, workflow,
documentation, and PR requests do not authorize skill changes. Reading
and following skills remains allowed.

Changes only `AGENTS.md`, replacing its automatic skill-maintenance
requirement with the same approval guidance as
https://github.com/PrimeIntellect-ai/prime-envs/pull/814.

Validation: `git diff --check` passed; file-scoped pre-commit hooks
completed (Python-only hooks skipped this Markdown-only change).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Markdown-only policy change in `AGENTS.md` with no runtime or security
impact.
> 
> **Overview**
> Updates **agent policy in `AGENTS.md`** so repository skills under
`skills/` are no longer auto-maintained when code or workflows change.
> 
> The Skills section drops the requirement to check and update skills
after codebase edits, and replaces the “you must update skills when you
fix workflows” rule with **explicit user approval**: propose a concrete
skill change, explain why, and wait before creating, editing, renaming,
deleting skills or their symlinks. Prior explicit approval still counts;
ordinary code, workflow, docs, or PR work does **not** grant permission
to touch skills. Agents may still read and follow skills unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6e13660903da49dda03394923b97dee985fe779b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-16 19:50:35 -07:00
b4a41d3f2c perf(deepseek-v4): fuse the mHC chain and route unweighted RMS norms through quack (#3558)
DeepSeek V4's manifold-constrained hyper-connection (mHC) chain ran
eager and cost far more than
its arithmetic warrants: a python Sinkhorn loop of roughly 119 tiny
launches over stream mixing
matrices, an fp32 copy of the flattened streams materialized purely as
an intermediate, a
multi-kernel write-back over the full (batch, sequence, stream, hidden)
tensor, and a `q_b_norm`
whose input was non-contiguous. This fuses or reroutes all four.

- The unweighted RMS norms (the mHC input norms and attention's
`q_b_norm`) dispatch to quack
through the same gate the shared `RMSNorm` uses, with an optional
`out_dtype`. `q_b_norm` moves
ahead of the head transpose so quack's flatten is a view rather than a
copy; RMS over the channel
  axis commutes with the transpose exactly.
- The input norms take the bf16 streams directly and emit fp32, so the
fp32 copy is never
  materialized. The gate math downstream of the norm stays fp32.
- The Sinkhorn loop and the write-back become two Triton ops vendored
from NVIDIA/Megatron-LM at
`bb5dfd08f` (BSD-3, full license text reproduced in the file header).
They require a power-of-two
`hc_mult` and a CUDA input, both of which Triton itself enforces, and
the eager implementations
move to `eager_reference.py`, where the tests measure the kernels
against them.
- The rank-4 mHC residual is named `mhc_states` throughout, so
`hidden_states` always means the
rank-3 collapsed sequence, and the write-back moves onto
`DeepseekV4HyperConnection` as
  `update_states`.
- Both fused paths are covered on GPU, measured against the eager
references rather than a
  runtime fallback branch.

Forward/backward ms per call on an H200 at batch 1, sequence 16384,
`hc_mult` 4, hidden dimension
4096 (the Sinkhorn row is measured on the stream mixing tensor):

| Op | Before | After |
| --- | --- | --- |
| mHC front half | 2.89 / 8.10 | 1.05 / 2.54 |
| Sinkhorn | 1.05 / 3.14 | 0.10 / 0.81 |
| Stream write-back | 5.96 / 7.89 | 0.40 / 0.94 |
| `q_b_norm` | 0.99 / 2.85 | 0.30 / 0.96 |

A 4-node full-depth A/B goes from 15.97 to 13.11 s/step at 4.2 GiB lower
peak. That was measured on
the SFT-optim stack, not this branch: on `main` step time is
optimizer-offload dominated, so the
same A/B there would hide the change inside the offload's shadow.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-16 20:35:30 -04:00
Mika SenghaasandGitHub d7339fcf25 fix(orchestrator): taper concurrency growth by KV usage (#3556)
## Summary

The adaptive controller currently grows the admission cap by 25% per
pipeline turnover until GPU-KV usage crosses 60%, then stops growing
until the 80% soft-cap. That discontinuity can carry the cap into a
corrective trim too quickly.

This changes growth to taper linearly from 1.20× per turnover at 0%
GPU-KV usage to 1.00× at the 80% soft-cap. Above the soft-cap, the
existing soft-trim behavior remains unchanged. The controller also
exposes the active growth multiplier as a gauge.

## Verification

Validation run from #3542. Qwen3-30B-A3B on Terminal Lego on 2 nodes.
Can observe oscillating heavy growth and hard cut prior to this PR and
sigmoidish growth and no episode preemptions.

<img width="582" height="245" alt="Screenshot 2026-09-15 at 9 26 47 PM"
src="https://github.com/user-attachments/assets/dedf2bbe-0c8e-4434-93fb-de79b829ff44"
/>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes orchestrator admission AIMD tuning, which can affect
throughput and preemption/cut behavior under load, though trims and cuts
above the soft-cap are unchanged.
> 
> **Overview**
> Replaces the **fixed 1.25× cap growth per pipeline turnover** (while
KV stayed below 60%) with a **usage-dependent multiplier** that scales
from **1.20× at 0% GPU-KV** down to **1.0× at the 80% soft-cap**, so
growth eases before trims instead of stopping abruptly at 60%.
> 
> **Signal handling** no longer treats “KV above grow threshold” as
overload for gating; **soft pressure** is tied to crossing
**`KV_USAGE_SOFT_CAP`**, while **persistent queue overload** still
drives **hard** signals. **`record_episode`** applies
**`growth_multiplier**` instead of a constant factor, and
**`concurrency/growth_multiplier`** is exported as a gauge for
observability.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bc42bf362df09c89e5a3c47bbb2f11bf21d5923d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-16 11:58:36 -07:00
c394c2e1bd feat: consolidate eval cli (#3471)
## Summary

Migrates the eval CLI from verifiers into the prime-rl ecosystem: `uv
run eval` is prime-rl's entrypoint for evaluating any model on any
environment, standalone or as the online evals of a training run.

Why:

- consolidation of features: adaptive concurrency, the local dashboard,
resume from the trace stream, live rollouts
- easier code sharing between the CLI entrypoints (`rl`, `sft`, `eval`)
- direct access to the pre-installed environments (`prime-envs`
submodule)
- one workspace for post-training: training and evals

Important:

- the verifiers eval CLI stays for a transition period as the quick
in-process path, renamed `uv run vf-eval` so prime-rl owns `eval`
(PrimeIntellect-ai/verifiers#2610 removes it later); env servers and
their streamed traces (PrimeIntellect-ai/verifiers#2512, merged; the
submodule points at verifiers `main`) are consumed here only
- evals run through env servers, for scalability; the launcher (`eval`,
`sft`, `rl`) owns them
- `--resume` continues an interrupted run from its trace stream: landed
episodes rejoin the epoch, only the owed rollouts run;
`num_examples`/`group_size` may change, the model, sampling and env
config may not
- multi-env capable (`[[source]]` blocks); the single-env command
shorthands are preserved
- adaptive concurrency only against local deployments (it reads vLLM
`/metrics`); against an API, concurrency is pinned via `min_inflight =
max_inflight` (the default pins 128)
- prime-rl's core dependencies are plain CPU; install them and the
environments with `uv sync --all-packages`
- Prime runs and traces integrate through the single monitor abstraction
(`--monitors.prime`, `--monitors.wandb`, the file monitor)

Examples:

```bash
uv run eval gsm8k                                            # default model on Prime Inference
uv run eval gsm8k -n 32 -r 4 -m openai/gpt-5.6-luna           # 32 tasks × 4 rollouts, another model
uv run eval terminal-bench-2 --env.taskset.tasks '["fix-git"]' --env.agent.harness.id bash -n 1 -r 2
uv run eval @ configs/debug/eval/single-turn.toml            # gsm8k, null harness
uv run eval @ configs/debug/eval/multi-turn.toml             # 16 terminal-bench-2 tasks, bash harness
uv run eval @ configs/debug/eval/multi-env.toml              # terminal-bench-2 under bash and rlm side by side
uv run eval @ configs/debug/eval/aime2026.toml               # AIME 2026, avg@16
uv run eval @ configs/debug/eval/tb2.toml                    # Terminal-Bench 2, avg@4
uv run eval @ configs/debug/eval/resume.toml --run.name x    # then: --resume
uv run eval gsm8k --monitors.prime                           # stream the evaluation to the platform
```

## Breaking

- `uv run evals` is `uv run eval` (`EvalsConfig` → `EvalConfig`); config
shape: `[eval.client]` → `[client]`, `[eval.concurrency]` →
`[concurrency]`, `[[eval.source]]` → `[[source]]`,
`eval.num_examples`/`eval.group_size` → top level. `[online]` is gone:
online evals are spawned by `sft`.
- `eval` has no `[ckpt]` block; `--resume` is a switch that reads the
run's trace stream.
- SFT online evals: no public entrypoint (`uv run sft` with an `[eval]`
block spawns it); `logs/attempt_N/evals.log` → `eval.log`, `evals.json`
→ `eval.json`, W&B label `online-eval`; `EvalsEvalConfig` →
`SFTOnlineEvalConfig`.
- `ratio` is accepted on training sources only, `interval` on online
eval sources only; a standalone eval's `[[source]]` takes neither.
- `orchestrator.env_server_base_port` and the eval entrypoint's
`env_server_base_port` are removed: launcher-managed env servers bind an
OS-assigned port and publish it
(`configs/attempt_N/resolved/envs/<split>/<name>.address`);
`serve.address` pins one. `uv run env-server` without `serve.address`
binds an OS-assigned port (`address_file` publishes it).
- `configs/evals/swe.toml` is removed (`uv run eval swebench-verified
--env.agent.harness.id bash`).

## Verification

- Unit: `uv run pytest tests/unit` green (configs, orchestrator, eval,
monitors incl. the live reader).
- Debug configs: single-turn, multi-turn, multi-env and aime2026 run to
completion against Prime Inference. Resume: single-env and multi-env
runs interrupted with SIGTERM and resumed hold exactly examples ×
group_size unique episodes with the plan and epoch metrics over the full
set; resuming with a larger `group_size` runs only the extra rollouts;
resuming with another model is refused.
- Core install (`uv sync` without extras) runs `uv run eval`; an SFT run
with online evals starts one env server per source.
- Live streaming, on the final code: gsm8k 16 single-turn episodes,
terminal-bench-2 fix-git with bash (13-14 turns, the pending preview
alternating with committed turns in the live files), kuhn-poker 4
two-seat episodes (8 traces), a 5-step reverse-text RL run (768 train
episodes with token ids, logprobs and masks); no assembly mismatch.
- Platform: `--monitors.prime` on a two-rollout fix-git eval opened the
evaluation 9 s after launch, streamed both rollouts and closed it; the
dashboard linked to it throughout.
- Dashboard behaviour checked in headless Chromium: live rows and viewer
follow, handover in place, metrics pane per env, filter menus, platform
button states.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking CLI and config renames affect existing scripts; env-server
address discovery replaces fixed ports across `rl`, `sft`, and `eval`
launch paths.
> 
> **Overview**
> **Replaces `uv run evals` with `uv run eval`** as the standalone
evaluation entrypoint, sharing the orchestrator eval pipeline
(per-source env servers, adaptive or pinned concurrency, file/W&B/Prime
monitors). Config is **flattened** (`[[source]]`, `[client]`,
`[concurrency]` at top level); **`--resume`** continues from the trace
stream instead of a `[ckpt]` cursor; SFT **online eval** is renamed and
typed as `SFTOnlineEvalConfig` (no public `[online]` block).
> 
> **Env server wiring changes:** fixed `env_server_base_port` ranges are
removed—launcher-managed servers bind **OS-assigned loopback ports** and
publish addresses via **`address_file`** /
`configs/.../envs/<split>/<name>.address`. Training **`ratio`** and
online-eval **`interval`** are scoped to the right source types only.
> 
> **Docs and examples** add `docs/eval.md`, per-example `eval.toml`
files, and `configs/debug/eval/*` smokes; **`configs/evals/swe.toml` is
deleted**. CI adds a **gsm8k eval** integration test on VM runners.
> 
> **Dashboard** gains live rollout APIs and eval-centric metrics
(plan-driven progress, platform links, eval run status), renames
**`evals.log` → `eval.log`**, and tightens static asset revalidation.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
82f2f0eda7628c874be6dcfcda700cab26fd4442. 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-16 11:04:24 -07:00
xianzheng shanandGitHub 0d372c1fd6 fix(inference):Fix native disk KV cache offload tier type (#3538)
## Summary

Align the disk-backed KV cache secondary tier with vLLM's registered
filesystem tier name: `fs`, not
`fs_python`.[#43600](https://github.com/vllm-project/vllm/pull/43600)

## Problem

The inference configuration emitted a secondary tier of the form

```python
{"type": "fs_python", "root_dir": <configured disk path>}
```

but the tier factory only registers the filesystem secondary tier under
the name `fs`:

```text
example, fs, p2p, obj
```

Because the identifier did not match, vLLM aborted engine initialization
with:

```text
ValueError: Unknown secondary tier type: 'fs_python'
```

## Changes

- Rename the filesystem secondary tier identifier from `fs_python` to
`fs` everywhere it is constructed or referenced — configuration
generation, tier-factory registration, and log messages.
- Keep `root_dir` as the configured disk path; no behavioural change to
the tier itself, only its name.
- Update the affected tests to use `fs`.
- No changes to the TOML configuration format.

## Validation

With CPU offload and disk offload both enabled, on vLLM `vLLM 0.28.0`
and a Qwen3-4B inference configuration:

- the engine initializes without the `Unknown secondary tier type`
error;
- `fs_python` no longer appears in generated configs or logs.
2026-09-16 17:35:16 +02:00
9f4eef81a3 perf(optim): reuse pinned CPU buffers in CPUOffloadOptimizer (#3552)
Allocate `CPUOffloadOptimizer`'s CPU-side buffers once, pinned, and copy
optimizer state into them non-blocking, instead of allocating a fresh
pageable buffer plus a fresh pinned buffer on every step.

- The old path copied each state tensor into fresh pageable memory
blocking, then `.pin_memory()` allocated a second buffer and copied
again host to host. `Tensor.to` cannot allocate pinned memory, and
`non_blocking` was set to `not self.pin_memory`, which disabled the
async path in the one case where a pinned destination would have made it
work.
- Buffers are keyed by `(parameter, state key)` and reallocated if a
state tensor's shape or dtype changes, which covers `load_state_dict`.
- One `torch.cuda.synchronize()` now ends the offload, replacing the
per-tensor stall. The `pin_memory=False` path and the host-to-device
direction are unchanged, the latter deliberately: those tensors must be
freshly allocated for the GPU memory to be released between steps.
- The first commit adds the tests with the buffer-reuse one marked
`xfail`, since the three correctness tests pass on the old code and only
that one exposes the bug. The second commit drops the `xfail`.
- Measured on DS V4-Flash SFT, one node of 8x H200 at 6 layers,
`seq_len` 131072, `cp=8`, `ep=8`, micro-batch 1, 10 steps, steady-state
medians, with the fix as the only change from production defaults:
optimizer 26.9 s to 3.0 s and whole step 30.9 s to 6.5 s, at an
unchanged 103.8 GiB peak. Trace of the old 26.7 s window: 18.2 s
pageable D2H at 2.2 GB/s, 5.4 s `pin_memory` re-copy, 1.5 s pinned H2D,
and 0.15 s of AdamW kernels. Per-rank optimizer state is what sizes this
window, and the 6-layer proxy carries 4.93e9 parameters per rank against
production's 4.44e9, so it is not a scaled-down number.

Verified on an H200: 3 passed / 1 xfailed at the test commit, 4 passed
at the fix commit, with `tests/unit/train/test_cpu_adam.py` and
`tests/unit/test_configs.py -k offload` still green.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 16:02:32 -07:00
1d9ab255eb fix(docker): drop removed gpt-oss extra from uv sync (#3549)
#3424 removed the gpt-oss optional-dependency group from pyproject.toml,
but Dockerfile.cuda still passed --extra gpt-oss to uv sync, which fails
on undefined extras and broke every image build since.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Build-only Dockerfile alignment with pyproject extras; no application
or dependency logic changes beyond fixing the sync command.
> 
> **Overview**
> Repairs **CUDA Docker image builds** that broke after the `gpt-oss`
optional extra was removed from `pyproject.toml` (#3424).
> 
> Both `uv sync` steps in `Dockerfile.cuda` (the cached third-party
layer and the full workspace sync after sources are copied) no longer
pass `--extra gpt-oss`. **`uv` was failing** on an undefined extra; the
remaining extras (`gpu`, flash-attn variants, `disagg`, `quack`,
`kernels`, `mamba-ssm`, etc.) are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b340617baed2ffb69a2a1adc800e9264f4c32ba2. 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: Johannes Hagemann <johannes@Johanness-MacBook-Pro.local>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 22:03:42 -07:00
samsjaandGitHub eff12f2483 chore: glm-4.5-air swe example to muon + 2 trainer / 4 inference nodes (#3546)
## Summary

Updates the GLM-4.5-Air `scaleswe` advanced example to mirror the
research-prod air ablation base config (research-prod PR #198): 2
trainer nodes with Muon instead of the single-node sign-SGD setup, and 4
one-node inference replicas. Router replay, `max_off_policy_steps`, and
the length-penalty weights stay unchanged.

## Changes

- **Deployment**: `1 train + 3 infer replicas` -> `2 train + 4 infer
replicas` (one-node replicas)
- **Optimizer**: `sign_sgd` -> `muon`; drop the sign-SGD-era
`optim_cpu_offload = false` / `full_offload = true` and `[trainer.ckpt]
skip_optimizer` (optimizer state is checkpointed again, so runs can
resume)
- **Trainer memory**: `fused_lm_head_token_chunk_size` (8192) and
`optim_cpu_offload` (true) use their defaults (per review); keep cp=4
(ulysses) and activation checkpointing + offloading
- **Orchestrator**: unchanged (`batch_size = 256`, `group_size = 16`,
`max_off_policy_steps = 32`, linear length penalty with
`num_output_tokens_weight = 0.0`, input/turns weights 0.1)
- **Router replay**: unchanged, stays enabled
(`trainer.enable_router_replay` +
`inference.vllm.enable_return_routed_experts`)
- **Inference**: added `enable_expert_parallel = true` and
`gpu_memory_utilization = 0.85` (TP=8 + EP)

## Validation

- `uv run rl @ examples/advanced/glm-4.5-air/swe.toml --dry-run`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Example TOML only; no application code, auth, or data-path changes.
> 
> **Overview**
> Updates **`examples/advanced/glm-4.5-air/swe.toml`** to match the
research-prod air ablation base (research-prod PR #198) instead of the
old single-node sign-SGD layout.
> 
> **Deployment** scales to **2 trainer nodes** and **4 inference
replicas** (was 1 train / 3 infer). **Training** switches the optimizer
from **`sign_sgd` to `muon`**, drops sign-SGD-only trainer settings
(`full_offload`, explicit LM-head chunk size, **`skip_optimizer`**
checkpointing), so **optimizer state is saved again** and jobs can
resume. Comments now describe Muon + two-node training and default
LM-head chunking / CPU optimizer offload.
> 
> **Inference** adds **`enable_expert_parallel = true`** and
**`gpu_memory_utilization = 0.85`** alongside existing TP=8 and router
replay. GRPO batch/group sizes, length-penalty weights, and router
replay behavior are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
91c71d25ac6b277aa1ddd5631384e40fb080f53f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-14 17:18:28 -07:00
e0886c152d chore(trainer): unify context-parallel setup across models (#3533)
Unifies all context parallel setup so that a single frozen `CPContext`
dataclass is shared by all cp-aware modules, stored under a
`self.cp_contex: CPContext` attr.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 14:03:40 -04:00
9ef21a64f1 docs(examples): restore launch READMEs, add vlm section, slim advanced examples (#3537)
## What

Related changes to `examples/` and `configs/`:

### 1. Launch walkthroughs for the advanced examples

`#3085` restructured `examples/` into `basic/` + `advanced/` and dropped
the per-example READMEs — the step-by-step launch guides. Since then the
advanced folders had no how-to-start documentation. This PR restores
them, rewritten against current usage (not copied from history):

- **`examples/advanced/glm-4.5-air/README.md`** — config-by-config table
(train/eval sources, node topology), sandbox setup (Prime Intellect
Sandboxes by default, swap `env.agent.runtime` for your own),
`SERPER_API_KEY` forwarding, launch via `uv run rl @ ...` with built-in
sbatch submission, `uv run dashboard` how-to, resume/export.
- **`examples/advanced/glm-5.2/README.md`** — 32-node RL configs, the
llm-d + Mooncake variant, the `infer/` pre-flights; documents that
`swe.toml` declares **no train source** and must be composed with a
source overlay.
- **`examples/advanced/qwen3-30b-a3b/README.md`** — same format: math
(subprocess runtime, no sandbox), SWE (sandbox), tool use (Modal
runtime, `modal setup`).

Why rewritten and not resurrected: `scripts/tmux.sh` was removed
(`#3351`, replaced by `uv run dashboard`), the `.env` auto-sourcing is
gone, `--wandb.*` became `--monitors.wandb.*`, and HF weight upload was
replaced by DCP checkpoints + `tools/convert_dcp_to_bf16.py`. Every
claim was checked against the configs on `main` and `docs/training.md` /
`docs/scaling.md`.

### 2. Refined `examples/README.md`

Proper `basic/`, `extra/`, and `advanced/` sections with per-example
one-liners (domains, node counts, context length), a where-to-start
pointer (reverse-text first), and a related-configs section.

### 3. `extra/` section

`dynamo/` (external Dynamo inference + NCCL weight updates) and the VLM
SFT configs (moved from the `examples/` root, `vlm_sft`/`vlm_sft_moe`)
now live in **`examples/extra/`** — material that doesn't follow the
basic eval → SFT → RL walk-through pattern. `basic/` keeps only the
core-environment walk-throughs.

### 4. Config-only folders move to `configs/`

- `minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`:
`examples/advanced/` → **`configs/advanced/`** — frontier configs
without tutorials are configs, not examples.
- `examples/evals/` → **`configs/evals/`** — standalone evals (`uv run
evals @ configs/evals/swe.toml`) are configs too; the reference in
`skills/training/start-run/SKILL.md` is updated.

All other references updated: root `README.md` (advanced list:
Qwen3-30B-A3B, GLM-4.5-Air, GLM-5), `examples/README.md`,
`configs/README.md`, `docs/configuration.md`, `docs/scaling.md`. Moves
are pure `git mv`; no config content changed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation and config path reorganization only; VLM loss-mask TOML
changes are equivalent defaults with clearer comments.
> 
> **Overview**
> Restores **step-by-step launch READMEs** for
`examples/advanced/glm-4.5-air`, `glm-5.2`, and `qwen3-30b-a3b` (SLURM
launch, sandboxes/Modal, dashboard, resume/export), and **reorganizes**
`examples/README.md` into `basic/`, `advanced/`, and new **`extra/`**
(`dynamo/`, `vlm/`).
> 
> Frontier configs **without** walkthroughs move from
`examples/advanced/` to **`configs/advanced/`** (`minimax-m2.5`,
`nemotron-3-super`, `deepseek-v4-flash`); standalone evals move to
**`configs/evals/`** (e.g. `swe.toml` path in comments and docs).
Cross-links update in the root README, `configs/README.md`,
`docs/configuration.md`, and `docs/scaling.md` (Nemotron/MiniMax now
point at `configs/advanced/`; advanced list trimmed/relabelled for
GLM-5).
> 
> Adds **`examples/extra/vlm/README.md`** and tightens VLM SFT TOMLs
with explicit `[data.loss_mask] assistant = true` (replacing the full
mask table in the MoE config). **`dynamo`** launch path updates to
`examples/extra/dynamo/rl.toml`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ed086f6797af9755e61acce6b672df50387f3b6d. 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: samsja <samsja@users.noreply.github.com>
2026-09-12 19:35:47 -07:00
samsjaandGitHub 1e7c6888b6 feat(trainer): add optional IcePop loss (#3526)
## Summary

Add IcePop as an explicit, opt-in RL loss while preserving IPO as the
default.

```toml
[trainer.loss]
type = "icepop"
ratio_low = 0.2
ratio_high = 5.0
```

Accepted tokens use the importance-weighted policy-gradient term; tokens
outside the inclusive trainer/inference ratio band are dropped. IcePop
has no separate KL term. `adv_tau` remains configurable.

The acceptance test is performed in log space and masked ratios are
replaced before exponentiation. This is mathematically equivalent for
accepted tokens while preventing a rejected extreme ratio from producing
`0 * inf = NaN` in the loss or gradient.

Addressing review feedback: the rl losses are now loss objects
(`IPOLoss`, `IcePopLoss`, `CustomLoss`) initialized from their loss
config, satisfying a structural `Loss` protocol with an explicit
`.loss()` method (no `__call__`), and `setup_rl_loss_fn` builds the
right object from `[trainer.loss]` via a class-pattern `match` statement
(review suggestions from @hallerite). The IcePop paper (Ring-1T
technical report, [arXiv 2510.18855](https://arxiv.org/abs/2510.18855))
is linked from `docs/algorithms.md`.

This PR intentionally contains no DPPO, cache-salt, or experiment
configuration changes.

## Verification

- `176 passed` in `tests/unit/test_configs.py`
- CPU loss/gradient checks passed for inclusive `0.2` and `5.0`
boundaries
- CPU loss/gradient checks passed for a rejected extreme ratio
(`exp(100)` case)
- CPU checks passed for the loss-object dispatch: `setup_rl_loss_fn`
builds `IPOLoss` / `IcePopLoss` / `CustomLoss`, and unsupported configs
raise `TypeError`
- CPU checks passed for the `Loss`-protocol `.loss()` path through
`compute_loss` (rl component, ipo + custom loss)
- Ruff formatting and lint checks pass

GPU unit coverage for the same boundary and numerical-safety cases is
included for CI.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes the core RL loss implementation and adds a new training
objective path; incorrect masking or numerics would directly affect
policy gradients, though IPO/default behavior is preserved and tests
cover boundary and NaN cases.
> 
> **Overview**
> Adds **IcePop** as an opt-in `[trainer.loss]` variant (`type =
"icepop"`) while **IPO remains the default**. IcePop keeps only tokens
whose trainer/inference importance ratio lies in an inclusive band
(`ratio_low` / `ratio_high`, defaults 0.2–5.0), applies the usual
importance-weighted policy-gradient term on accepted tokens, and **drops
IPO’s separate KL penalty**; `adv_tau` is still configurable.
> 
> The RL loss path is refactored from free functions into callable
**`IPOLoss`**, **`IcePopLoss`**, and **`CustomLoss`** objects wired
through `setup_rl_loss_fn`. IcePop evaluates the acceptance band in log
space with a **detached** mask and zeroes rejected log-ratios before
`exp` so extreme off-policy ratios cannot yield `0 × inf` NaNs in loss
or gradients. Config adds `IcePopLossConfig` with pydantic validation
that `ratio_low ≤ ratio_high`.
> 
> Docs (`docs/algorithms.md`, config skill) describe enabling IcePop;
unit tests cover ratio boundaries, gradients, the extreme-ratio safety
case, and config parsing.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f69d2e69ad4802ce6fdb2e48fb9fd7d0c87f88c8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-12 17:51:42 -07:00
815d1c0cad chore(examples): drop empty [monitors.prime] sections (#3536)
## What

Removes the bare `[monitors.prime]` sections (empty tables, no keys)
from the example configs:

- `examples/advanced/glm-4.5-air/search.toml`
- `examples/advanced/glm-4.5-air/swe.toml`
- `examples/advanced/glm-4.5-air/terminal.toml`
- `examples/advanced/nemotron-3-super/swe.toml`

## Why

An empty `[monitors.prime]` table silently enables Prime Lab platform
monitoring (streaming metrics/episodes to the platform) for anyone who
starts a run from these examples. Dropping the section keeps the
examples monitoring-free apart from W&B, matching the other examples
(`glm-5.2`, `intellect-3.1`, `minimax-m2.5`, `qwen3-30b-a3b`, and all
`basic` examples), which never declare it.

Users who want platform monitoring can re-enable it with
`--monitors.prime` or the section itself (see `docs/training.md` ->
Platform monitoring).

## Notes

- Pure deletion of 8 lines across 4 files; all files still parse as
valid TOML.
- `configs/debug/concurrency.toml` also declares `[monitors.prime]`;
left untouched since this PR is scoped to examples.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Example-only TOML deletions; default monitoring behavior for runs
started from these four configs changes from implicit Prime Lab on to
off, with no runtime or training logic changes.
> 
> **Overview**
> Removes bare **`[monitors.prime]`** blocks (empty tables with no keys)
from four advanced example training configs: GLM-4.5-Air **search**,
**swe**, and **terminal**, plus **nemotron-3-super** SWE.
> 
> Those sections were enough to turn on **Prime Lab platform
monitoring** (metrics/episodes streaming) for anyone launching from the
examples, even though only **`[monitors.wandb]`** was intentionally
configured. After this change, the examples match the rest of the tree
(W&B only unless users opt in via **`--monitors.prime`** or a populated
**`[monitors.prime]`** section).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2fb5bd42edfef2ea4ed67951352a0519a9964e57. 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: samsja <samsja@users.noreply.github.com>
2026-09-12 17:20:05 -07:00
Matej SirovatkaandGitHub 28bb83bea7 fix(qwen3.5): address follow-up review cleanup (#3534)
Follow up on Garrett's review of #3429. Composite MoE models store
expert counts in `text_config`, so `is_tt_moe_model` missed them and the
trainers skipped their load-balancing statistics. Resolve the text
config before checking expert counts, with a CPU check covering
dense/MoE text and VLM configs.

Remove the unused-argument `del` statements while preserving the public
signatures. Drop the zero-initialization assertion and the two-rank GDN
test that ordinary CI always skipped, as requested in review. Keep the
native forward/backward, packing, vision, MRoPE, and router replay
coverage.

Retain the existing compiler disable for CP convolution and link its
exact upstream bug. Two-rank H200 testing on PyTorch 2.13.0+cu130 / FLA
a954753 reproduces a Dynamo `copy_` shape error without the disable: the
functional collective returns `[6, 8192]`, while FLA supplies a stacked
`[2, 3, 8192]` output buffer. The same operation works eagerly; an
isolated compiled collective using a concatenated buffer followed by
reshape also passes.

Upstream status checked September 12: FLA main (`516143e`) still has the
identical communication helper. PyTorch issues
[#138795](https://github.com/pytorch/pytorch/issues/138795) and
[#155632](https://github.com/pytorch/pytorch/issues/155632) remain open.
The matching [fix
#177205](https://github.com/pytorch/pytorch/pull/177205) closed without
merging, and current PyTorch main still lacks the reshape. FLA's
[graph-capture RFC
#1155](https://github.com/fla-org/flash-linear-attention/issues/1155#issuecomment-5354945885)
defers CP; no exact FLA fix was found.

Validation:

- H200 Slurm 486: Qwen3.5 and shared MoE suite, **33 passed**. CPU MoE
suite: **15 passed**. Ruff check/format and whitespace checks pass.
- Standalone GDN probes use two H200 ranks and `torch.compile` with
default settings (graph breaks allowed), two packed layouts, native
unsharded output/input-gradient comparisons, and finite parameter
gradients. These isolate the convolution boundary; they do not establish
full trainer or image+CP compilation support.

| CP convolution disable | Selective AC | Result | Slurm job |
|---|---|---|---|
| Present | Off | Both layouts pass on both ranks | 484 |
| Removed in probe | Off | Dynamo collective shape error | 485 |
| Present | On | Both layouts pass on both ranks | 487 |
| Removed in probe | On | Both layouts pass on both ranks | 488 |

The checkpointed probe passing does not make removal safe: the supported
non-checkpointed configuration still fails. The isolated
stacked/concatenated collective comparison passed its expected failure
and parity checks (Slurm 489). Probe scripts and logs are retained
outside the repository under
`/home/matej/prime-rl-verify/qwen35-review-20260912/`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Targeted config lookup and test/doc cleanup; MoE detection fix reduces
risk of missing load-balance metrics on composite MoE models.
> 
> **Overview**
> **MoE detection** now reads expert counts from `text_config` when
present, so Qwen3.5 MoE VLMs are recognized and trainers collect
load-balancing stats instead of treating them as dense models. A CPU
parametrized test covers dense/MoE text and VLM config classes.
> 
> Review cleanup removes unused `del` stubs on public APIs
(`from_config`, RoPE helpers), drops CI-skipped Qwen3.5 tests (zero-init
norm assertion and two-rank gated-delta-net CP parity), and tightens the
comment on why context-parallel `causal_conv1d` stays outside
`torch.compile` (Dynamo all-gather vs FLA buffer layout,
[pytorch#155632](https://github.com/pytorch/pytorch/issues/155632)).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0520d09809547dfb8e982f2590702eee079c7e4f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-12 21:09:58 +02:00
Matej SirovatkaandGitHub 534888b77d feat(models): add native Qwen3.5 family implementation (#3429)
## Summary

Unify Qwen3.5 dense, MoE, and VLM training under a native
implementation, including the Qwen3.8 checkpoint that uses this
architecture. Remove the separate MoE package and global Transformers
model patches.

- Keep `Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL)` shared by the
backbone and causal LM; remove unused Transformers TP/PP plans,
split-module metadata, cache arguments, and redundant initialization.
Modules own their initialization, including zero-centered RMSNorm.
- Use Prime's shared attention and MoE runtime. Gated full attention
consumes the fused QKV projection with the correct doubled query width;
configured MoE load balancing allocates its router selection bias.
- Own packed DeltaNet, zero-centered RMSNorm, MRoPE, and the vision
encoder. Hybrid layers support Ulysses CP through FLA boundary-state
exchange; full attention uses common attention dispatch.
- Convert official fused MoE expert weights to Prime's split projections
and back, excluding MTP weights.
- Keep the narrow compiler boundary for FLA CP convolution, whose
collective layout fails Dynamo tracing. Vision FlashAttention has no
compiler disable and uses each backend's declared return format
directly.

Qwen tests live under `tests/unit/train/models/qwen3_5/`:
`test_model.py` parametrizes initialization, context-parallel setup, and
forward/backward/packing checks over dense and MoE configs;
`test_vlm.py` groups vision tests with CPU MRoPE checks. MoE router
replay remains a dedicated check. Tests use native configs and models
without Transformers reference models, HF weight comparisons, or Hub
downloads. Public model helpers use
`AutoModelForCausalLMPrimeRL.from_config` with the trainer's shared
auto-attention resolver, without hardcoded backends or private attention
config writes. Remove the class/source-introspection test and duplicate
shared-attention checks. Remove the blanket BF16 optimizer/reduction
restriction for RL VLMs; FP32 defaults remain unchanged and FSDP still
computes in BF16.

Text and vision consume Prime's resolved `model.attn` configuration
directly, including under Ulysses CP. Remove Qwen constructor
fallback/propagation logic, the forced vision SDPA override, and its
unused vision branch.

MTP and video training are outside this runtime's scope.
`scripts/mini_moe.py` is unchanged from main and is outside this PR's
validation.

## Math KL validation

Both checkpoints completed 20 steps on `math-env`
(`PrimeIntellect/Hendrycks-Math`, train split), with **batch size 64**.
Every step-mean KL is below **0.015**.

| Checkpoint | Steps | Mean KL over 20 steps | Highest step-mean KL |
|---|---:|---:|---:|
| `Qwen/Qwen3.8-27B` | 20 | 0.000359685 | 0.000953884 |
| `Qwen/Qwen3.5-35B-A3B` | 20 | 0.000208713 | 0.000462048 |

Runs executed concurrently on separate H200 nodes using `uv run rl @
<config>`, with four trainer and four inference GPUs per model. Both
Slurm jobs completed with exit code 0: dense job 387, MoE job 386.
Tested commit: `9983e7bed`.

Settings: main's `debug` algorithm with constant per-token advantage
1.0; original task sampler; math-verify scoring without the optional LLM
judge; Prime VM runtime enforcing the task network policy; sequence
length 4096, maximum completion length 2048, group size 8, learning rate
1e-6, compilation, selective activation checkpointing, FlashAttention 3,
and NCCL weight updates. MoE additionally uses EP=4 and router replay.
Inference uses `max_num_seqs=64`. Optimization and reduction dtypes
retain their FP32 defaults.

All 20 batches per model contained 64 trainable episodes, and all
gradient norms were finite. These are asynchronous E2E measurements of
`mismatch_kl/all/mean`; the summary averages the 20 step means and
includes normal policy staleness. The debug algorithm exercises training
with synthetic advantages, so this is a correctness check, not a
learning-quality benchmark. These 20-step runs use text inputs; packed
image-conditioned validation is recorded below.

<details>
<summary>All 20 step-mean KL values</summary>

| Step | Dense mean KL | MoE mean KL |
|---:|---:|---:|
| 1 | 0.000087817 | 0.000103068 |
| 2 | 0.000133938 | 0.000132430 |
| 3 | 0.000112734 | 0.000115124 |
| 4 | 0.000193951 | 0.000099179 |
| 5 | 0.000205668 | 0.000214333 |
| 6 | 0.000359477 | 0.000348763 |
| 7 | 0.000838096 | 0.000161281 |
| 8 | 0.000150568 | 0.000207813 |
| 9 | 0.000190916 | 0.000158351 |
| 10 | 0.000246897 | 0.000258552 |
| 11 | 0.000492465 | 0.000462048 |
| 12 | 0.000236148 | 0.000177551 |
| 13 | 0.000311170 | 0.000316216 |
| 14 | 0.000953884 | 0.000286797 |
| 15 | 0.000817523 | 0.000233271 |
| 16 | 0.000320892 | 0.000184788 |
| 17 | 0.000567697 | 0.000175972 |
| 18 | 0.000280278 | 0.000164684 |
| 19 | 0.000264224 | 0.000196673 |
| 20 | 0.000429352 | 0.000177372 |

</details>

## Packed VLM validation

Both models completed five packed image RL updates on MMMU Math dev,
with batch size 32 and an 8192-token trainer packing limit. All 160
samples per model included images.

| Model | Steps | Mean KL | Maximum step-mean KL | Images per packed
microbatch |
|---|---:|---:|---:|---:|
| Qwen/Qwen3.8-27B | 5 | 0.000501153 | 0.000729994 | 5–6 |
| Qwen/Qwen3.5-35B-A3B | 5 | 0.000346154 | 0.000458347 | 5–6 |

| Step | Dense KL | MoE KL |
|---:|---:|---:|
| 1 | 0.000231250 | 0.000167199 |
| 2 | 0.000387219 | 0.000343682 |
| 3 | 0.000553381 | 0.000360291 |
| 4 | 0.000729994 | 0.000401253 |
| 5 | 0.000603919 | 0.000458347 |

Native models; trainable vision encoder; FA3; compiled decoder blocks
and selective activation checkpointing; FP32 optimization and gradient
reduction; CP1; MoE EP4 and router replay; debug advantages; group size
8; maximum completion length 1024; inference context 4096; NCCL weight
broadcasts. These are correctness smokes on four repeated diagram
questions, not learning-quality benchmarks.

Packed MRoPE exactly matched individual-document MRoPE for all 320
training samples, and image-grid/pixel-patch counts matched each
document’s image-token spans. Both Slurm jobs exited 0 (dense 400, MoE
399). MoE needed allocator retries at the H200 memory limit.

Image+CP+compile remains separately unresolved; these E2E runs use CP1.

Tested runtime contents: `dcdf770df` (subsequent commits only change
tests). Run configs and detailed batch/position evidence are under
`/home/matej/prime-rl-verify/pr3429-20260910/`.

## Other validation

- Attention cleanup at `a2173601f`: H200 Qwen suite 24 passed, one
skipped; official dense/MoE model loading preserves configured attention
for text and vision at CP sizes 1 and 2. An additional compiled image/CP
backward check exposed `Autograd not support dtype: Int` with selective
activation checkpointing; the same error reproduces using the previous
SDPA vision path. Compiled image/CP validation remains unresolved. The
completed math runs above use CP=1.

- Native-only H200 Qwen suite: **20 passed, one expected single-rank CP
skip**, with `HF_HUB_OFFLINE=1` and `TRANSFORMERS_OFFLINE=1` (Slurm 407;
consolidated dense/MoE suite). Existing config suite: **175 passed**.
Ruff check/format pass. Both dense and MoE run the shared
packed-versus-unpacked comparison. MoE replays identical expert
selections to isolate document boundaries; ordinary routing
forward/backward remains covered.
- CI at `9983e7bed`: CPU unit tests, Ruff, slim install, and CodeQL
pass. GPU CI passes the Qwen tests; its five failures are in unchanged
DeepSeek V4 tests (three packed-batch assertions reproduced on
unmodified main `bad80b1a3`, two FP8 architecture failures). GPU CI: 66
passed, 82 skipped, 599 deselected, five failed.
- Two-rank H200 compiled packed DeltaNet output and input-gradient
checks passed with the CP convolution compiler boundary.
- Exact official checkpoint key/shape conversion and reverse conversion
passed: dense 1,199 source keys to 1,184 runtime keys; MoE 1,811 source
keys to 1,066 runtime keys after excluding MTP.
- Full H200 unit suite: 737 passed, 12 skipped, three DeepSeek V4
failures also reproduced on unmodified main. The weight-transfer test
imports the unified model.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Large change to core training models (hybrid attention, MoE weight
conversion, packed multimodal RL) with removed Transformers workarounds;
regressions would affect Qwen3.5/3.8 RL and VLM correctness rather than
peripheral code.
> 
> **Overview**
> Replaces the split **Qwen3.5 dense + MoE packages** and **Transformers
runtime monkey-patches** with one **native PrimeRL implementation**
under `models/qwen3_5/`. Dense text, MoE text, and composite VLMs all
dispatch to **`Qwen3_5ForCausalLM`**, driven by local configs
(`Qwen3_5TextConfig`, `Qwen3_5MoeTextConfig`, vision/composite configs)
and updated **`AutoConfig` / VLM registration**.
> 
> The rewrite drops the HF-backed text stack in favor of **Prime
`FlashAttention`**, **packed varlen GatedDeltaNet** (FLA + Ulysses CP),
**zero-centered RMSNorm**, **MRoPE**, a **custom vision encoder**, and
**MoE layers** with HF↔Prime **expert weight conversion** (MTP dropped).
VLM prep keeps dummy vision runs for FSDP symmetry and shards
**`routed_experts`** under CP. **`model.py`** no longer applies Qwen3.5
checkpoint/MRoPE/varlen patches or forces vision SDPA under CP.
> 
> **Trainer/config cleanup:** removes the **VLM must use bfloat16**
validator and the duplicate check at model load; **`parallel_dims`**
treats MoE on nested **`text_config`**. Ring/Ulysses patching no longer
lists Qwen-specific attention classes because **`Qwen3_5Attention`
subclasses `FlashAttention`**.
> 
> **Tests/docs:** deletes HF-comparison tests and the old `qwen3_5_moe`
tree; adds **`tests/unit/train/models/qwen3_5/`**
(forward/pack/CP/VLM/MRoPE). **`development.md`** points VLM authors at
the unified package.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d9162ce07425b56e01f6b62d3b24b141a8ff4a51. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-12 17:08:22 +02:00
43b4e2bd13 feat(deepseek_v4): support context parallelism (#3508)
Adds `ring` style CP support to deepseek v4.

The comms requirements are a bit different than those of other models
currently supported. As a point of comparison, for GLM which also has
key/value compression, the key/value creation is embarrassingly parallel
along the seq dim and the compressed key/values can be created from
cp-rank-local data. Comms are of the form `gather_for_cp(kv_cp_shard)`.

For deepseek v4 attention layers there are two general components:
sliding-window parts and compressed attention parts. The SWA treatment
is embarrassingly parallel and handled analogously to GLM. The
compressor components are not embarrassingly parallel and require
different handling. The compression step involves pooling along seq
dimension, which is what removes the embarrassingly parallel property
and necessitates cross cp-rank communication prior to kv formation. This
means that the `gather_for_cp` needs to occur at a comparatively earlier
step than in GLM, say: we never create a sharded version of `kv` (for
the compressed component) and instead use `gather_for_cp` to gather the
tensors required to create the unsharded `kv` directly.

A more memory optimized approach would only pass small windows of tokens
across CP ranks and then all-gather the small, post-compression tensors,
but we re-use `gather_for_cp` and go for simplicity here.

---------

Signed-off-by: Garrett Goon <44747910+garrett361@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-09-11 09:03:10 -04:00
550beb6f43 chore(deepseek_v4): production attention path cleanup (#3517)
Moves the eager-model helpers off the production path and into the eager
impl file for cleaner prod code. Also fixes a previous CI breakage where
we asserted on batch size == 1 which broke packing equivalence tests,
and performs other minor cleanup.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 12:39:44 -04:00
Matej SirovatkaandGitHub bad80b1a30 feat(models): add native Nemotron-H implementation (#3426)
Nemotron-H now runs as a native PyTorch module through PrimeRL Mamba-2,
shared attention, and unified MoE layers. Both Nano (regular MoE) and
Super (latent MoE) layouts are retained. Packed convolution and SSD
reset at document boundaries, and Mamba owns the full-sequence/head
redistribution required by Ulysses context parallelism. Checkpoint
conversion maps official per-expert and latent-expert weights into the
canonical runtime layout.

Updated against main (`daa72a91d`), retaining current fusion,
normalization, and CP interfaces. Restored LoRA adapter `mixer` names
and installed Mamba SSD through the GPU extra. The pinned upstream
source uses Triton without requiring the optional selective-scan CUDA
extension. Configuration guards and HF execution comparisons were
removed; existing packed-boundary tests exercise real GPU kernels.
Router compute follows `trainer.model.moe_router_dtype` (`float32` by
default, optionally `bfloat16`); the model does not force an override.

`NemotronHModel` and `NemotronHForCausalLM` both inherit
`NemotronHPreTrainedModel`, following the existing pattern used by other
architectures. The shared Nemotron base retains the config type and
architecture-specific conversion/CP hooks. Unused TP/PP plans, no-split
metadata, checkpointing flags, redundant attributes, and obsolete
`use_mamba_kernels` handling are removed. Shared model construction,
LoRA, LM-head patching, and weight-transfer code remain unchanged.
Broader removal of the model abstractions is deferred to a follow-up PR.

Garrett's config-docstring and unused-HF-attribute comments are
addressed. The broader context-parallel setter refactor and additional
gradient tests remain deferred.

## Validation

All GPU validation used Slurm-allocated Hopper H200s. Current revision
`f6d7a4033` restores the shared Nemotron base while retaining the
attribute cleanup. Ruff lint/format checks, factory
construction/dtype/inherited-hook checks, and all **15 existing model
tests** passed (Slurm job 343).

- Full unit suite: **699 passed, 11 skipped**, rerun after the nn.Module
cleanup (Slurm job 336).
- Targeted Nemotron, packed-boundary, and KL tests: **15 passed**, rerun
after removing the router override.
- H200 checks verified gate GEMM and weight-gradient dtypes for both
BF16 and FP32 router settings.
- Compiled two-GPU Mamba Ulysses: output, input-gradient, and reduced
parameter-gradient checks passed.
- Fused QKV + compiled selective activation checkpointing:
forward/backward and meta-buffer initialization passed.
- Eight two-GPU checkpoint-resume combinations: exact weights,
CPU-offloaded AdamW state, and next update across fused/unfused QKV and
FSDP shard placements.
- Official Nano checkpoint: exact key/shape conversion round trip,
**6,243 → 401 → 6,243 tensors**.
- `uv sync --all-extras --all-packages`, Ruff lint, and format checks
passed.

The 20-step run below was completed at `a7f798048` (Slurm job 339),
before restoring the original shared base. The preceding revision
`00746d6d2` was also validated: direct inheritance and the original
factory passed construction checks; compiled two-GPU Mamba and fused-QKV
selective-AC checks passed again (job 341). All 15 targeted unit tests
passed (job 340). The two-step end-to-end Nano run completed (job 342),
with mismatch KL **0.00475226** and **0.00522814**, finite gradients,
and three successful NCCL weight updates including startup. Compiled
Mamba/selective-AC and eight checkpoint-resume probes also passed again
on this code (jobs 337–338). The end-to-end run used
`nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16` on eight Slurm-allocated
H200s: four trainer GPUs with EP=4 and four inference replicas. The
native trainer used FlashAttention 3, compilation, selective activation
checkpointing, and NCCL weight updates. Reverse-text used batch size 64,
group size 8, sequence length 1024, and maximum completion length 512.
Optimization and reduction dtypes retained their defaults.

Launched with `uv run rl @ rl-module-cleanup.toml`. The config sets
`trainer.env_vars.TRITON_CACHE_DIR` to node-local `/tmp` to avoid
shared-home artifact read failures; no diagnostic hooks are present in
this run.

The automated review requests a math-environment table. This run uses
reverse-text and does not satisfy that environment-specific requirement:
the current math task requires a policy-aware container runtime, which
is unavailable on the validation nodes.

**20/20 steps completed**, with **21 successful NCCL weight reloads**
(startup plus every update). Mismatch KL: mean **0.0059826873**, maximum
**0.0076148757**, final **0.0071559078**. All step KL values and
gradient norms were finite. Super latent behavior was exercised by small
model tests and distributed probes; no full-size Super run was
performed.

| Step | Mean mismatch KL |
| ---: | ---: |
| 1 | 0.0061262716 |
| 2 | 0.0044362689 |
| 3 | 0.0046579577 |
| 4 | 0.0057872585 |
| 5 | 0.0052399668 |
| 6 | 0.0067561148 |
| 7 | 0.0045683677 |
| 8 | 0.0047115656 |
| 9 | 0.0063753380 |
| 10 | 0.0065832101 |
| 11 | 0.0062584030 |
| 12 | 0.0072330278 |
| 13 | 0.0066353143 |
| 14 | 0.0060227909 |
| 15 | 0.0053012762 |
| 16 | 0.0066529727 |
| 17 | 0.0055223401 |
| 18 | 0.0060145170 |
| 19 | 0.0076148757 |
| 20 | 0.0071559078 |

CI at `a7f798048`: Ruff, slim install, and CodeQL passed; remaining jobs
were running or queued at the last check. On the previous commit
(`a60d27578`): all 15 Nemotron tests passed. The GPU unit job had five
failures in unchanged DeepSeek-V4 tests (packed-batch assertions and
unsupported FP8 kernels on that runner); CPU unit tests, Ruff, slim
install, and CodeQL passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Large rewrite of a hybrid MoE/Mamba training path, checkpoint layout,
and distributed Mamba CP, with dependency pins that affect the whole GPU
stack.
> 
> **Overview**
> Replaces the Hugging Face–wrapped Nemotron-H stack with a **native
hybrid model**: one `NemotronHDecoderLayer` per block type (Mamba,
attention, MoE), a first-party **`NemotronHMamba2`** that uses FLA
packed causal conv plus **`mamba_ssm` Triton SSD**, and Ulysses CP via
**sequence↔head all-to-all inside the Mamba module** (the shared
`cp_mamba` helper is deleted).
> 
> **Checkpoint and config:** `NemotronHConfig` is realigned to current
HF field names and `layer_types`; conversion is **explicit per layer
type** instead of inferring from key presence (the old router-bias
`MapValue` shift is gone). Install/docs now pull **`mamba-ssm` from a
pinned git rev** through the **gpu** extra, with **`tilelang==0.1.12`**
pinned for vLLM compatibility; trainer init no longer disables
`use_mamba_kernels` or monkey-patches HF Mamba.
> 
> Tests drop HF parity checks and instead exercise native packed
boundaries, CP wiring on `NemotronHMamba2`, and existing KL/conversion
coverage.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f6d7a403332bd90d26efa3dcb4c8358a5e95f92e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-10 14:04:38 +02:00
samsjaandGitHub aa3a6522b4 feat(algo): add debug advantage algorithm (#3521)
## What

Adds a `debug` algorithm (`[orchestrator.algo] type = "debug"`) that
assigns the same constant advantage (default `advantage = 1.0`) to every
sampled token of every clean trainable trace, ignoring rewards entirely.

## Why

Purely a debugging feature for infra work: with constant advantages
every admitted rollout is trainable and every action token carries
gradient signal, so the full RL path — advantage transport, importance
ratios, trust region, trainer loss, optimizer, weight update — can be
exercised regardless of the reward function (e.g. to rule out "all-zero
advantages / nothing trainable" when smoke-testing a pipeline). The
config validator rejects `advantage = 0`, the exact failure this tool
exists to rule out.

## How

Follows the existing "a new credit-assignment scheme is a new named
class" pattern:

- `DebugAlgoConfig` in `prime_rl.configs.algorithm` (discriminated-union
member, `action_loss_type = "rl"`, nonzero-advantage validator)
- `DebugAlgorithm` (`score_episode` — the signal is rollout-local, no
group-relative work needed) registered in `ALGORITHM_CLASSES`

Intentionally not documented in `docs/` or the skills — it is a debug
tool, and the code docstrings are the reference.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Opt-in debug algorithm only; no changes to existing algo behavior or
production defaults.
> 
> **Overview**
> Adds a **`debug`** training algorithm for pipeline smoke tests: set
`[orchestrator.algo] type = "debug"` to assign the same constant
per-token advantage (default **1.0**) on every clean trainable trace,
**ignoring rewards**, so admitted rollouts always produce RL gradient
through the full stack (advantage transport, ratios, trust region,
trainer, optimizer).
> 
> **Config:** `DebugAlgoConfig` joins the `AlgoConfig` discriminated
union with `action_loss_type = "rl"` and a validator that rejects
`advantage = 0` (the “nothing trainable” case this mode is meant to rule
out). **Runtime:** `DebugAlgorithm` implements `score_episode` via
`iter_trainable_traces` + `assign_advantages`, registered in
`ALGORITHM_CLASSES` like other algorithms. Docstrings mark it as
infra-only—not a real training signal.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ce6ca60585b3f259780492b892157b356b0569cf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-10 00:19:14 +02:00
3f0c2e3b5a feat(trainer): select MoE compute by layer (#3518)
Select the model layers that use the configured MoE compute backend with
`model.moe.compute.apply_to`:

- `"all"` (default): all routed-expert groups.
- `"85%"`: the first 85% of model layers, rounded down; 48 layers
selects indices 0–39.
- `[0, 1, 2, 3]`: explicit zero-based model layer indices. `[]` selects
none.

Non-MoE blocks in hybrid models count toward indices and percentages.
Other expert groups use BF16 compute and transport while retaining the
configured dispatch backend and expert parallelism. Out-of-range indices
and invalid percentages fail early. Dense linear quantization is
unchanged.

```toml
[trainer.model.moe.compute]
type = "mxfp8"
apply_to = "85%"
```

BF16, DeepGEMM FP8 and MXFP8 configs inherit the common selector. NVFP4
inherits it in #3511. Inference precision remains configured separately.

First PR in the stack: main → #3518 → #3515 (filter flag) → #3513 (vLLM
upgrade) → #3511 (NVFP4).

Validation: 62 focused MoE/config tests passed on this main-based
branch, including all three forms through CLI/config round trips,
percentage rounding, hybrid-layer indexing, and invalid indices. Ruff
lint/format and whitespace checks passed. GB200 mixed DeepGEMM-FP8/BF16
forward/backward passed with an exact BF16 fallback output and unchanged
parameters/checkpoint keys. EP2 with layer-index selection verified
MXFP8 transport for the selected group, BF16 transport for the excluded
group, both forwards, and BF16 fallback backward. MXFP8 backward has a
separately reproduced CuTe TMA-alignment compiler failure in the
existing kernel; that kernel is unchanged here.

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Per-layer MoE precision and transport wiring affects forward/backward
numerics and expert-parallel paths; misaligned trainer vs inference
precision could skew RL logprobs if rollout config is not matched
manually.
> 
> **Overview**
> Adds **`model.moe.compute.apply_to`** so BF16, DeepGEMM FP8, and MXFP8
routed-expert backends can target **all layers**, a **leading
percentage** (e.g. `"85%"`, rounded down), or **explicit zero-based
layer indices** (including `[]` for none). Shared
**`MoEComputeConfigBase`** validates inputs and **`resolve_layers`**
maps selections to layer sets; out-of-range indices fail at resolve
time.
> 
> **`configure_moe_runtime`** maps selection onto language-model
**`layers`** (including VLM via **`get_language_model`**): selected MoE
modules get the configured grouped GEMM; others **fall back to BF16**
compute and matching token dispatch alignment. **MXFP8 torch transport**
is used only when that layer’s grouped GEMM is actually
**`MXFP8GroupedGemm`**, so excluded layers no longer take MXFP8
all-to-all when compute is partial. Startup logging reports selected vs
total MoE layers.
> 
> Docs describe hybrid-layer counting, dense-quant independence, and RL
rollout/inference precision alignment. Unit tests cover config/CLI
round-trips and BF16 fallback without loading MXFP8 backends when
nothing is selected.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f367d4866ddcc0debd53faebe8944f096eb3ba44. 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-10 00:11:35 +02:00
6b0d9e504b fix(deepseek_v4): hardware guards for unrunnable gpu CI tests (#3512)
Custom deepseek v4 flash attention requires more SMEM than some gpus
(like the current CI runners) have. Skip the tests in those cases.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 11:06:46 -04:00
751a235af8 perf(deepseek_v4): score the Lightning Indexer with the fused FP8 kernel (#3504)
Second of three stacked PRs, builds on #3479.

Scores the DeepSeek V4 Lightning Indexer with `fp8_indexer`, the fused
Triton kernel GLM DSA already runs, dropping the eager float32 `(batch,
seq_len, heads, entries)` intermediate.

The indexer now rejects a batch larger than 1 instead of looping over
the batch axis: the entry ranges it hands the kernel are built from
sample 0's causal thresholds, so every other sample would have been
scored against the wrong range.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 10:51:22 -04:00
Matej SirovatkaandGitHub daa72a91d8 feat(models): add native GPT-OSS implementation (#3424)
## Summary

Replace the Transformers/hub-kernel GPT-OSS runtime with a Prime-owned
model, FA4 attention with learned sinks, and canonical grouped experts.
BF16 GPT-OSS checkpoints load through lossless expert-layout conversion;
inference policy updates route prepared expert and sink tensors through
vLLM's registered parameter loaders.

This branch targets `main` and supports runtime QKV and gate/up fusions,
canonical checkpointing, and the CP capability interface. Main's
dependency pins are retained; the obsolete `gpt-oss` hub-kernel extra is
removed.

## Supported configuration

- `model.impl = "auto"` selects native GPT-OSS. Validated checkpoint:
`unsloth/gpt-oss-20b-BF16`. Original MXFP4 checkpoint loading is outside
this change.
- Direct FA4 calls preserve learned sinks, sliding/full attention, and
packed-document boundaries. FA4 explicitly returns `(output, lse)`;
FA2/FA3 default calls return a tensor.
- Ring and Ulysses CP preserve sink gradients; common expert parallelism
and runtime fusions are supported.
- Hopper is the validation target. The vLLM loader patch handles
prepared expert and sink tensors with the pinned vLLM.

GPT-OSS and shared FA4 attention no longer use `torch._dynamo.disable`.
There is no forwarding wrapper around the native FA4 function. Native
configuration/input guards and HF GPT-OSS execution-comparison tests are
removed; checkpoint conversion and CP checks remain. There are no
example or skill changes relative to main.

## Context-parallel attention

Every CP helper replaces an attention compute method. GPT-OSS's ring
adapter is separate because the shared ring custom operators have no
learned-sink input or sink-gradient output. It uses differentiable K/V
gathers and FA4 to preserve those gradients. Its Ulysses adapter passes
the model's FA4 function, scale, and sinks into the shared sink-aware
Ulysses implementation. That thin adapter is an organizational choice;
directly assigning the existing generic closure would omit these
arguments.

## Validation

- H200 full unit suite after cleanup: **701 passed, 11 skipped**. After
the final direct-FA4 assignment, the targeted checkpoint roundtrip and
compiled attention/CP checks passed again.
- Cold `torch.compile(fullgraph=False)` forward/backward and
eager-output agreement passed for GPT-OSS and shared FA2/FA3/FA4
attention.
- Two-GPU eager and compiled GPT-OSS ring/Ulysses output and
Q/K/V/sink-gradient checks passed. Compiled shared FA4 Ulysses output
and Q/K/V gradients passed on both ranks.
- The CP tests reuse one process group across cases, avoiding
teardown/reinitialization reconnect failures.
- Earlier integration validation covered eight checkpoint/resume
combinations and a real 20B export matching all 411 checkpoint
keys/shapes and sampled tensor values.
- Ruff lint/format and git whitespace checks passed.

## Final 20-step H200 RL run

After all code changes, `uv run rl @ config.toml` completed through the
standard Slurm launcher on eight H200 GPUs: four trainer and four
inference GPUs, `unsloth/gpt-oss-20b-BF16`, reverse-text, batch 64,
group 8, sequence length 1024, completion budget 512, EP=4, QKV/gate-up
fusions, compilation, selective activation checkpointing, and NCCL
policy reloads. Rollout concurrency starts at 32 and is capped at 64.

Slurm job **326 completed with exit code 0**, in 24m42s. All **20
optimizer steps** completed and inference acknowledged **21 successful
reloads** (startup plus 20 updates). Rollout errors were 0%. The short
completion budget truncates most reasoning; this validates numerical
consistency and pipeline operation.

The table reports `mismatch_kl/all/mean` on commit `c3fe30c29`.

Completed steps: 20
Mean of step means: 0.0014423477
Min: 0.0007825278
Max: 0.0027635854

| Step | Mismatch KL |
| ---: | ---: |
| 1 | 0.0007825278 |
| 2 | 0.0008648058 |
| 3 | 0.0010610037 |
| 4 | 0.0015761884 |
| 5 | 0.0012348450 |
| 6 | 0.0023151361 |
| 7 | 0.0016181732 |
| 8 | 0.0012400812 |
| 9 | 0.0010534789 |
| 10 | 0.0017238446 |
| 11 | 0.0027635854 |
| 12 | 0.0023905332 |
| 13 | 0.0015134896 |
| 14 | 0.0014993388 |
| 15 | 0.0011815884 |
| 16 | 0.0012801469 |
| 17 | 0.0012795344 |
| 18 | 0.0012338012 |
| 19 | 0.0011749482 |
| 20 | 0.0010599031 |

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches core training attention/MoE and vLLM weight loading for a new
architecture; mistakes could affect numerics or checkpoint load, though
conversion and CP tests mitigate this.
> 
> **Overview**
> Replaces the Transformers / hub-kernel GPT-OSS path with a
**Prime-owned** `gpt_oss` stack: custom config, packed-batch forward
(`seq_lens`), grouped MoE, and **FlashAttention 4** attention with
**learnable sink** parameters wired through ring and Ulysses context
parallelism (including sink gradients).
> 
> **Training/runtime:** Drops Hopper-only checks and explicit hub-kernel
enablement; hub kernels stay disabled globally. Shared FA4 call sites
now handle `(output, lse)` returns and drop `torch._dynamo.disable`
wrappers. Ulysses varlen attention gains optional `learnable_sink`
sharding.
> 
> **Inference:** Registers a vLLM startup patch to load prepared BF16
MoE expert and **`.sinks`** tensors via weight loaders until upstream
vLLM catches up.
> 
> **Packaging/docs:** Removes the `gpt-oss` optional extra (`kernels`
dependency); docs point at BF16 checkpoints (e.g.
`unsloth/gpt-oss-20b-BF16`) and SM90/SM100+ for FA4 sinks. Tests add
2-GPU ring/Ulysses CP checks and drop HF MoE parity.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c3fe30c2956c167563821a0542ec587069704b00. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-09 16:33:45 +02:00
dad79d1ce8 feat(inference): add Dynamo admin plane integration (#3491)
## Overview

Add a minimal Dynamo admin-plane integration for Prime-RL weight
synchronization. Prime-RL discovers and pins one Dynamo inference
worker, routes administrative operations directly to it, propagates
configured authentication to the worker client, and uses the existing
custom NCCL sender and receiver for policy updates.

This PR is intentionally limited to a singleton text-model RL training
loop. It excludes managed Dynamo process launch, multi-worker or
multi-rank topology, multimodal training, routed-expert transfer, and
LoRA. Managed process launch is the stacked follow-up #3493; the
unrelated `skip_gather` compatibility fix remains isolated in #3492.

## Changes

- Add optional Linux-only Dynamo dependency support and compatibility
metadata for the upstream Pydantic bound.
- Add `orchestrator.model.client.dynamo` with `enabled` and optional
`discovery_url`.
- Derive an omitted discovery URL from the OpenAI base URL by stripping
its path and incrementing its explicit non-default port.
- Discover exactly one model-matching worker and pin its instance
identity and private admin origin.
- Propagate static headers, environment-derived headers, and a non-empty
API-key bearer token to Dynamo discovery and worker administration.
- Initialize Prime-RL's existing NCCL communicator through Dynamo
collective RPC and transfer policy weights without adding another
transport protocol.
- Preserve existing filesystem and NIXL behavior outside the
Dynamo-specific NCCL path.
- Add `examples/basic/dynamo/rl.toml` and a runnable README with
loopback-safe commands, endpoint checks, GPU isolation, trusted-network
guidance, and the Prime-RL command.
- Keep the `uv.lock` conflict resolution isolated from upstream source
changes.

## Validation

### Local

- `uv lock --check` — passed at functional source head
`55d8f2f658b543aea08d13b4ce53bb6ec91ab82d`.
- `uv run --frozen pytest -q tests/unit/inference/test_dynamo.py` — 15
passed.
- Ruff lint and format checks — passed for all five changed Python
files.
- `git diff --check origin/main...HEAD` — passed.
- Signed conflict-resolution commit
`dc1e7910977e8a847d6081ceb204f779081ebe36` changes only `uv.lock` (39
additions, 2 deletions in that commit).
- `git merge-tree --write-tree HEAD origin/main` — passed without
conflicts at current head.
- The current `uv.lock` PR delta against main is 139 additions and 17
deletions.

### Kubernetes

- The exact functional source head
`1cdcaff56972aab55ed1456a2829555052285099`, with the separate #3492
`skip_gather` compatibility overlay required by the installed vLLM-RS
build, completed a five-step Qwen3-0.6B Math run in `bis-rl-3` over SSH.
- Trainer and orchestrator completed steps 1 through 5; vLLM received
startup policy `v0` and updates `v1` through `v5`; every step reported
0% rollout errors and 0% truncation; post-update generation succeeded;
the runner exited zero.
- The subsequent authentication change at
`dec4f82b66c3a231f56f8b759c1c4dcb20685a8b` was also exercised in the
stacked #3493 managed-Dynamo five-step run, which completed 1,001
generation requests and policy updates `v0` through `v5`.
- Current-head commits after that runtime validation modify only
`uv.lock` and one trailing blank line; no production behavior changed.

## Operational notes

- Keep Dynamo discovery and worker administration on a trusted loopback
or private network.
- The Dynamo frontend must expose the native generate route with
`DYN_VLLM_ENABLE_INFERENCE_V1_GENERATE=1`.
- The included vLLM-RS recipe uses `top_k = 0` because that backend
rejects Verifiers' default `top_k = -1`.

---------

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-09-08 21:03:02 -07:00
dd2dd5461b prime-runs (#3459)
Replaces `monitors/prime.py`'s`TrainRun` with `pr.init(kind="train",
...)`.

## What moved where

| was in prime-rl | now |
| --- | --- |
| `TrainRun.create` / `$RUN_ID` attach | `pr.init(kind="train", model=,
environments=, training=pr.TrainingSpec(...), config=, ...)` /
`pr.init(kind="train", id=$RUN_ID)` |
| `TrainRun.log_metrics` (fire-and-forget task per POST) |
`run.log_metrics(values, step=)` — a queue put; the SDK's uploader owns
retries, `Retry-After`, backpressure |
| `episodes_to_parquet_bytes` + `SAMPLE_SCHEMA` + presign→PUT→confirm |
`prime_runs.projection` + the SDK's training samples sink (same schema,
same flow) |
| the `step % 10` cadence in `log_episodes` | the sink
(`step_interval=10`), keyed on each episode's `run.work.step` — the
`TrainRunInfo` the dispatcher stamps |
| `finalize` → `POST /finalize`, fallback `set_status` | `run.finish()`
— drain, then an idempotent finalize; 409 on the failure path is treated
as already-closed |
| atexit `_mark_failed` | the SDK's atexit hook reports **crashed**
(with a message); an attached run's failure marking stays with the
launcher, as before |

The `kind == "train" and subset == "effective"` cohort filter stays
here. The monitor keeps `sanitize()` so dropped non-finite metric paths
are still named in the log (the SDK would drop them silently).
`$PRIME_API_BASE` still works — it historically points at
`…/api/v1/rft`, so the monitor strips what the SDK re-adds.

## Decisions

- **Step keying.** The samples sink keys each episode by the step it was
*dispatched* at (`run.work.step`), not the batch step; the platform
keeps one Parquet object per upload and the viewer unions every object
under a step, so an off-policy episode landing in a later batch adds an
object rather than replacing one, and each object numbers its
`sample_id`s in its own range (SDK side, `aba26790`). "Step N" in the
sample viewer therefore means dispatched at N, while the metrics at N
describe the batch trained at N.
- **Run identity.** The orchestrator keeps the launcher's `PRL_RUN_ID`
(or a local uuid) as the run identity for episodes, W&B and sandbox
labels, exactly as on `main`. The SDK keys every uploaded record to the
platform run (`run.id` / `run.type` on the uploaded copy, `work` kept),
so Prime Traces documents carry the id the dashboard shows without the
orchestrator learning it.

## Dependency

`prime-runs[train]>=0.1.1` from PyPI
([0.1.1](https://pypi.org/project/prime-runs/0.1.1/),
PrimeIntellect-ai/prime#896); the lock carries `prime-runs 0.1.1` +
`prime-traces 0.0.3` from the registry. The monitor's own unit tests run
in CI; there is no GPU-free end-to-end path for the training seam, so
the RFT contract was verified by reading the platform's `/api/v1/rft/*`
and `/api/internal/rft/*` routes against the SDK's calls.

## Hosted managed runs

Since PrimeIntellect-ai/platform#4885, hosted managed runs start the
orchestrator with `--monitors.prime.name`, `RUN_ID`, a per-run token in
`PRIME_API_KEY` and `PRIME_API_BASE=<platform>/api/internal/rft`.
prime-runs 0.1.1 (PrimeIntellect-ai/prime#895) addresses that internal
router and sends the run's token in `x-api-key`, the header it
authenticates on; 0.1.0 only spoke `/api/v1` with a Bearer header and
would have left those runs silently unmonitored. This monitor's
`_base_url()` passes `$PRIME_API_BASE` minus the trailing `/rft`, which
0.1.1 accepts, so the floor bump is the whole change. External runs
(prime-rl launched outside the platform) were never affected.

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

https://claude.ai/code/session_01Fk5fBAAaTiPfJ5UpNyqxXR


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how training runs register and upload to the Prime platform
(including hosted `$RUN_ID` / internal RFT paths); misconfiguration now
fails launch instead of silently skipping monitoring, but orchestrator
run identity for W&B stays unchanged.
> 
> **Overview**
> **Replaces** the in-repo `TrainRun` HTTP/Parquet implementation in
`PrimeMonitor` with **`prime-runs[train]>=0.1.1`**, so run registration
(or `$RUN_ID` attach), metrics streaming, episode sample uploads,
finalize, and crash reporting are owned by the SDK uploader instead of
custom `httpx` + fire-and-forget tasks.
> 
> The monitor layer is now a thin adapter: `pr.init(kind="train", …)` on
startup, `run.log_metrics` / `run.log_episodes` via `asyncio.to_thread`,
and `run.finish()` with a **60s** drain timeout. Local behavior kept
where it matters: non-finite metrics are still **sanitized with named
warnings**, only **train / effective** episodes are forwarded, and
**`$PRIME_API_BASE`** is normalized for the SDK. Episode
**every-10th-step** upload cadence moves into the SDK sink (keyed on
dispatch step on `run.work`).
> 
> **Docs** in `training.md` describe the SDK, team allowlisting,
**`PRIME_RUNS_MODE=disabled`**, and **`RUN_ID`** attach.
**Lock/pyproject** add `prime-runs` and transitive **`prime-traces`**,
with fast-track resolver entries.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
aed9bbfb509367d7cad1fb8cd869c2b835fa8860. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-08 20:06:21 -07:00
cea63f9ef3 feat(deepseek_v4): sparse attention kernels (#3479)
Adds a TileLang implementation of the flash-attention style kernel for
DS V4. Based on the similar kernel used for GLM. The kernel is wired
through the DS V4 model and the attention arguments are refactored to
naturally adapt to the shape expected by the efficient kernel (e.g. no
more `attention_mask` realization).

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 21:11:30 -04:00
6a360c3029 feat(trainer): add runtime gate/up and qkv fusions (#3451)
## Summary

Adds runtime parameter fusions, on by default: `model.fusions` packs
parameters that are always computed together into one tensor, turning
several GEMMs into one. Fusions are runtime-only — checkpoints keep the
canonical parameter names and shapes, so a run can enable or disable one
at any point and still load its own checkpoints.

```toml
[trainer.model.fusions]
enabled = ["gate_up", "qkv"]   # default; [] disables
raise_on_fail = false          # default: a fusion no module supports logs a warning
shard_fused_on_dim1 = false    # default; experimental zero-copy checkpointing, see Notes
```

- **`gate_up`** — each gated MoE expert's `gate_proj` and `up_proj`
become one `[num_experts, 2 * intermediate_size, hidden_size]` weight.
The forward is a single grouped GEMM whose transpose and chunk are
views; there is no weight reshape.
- **`qkv`** — an attention layer's `q_proj`, `k_proj` and `v_proj` (and
their biases) become one `nn.Linear`. `FlashAttention.project_qkv` is
shared with `LagunaFlashAttention` so both support it.

## Review fixes and verification (2026-09-08)

Review found and fixed three previously unchecked checkpoint cases:

- **Exports and model-only resume:** DCP returns `{}` when no optimizers
are supplied. Both fusion optimizer-state translators now preserve that
empty dictionary instead of raising `KeyError: 'state'`.
- **AdamW resume with optimizer-state CPU offload:** packed parameters
restored their moments but lost scalar state, including AdamW's step
counter. The write-back now restores scalar tensors and non-tensor state
as well as packed moments.
- **Full CPU offload checkpoint save:** splitting packed CPU optimizer
tensors requires CPU collectives. Both training entrypoints now enable
Gloo alongside NCCL when full offload is enabled.

Verified on H200s through Slurm job **232**:

- The complete existing unit suite and Ruff checks passed.
- All **32 distributed checkpoint combinations** passed: AdamW/Muon,
fused/unfused save and load, default/dimension-1 sharding, and
optimizer-state CPU offload on/off. Canonical weights, optimizer state,
and the next update with identical gradients were bitwise exact.
- Full CPU offload completed model-only resume/save and optimizer
resume/save. All **311 model tensors** were exact after model-only
resume; **931 model/master/step tensors** were checked across optimizer
resume, with unchanged weights and correctly incremented counters.
- Expert outputs and matrix-weight gradients, and QKV projections
with/without bias, were exact. BF16 input-gradient relative differences
were about 0.29%; bias-reduction variation also occurred in repeated
unfused calculations.
- All **11 RL/SFT training, resume, and export checks** passed (6 SFT, 5
RL). BF16 and FP8 exports reload in HF, and direct DCP-to-FP8 matches
chained conversion byte-for-byte. RL completed 20 steps with final
reward **0.8362** and passed its mismatch-KL checks.

The dashboard browser checks cannot install OS dependencies on this
cluster because they require sudo. The prior A6000 benchmark CI job was
cancelled without executing any steps; its hardware-specific baseline
was not validated on H200. Blackwell-only MXFP8 was not exercised.

Verification artifacts: `/home/matej/prime-rl-verify/pr3451-20260908/`.
This review changes only the fusion helpers and RL/SFT distributed
initialization; it adds no tests or skill changes.

## Design

A fusion is a function that replaces some of a module's parameters with
one `PackedParameterSpec`, which owns the split sizes, the packing
dimension, and the canonical names it stands in for. Everything else
falls out of that description, so a new fusion adds no machinery:

- **Checkpoints** — state-dict hooks registered alongside the packing
swap the packed entry for its canonical entries on the way out and back
on the way in. The canonical entries are views of the packed storage
when the packing dimension is unsharded (`gate_up`: experts shard on dim
0, pack on dim 1); a DTensor sharded along the packing dimension (`qkv`:
FSDP shards dim 0) is unsharded by the split, so those entries are
replicated copies. Anything that loads into the state dict in place
therefore packs the loaded entries back explicitly
(`write_back_loaded_packed_parameters` after the HF weight load,
`write_back_loaded_packed_optimizer_state` /
`join_loaded_optimizer_state_for_runtime` on resume). DCP therefore
writes `gate_proj`/`up_proj` and `q_proj`/`k_proj`/`v_proj` and never
sees the packed layout. The optimizer has no equivalent hook (its
`state_dict()` hooks fire while state is still keyed by integer param
ids, before DCP maps them to FQNs), so the same translation is applied
explicitly around `get_state_dict` in `AppState`.
- **Muon** — `PackedParameterSpec.muon_matrix_partitions` yields the
split sizes when the packing is on the output dimension. Those go to
Dion's new `matrix_partitions` argument, which orthogonalizes each
logical matrix separately on the one physical parameter, with a
per-partition learning-rate adjustment. A packed parameter therefore
trains exactly as the parameters it replaces would — including
per-projection scaling for grouped-query attention — while keeping a
single momentum tensor. Uses the merged matrix-partition support in the
pinned `samsja/dion@99e5f7e` (samsja/dion#3).

Modules advertise fusions through `supported_fusions`; requesting one
that no module supports logs a warning, or fails at startup with
`raise_on_fail = true`. Fusions are skipped when LoRA is enabled, since
it targets the unfused projections.

## Performance

Qwen3-30B-A3B, 8×H200, EP=8, `seq_len=8192`, torch EP dispatch,
selective AC, compile, no offload. Mean throughput over steps 3–6:

| precision | unfused | fused | |
|---|---|---|---|
| BF16 | 37636 tok/s (MFU 13.3%) | 37352 tok/s (MFU 13.2%) | −0.8% |
| FP8 (`quantization.type=fp8` + `moe.compute.type=deepgemm_fp8`) |
30594 tok/s (MFU 10.8%) | 34062 tok/s (MFU 12.0%) | **+11.3%** |

BF16 is unchanged, as expected: the separate GEMMs already read the same
activation, so there is nothing to save. The gain is under FP8, where
each GEMM quantizes its activation independently — unfused casts the
same tensor 3× for q/k/v and 2× for gate/up, fused casts it once. Peak
memory is unchanged (101.8 → 102.0 GiB).

## Validation

Correctness, on GPU:

- Forward output and all weight gradients of the fused grouped experts
are **bitwise identical** to the unfused module; the packed q/k/v
projections are bitwise identical to the separate ones. Only the MoE
input gradient differs (max abs `1.5e-5` on a `2.4e-3` scale), by one
bf16 accumulation rounding from doing one `[T, 2I]` dgrad instead of two
`[T, I]`.
- Muon updates on a packed parameter are **bitwise identical** to
updating the parameters it replaces, over multiple steps, for both
fusions.
- All four fused/unfused optimizer checkpoint round trips are exact,
including the next optimizer update after each. For `gate_up` the
checkpoint entries alias the packed storage; for `qkv` under FSDP they
are replicated copies of the q/k/v weights and their optimizer state,
materialized transiently on every rank at load and checkpoint time (~1
GB bf16 weights + ~2 GB fp32 Muon momentum for Qwen3-30B-A3B).
`shard_fused_on_dim1 = true` (experimental, default off) shards fused
2-D parameters along dim 1 via FSDP2's `shard_placement_fn`, so the
split stays a local view: the q/k/v weight entries alias the packed
storage and `model.state_dict()` holds 0.1 MiB extra instead of 72 MiB
on the mini model (0 / 144 → 72 / 72 weight entries aliasing; biases
stay copies, having no second dimension). It is not a correctness fix on
its own — biases would still load as zero and the optimizer-offload
resume path replaces its state tensors after the template is built, so
the explicit write-back stays in place with the flag on or off.
Constraints: `hidden_size % dp_shard == 0` (FSDP2 raises otherwise) and
an extra chunk-cat per all-gather of dim-1 shards. #3486 measured the
placement alone and is closed in favour of this flag.
- DCP metadata for a fused EP=2 checkpoint contains 94 `gate_proj` and
94 `up_proj` entries and zero `gate_up_proj` entries.

End to end on SLURM (2 GPUs, EP=2, compiled, Muon, both fusions unless
noted):

| run | result |
|---|---|
| BF16 fake-data training + checkpoint save | ✅ |
| resume: fused ckpt → fused runtime | ✅ |
| resume: fused ckpt → **unfused** runtime | ✅ |
| resume: unfused ckpt → **fused** runtime | ✅ |
| optimizer-state CPU offload, save + resume | ✅ |
| DeepGEMM FP8 expert compute | ✅ |
| pretrained `mini-glm-moe` RL run with vLLM weight reload | ✅ mismatch
KL `0.0001` at both steps |

Plus `ruff format`/`ruff check`, and `pytest tests/unit/train/models
tests/unit/test_configs.py` (`215 passed, 3 skipped`), including a new
`tests/unit/train/models/test_fusions.py`.

## Notes

- `pyproject.toml` and `uv.lock` pin `samsja/dion@99e5f7e`, which
contains the merged matrix-partition support from samsja/dion#3.

## Verification on merged `main` (2026-09-04)

Branch merged with `main` (no conflicts) and re-verified on 8×H200 nodes
via SLURM. `ruff check`/`ruff format --check` clean; `pytest tests/unit
-m "not gpu"`: 536 passed, 1 skipped; `pytest tests/unit -m gpu`: 81
passed, 8 skipped.

**Numerics against an fp32 reference** (`samsja/mini-glm-moe`, single
GPU, no FSDP, 512 random tokens; reference is HF `Glm4MoeForCausalLM` in
fp32 eager). Whole-model outputs are not bitwise identical between fused
and unfused bf16 — the packed GEMMs take a different accumulation path —
but the fused model is exactly as close to fp32 as the unfused one:

| model (bf16) | logits mean abs diff vs fp32 | KL(fp32 ‖ model) | grad
rel. err vs fp32: q/k/v · experts gate/up · rest |
|---|---|---|---|
| unfused | 7.64e-3 | 3.97e-5 | 4.52e-2 · 4.96e-2 · 4.48e-2 |
| fused `qkv` | 7.64e-3 | 3.82e-5 | 4.14e-2 · 4.81e-2 · 4.12e-2 |
| fused `gate_up` | 7.22e-3 | 3.83e-5 | 4.52e-2 · 5.19e-2 · 4.51e-2 |
| fused both | 7.27e-3 | 3.88e-5 | 4.31e-2 · 4.87e-2 · 4.27e-2 |
| HF bf16 sdpa (noise floor) | 7.72e-3 | 4.48e-5 | 4.48e-2 · 5.19e-2 ·
4.46e-2 |

Fused vs unfused state dicts are bitwise identical after loading, and
each packed parameter equals the concatenation of the parameters it
replaces.

**Fake-data training matrix** (`mini-glm-moe`, 2 GPUs, EP=2, Muon,
compile + AC on, `ckpt.interval=5`, 10 steps), all runs complete without
errors:

| run | result |
|---|---|
| fused / unfused, optimizer offload on / off | ✅ losses agree to ≤ 5e-4
relative on every step |
| `shard_fused_on_dim1 = true`: load, resume (both offload paths), fused
↔ unfused resume, 10-step loss vs unfused | ✅ (verified with this code
before the flag existed; see #3486 for the measurements) |
| fused ckpt → fused resume, fused ckpt → unfused resume | ✅ post-resume
losses agree to ≤ 1e-3 relative |
| unfused ckpt → fused resume vs unfused ckpt → unfused resume | ✅ |
| the same three resumes with optimizer-state CPU offload | ✅ |
| DeepGEMM FP8 (`quantization.type=fp8`,
`moe.compute.type=deepgemm_fp8`), fused and unfused | ✅ |

(Resumed runs deliberately diverge from the un-interrupted run:
`FakeDataLoader` reseeds from a batch counter that restarts at 0, so a
resume replays the first batches. Fused and unfused resumes see
identical data and are compared against each other.)

**RL end to end** (`configs/ci/integration/reverse-text-moe/start.toml`,
custom impl, EP=2, 2 trainer GPUs + 1 vLLM GPU, 20 steps, filesystem
weight broadcast): fused `mismatch_kl/all/mean` 1.8e-4–2.2e-4 on every
step vs 1.9e-4–2.1e-4 unfused.

**Fix included in this branch.** Before `fix(trainer): load packed
parameters and their optimizer state explicitly`, the same runs showed
the `qkv` fusion training from zero attention weights: the HF weight
load wrote into the replicated q/k/v copies, every q/k/v tensor in a
fused checkpoint was exactly 0, the fused/unfused step-1 loss differed
by 20% reproducibly under both bf16 and FP8, and the RL run aborted with
no trainable rollouts. A fused resume also lost the Muon momentum of
every packed parameter (verified with lr=0: momentum after resume was
1.00× instead of 1.95× the saved value; both fusions with optimizer CPU
offload, `qkv` without). With the fix, loaded weights are bitwise
identical to the source and momentum is restored on both resume paths.
Full optimizer offload (`model.full_offload`) with fusions was not
exercised. MXFP8 expert compute needs Blackwell and could not be tested
on H200.

## Cluster verification with merged Dion (2026-09-05)

Pinned `samsja/dion@99e5f7e` (merged samsja/dion#3) and refreshed
`uv.lock`; its tree is identical to the prior fork pin. Synced with `uv
sync --all-extras --inexact`, then ran GPU verification through Slurm on
H200s:

- 10 prime-rl fusion/activation-checkpointing tests, 13 Dion single-GPU
tests, and 4 Dion distributed tests passed.
- All **16 distributed checkpoint combinations** passed: fused/unfused
save and load, default/dimension-1 sharding, and optimizer-state offload
on/off. Canonical weights, optimizer state, and the next Muon update
with identical supplied gradients were **bitwise exact**.
- **13 compiled EP=2 training/resume variants** completed on
`samsja/mini-glm-moe` (512-token fake batches): both fusion modes, all
four resume combinations, state offload, dimension-1 sharding, and
DeepGEMM FP8. Fused/unfused BF16 losses differed by at most **0.031%**
across the three initial steps.
- All **406 pretrained model tensors** were bitwise exact in the zero-LR
checkpoint and after its offloaded resume. All 13 variants saved
canonical model/optimizer projection names, with no packed `qkv_proj` or
`gate_up_proj` entries.
- The real **2-step RL run with vLLM weight reloads** completed with
mismatch KL **0.00019046 / 0.00019005**. Fake-data runs use random
inference logprobs, so their mismatch KL is not a trainer/inference
agreement metric.
- H200 module checks: gate/up outputs and matrix-weight gradients, plus
Q/K/V outputs with/without bias, were exact. BF16 MoE input-gradient
relative differences were ~0.29%. Bias reductions in an all-BF16 module
varied ~1.5%, also reproduced by repeating the unfused calculation
itself.

Slurm evidence: 147/148 (test suites), 149 (RL), 150/158 (checkpoint
equivalence), 153 (training matrix), 157 (saved checkpoint inspection).
Job 148's test suites passed before an overly strict ad-hoc BF16 bias
assertion stopped that script; the numerical diagnostic was resolved
separately. Full optimizer offload and Blackwell-only MXFP8 were not
exercised.

## CI collection fix (2026-09-05)

The `reverse_text` integration job failed before running any tests
because importing `prime_rl.utils.weights` first triggered a circular
import through the model registry and `fusions`. Import
`PreTrainedModelPrimeRL` inside `convert_state_dict_to_hf`, its only
use, so loading weight utilities no longer eagerly imports the model
registry.

Reproduced the failing import locally before the fix. After the fix,
standalone collection of `test_reverse_text.py` succeeds (6 tests), the
complete integration suite collects (38 tests), and all 6 fusion unit
tests pass. Ruff lint/format checks and `git diff --check` pass.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core training paths (FSDP sharding, weight load, DCP optimizer
state, Muon) and defaults fusions on; incorrect packing/load logic would
corrupt weights or momentum on resume, though extensive
checkpoint/resume testing is described in the PR.
> 
> **Overview**
> Adds **runtime parameter fusions** (on by default via
`[trainer.model.fusions]`) that pack related weights into single tensors
so MoE **gate/up** and attention **q/k/v** run as one GEMM each, while
**checkpoints and exports still use canonical names** (`gate_proj`,
`q_proj`, etc.).
> 
> A new **`fusions` module** implements packing (`PackedParameterSpec`),
state-dict hooks, HF/DCP load **write-back** for packed weights, and
explicit **optimizer-state split/join** around distributed checkpoint
save/load (including CPU-offload resume). Optional
**`shard_fused_on_dim1`** wires FSDP2 **`shard_placement_fn`** for
experimental zero-copy fused weight/optimizer I/O.
> 
> **Attention and MoE layers** advertise fusions through
`supported_fusions`; forwards use **`project_qkv`** / a single grouped
**`gate_up`** GEMM when fused. Fusions are **skipped with LoRA**.
**Muon** gets **`matrix_partitions`** from packed params via an updated
**dion** pin. Docs and unit tests cover config and canonical state-dict
behavior.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
52e736c685485fdbca109c86721017ab8065f65d. 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 (1M context) <noreply@anthropic.com>
2026-09-08 19:47:47 +02:00
samsjaandGitHub 04a61d3b75 fix: warm Muon all-to-all connections during optimizer initialization (#3490)
## Summary

Automatically establish the NCCL peer connections used by Dion's Muon
optimizer immediately after constructing Muon and before returning it to
the trainer.

The warm-up runs only for Muon. It covers the exact main optimizer
process group and, when expert parameters use expert parallelism, the
separate expert-shard process group. Single-rank and non-NCCL groups
remain no-ops; AdamW, SGD, and other optimizers are unchanged.

This is a required correctness workaround for a reproducible multi-node
GLM-4.5-Air first-step deadlock. The source now documents that optimizer
refactors must preserve the warm-up, its process groups, and its
placement between Muon construction and the first optimizer step.

## Failure signature

Pretrained GLM-4.5-Air training with Muon reproducibly stalled while
submitting the first optimizer all-to-all on two nodes. All 16 ranks
reached the collective, but only rank 0 enqueued it successfully; ranks
1–15 remained inside submission until the NCCL watchdog fired.

The clearest controlled failure was job 1182:

- Nodes `qpn01gpu009` and `qpn01gpu011`, 16 GPUs total.
- Pretrained eight-layer GLM-Air reproduction with CP4, EP8/automatic
expert mesh, BF16 compute, and optimizer-state offload.
- First Muon all-to-all was NCCL sequence 67 with 50,331,648 BF16
elements per rank.
- The watchdog fired after 182 seconds.
- Setting `NCCL_CUMEM_ENABLE=0` did not resolve it.

This was not a generic inability of the nodes to communicate: Adam
training and standalone all-reduce/all-to-all controls completed on the
same cluster. Fake-weight and reduced-model tests further isolated the
trigger to Muon's pretrained-model initialization state and first bulk
all-to-all.

## Implementation

`_warmup_muon_mesh` takes the `DeviceMesh`, resolves its single process
group, and performs a bulk BF16 list all-to-all matching Dion's
communication path, waits for completion, and synchronizes CUDA before
releasing its temporary buffers. A scalar collective is intentionally
not used because it may not initialize the same bulk-transfer peer
channels. Meshes with more than one dimension (the replicate-only world
mesh) have no single group and are skipped; Dion's Muon only accepts 1-D
meshes there anyway.

The ordering is part of the fix:

1. Construct the Dion Muon optimizer.
2. Warm Muon's main distributed NCCL group.
3. If expert parameters and EP are active, warm the independent
expert-shard NCCL group.
4. Return the optimizer only after both required warm-ups complete.

The temporary allocation is approximately 12 MiB per peer for send plus
receive buffers. No config flag is introduced because making this
optional would allow the known deadlock to recur.

Patch scope remains one optimizer source file. There are no
trainer-loop, dependency, precision, optimizer-offload, allocator, Dion,
or experiment-config changes.

## Validation

- Ruff lint/format and whitespace checks passed.
- Existing configuration tests passed: 70 passed, 67 deselected.
- Job 1183, reduced pretrained model with early connection warm-up: one
full step passed on all 16 ranks; 42.6 seconds, loss 15.4930, gradient
norm 49.0578, clean exit.
- Job 1184, full 46-layer pretrained GLM-4.5-Air with the earlier
pre-model-load placement: three fake-data steps passed with finite
losses and nonzero gradient norms.
- Job 1185, full 46-layer model with the final optimizer-construction
placement in this PR: three steps passed on all 16 ranks. Losses were
13.2325, 13.1564, and 13.3399; gradient norms were 27.9833, 27.8885, and
31.8815; clean exit.
- The research-prod Air ablations pin the backport of this
implementation. IPO-KL, IPO, DPPO, and IcePop have each subsequently
advanced beyond 400 Muon steps without recurrence of the initialization
deadlock.
- Review follow-up (`dfa07cd7e`): the warm-up now resolves the process
group from the mesh and no-ops on non-1-D meshes. Verified on 2 GPUs
with NCCL: the `dp_shard` path still completes the warm-up collectives,
and the 2-D replicate-only world mesh returns cleanly where the previous
no-arg `get_group()` call raised `RuntimeError`.

Both full-model validations used `qpn01gpu009/011`, 16 GPUs, CP4 + EP8,
optimizer-state offload, BF16 compute, and expandable CUDA allocator
segments. They used fake data with no evaluation or checkpoint overhead.

Job 1185 artifacts are retained at:

```text
/home/outputs/int4-debug/sft-air-full-muon-init-warmup-2n-009-011
```

## Confidence and limitations

Confidence is high that this initialization prevents the observed
first-all-to-all deadlock: the failure was reproducible without it, the
matching warm-up removed it in progressively more production-like tests,
and the final implementation has continued to work in four long-running
RL jobs.

The exact NCCL-native deadlock mechanism remains unproven. The warm-up
changes connection state, allocation history, and startup timing, so
this should be described as a targeted correctness workaround rather
than proof of a particular NCCL defect. Removing or moving it requires
reproducing the original multi-node pretrained GLM-Air Muon case, not
merely passing a standalone collective test.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes distributed initialization for Muon only, but incorrect group
selection or removal could reintroduce multi-node deadlocks or add
startup memory/time on every Muon run.
> 
> **Overview**
> Adds a **correctness workaround** for multi-node Muon training: NCCL
peer channels for bulk all-to-all are established **right after** Dion
`Muon` is built and **before** the first optimizer step, so
GLM-Air-style jobs avoid deadlocking on the initial Muon collective.
> 
> New helper `_warmup_muon_process_group` no-ops for single-rank or
non-NCCL groups; otherwise it runs an async **list** `all_to_all` on ~3
MiB BF16 buffers per rank (matching Dion’s bulk path), waits, and
synchronizes CUDA. Warm-up runs on the main **`dp_shard_cp`** (or world)
process group and, when expert MLP params use EP, separately on
**`dp_shard_mod_ep`**. AdamW, SGD, and other optimizers are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d0b707438f77780e4b5e0ed69237c08435ba3a41. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-07 11:20:40 -07:00
26b3131d27 fix(transports): make NCCL respect keep_in_fp32_for_weight_transfer (#3480)
The NCCL weight-broadcast transport hardcoded every tensor to
`bfloat16`, ignoring `keep_in_fp32_for_weight_transfer`. This PR makes
NCCL transport respect the fp32 overrides. This makes NCCL honor the
same declaration the other two transports already respect. Note: NIXL
does its own thing and does not use this shared helper, yet.

- Extracted `resolve_wire_dtype()` so the filesystem and NCCL paths
share one implementation.
- Lifted `NCCLBroadcaster._resolve_dtensors` to a module-level
`resolve_dtensors()`, since a method reachable only through a live
`PyNcclCommunicator` can't be unit tested.
- Added `tests/unit/utils/test_weights.py`, the flag's first test
coverage, parametrized over all six models that declare it.

Ran various experiments with small models to see if this affected KL mismatch in any way, but results were inconclusive. See commit https://github.com/PrimeIntellect-ai/prime-rl/pull/3480/changes/4b152bf3fa551ff5a1fc1752036262d14520c343 for example experiment configs.


---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 16:57:19 -04:00
samsjaandGitHub ef9dea1781 chore(inference): introduce admin plane abstraction (#3472)
## Summary

- consolidate the inference control path into a single `AdminPlane`
abstraction over its worker HTTP clients
- make the static plane own readiness, NCCL setup, weight updates, and
lifecycle management
- expose one typed `update_weights` operation; each receiver identifies
its transport explicitly
- route filesystem, NCCL, and NIXL receivers through the admin plane
instead of passing raw HTTP client lists
- remove the separate admin-plane protocol, unused factory argument, and
pass-through weight-update wrapper

`InferenceClient` remains the data-plane client for generation and
scoring, while `AdminPlane` coordinates control operations against one
or more inference workers. Alternate backends can specialize a transport
operation without adding backend flags to weight receivers.

## Validation

- `uv run ruff check src/prime_rl/orchestrator/clients.py
src/prime_rl/orchestrator/orchestrator.py src/prime_rl/evals/evals.py
src/prime_rl/transports/weights tests/unit/orchestrator/test_clients.py`
- `uv run python -m compileall -q src/prime_rl/orchestrator/clients.py
src/prime_rl/orchestrator/orchestrator.py src/prime_rl/evals/evals.py
src/prime_rl/transports/weights`
- `uv run pytest -q tests/unit/orchestrator/test_clients.py` (10 passed)

The transport test module could not be collected on this host because
its optional CUDA import chain requires `flash_attn`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Refactors the weight-broadcast control path (pause/resume,
NCCL/NIXL/filesystem updates) used during training; behavior should be
equivalent but mistakes here can strand engines paused or desync policy
versions.
> 
> **Overview**
> Renames **`AdminClients`** to **`AdminPlane`** and makes it the single
control-plane entry point for inference workers (readiness, NCCL init,
weight updates, LoRA load, teardown).
> 
> **NCCL setup** and **weight updates** move from module-level helpers
into **`AdminPlane.initialize_nccl`** and
**`AdminPlane.update_weights`**, with callers passing an explicit
**`transport`** (`filesystem` | `nccl` | `nixl`). Orchestrator, evals,
and all **`WeightReceiver`** implementations now take an
**`AdminPlane`** instead of raw **`httpx`** client lists;
**`load_lora_adapter`** and **`init_nixl_broadcast`** follow the same
pattern.
> 
> Unit tests are updated and **`test_admin_plane_initializes_nccl`** is
added.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
65043370b7a9c857e6e3302f665b0b8c389043f1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-03 16:36:16 -07:00
Konstantin DunasandGitHub 6c7b1ef375 feat: visualize compaction attempts and exclude rejected branches (#3478) 2026-09-03 22:09:41 +02:00
samsjaandGitHub 608c75c0af feat(dashboard): add timed terminal trace replay (#3456)
## Summary


https://github.com/user-attachments/assets/cd2caaa1-d700-40e5-8465-911812313f15

- add a terminal-style Replay view for rollout traces using recorded
model-call and tool timing
- add play/pause, seek, restart, 0.5x-32x speed controls, and an
inference-skipping tool-timing mode
- expose recorded model thinking with a toggle and T shortcut
- support Top/Live transcript navigation with Home/End shortcuts
- document replay timing semantics and extend dashboard smoke coverage

## Rebase notes

Rebased onto main (past #3444 overlays, #3465 chunked trace streams,
#3470 task/judge evidence, and #3455 semantic traces). Resolutions:

- `app.js` view state: trace viewer now has four modes — transcript,
timeline, replay, semantic; `setTraceView` keeps main's `persist` option
(replay is never persisted as a preference) and stops replay playback on
view switches; control visibility unions both sides (token-signal /
view-mode / collapse / expand hidden in graph, evidence, and replay
modes)
- `app.js` keyboard handler: replay T/Home/End shortcuts run first, then
main's step-bar arrow-key walking
- `app.js` click handler: replay control handlers first, then the
copy-button selector (including main's task/judge copy buttons)
- `index.html`: Replay button sits alongside main's Semantic button and
its episode-nav row
- `docs/training.md` / `skills/dashboard/SKILL.md`: describe all four
trace views together

## Validation

- `node --check src/prime_rl/dashboard/static/app.js` (rebased)
- `uv run --frozen ruff check tests/integration/dashboard_smoke.py`
(rebased)
- focused Playwright checks were run on the original branch (timed
playback, inference skipping, thinking toggles, keyboard shortcuts,
Top/Live navigation)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Read-only dashboard frontend and documentation; no changes to
training, inference, or data persistence.
> 
> **Overview**
> Adds a **Replay** tab to the rollout trace viewer that plays the
selected branch as a terminal session, using recorded model-call and
message timestamps for wall-clock pacing.
> 
> Playback includes play/pause, seek, restart, **0.5×–32×** speed
(default **8×**), **Skip inference** (instant model replies while
keeping tool delays), optional **Thinking** display (**T**), and **Top**
/ **Live** scroll follow (**Home** / **End**). Response text is revealed
evenly across each model-call span and labeled as inferred when
per-token timestamps are absent; prompt nodes committed at response time
are aligned to call start to avoid false idle gaps. Transcript-only
controls are hidden in Replay mode, and integration smoke tests cover
the new UI.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fddf8349c2f99ec4ac658b6bbfacb2e8f24532c9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-02 16:50:33 -07:00
Konstantin DunasandGitHub b28714289a feat(dashboard): visualize semantic agent traces (#3455) 2026-09-03 01:33:18 +02:00
Konstantin DunasandGitHub 903baaaa01 fix(dashboard): hide repeated timeline rewards (#3473) 2026-09-03 00:51:31 +02:00
Konstantin DunasandGitHub ae170acda1 feat(dashboard): surface task and judge evidence (#3470) 2026-09-03 00:45:13 +02:00
samsjaandGitHub c84068cf9e fix(evals): show error rate on partially evaluated epochs (#3462)
## Summary

- the partially-evaluated (cancelled-epoch) warning line in the `uv run
evals` entrypoint log now shows the `Error` rate next to `Reward` —
previously it reported reward with no signal of how many completed
episodes errored

```
Partially evaluated swebench-pro (Step 240) |  1m 32s | Reward 0.4167 | Error 5.0% | Completed 92/100 | Cancelled 8/100
```

The completed-epoch success line already shows `Error` and is unchanged:

```
Evaluated swebench-pro (Step 240) |  1m 32s | Reward 0.4167 | Turns 3.2 | Branches 1.0 | Error 5.0% | Truncation 2.0%
```

## Verification

- `uv run ruff check src/prime_rl/evals/evals.py` — passed
- `uv run ruff format --check src/prime_rl/evals/evals.py` — passed

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Logging-only change in eval finalization; no behavior, scheduling, or
metric emission changes.
> 
> **Overview**
> When an eval epoch is **cancelled** (e.g. superseded by a newer
checkpoint), the warning log line now includes the **Error** rate from
completed episodes, using the same `full.has_error` formatting as the
full **Evaluated** success line.
> 
> Previously that partial-eval message only showed reward and
completion/cancel counts, so operators could not see how many finished
rollouts failed without digging into metrics.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
010a7eceb61c71fa105ffadf7b4dc4e6708fc188. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-02 13:26:03 -07:00
Mika SenghaasandGitHub 7ad1bb9123 feat: chunk and seal trace streams (#3465)
## Summary

- Each trace stream (`traces/stream`, `traces/annotations/<producer>`)
is now a directory of numbered chunks. `ChunkedJsonl`
(`monitors/file/traces/chunks.py`) rolls at `monitors.file.chunk_bytes`
(default 5 GiB; a line never spans chunks) and, with
`monitors.file.compress` (default on), seals each full chunk with zstd
in a background thread. The live chunk stays plain text; a finished run
seals its live chunk too. A relaunch resumes the live chunk it finds and
seals anything a crash left mid-seal.
- Sealed chunks use zstd's seekable format (`pyzstd`, 4 MiB frames), so
a seek costs one frame, not the chunk. `zstd -dcf stream/* | jq` reads a
whole stream, sealed and live alike.
- Index rows carry `chunk` beside `offset`; the dashboard resolves both
through `open_chunk` (plain or sealed) for episodes and annotation
records, keys its caches and etags on the index size, and parses chunked
streams for the series view through the index, one chunk open at a time.
Annotation readers rely on the producer's index (the file monitor always
writes one).
- `monitors.file.float_decimals` (default 4, `None` for every digit)
sets the precision of per-token float streams in both the episode
records (`to_record(float_decimals=...)`) and the trainer's annotation
streams. Trainer streams also hold `null` outside the loss mask - the
fold keeps sampled tokens only, so nothing a reader sees changes, and
runs of nulls seal to nothing. The trainer finalizes its monitors on
exit so its live chunk seals.
- Submodule bump to verifiers main `cfc7c474`
(PrimeIntellect-ai/verifiers#2495, merged): JSON records round per-token
floats to `to_record(float_decimals=...)`, 4 by default. The msgpack
wire keeps full precision, so the importance ratio is unaffected.

## Measurements

Replayed the 100-step, 33,342-episode scaleswe baseline
(`ipo-baseline-rollouts-steps1-100`, 15.17 GB as one `stream.jsonl`)
through the new writer with 5 GiB chunks:

| | raw | 4 dp | on disk (sealed) | total |
|---|---|---|---|---|
| 10 steps (5,696 episodes) | 1.06 GB | 0.89 GB | **0.10 GB** | 11.0x |
| 100 steps (33,342 episodes) | 15.17 GB | 12.66 GB | **1.38 GB** |
11.0x |
| 1000 steps (extrapolated from steps 11-100: 307 episodes, 157 MB raw
per step) | 156 GB | 130 GB | **14.2 GB** | 11.0x |

Rounding contributes 1.20x on the plain bytes and lifts zstd from 6.9x
to 9.2x, since mantissa digits were the incompressible part. Writing 33K
episodes took 81.8 s with sealing vs 80.4 s plain: sealing runs beside
the writer, not in front of it. The final 2.7 GB live chunk sealed in 4
s.

Dashboard against the sealed run (same box, 5 GiB chunks): open one
episode 5.8 ms cold / 4.0 ms warm vs 3.9 / 3.4 ms plain; table page 17
ms cold (index only, unchanged); series view full parse of all 33K
records 35.7 s sealed vs 39.7 s plain (orjson-bound, cached and
persisted after the first pass). Browser check: traces table renders,
episode viewer opens from a sealed chunk, no console errors. Unit suite:
571 passed.

## Breaking

- On-disk trace layout: `traces/stream.jsonl` →
`traces/stream/<NNNNN>.jsonl[.zst]`,
`traces/annotations/<producer>.jsonl` →
`traces/annotations/<producer>/<NNNNN>.jsonl[.zst]`; index rows gain
`chunk` and their `offset` is chunk-relative. Read a stream with `zstd
-dcf <stream dir>/* | jq`. The dashboard reads only the new layout.
- Per-token floats in records (`logprobs`, `reference_logprobs`,
`advantages`, trainer `trainer_logprobs`/`entropies`) are written with 4
decimals by default; set `monitors.file.float_decimals = None`
(orchestrator and trainer) to keep full precision.
- New dependency `pyzstd`.


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking on-disk trace layout and default float precision affect
observability and external readers; dashboard and monitor paths are
heavily touched but training wire precision is unchanged per PR notes.
> 
> **Overview**
> **Trace on-disk layout is now chunked directories** instead of single
`stream.jsonl` / `annotations/<producer>.jsonl` files. The file monitor
writes through `ChunkedJsonl`: rolls at `monitors.file.chunk_bytes`
(default 5 GiB), optionally seals full chunks with seekable zstd in
background threads (`monitors.file.compress`, default on), and seals the
live chunk on `finalize()` (trainer now calls
`asyncio.run(monitors.finalize())` at shutdown). Index rows add
**`chunk`** beside chunk-relative **`offset`**.
> 
> **`monitors.file.float_decimals`** (default 4) rounds per-token floats
in episode `to_record(...)` and trainer annotation streams; trainer
streams also emit **`null`** outside the loss mask for better
compression without changing what readers fold onto traces.
> 
> The **dashboard** detects chunked streams via the index, reads
episodes and annotations with `open_chunk` (plain or `.zst`), versions
caches/etags on index size, and builds series summaries by walking the
index one chunk at a time. **Breaking:** tools and scripts must use
`zstd -dcf <stream-dir>/*` and per-producer chunk dirs under
`annotations/`. New dependency **`pyzstd`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
62a6893f75cbc770cbad06fd65d640aec13f058b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-02 11:37:29 -07:00
5990b1b9ba feat: add deepseek v4 (step 0) (#3325)
Initial commit for adding deepseek v4 flash. 

This architecture brings in multiple new ingredients and will require
multiple commits for a fully mature implementation to be ready. The
present PR should be regarded as the very rough first draft, focused on
unblocking basic SFT runs.

Other notes:
* I am attempting to isolate most changes to live under
`trainer/models/deepseek_v4/` to keep the PR clean and easier to iterate
on later without entangling this code with other `prime-rl` changes.
E.g. the `deepseek_v4/attention.py` impls may eventually get hoisted to
`attn.py`
* Does not yet implement methods needed for RL weight broadcasting
(blocking evals as well)
* We will incrementally pull in kernels to replace the current
pure-eager torch impl

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-02 11:34:01 -04:00
ffb845c13c fix(trainer): zero-index position_ids fallback in LM-head wrapper (#3466)
Use the standard zero-indexing convention for `position_ids` in patched
LM head forward, (`_patch_model_forward`), rather than one-indexing.

A uniform shift is mathematically invisible to RoPE, which sees only
query-key angle differences, but it is wrong for attention that keys off
absolute token indices (as is important for deepseek v4 where
compression boundaries are tied to absolute positions).

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 10:05:32 -04:00
Mika SenghaasandGitHub 421198cb93 feat: constant trainer batch size (#3463) 2026-09-01 20:22:40 -07:00
e3fdadedc5 feat: trainer trace annotations + dashboard overlays (#3444)
## Summary

Every rollout episode is written to disk exactly once, as an
arrival-ordered stream, and everything learned about it afterwards is an
append-only annotation folded back on read. The trainer's recomputed
per-token streams ride that mechanism, and the trace viewer renders them
as overlays (entropy, the trainer↔sampling mismatch, the IPO stable
mask) next to the loss mask.

**Layout** (replaces
`rollouts/step_N/{train,eval}/{all,effective}/traces.jsonl`):

```
<run_dir>/monitors/file/metrics.jsonl                              # every metric row, tagged by producer
<run_dir>/monitors/file/traces/stream.jsonl                        # every episode, appended as it arrives
<run_dir>/monitors/file/traces/stream.index.jsonl                  # one compact row per episode, with its byte offset
<run_dir>/monitors/file/traces/annotations/<producer>.jsonl        # trace updates: orch ship-time facts, trainer per-token streams
<run_dir>/monitors/file/traces/annotations/<producer>.index.jsonl  # each update's scalars and where its record sits
```

Everything the file monitor dumps lives under its own directory, and
nothing is written there when the monitor is off. The traces and
everything written about them sit under `traces/`, and every index is
named for the stream it indexes and sits beside it. Each file is
append-only with exactly one writer, so there are no locks and live
tailing keeps working.

**Steps are events, not locations.** A trace is dispatched at one step,
arrives at another and is trained at a third, so a step directory could
only ever be honest about one of them — and picking arrival forced the
arrival step onto the batch wire just so the trainer could find the
right directory. Instead each step is stamped as its own event on the
record. `orchestrator/annotations.py` owns both events: `stamp_arrival`
puts `info.kind` plus `info.dispatch` / `info.arrival` (`{step, time}`)
on a trace as its episode lands, and `stamp_ship` produces the update
carrying `info.effective` and `info.ship` — the orchestrator step whose
batch shipped the cohort, or for eval the policy version the epoch
measured. Staleness is `ship.step - dispatch.step`; the trace viewer
shows all three for a train trace, and an eval trace shows the step it
measured instead (it never ships in a batch and never goes stale).

- **Annotations**: one record format and one fold, in
`prime_rl.monitors.trace_updates`, used by the file monitor, the trainer
writer and the dashboard. An update names a trace and carries an `info`
dict merged into the trace's own plus per-branch token streams,
full-length over the branch's token prefix (nulls mark unknown
positions) so folding never depends on the producer's loss mask.
- **Indexes**: the file monitor summarises each episode into
`stream.index.jsonl` as it writes it, and each update's scalars into the
producer's `.index.jsonl`, both with byte offsets. A reader browses the
indexes and seeks for the one episode it opens, so the cost of listing a
run stops scaling with the token streams — which outweigh the episodes
themselves.
- **Branch identity on the batch wire**: `TrainingSample` gains
`trace_id` / `branch_index`; `MicroBatch` carries them per sequence,
parallel to `sequence_lengths`, preserved through packing/padding and
nulled on dummy micro batches.
- **Trainer**: accumulates one update per trained sequence per forward
(packing-boundary first value and non-finite values are null), gathers
them to rank 0 at the end of each step, and logs them through its own
file monitor — the same monitor it already logs metrics through — rather
than writing to disk behind it. Always on; the token-export path is
gone.
- **Dashboard**: same HTTP API shape. The traces tab opens on the whole
stream — newest first, paged as you scroll, with a histogram of episodes
finished per interval you can click to narrow to a moment — and switches
to step mode for the cohort that shipped at one step (arrow keys walk
the step bar). Episode reads fold every annotation onto the record, so
the overlays work in both views. Token signals are Advantage, Entropy,
Mismatch (`r − log r − 1`, computed client-side from the trainer and
sampling logprobs), Stable mask (`|Δp|` vs the run's IPO `eps`), Loss
Mask and Content Mask; an overlay the open episode cannot colour is
disabled in the selector and names the input it is missing, rather than
silently painting nothing. In a token overlay the reasoning renders
inside the token spans that already cover it instead of in its own box.
- Verifiers gained only the two per-token node fields the records land
on (`MessageNode.trainer_logprobs` / `entropies`, with matching `Branch`
spread properties) —
[verifiers#2481](https://github.com/PrimeIntellect-ai/verifiers/pull/2481),
merged; `deps/verifiers` tracks verifiers main.

## Verification

Reverse-text, 4 steps: 645 episodes on one stream, 496 annotated by both
producers, 55,694 masked tokens folded with every node's compact arrays
equal to its masked-token count. Mean KL mismatch 0.0014, mean entropy
0.61. Staleness came out as 336 traces shipped at their dispatch step
and 160 a step later — the lag the old layout could not express. Re-run
end to end on a 20-step reverse-text run after the layout change.
SFT-online-eval and verifiers `uv run eval` run shapes checked through
the real API with a FastAPI test client; the dashboard's browser smoke
suite covers the stream/step views, the histogram, the step bar and
every token signal.

## Breaking

- The `rollouts/` trace tree is gone. Episodes now live in one
`monitors/file/traces/stream.jsonl` stream, written once at arrival,
with the effective cohort expressed as
`monitors/file/traces/annotations/<producer>.jsonl` records instead of
duplicate episode copies (per-token advantages and the scalar advantage
now arrive via annotations). The dashboard reads only the new layout;
runs recorded before this change need the old dashboard.
- `metrics.jsonl` moves from the run root to
`monitors/file/metrics.jsonl`.
- `trainer.enable_token_export` is removed and `token_exports/` is no
longer written; the trainer's per-token streams are always logged as
annotations.
- The filesystem batch transport writes packed micro batches to
`batches/step_<n>/rank_<r>.bin` (previously `rollouts/step_<n>/`).

## 20-step GLM-Air ScaleSWE comparison

- The baseline ran `main`; the comparison ran this PR. The code change
was the only behavioral difference. Run names, output directories, and
conversion cache paths were isolated.
- Trainer step 1: before 874.0 s; after 822.0 s (-5.9%).
- Trainer steps 1–20: before 3,179.2 s; after 2,995.2 s (-5.8%).
- Steady trainer steps 2–20: before 121.3 s mean / 120.0 s median; after
114.4 s mean / 99.0 s median. The after run was 5.7% faster by mean step
time.
- Trace data at each run's trainer step-20 cutoff: before 3.516 GB
across duplicated `all` and `effective` traces; after 3.476 GB across
the arrival stream plus orchestrator and trainer annotations. The after
layout was 1.1% smaller despite 864 MB of per-token trainer logprob and
entropy annotations.
- Dashboard on the after run at step 20: a 128-episode page took 15.7
ms, a 2.22 MB annotated episode took 42.7 ms, and its timeline took 9.7
ms.

The after job was cancelled after step 24 at the researcher's request.
The baseline completed trainer step 20.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Large observability and on-disk contract change (breaking paths and
removed `trainer.enable_token_export`); training/orchestration logic is
mostly additive but any tool still expecting `rollouts/` or root
`metrics.jsonl` will break.
> 
> **Overview**
> Replaces the per-step `rollouts/.../traces.jsonl` tree with a **file
monitor layout** under `monitors/file/`: metrics at `metrics.jsonl`,
episodes in one append-only `traces/stream.jsonl` plus sidecar indexes,
and **append-only trace annotations** per producer (orchestrator
ship-time facts, trainer per-token streams).
> 
> **Orchestrator/evals** stamp arrival metadata on episodes at log time
and log **effective cohort** membership, advantages, and ship step via
`log_annotations` instead of duplicating episode files. **Trainer**
drops `enable_token_export` / `token_exports/`; per-token logprobs and
entropies always go through the same annotation path. **Dashboard**
reads the new layout: stream vs step cohort views, paged
`/api/runs/.../episodes`, arrival histogram, and token overlays
(entropy, mismatch KL, IPO stable mask, masks) folded from annotations.
> 
> Docs, skills, configs, and `run_single_benchmark.py` are updated for
the new paths and for skipping non-step metric rows. Filesystem batch
transport writes to `batches/step_*` instead of under `rollouts/`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
16bf663b7805ecfe7d993ff6b6d34c8b7bc47308. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-01 17:17:54 -07:00
Mika SenghaasandGitHub 84e7312f33 feat: top-p/top-k train sampling with native sampling replay (#3431)
## Summary

- Add typed top-p and top-k settings for policy rollouts.
- Capture vLLM 0.28 sampling masks and replay the truncated distribution
in the trainer.
- Bound sampling masks with a default `top_k = 512` when truncation is
enabled.
- Use Model Runner V2 for router replay on standard deployments.
- Support router replay and sampling replay together on Model Runner V2.
- Keep NIXL P/D router replay on V1 and reject the unsupported combined
P/D mode.
- Use `SamplingMask` and `sampling_mask` across Renderers, Verifiers,
and prime-rl.
- Pin merged Renderers and require its published `0.1.12.dev2` build.
- Pin Verifiers to the latest `main` after its sampling-mask merge.
- Document standalone capture, the NIXL replay matrix, and sampling-mask
layout examples.
- Shard sampling masks with labels for multimodal context-parallel
training.
- Reject mixed enabled and disabled top-k settings across live-policy
train sources.

This builds on vLLM 0.28.0 from #3430. It supersedes #3235. The capture
side uses vLLM's native sampling-mask support from
[vllm#49577](https://github.com/vllm-project/vllm/pull/49577).

## Usage

```toml
[orchestrator.train.sampling]
top_p = 0.95
top_k = 20
```

There are no replay flags for sampling replay. Truncated policy sampling
enables mask capture and trainer replay automatically.

Set `trainer.enable_router_replay = true` to combine router replay with
sampling replay. Standard deployments use Model Runner V2 for both
captures. Disaggregated NIXL deployments keep router replay on V1 and
cannot combine both replay modes.

## Behavior

- Policy sampling with `top_p < 1` or `top_k` gets a bounded sampling
mask.
- Truncation without an explicit `top_k` defaults to 512.
- Different truncating sources can use different top-p values; each gets
a positive top-k.
- Mixed top-k capture modes across live-policy sources are rejected.
- Values above 512 are rejected to bound trainer memory.
- The trainer renormalizes each sampled token over the same mask as
inference.
- Frozen-source environments do not require masks.
- `opd` and `opsd` reject truncated policy sampling because their
reference scores use the full vocabulary.
- vLLM rejects sampling-mask requests with `temperature <= 0` or without
an effective `top_k > 0`.

## Runs

GLM-4.5-Air on `scaleswe` on 4 nodes

| Run | Runner | Router replay | Top-p | Effective top-k | Nodes |
| --- | --- | --- | --- | --- | --- |
| `glm-air-v1-baseline` | V1 | Off | 1.0 | Off | 6 |
| `glm-air-v2-baseline` | V2 | Off | 1.0 | Off | 6 |
| `glm-air-v2-router-replay` | V2 | On | 1.0 | Off | 6 |
| `glm-air-v2-top-p-0.95` | V2 | Off | 0.95 | 512 | 6 |
| `glm-air-v2-router-replay-top-p-0.95` | V2 | On | 0.95 | 512 | 6 |

<img width="279" height="238" alt="Screenshot 2026-09-01 at 3 45 20 PM"
src="https://github.com/user-attachments/assets/bbbf5334-4b06-4573-9232-80d9207a97e6"
/>

<img width="286" height="226" alt="Screenshot 2026-09-01 at 3 46 03 PM"
src="https://github.com/user-attachments/assets/8d048fb1-3e2a-4484-a437-8084d845d47e"
/>

<img width="285" height="238" alt="Screenshot 2026-09-01 at 3 45 39 PM"
src="https://github.com/user-attachments/assets/ca5c21c7-6355-497f-a553-adade238dc1a"
/>

Sampling replay leads to
- no reduction in step 0 KL mismatch
- more stable KL mismatch in conjunction with router replay
- more stable entropy (not rising)
- slower step time (follow-up perf investigation TBD)

## Verification

- `uv run pytest -q tests/unit/test_configs.py -k 'policy_sources'`: 2
passed.
- `uv run pytest -q tests/unit/test_configs.py -k 'not
test_load_configs'`: 69 passed and 67 deselected.
- Pre-commit checks passed for the changed config and test files.

- `uv run pytest tests/unit/train/rl/test_fused_lm_head.py
tests/unit/train/rl/test_loss.py -q`: 19 passed and 1 skipped after the
context-parallel fix.

- `uv run pytest
tests/unit/test_configs.py::test_combined_replay_uses_v2_runner -q`:
passed after the documentation review.

- `uv sync --all-extras`: passed with merged Renderers and Verifiers
dependencies.
- `uv run pytest tests/unit/orchestrator tests/unit/inference
tests/unit/train/rl/test_loss.py
tests/unit/train/rl/test_fused_lm_head.py
--ignore=tests/unit/orchestrator/test_qwen3_vl_e2e.py -q`: 108 passed
and 1 skipped.
- The excluded Qwen3-VL test has an existing fake-response fixture
mismatch.
- `uv run rl @ examples/basic/reverse-text/rl.toml --max-steps 5
--orchestrator.train.sampling.top-p 0.95`: completed five trainer and
orchestrator steps on the final dependency chain.
- The end-to-end run used Model Runner V2, effective `top_k = 512`, and
sampling-mask capture. Final mismatch KL was 0.0035 with no rollout
errors.
- Renderers: `uv run pytest tests/test_client.py -q`: 21 passed and 5
skipped. Ruff and format checks pass.
- Latest Verifiers main: `uv run pytest
deps/verifiers/tests/v1/test_graph.py
deps/verifiers/tests/v1/test_trace.py -q`: 21 passed. Ruff, format,
type, and pre-commit checks pass.
- Reverse-text baseline, top-p 0.95, and top-p 0.95 plus top-k 20 runs
completed with 100% sampling-mask coverage.

W&B:
`reverse-text/reverse-text-native-replay-{baseline,topp095,topp095-topk20}`.

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





<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes core RL logprob/importance-ratio math and vLLM runner
selection; misconfiguration or missing masks can bias training or fail
at runtime, though validation and runtime checks aim to catch
incompatible modes.
> 
> **Overview**
> Adds **sampling replay** so policy rollouts with `top_p < 1` or
`top_k` stay aligned with trainer importance ratios: vLLM 0.28 returns
per-token sampling masks (`enable_return_sampling_mask` /
`--return-sampling-mask`), and the trainer renormalizes logprobs over
the same mask instead of the full vocabulary.
> 
> **Config & orchestration:** `TrainSamplingConfig` gains typed `top_p`
and `top_k` (truncation via `extra_body` is rejected). The `rl`
entrypoint auto-enables mask capture when policy sampling truncates;
unbounded truncation defaults `top_k = 512`, values above 512 are
rejected, `temperature = 0` and `opd`/`opsd` are blocked. Policy train
sources must agree on top-k capture mode (engine-wide). **Inference:**
new `enable_return_sampling_mask`; vLLM env setup prefers **V2** for
sampling capture and for router replay on standard deployments, while
**disaggregated NIXL P/D** keeps routed-expert capture on V1 and
**rejects** router + sampling replay together.
> 
> **Data path:** `SamplingMask` on `TrainingSample` / `MicroBatch`,
encoding in trajectories, packing/padding in the trainer batch builder,
and a hard error in `TrainSink` if truncated rollouts lack masks.
**Trainer:** masks flow through CP sharding; fused `lm_head` and
vanilla-path `selective_log_softmax_with_sampling_mask` compute
mask-renormalized logprobs (Gemma softcap heads explicitly unsupported).
Docs cover sampling replay; `renderers` is bumped for mask support in
the rollout stack.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
cee517e2266a2b819765612ccf3a10ba8801a23e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 15:47:54 -07:00
Mika SenghaasandGitHub fe325ac460 chore: bump verifiers (#3460)
## Summary

- advance the `deps/verifiers` submodule from `e2103d6` to `d4a2177`
- include merged Bash and RLM context compaction from verifiers #2454
and #2459
- pick up nano-rlm compaction commit `4ef3438` through the default RLM
harness pin
- refresh `uv.lock` for verifiers' `aiohttp>=3.14.1` requirement
- migrate three RLM examples to `compaction.summarize_at_tokens`; use
the former range's `98_304` midpoint
- include the optional ACP semantic-edge and shared harness utility
changes already on verifiers `main`

Companions: [verifiers
#2454](https://github.com/PrimeIntellect-ai/verifiers/pull/2454),
[verifiers
#2459](https://github.com/PrimeIntellect-ai/verifiers/pull/2459), and
[nano-rlm #147](https://github.com/PrimeIntellect-ai/nano-rlm/pull/147).

## Breaking

- RLM harness configs must move `summarize_at_tokens` to
`compaction.summarize_at_tokens`.
- Leave `compaction` unset to disable proactive and reactive compaction.

## Verification

- `git diff --check`
- `uv lock`
- `uv lock --check`
- `uv run pytest -q tests/unit/test_configs.py` — 133 passed
- `git submodule status deps/verifiers` —
`d4a217794fc0bfd70369a8230e56653c193da8ce`
- verified that `d4a2177` descends from the previous `e2103d6` pin

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Submodule bump plus a breaking harness config shape affects all RLM
runs still using the old `summarize_at_tokens` field; example migrations
are mechanical but custom configs must be updated.
> 
> **Overview**
> Advances the **`deps/verifiers`** submodule to pick up merged Bash/RLM
**context compaction** (and related harness defaults), with
**`uv.lock`** refreshed so **`aiohttp`** meets the new **`>=3.14.1`**
floor.
> 
> **Breaking for RLM harness TOML:** flat
**`env.agent.harness.summarize_at_tokens`** is replaced by
**`env.agent.harness.compaction.summarize_at_tokens`**. The three
advanced examples (**`glm-4.5-air/search`**, **`glm-4.5-air/terminal`**,
**`nemotron-3-super/swe`**) are updated accordingly—train sources that
used a two-threshold list **`[65536, 131072]`** now use a single
**`98304`** threshold; eval sources keep **`98304`** but under the
nested **`compaction`** key.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7429aba97da77a30db191432d5295827c64ae621. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 11:46:35 -07:00
samsjaandGitHub 0f22eeb862 feat(evals): add resumable standalone runs (#3413)
## Summary

- add top-level `[ckpt]` and `[resume]` support to standalone `uv run
evals`
- write atomic cursor checkpoints at
`<output_dir>/checkpoints/step_N/evals/progress.pt`, where N is the
durable eval-source task cursor
- store only the cursor in eval progress checkpoints; generated episode
records are not copied into checkpoint payloads
- resume with `--resume`, `--resume.step N`, or `--resume.dir
path/to/checkpoints/step_N` by skipping the durable cursor prefix
- retry partial groups and out-of-order completions beyond the durable
cursor
- size resumed eval batches to the remaining queued task suffix
- reject checkpointing in online mode, where progress is coupled to the
trainer weight-broadcast lifecycle
- keep the training start-run skill current with the new workflow
- clarify that checkpoint writes use temp-file replacement so resume
never observes a partial pickle

## Verification

- `uv run pytest tests/unit/evals/test_ckpt.py` — 3 passed
- focused `ruff check` — passed
- focused Python `ruff format --check` — passed
- `git diff --check` — passed

Local note: `uv run evals --help` is currently blocked before CLI
loading by the locked `prime-sandboxes==0.2.39` / `connectrpc==0.11.1`
import mismatch (`connectrpc.client` is missing).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Shared orchestrator types (`Dispatcher`, `EvalSource`, `EvalSink`)
change, but checkpoint/resume logic is gated to standalone evals with
config validation; unit tests cover cursor and I/O semantics.
> 
> **Overview**
> Standalone `uv run evals` can now be made **interruptible** via
optional `[ckpt]` and `[resume]` on `EvalsConfig` (rejected when
`[online]` is set).
> 
> Progress is a **task cursor** over round-robin eval tasks:
`EvalSource` assigns `source_index`, advances the durable cursor only
over a fully completed prefix (`mark_completed`), and on resume skips
tasks below the loaded cursor. `CheckpointManager` writes only
`{"cursor": N}` to `<output_dir>/checkpoints/step_N/evals/progress.pt`
using atomic temp-file replace; saves run every `ckpt.interval`
completed groups in standalone mode.
> 
> The evals loop loads resume state at setup, sizes epochs with
`EvalSink.set_batch_size` from remaining queued tasks, and on each
finished eval group calls `dispatcher.pop_source_index` to drive
checkpointing. Online eval rollout totals use the triggered queue
instead of full env example counts.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d4dc69fac552a55cb6c7c412a0d4e1b194a39c03. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-31 19:31:16 -07:00
JannikStandGitHub 1fbf0b47a4 bugfix: install EFA userspace stack in-place in the runtime stage (#3454)
## Why

`libfabric` needs a newer `libefa.so.1` (symbol version `EFA_1.4`) than
this image's own apt-installed rdma-core provides, so NCCL fails to load
the OFI plugin: `version 'EFA_1.4' not found`.

## What

- The AWS EFA installer upgrades rdma-core system-wide via its own
apt/dpkg step, but running it in a separate build stage and copying out
only `/opt/amazon` left that system-wide upgrade behind — libfabric
ended up paired with the older, separately-apt-installed rdma-core.
- Run the installer directly in the runtime stage instead, so its
rdma-core upgrade lands in place with no copy-forwarding gap.
- Verified locally: before the installer, stock rdma-core
(50.0-2ubuntu0.2); after, upgraded to 61.0-1 system-wide,
`libfabric.so.1` resolves `libefa.so.1` cleanly, and
`libnccl-net-ofi.so` dlopens with zero missing dependencies.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes CUDA image build and RDMA/EFA library versions used for
multi-node NCCL; incorrect pairing could still break distributed
training on EFA hosts, but the change targets a known symbol-version
mismatch.
> 
> **Overview**
> Fixes NCCL OFI plugin load failures (`EFA_1.4` not found) by changing
**how** the CUDA image gets the AWS EFA stack, not by adding new runtime
behavior.
> 
> The dedicated `efa-installer` build stage and `COPY
--from=efa-installer /opt/amazon` are removed. The same AWS
`efa_installer.sh` run (still with `--skip-kmod` and
`--skip-limit-conf`) now executes **in the final runtime image**,
immediately after the base `apt` install of `libibverbs` / `librdmacm`
and related packages. That way the installer’s system-wide rdma-core
upgrades stay in the image libfabric actually runs in, instead of
shipping only `/opt/amazon` from an isolated stage paired with older
distro rdma-core.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6f879a4bf88704c58b5719b1c8635258121ae2de. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 02:45:32 +02:00
JannikStandGitHub 799ac26258 bugfix: install libhwloc15 for aws-ofi-nccl in runtime image (#3452)
## Why

NCCL now finds `libnccl-net-ofi.so` but fails to load it:
`libhwloc.so.15: cannot open shared object file`, falling back to
sockets.

## What

- Add `libhwloc15` to the runtime stage's apt install list.
- The EFA installer stage pulls in libhwloc as one of its own
dependencies, but only `/opt/amazon` gets copied forward into the
runtime stage — the shared lib itself never did.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single-package addition to the Docker runtime image with no
application code or auth/data-path changes.
> 
> **Overview**
> Fixes NCCL failing to load the AWS OFI network plugin
(`libnccl-net-ofi.so`) because **`libhwloc.so.15`** was missing at
runtime, which forced a fallback to sockets.
> 
> The CUDA **runtime** stage now **`apt install`s `libhwloc15`**
alongside the other RDMA/EFA-related packages. The EFA installer stage
already pulled in hwloc as a dependency, but only **`/opt/amazon`** is
copied into the final image—not the distro **`libhwloc`** package—so the
shared library never landed in the runtime filesystem.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a1d18804238afc171a4e8b856e86c24818d2b95d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 00:57:11 +02:00
JannikStandGitHub d5b38216a5 bugfix: install prime-kernels extra in Docker build (#3449)
## Why

Trainer crashes with `ModuleNotFoundError: No module named
'prime_kernels'` on startup. `collectives.py` imports it unconditionally
at the top of the file.

## What

- `prime-kernels` is declared and pinned in `pyproject.toml`/`uv.lock`
under its own `kernels` extra, but that extra was never passed to `uv
sync` in `Dockerfile.cuda` — so it resolves but never actually installs.
- Add `--extra kernels` to both `uv sync` calls.
- Add `prime-kernels` to the post-sync version-check so a missing
install fails the build loudly instead of shipping silently.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Docker build-only dependency wiring with no runtime logic changes;
slightly larger images when the kernels extra is enabled.
> 
> **Overview**
> Fixes CUDA Docker images that could start the trainer without
**`prime-kernels`**, causing **`ModuleNotFoundError: No module named
'prime_kernels'`** even though the package is pinned under the
**`kernels`** optional extra.
> 
> Both **`uv sync`** stages in **`Dockerfile.cuda`** now pass **`--extra
kernels`**, so the wheel is actually installed into the venv. The
post-sync **`importlib.metadata`** smoke check also includes
**`prime-kernels`**, so a missing install fails the image build instead
of surfacing only at runtime.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
180ec8e7944f5be98a55a24200959fff882b652d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 00:28:16 +02:00
JannikStandGitHub f87ebcc239 improvement(docker): bundle AWS EFA libfabric + aws-ofi-nccl (#3448)
## Summary
- Bundles libfabric + the aws-ofi-nccl NCCL plugin into the image via
AWS's official installer, so NCCL can find the OFI plugin at runtime
instead of silently falling back to sockets
- Inert by default — only takes effect where a deployment's config
points `LD_LIBRARY_PATH` at it

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Docker build-only change that adds optional EFA libraries without
altering default runtime env or application code; main risk is larger
images and relying on the pinned AWS installer URL/version.
> 
> **Overview**
> The CUDA runtime image now **ships the AWS EFA userspace stack**
(libfabric and the **aws-ofi-nccl** NCCL plugin) so multi-node jobs on
EFA-capable hosts can use NCCL’s OFI path instead of silently falling
back to sockets.
> 
> A new **`efa-installer` build stage** on the same Ubuntu 24.04 base as
runtime downloads AWS’s official installer (default **1.47.0**), runs it
with **`--skip-kmod`** and **`--skip-limit-conf`**, and copies
**`/opt/amazon`** into the final image. **`LD_LIBRARY_PATH` is
unchanged** in the Dockerfile—deployments that have EFA on the host are
expected to prepend those libraries when needed; elsewhere the bundle
stays inert.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
007d6d6b8af5e5f567fa94fce5e2b6f06e02d62a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-31 23:41:31 +02:00
Matej SirovatkaandGitHub 866c3e1438 refactor(trainer): make activation checkpointing operator-based (#3419)
## Summary

- Replace method- and attribute-based selective activation checkpointing
with one non-reentrant checkpoint region around each selected
transformer block.
- Keep `mode = "full"` as the default. Full mode retains only mandatory
non-replayable operations and recomputes everything else; selective mode
additionally retains configured expensive operations through the same
Prime-owned policy.
- Allow selective mode to replace its public default targets with
explicit operator names or namespaces. Correctness-required targets
remain active for every selective configuration.
- Register real runtime boundaries for Torch EP/CP collectives, DeepEP
combine, ring attention, sparse MLA, dense/grouped DeepGEMM, MXFP8
transport, and MoE routing telemetry so checkpointing, autograd, and
compile observe the same operations.
- Keep sparse MLA dispatcher, fake, and autograd registration beside the
vendored forward/backward kernel entrypoints rather than in GLM model
code.
- Collapse ring attention into one backend-neutral forward/backward
custom-op pair. Its adapters call only the pinned FA2, FA3, and FA4 APIs
explicitly, without signature probing or generated per-backend
registrations.
- Remove checkpoint-only attention helpers and the model-specific
checkpointing module. Generic attention, AFMoE, Qwen3.5, and Laguna keep
their projection/output logic directly in `forward`; GLM DSA keeps only
its substantive `mla_latents` and `mla_up_proj` helpers.
- Rebase onto the Torch 2.13, CUDA 13, and vLLM 0.28 runtime from
current `main`, and update FlashAttention 4 to `0251105` with the shared
TVM FFI version required by vLLM.
- Ignore FSDP replay-only profiler markers when selective checkpointing
validates the saved forward operation sequence.
- Prefetch the final MoE block, experts, and separately wrapped router
before backward replay so FSDP collectives occur in the same order as
the saved forward.

## Runtime contract

- Model implementations do not expose checkpoint target names or
checkpoint-only methods.
- `freq` selects whole transformer blocks; the dispatched operator and
selected target set determine whether selective AC saves or recomputes
its result.
- Both modes retain mandatory MoE routing, telemetry, non-replayable
DeepEP, and CUDA-to-CPU metadata operations so they execute once. Full
mode recomputes every other operation; selective mode additionally
retains its configured targets.
- The default selective targets retain supported attention, matrix
multiplication, grouped GEMM, and distributed communication operators.
Elementwise operations, norms, reshapes, and RoPE replay.
- Custom targets replace the selective defaults and match either an
exact operator name or an operator namespace. They cannot exclude
mandatory routing, telemetry, non-replayable communication, or
CUDA-to-CPU metadata operations.
- Unsupported or missing backend operators fail at their normal call
site; there is no checkpoint fallback layer.
- MXFP8 transport resolves `mxfp8_moe` inside its custom-op
implementation. MXFP8 grouped compute still resolves it during runtime
setup because the exported grouped GEMM is already an operator boundary.

## Configuration

```toml
[trainer.model.ac]
mode = "selective" # full | selective
freq = 1
# targets = ["aten::mm", "prime_rl_collectives"]
```

Omitting `targets` uses the public Prime defaults. Any explicit list
replaces those defaults; an empty list retains only the mandatory
operations.

## Validation

- Ruff, Ruff formatting, `uv lock --check`, and `git diff --check`
passed.
- Focused config, checkpointing, and Qwen3.5 CP tests on the rebased
dependency stack: 138 passed.
- A6000 CI regression suite passed all eight checks: four-GPU peak
memory was 6.2467 GiB against the 6.2988 GiB baseline (down from 6.6185
GiB before the fix); one-GPU peak memory was 10.6738 GiB.
- Compiled selective AC with DeepEP completed a two-GPU, two-step
`samsja/mini-glm-moe` training smoke after rebasing onto the merged MoE
runtime.
- The pinned FA2, FA3, and FA4 varlen backends all use the `[heads,
total_tokens]` LSE layout; the ring fake and backward paths enforce that
single contract.
- Two-H200 compiled ring validation matched each backend's direct
attention reference exactly for FA2, FA3, and FA4 output and `dq`, `dk`,
and `dv`.
- Full H200 unit suite: 574 passed, 9 skipped.
- Eager and compiled output/gradient/replay validation passed for local
MoE, Torch EP, DeepEP with and without chunking, CP, FA2/FA3 ring
attention, sparse MLA, dense DeepGEMM, grouped DeepGEMM, and the
production MXFP8 transport boundary with a fake numerical kernel.
- FSDP parameter/state-dict parity and selective AC plus activation
offloading passed.
- Whole-model parity passed for Llama, Nemotron-H, GPT-OSS, AFMoE,
Laguna, and Qwen3.5 full-attention layers. Sparse MLA parity also passed
after restoring its substantive helper structure.
- On the stacked Qwen3.8 Flash Next implementation, selective and full
activation checkpointing each completed 20 RL steps on 24 H200s with
compile, FSDP, expert parallelism, SignSGD, NIXL policy reload, and CPU
optimizer-state offload. Steps 2-20 averaged 8,008 tokens/s for
selective and 7,211 tokens/s for full; both peaked at 130.4 GiB and held
mismatch KL at 0.0014-0.0021 with a final value of 0.0016.

## Hardware boundary

- Numerical MXFP8 grouped GEMM and transport still require SM100
hardware. The H200 validation exercised the production
custom-op/autograd/compile boundary with a BF16 fake transport kernel.
- FA4 forward/backward numerical validation passed on H200 (SM90);
Blackwell remains untested in this PR.
- Qwen3.5 GatedDeltaNet whole-model parity did not reach execution
because the no-AC reference forward remained in FLA kernel compilation
until the diagnostic jobs were cancelled. Qwen3.5 full-attention parity
passed, and the GatedDeltaNet runtime code itself is unchanged.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Touches core training memory/throughput (activation checkpointing),
distributed MoE/DeepEP/ring attention autograd, and compile
boundaries—incorrect replay or double-counted routing would show up as
silent wrong grads or NCCL deadlocks.
> 
> **Overview**
> **Replaces layer-specific selective activation checkpointing** with
whole-block non-reentrant checkpointing driven by a PyTorch selective
operator policy (`activation_checkpointing.py`). Semantic targets like
`norm` / `attn_proj` are gone; `model.ac.targets` is now optional
operator names or namespaces that replace Prime’s defaults, while
mandatory saves still cover MoE routing/top-k, DeepEP, and CUDA→CPU
copies.
> 
> **Registers distributed and kernel paths as `torch.library` custom
ops** so checkpoint replay, autograd, and compile see the same
boundaries: new `prime_rl_collectives` for EP/CP all-to-all and
gather/reduce-scatter, `deepep::combine`, unified `prime_rl_ring` ring
attention (FA2/FA3/FA4), `prime_rl::sparse_mla`, FP8/grouped FP8 GEMMs,
and `record_moe_routing_statistics` so routing counters are not
double-applied on recompute. Inline `autograd.Function` wrappers in
token dispatch, Mamba CP, and ring attention are removed in favor of
these ops.
> 
> **Simplifies trainer wiring and models**: `apply_ac` always wraps
whole transformer blocks; the old `layers/checkpointing.py` hook layer
is deleted and attention modules no longer expose checkpoint-only
`attn_projections` / `output_proj` splits. FSDP backward prefetch now
includes the last block’s MoE experts/router. Docs, examples, and
benchmarks drop legacy selective target lists; **flash-attn-4** is
bumped to `0251105` with a pinned **apache-tvm-ffi** override.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3a51c78f1ed46b0603ec42c1011c36e14533b710. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-31 22:52:33 +02:00
Konstantin DunasandGitHub c176840626 chore: bump renderers to 0.1.11, verifiers and prime-envs to main (#3441) 2026-08-31 22:14:00 +02:00
Mika SenghaasandGitHub bb0c103f08 fix: shard SFT data and report worker progress (#3417)
## Summary

- Resolve SFT data shard identities after worker processes start.
- Shard fake data by DP rank while replicating it across CP ranks.
- Read epoch and sample progress from the furthest worker cursor.
- Aggregate per-source sample and token counters across workers.
- Preserve worker counters across dataloader checkpoint resume.
- Extend the existing CPU dataloader suite with tiny in-memory SFT data
across worker, DP, and CP layouts.
- Clarify the dummy renderer token decode in the sharding test.

## Verification

A one-GPU SFT run used two local dataset splits, two data workers, and
four logged steps.

- Before: sample progress was `5, 5, 9, 9`, and source ratio metrics
were absent.
- After: sample progress was `9, 10, 17, 18`, and source sample and
token ratios were present at every step.
- Before the sharding fix, two workers yielded `0, 0, 1, 1, 2, 2, 3, 3`
from increasing fake data.
- The CPU regression matrix verifies unique DP shards, CP replicas,
checkpoint resume, counters, and the `0 → 1` epoch transition.
- The fake-data test verifies distinct samples across DP ranks and
identical samples across CP ranks.
- The uneven-packing regression verifies that worker progress never
moves backward.
- `uv run pytest tests/unit/train/sft/test_dataloader.py -q` passed with
16 tests.
- `uv run ruff check tests/unit/train/sft/test_dataloader.py
src/prime_rl/trainer/sft/data.py src/prime_rl/trainer/sft/train.py`
passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes distributed data partitioning and checkpointed iterator state,
which can silently skew training if wrong; behavior is covered by
expanded unit tests but affects core SFT loops.
> 
> **Overview**
> Fixes **incorrect SFT data sharding and stale progress metrics** when
using multiple DataLoader workers and/or context-parallel (CP) ranks.
> 
> **Sharding:** `data_rank` / `data_world_size` are now derived from
**DP rank only** (`rank // non_dp_size`), so CP ranks see the same
samples while DP ranks stay distinct. Rank/worker identity is resolved
in **`__iter__` via `_setup_world_info()`** instead of at dataset
construction, so worker processes get the right shard after fork.
> 
> **Progress & checkpoints:** `CatDataset` state now stores and restores
per-source **`num_samples` / `num_tokens`**. New
**`get_dataset_progress()`** reads worker snapshots, uses the **furthest
worker** for `step`/`epoch`, and **sums** counters across workers. SFT
training logs **`progress/*`** from the dataloader instead of the
main-process dataset object (which stayed at zero after resume).
> 
> **Tests:** Dataloader tests drop the heavy tokenizer/GPU mark, add a
shared dummy renderer, and cover multi-rank/worker sharding, resume, CP
replication, and monotonic progress under uneven packing.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
30f7de1d229f8e88e0f334be6b8baaa7d2dccf14. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-31 13:00:38 -07:00
Mika SenghaasandGitHub 3fc28ddfb3 fix: remove dispatch failures from summaries (#3432)
## Summary

- Remove dispatch-failure rates from per-step success logs.
- Exclude dispatch-failure metrics from curated W&B overview panels.
- Keep raw dispatch-failure metrics unchanged.

## Verification

Before: training success lines and W&B overview panels showed
dispatch-failure rates.

After: both summaries omit dispatch failures while the raw metrics
remain available.

- `uv run ruff check src/prime_rl/orchestrator/orchestrator.py
src/prime_rl/monitors/wandb/overview.py`
- `UV_PROJECT_ENVIRONMENT=/home/ubuntu/prime-rl/.venv uv run --no-sync
pytest tests/unit/orchestrator/test_metrics.py`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Presentation-only changes to logs and W&B overview panels; dispatch
failure metrics and pipeline handling are unchanged.
> 
> **Overview**
> **Dispatch failure rates are removed from operator-facing train
summaries** while leaving underlying W&B metrics intact.
> 
> The per-step **Step …** success log (aggregate and per-env `╰─` lines)
no longer computes or prints **Dispatch Failure**; multi-env breakdowns
also stop folding `batch.failures` into env name lists. Docstrings now
describe window metrics as **Error**, **Cancelled**, and **Ratio** only,
and clarify that cancellations are pipeline decisions rather than
rollout failures.
> 
> The curated W&B **overview** saved view drops
`all/dispatch_failure/mean` from `COMMON_METRICS`, so the default
dashboard panels no longer highlight dispatch-failure rate alongside
turns, tokens, and error/truncation signals. `dispatch_failure_metrics`
in `finalize_train_batch` is unchanged, so raw
`train/*/all/dispatch_failure/*` series remain available outside the
overview.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
db0d538c93bbcfa9e764e9f9f295dca9c1b45ab3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 22:06:11 -07:00
Mika SenghaasandGitHub eaad03b9df chore: bump vllm to 0.28.0 (#3430)
## Summary

Builds on the CUDA 13, Torch 2.13, and vLLM 0.27.1 stack from #3425.

- Bump vLLM to 0.28.0. Torch stays at 2.13.0+cu130; only the wheel pins
move. vLLM 0.28 requires `nvidia-cutlass-dsl == 4.6.2` and
`quack-kernels == 0.6.4`, so the override pin and its dependency
metadata move with it.
- Drop patches obsoleted by the pinned release (reviewed the
0.27.0/0.27.1/0.28.0 release notes and diffed the patched vLLM sources
between 0.27.1 and 0.28.0):
- `monkey_patch_harmony_stop_token_propagation` — fixed upstream by
vllm#35076 (in the release since 0.27.1).
- `monkey_patch_fp32_router_logits` — vLLM reads `moe_router_dtype` off
the HF config (vllm#47410) and forces fp32 routing for GLM-5.x.
`inference.enable_fp32_router_logits` keeps its name and default but now
injects `hf_overrides = {"moe_router_dtype": "float32"}` instead of
patching `DeepseekV2MoE`.
- `PrimeRlServingTokens` — upstream `serve_tokens` now handles DP-rank
header routing, server-side `max_tokens` defaulting, and `usage`
reporting (cached tokens surface via `--enable-prompt-tokens-details`,
which the launcher now sets). The subclass shrinks to the compact
`routed_experts` export and the `kv_transfer_params` engine bridge
(vllm#42644 merged 6h after the 0.28.0 cut — drop at the next bump).
- Follow vLLM's own V1/V2 model runner resolution instead of pinning V1
globally. vLLM resolves non-MoE generate models (plus an arch allowlist)
to the V2 runner. Only routed-experts capture still requires V1 (the V2
runner silently never captures routing decisions): the launcher pins
`VLLM_USE_V2_MODEL_RUNNER=0` when `enable_return_routed_experts` is set,
and the NIXL routed-experts patch rejects a V2 resolution explicitly.

Patches verified still needed on 0.28.0 (targets byte-identical or issue
still open): kv-xfer freed-request assert (vllm#46240), qwen3_coder
param newline trim, minimax-m2 think-end passthrough, TokenizeParams
validation, DP coordinator startup timeout, LoRA expert-key acceptance
(vllm#38522 closed unmerged), Qwen3.5-MoE 2D LoRA format, online-fp8
Parameter cast, nano_v3 reasoning parser, fp32 lm_head (kept over vLLM's
`head_dtype=float32`, which upcasts the weight per forward instead of
using an fp32-out GEMM), chat routed-experts strip.

Known 0.28 caveats:
- NIXL connector handshake version bumps 5 → 7: a 0.27 and a 0.28 engine
refuse to transfer KV to each other, so rolling P/D upgrades need a full
pool restart.
- vllm#50465 (batch-sharded sampling, merged after 0.28.0) silently
drops sampling masks under TP; re-check vllm#53826 before the next bump.

Validated on GLM-4.5-Air SWE

<img width="882" height="241" alt="Screenshot 2026-08-28 at 9 08 56 PM"
src="https://github.com/user-attachments/assets/d1af34c4-a80a-410b-bcdc-afdf0ffabd81"
/>

## Verification

- `uv lock --check`
- `uv run --frozen pytest -q tests/unit/test_configs.py
tests/unit/inference` (137 passed)
- Ruff check and format checks for the changed Python files
- E2E reverse-text RL on this branch (Qwen3-0.6B-Reverse-Text-SFT, 20
steps, 1 trainer + 1 inference GPU, NCCL broadcast): reward 0.18 → 0.81,
0% rollout errors, 100% trainable, mismatch KL 0.003–0.005. The engine
ran the V2 model runner (vLLM's default for this model) with the fp32
lm_head patch active. W&B: `reverse-text/reverse-text-vllm028-smoke`.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> A broad inference dependency bump plus behavioral changes to MoE
routing, model-runner selection, and P/D KV transfer bridging;
misconfiguration could affect logprob fidelity, router replay, or
disaggregated decode performance until upstream fixes land.
> 
> **Overview**
> Upgrades the GPU inference stack from **vLLM 0.27.1 to 0.28.0**, with
matching lockfile and wheel pins (`nvidia-cutlass-dsl` 4.6.2,
`quack-kernels` 0.6.4).
> 
> **Config / launcher:** `to_namespace()` now defaults
**`enable_prompt_tokens_details`** so `/inference/v1/generate` `usage`
includes cached prompt tokens for router billing.
**`enable_fp32_router_logits`** no longer sets `additional_config`; it
injects **`hf_overrides.moe_router_dtype = "float32"`** so vLLM’s native
MoE routing path applies. **`VLLM_USE_V2_MODEL_RUNNER=0`** is set only
when **`enable_return_routed_experts`** is on (V2 never captures routed
experts); other models follow vLLM’s V1/V2 resolution.
> 
> **Removed patches** superseded by 0.28: harmony stop-token merge on
chat completions, `DeepseekV2MoE` fp32 router monkey-patch, and most of
the custom `ServingTokens` fork (DP routing, `max_tokens` defaulting,
manual `usage` assembly). **`PrimeRlServingTokens`** now delegates to
upstream `serve_tokens` except for **`kv_transfer_params` →
`sampling_params.extra_args`** (PD disagg until vllm#42644 ships) and
compact **`routed_experts`** post-processing.
> 
> **Other:** NIXL routed-experts guard uses
**`config.use_v2_model_runner`** instead of the env flag. Unit tests for
deleted helpers are trimmed; post-process test asserts `usage` is
preserved from upstream responses.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
77c9264df8bb12af89eda7c238e2415e9a339857. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 21:57:26 -07:00
Mika SenghaasandGitHub 70117046ac fix: bump torch 2.13 + vllm 0.27.1 + custom wheels for cuda 13 (#3425)
## Summary

- upgrade Torch to 2.13 and vLLM to 0.27.1 on CUDA 13
- pin matching CUDA 13 wheels for FlashAttention, prime-kernels, DeepEP,
DeepGEMM, TorchAO, NIXL, CUTLASS DSL, cuDNN, and vLLM
- load DeepGEMM only when FP8 kernels execute so CPU imports do not
require a CUDA toolkit
- reject TorchAO MXFP8 on GPUs other than SM100
- move native wheel builds to prime-kernels and remove the duplicate
PrimeRL workflow and build scripts
- use the CUDA 13 toolkit and runtime in the PrimeRL CUDA image

Validated against GLM-4.5-Air SWE run

<img width="295" height="227" alt="Screenshot 2026-08-28 at 7 29 36 PM"
src="https://github.com/user-attachments/assets/d125177e-86e0-4a2e-bb78-3a44bb4f15ce"
/>

<img width="294" height="239" alt="Screenshot 2026-08-28 at 7 30 05 PM"
src="https://github.com/user-attachments/assets/ea277670-c42a-49b6-a2cc-b10c5d9b8713"
/>

## Breaking

- remove `scripts/install_deep_gemm.sh` and
`scripts/install_ep_kernels.sh`; use the builders under
`deps/prime-kernels/scripts/` for source builds

## Verification

- `uv lock --check`
- `git diff --check`
- `bash -n deps/prime-kernels/scripts/install_deep_gemm.sh
deps/prime-kernels/scripts/install_ep_kernels.sh`
- Ruff check and format checks for the changed Python files
- verified that importing `prime_rl.trainer.model` does not import
DeepGEMM
- verified that MXFP8 rejects the local SM120 GPU with an SM100
requirement
- ran FlashAttention 2 forward on the local SM120 GPU
- `uv run pytest tests/unit -m "not gpu"`: 476 passed and one unrelated
Qwen3-VL fake-response assertion failed
- after merging `main`, focused config and MoE tests passed: 148 passed
and 3 skipped


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Wide dependency and Docker CUDA migration affects training, inference,
MoE/FP8, and disaggregated NIXL paths; MXFP8 now fails on non-SM100 GPUs
that previously passed the SM100+ check.
> 
> **Overview**
> Moves the GPU stack from **CUDA 12.8 / torch 2.9 / vLLM 0.26** to
**CUDA 13 / torch 2.13 / vLLM 0.27.1**, with matching prebuilt wheels
(FlashAttention, prime-kernels, DeepEP, DeepGEMM, torchao, NIXL, cuDNN,
CUTLASS) pinned via `[tool.uv.sources]` to **prime-kernels** release
assets instead of prime-rl releases. `uv` **dependency-metadata**
overrides steer NIXL and CUTLASS toward CUDA 13 variants so cu12
packages are not pulled alongside extras.
> 
> **CI and packaging:** Deletes `.github/workflows/build_kernels.yaml`
and the release jobs that built kernel wheels before publishing; native
wheel builds are documented as owned by the **prime-kernels** repo.
Removes in-repo `install_deep_gemm.sh` / `install_ep_kernels.sh` in
favor of `deps/prime-kernels/scripts/`.
> 
> **Docker:** `Dockerfile.cuda` uses **nvidia/cuda 13.0.1** end-to-end,
drops the sidecar CUDA 13 runtime copy used for deep-gemm, and installs
**nixl_cu13** when building NIXL from source.
> 
> **Runtime behavior:** **DeepGEMM** is imported lazily inside FP8
autograd paths so CPU-only imports do not require the CUDA toolkit.
**MXFP8** quantization is restricted to **exactly SM100** (not
“SM100+”), and torchao’s MXFP8 linear helper import path is updated.
Benchmark baseline JSON files are refreshed for the new commit and
benchmark harness fields.
> 
> **Docs/skills:** Install and kernels skills describe `uv sync --extra
disagg` and prime-kernels release workflow instead of the removed
PrimeRL kernel CI.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4f6159cbe8333759cb55720ca2abaeeb7ff8b40b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 21:01:28 -07:00
Matej SirovatkaandGitHub b2c6fe9aec refactor(moe): unify runtime and checkpoint layout (#3411)
## Summary

### Model and checkpoint contract

- Replace the separate standard, GPT-OSS, and Nemotron expert/router
implementations with one canonical MoE tree.
- Store routed expert weights as separate `gate_proj`, `up_proj`, and
`down_proj` parameters. Non-gated experts omit `gate_proj`.
- Nest every custom router at `mlp.router.gate`, routed experts at
`mlp.experts`, and optional shared experts inside `mlp`.
- Store the single selection-only router bias at
`mlp.router.selection_bias`; model-specific checkpoint names are
converted only at the HF boundary.
- Keep shared expert projections canonical. Qwen3.5 alone nests its
scalar sigmoid gate at `mlp.shared_expert.output_gate`, with conversion
mapping the standalone Hugging Face key at the boundary.
- Use the same activation protocol and `FeedForward` implementation for
dense MLPs, shared experts, and grouped experts.
- Make shared-expert construction exclusively parent-owned: model layers
pass an explicit `FeedForward`/subclass or `None`, while `MoEArgs` and
`MoE` never infer or construct one.
- Keep existing HF source layouts at the conversion boundary. GPT-OSS
alone adds the structural split/join required for its interleaved source
tensor.
- Require `.prime-v1` in reusable `<conversion_dir>/prime` caches so
legacy Prime layouts fail before loading.

### MoE runtime contract

- Use one routed execution sequence for every backend: dispatch tokens,
run canonical grouped experts, combine tokens.
- Select grouped expert compute through explicit BF16, DeepGEMM FP8, or
MXFP8 implementations. `MoEArgs` remains architecture-only.
- Select local/Torch or DeepEP token dispatch once during model setup.
Dispatchers own routing metadata, communication, padding, chunking, and
synchronization.
- Keep `TokenDispatcher` as the structural interface while a shared base
owns the canonical run/synchronize sequence; local, Torch, and DeepEP
implementations own only their dispatch/combine details.
- Keep DeepEP combine events, concatenate streams, and flattened
dispatch state owned by each dispatcher; chunking uses the equal input
shape shared by EP ranks and does not synthesize empty chunks.
- Ignore dispatch configuration when expert parallelism resolves to one
rank; local dispatch remains active and DeepEP has no optimizer side
effects.
- Keep grouped expert execution directly in `GroupedExperts.forward` and
router confidence accounting directly in
`TokenChoiceTopKRouter.forward`.
- Shard every canonical expert parameter with one backend-independent
`Shard(0)` placement.
- Keep dense linear quantization, routed-expert compute, and EP
transport independent.
- Remove the TorchTitan module hooks, expert decorator, dynamically
attached process group, backend attributes, tensor-subclass
interception, and process-global MXFP8 patches from the reachable path.
- Vendor the narrow MXFP8 grouped-GEMM and Torch EP transport
implementation in [prime-kernels PR
#1](https://github.com/PrimeIntellect-ai/prime-kernels/pull/1),
preserving the pinned torchao revision and BSD license.

## Public contracts

Checkpoint tree:

- `mlp.router.gate`: `nn.Linear`
- `mlp.router.selection_bias`: optional persistent selection-only buffer
- `mlp.experts.gate_proj`: stacked `nn.Parameter` for gated experts,
absent for non-gated experts
- `mlp.experts.up_proj`: stacked `nn.Parameter`
- `mlp.experts.down_proj`: stacked `nn.Parameter`
- `mlp.shared_expert.{gate_proj,up_proj,down_proj}`: `FeedForward`
projections when present
- `mlp.shared_expert.output_gate`: Qwen3.5-only scalar `nn.Linear`
- expert matrices: `[num_experts, output_features, input_features]`

Runtime configuration:

```toml
[trainer.model.moe.compute]
type = "bf16"  # bf16 | deepgemm_fp8 | mxfp8

[trainer.model.moe.dispatch]
type = "torch"  # torch | deepep
transport = "bf16"  # bf16 | mxfp8 for torch dispatch
```

DeepEP owns its tuning fields:

```toml
[trainer.model.moe.dispatch]
type = "deepep"
num_sms = 20
token_chunk_size = 4096
```

This is intentionally breaking. `enable_grouped_gemm`, `enable_a2a`,
`ep_comm_backend`, `deepep_num_sms`, and `deepep_token_chunk_size` are
removed without aliases.

## Validation completed

- Foundation conversion, detector, marker, state-loading, checkpoint,
NIXL graph, and wire-format tests passed.
- Focused CPU configuration and MoE contracts: 143 passed.
- Focused MoE runtime configuration parametrizations after the EP=1
no-op change: 6 passed.
- Affected custom-model CUDA suite: 24 passed, 3 skipped across AFMoE,
GLM, GPT-OSS, Nemotron, Qwen3/Qwen3.5, and state loading.
- Final H200 model suite after execution-path cleanup: 81 passed, 3
skipped (Slurm 2597).
- Torch EP on two H200 GPUs passed with BF16 and DeepGEMM FP8, top-k 2,
both score locations, shared experts, gated/non-gated/bias variants,
uneven routing, a rank receiving zero routed tokens, and
input/router/expert gradients.
- Final Torch EP BF16 and DeepGEMM FP8 matrix passed after the cleanup
(Slurm 2596).
- DeepEP on two H200 GPUs passed with BF16 and DeepGEMM FP8, chunking
on/off, both score locations, shared experts, a rank receiving zero
routed tokens, and gradients.
- Final DeepEP BF16 and DeepGEMM FP8 matrix passed after the cleanup
(Slurm 2595).
- Parent-owned shared-expert construction: 16 focused CPU tests and 64
H200 model tests passed, with 3 expected skips (Slurm 2600).
- Full-graph MoE and shared `FeedForward` compile validation passed
after the ownership cleanup (Slurm 2601).
- Local DeepGEMM FP8 passed across all supported topology, activation,
and bias combinations.
- `torch.compile(fullgraph=True)` forward/backward passed for the full
MoE and shared `FeedForward` across all supported topology/activation
combinations.
- Single-rank DCP and Torch EP + FSDP DCP model/optimizer resume passed.
- The `mxfp8_moe` wheel build includes its public module, manifest, and
license; the module imports against the pinned torchao build.
- Unsupported H200 MXFP8 selection fails before model mutation.
- Review audit: every queued DeepEP combine event is now synchronized,
including chunked execution (two-H200 Slurm 2604).
- Dispatcher review cleanup passed on two H200s: DeepEP BF16/DeepGEMM
with chunking and a zero-receive rank (Slurm 2847), plus Torch EP
topology/bias/zero-receive coverage (Slurm 2848).
- The exact `reverse_text_moe` integration passed end-to-end on two
H200s with an isolated conversion cache (Slurm 2607).
- Conversion ranks now make the create decision on master and validate
`.prime-v1` only after the final all-rank barrier.
- Canonical router selection bias: 12 CPU MoE/conversion tests passed;
CUDA checkpoint loading, Nemotron, and GLM model tests passed, with the
existing GLM BF16 gradient comparison passing on isolated rerun after
one threshold-edge miss (Slurm 2851/2852).
- Ruff, Ruff formatting, compileall, and `git diff --check` passed.

## Deliberate exclusions

- MultiLoRA is not adapted to the new runtime and may fail.
- Fused-MoE trainer integration is removed and will be reconsidered only
after the canonical runtime is finalized.
- Routed-expert selective activation checkpointing is removed; the
remaining selective targets are unchanged.

## Remaining before marking ready

- Run numerical MXFP8 grouped-GEMM and MXFP8 Torch EP transport
forward/backward on SM100 hardware. The available Slurm fleet currently
has only H200 nodes.
- Merge prime-kernels PR #1, publish wheels containing `mxfp8_moe`, and
update the `pyproject.toml`/lock wheel pins. The currently pinned v0.8.0
wheel does not contain this module.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> This changes the MoE forward/backward path, expert-parallel dispatch,
checkpoint key layout, and trainer TOML in breaking ways across all
custom MoE models.
> 
> **Overview**
> **Breaking trainer config:** MoE is configured via
`[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, `mxfp8`) and
`[trainer.model.moe.dispatch]` (`torch` with `transport`, or `deepep`
with `num_sms` / `token_chunk_size`). Dense
`[trainer.model.quantization]` no longer drives expert GEMMs or EP
transport. Removed flags include `ep_comm_backend`, `deepep_*`,
`moe_use_grouped_mm`, `moe_fused_kernel`, and quantization
`enable_grouped_gemm` / `enable_a2a`.
> 
> **Unified MoE execution:** All custom models share one `MoE`
path—`TokenChoiceTopKRouter`, stacked `GroupedExperts` (`gate_proj` /
`up_proj` / `down_proj`), and a pluggable `TokenDispatcher`
(`LocalTokenDispatcher`, `TorchTokenDispatcher`,
`MXFP8TorchTokenDispatcher`, `DeepEPTokenDispatcher`).
`configure_moe_runtime` wires grouped GEMM backends and dispatch at
setup; EP weight sharding is only `ExpertWeightParallel`. DeepEP
dispatch/combine, grouped-GEMM permutation, and chunk pipelining live in
the new dispatcher layer instead of ad hoc `MoE` hooks.
> 
> **Checkpoint and model surface:** PrimeRL checkpoints rename routed
weights from `w1/w2/w3` to `gate/down/up_proj`, move selection bias to
`mlp.router.selection_bias`, and add GPT-OSS HF↔prime conversion.
`LatentMoE` / Nemotron-specific expert classes are folded into the
canonical tree; dense layers use `FeedForward`. Reusable `prime`
conversion caches must include a `.prime-v1` marker.
> 
> **Removed / docs:** Fused `flash_moe` trainer integration and
`bench_fused_moe.py` are dropped; `routed_experts` selective activation
checkpointing is removed. Docs and examples (e.g. GLM-5) are updated for
the new tables.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ffd5be7d48d28b889f9d73c8815ab0eb618b9dc9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-29 01:03:32 +02:00
Yaser AfsharandGitHub 66e1c2cb07 chore(nixl): use canonical VRAM mem_type (#3215)
## Change

`prep_xfer_dlist(mem_type=...)` passed `"cuda"`, which nixl marks
deprecated in
favor of `"VRAM"` (`src/api/python/_api.py`):

    "VRAM": nixlBind.VRAM_SEG,
    "cuda": nixlBind.VRAM_SEG,  # deprecated

Both resolve to `VRAM_SEG`, so this is a no-op at runtime. `"VRAM"` is
also the
spelling nixl's own `_tensor_mem_type()` helper emits.

## Note

The accelerator-derived `UCX_TLS` defaults this PR originally carried
are dropped
per review. Since `set_ucx_env_defaults()` uses `setdefault`, a non-CUDA
accelerator supplies its own copy transport from the launcher
environment.

---------

Signed-off-by: Yaser Afshar <yaser.afshar@intel.com>
2026-08-29 00:27:17 +02:00
Matej SirovatkaandGitHub 26af0c49e6 perf(nixl): pipeline reusable weight pulls (#3341)
## Summary

- use ModelExpress only for startup peer discovery and the trainer
tensor table, then use exact versioned NIXL notifications for all policy
transfers, including startup
- prepare static NIXL READ requests once, repost them after completion,
and post every trainer-rank pull in a group before waiting
- attach trainer arena credits to READ completion instead of performing
a separate acknowledgement handshake
- add explicit, opt-in two-arena overlap through
`weight_broadcast.overlap_transfer_and_replay`

The path remains receiver-driven PULL. The default remains one arena
because the second arena has a model-dependent GPU-memory cost. This PR
adds no fallback protocol, runtime sizing heuristic, profiling
instrumentation, or inference-scheduler change.

## Protocol

ModelExpress is the one-time startup discovery plane. It exchanges the
trainer tensor table and NIXL agent metadata, after which the fixed
peers establish NIXL/UCX connections. The shared
`WeightSender`/`WeightReceiver` sentinel handshake offers and
acknowledges every policy version before the NIXL transport runs; this
is the same outer lifecycle used by the other transports. MX source
statuses are not used. Policy 0 and later policies use exact NIXL ready
and complete notifications for the transfer itself.

```mermaid
sequenceDiagram
    participant T as Trainer ranks
    participant B as Broadcast directory
    participant R as NIXL weight receiver
    participant MX as ModelExpress
    participant I as Inference ranks

    Note over T,I: One-time setup
    I->>MX: Publish inference NIXL metadata
    R->>MX: Publish receiver NIXL metadata

    loop Each policy version
        T->>B: Offer version with sender ready marker
        R->>B: Acknowledge with receiver ready marker
        T->>B: Mark transfer started
        alt First version
            T->>MX: Publish tensor table and trainer metadata
            T->>MX: Fetch inference and receiver metadata
            R->>MX: Fetch trainer table and metadata
            Note over T,I: Establish NIXL and UCX connections once
        end
        T-->>R: NIXL policy ready notification
        R->>I: Update weights
        loop Each transfer group
            T-->>I: NIXL group ready notification
            I->>T: Post READs to every trainer rank
            T-->>I: RDMA payload
            I-->>T: READ completion returns arena credit
        end
        I-->>R: Update complete
        R-->>T: NIXL policy complete notification
        T->>B: Commit version with finished marker
    end
```

Each group signal contains `(group index, generation)`, and each policy
signal contains `(step, event)`, so it is consumed exactly once. A
trainer staging slot is reused only after every inference rank completes
its READ from that slot.

`NIXLWeightReceiver` owns the ModelExpress discovery session, local NIXL
agent, and typed trainer peer in the orchestrator process. The generic
orchestrator and `WeightWatcher` only use the `WeightReceiver` API and
contain no NIXL-specific state. Transfer plans and the trainer
broadcaster store ordered `NixlPeer` lists, so positional trainer-agent
indices stay direct list lookups and raw NIXL agent names remain inside
the adapter. On the trainer, `finish_transfer_group` waits for every
inference rank to complete a group before advancing its generation and
allowing its arena slot to be reused.

Tensor addresses, shard routes, peers, and descriptor lists remain
static for the worker lifetime. Requests are therefore prepared once and
reposted after completion. For each group, inference waits for every
serving trainer rank, posts all trainer-rank READs, and then waits for
completion. Inference ranks rotate their trainer order, while #3340 pins
each process to the active InfiniBand port nearest its GPU.

With overlap enabled, trainer and inference allocate exactly two
largest-group-sized arenas. Inference replays and quantizes group N
while receiving group N+1. Allocation is explicit: there is no
free-memory probe, automatic downgrade, or hidden retry.

## Measured results

Every populated cell below is the median of the positive framework
`time/broadcast_weights` samples; terminal zero entries are excluded.
This is the only timing definition used in the description. Parentheses
contain Slurm job IDs, and blank cells mean that configuration was not
measured.

| Model | Old NIXL | New NIXL | New NIXL + overlap | NCCL |
|---|---:|---:|---:|---:|
| Qwen3-30B-A3B | 4.651 s (2260) | 1.898 s (2278) |  |  |
| GLM-4.5-Air | 8.676 s (2286) | 4.125 s (2288) | 3.043 s (2305) | 7.616
s (2289) |
| GLM-5.2 |  | 12.513 s (2297) | 8.577 s (2317, EP32) |  |

All NIXL baselines use the correct rail pinning, and router replay is
disabled. The GLM-4.5-Air old, new, and overlap measurements are 20-step
Hendrycks-math runs with 4096 maximum sampling tokens; the NCCL
comparison uses the same model and node roles over three positive
broadcasts. NCCL uses BF16 checkpoint-format transfer with
`quantize_in_weight_transfer = false`.

GLM-5.2 job 2317 completed 20 rollout steps and 18 steady trainer
broadcasts on 64 trainer and 32 inference H200s. Framework
`time/broadcast_weights` was 8.577s median and 12.987s p95. At the
inference client, end-to-end synchronization was 7.899s median and
12.577s p95: pause was 5.204s median / 9.882s p95, while the weight
update itself was 2.842s median / 2.960s p95. Each inference GPU
received 82.501 GB per policy; across all 576 rank/version samples, RDMA
was 1.864s median / 2.027s p95, replay was 1.954s median / 1.993s p95,
and their overlapped process time was 2.682s median / 2.836s p95. Median
payload was 44.26 GB/s per GPU, or approximately 354 GB/s across an
eight-GPU inference node. The [W&B
run](https://wandb.ai/primeintellect/prime-rl/runs/c3bee790465640d88958f100fb3d74f4)
contains the completed training metrics.

On this single framework metric, Qwen improves by 59.2% from old to new.
GLM-4.5-Air improves by 52.5% from old to new and 64.9% from old to the
final overlapped path; the final path is 60.1% faster than NCCL. GLM-5.2
improves by 31.5% from the measured EP16 one-arena path to the EP32
overlap run. Holding overlap constant, EP32 reduces median framework
broadcast time by 11.4% from the EP16 result (9.683s, job 2301), while
median client update time falls by 19.4% from 3.524s to 2.842s.
Framework timing includes the unchanged vLLM pause/resume interval,
whose variance dominates the EP32 tail, so it should not be interpreted
as raw fabric bandwidth.

## Memory and scope

Overlap adds one largest-group arena rather than another model copy. For
GLM-5.2, that is 0.308 GB per trainer GPU and 3.807 GB per inference
GPU. The EP32 run therefore used a 7.613 GB two-buffer arena per
inference GPU and added 141.5 GB across the tested
64-trainer/32-inference topology. The option is disabled by default;
models without that headroom retain the one-arena path.

GLM-5.2 uses 64 trainer H200s with EP=8 and full offload, plus DP/EP
inference with online blockwise FP8 and DeepGEMM. EP16 receives 127.800
GB per inference GPU and retains 5,056 host-side handles per rank; EP32
receives 82.501 GB per GPU and prepares 72,819 descriptors across 79
transfer groups per rank. These request structures add no model-sized
GPU allocation.

Every serving trainer rank connects to every inference rank so
completion returns exact source credits. Static membership is the
expected hot path; elastic scaling and fault tolerance remain out of
scope.

## Numerical validation

Jobs 2286 and 2305 completed the configured 20 GLM-4.5-Air rollout steps
and finalized metrics. Step 20 of job 2305 contained 0/8 trainable
traces, so it correctly emitted no optimizer or mismatch-KL row. Across
the 19 steps with measurements in both runs, mean mismatch KL was
0.002602538 before and 0.002608075 after (+0.2%); median was 0.002786405
before and 0.002702605 after (-3.0%). Router replay was deliberately
disabled, so individual steps include normal sampling variation.

## Validation

- Ruff 0.15.14: `uv run ruff format --check` and `uv run ruff check`
- `uv run python -m compileall` on changed Python modules
- `uv run pytest -q tests/unit/test_configs.py`
- ported onto main at `21a4a3245` through #3340 at `0d809b1e4`; the
generic orchestrator and `WeightWatcher` are unchanged
- two-node, three-step Qwen3-0.6B end-to-end NIXL smoke (Slurm job
2451): startup policy v0 and policies v1-v3 synchronized; trainer and
orchestrator completed
- Qwen3-30B-A3B and GLM-4.5-Air eight-rail transfer benchmarks
- GLM-5.2 ten-node EP16 and twelve-node EP32 runs with full trainer
offload, online blockwise FP8 inference, and DeepGEMM
- matched NCCL comparison on GLM-4.5-Air
- final 20-step GLM-4.5-Air Hendrycks-math run with 4096 sampling tokens
and router replay disabled

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core distributed weight-sync choreography between trainer,
orchestrator, and vLLM; mis-sync would cause stale weights or hangs,
though scope is limited to the NIXL transport path.
> 
> **Overview**
> **NIXL weight broadcast** is reworked so ModelExpress is only used for
one-time peer discovery (trainer tensor table and NIXL agent metadata).
Per-group and per-policy coordination now uses **versioned NIXL
notifications** instead of ModelExpress READY/INITIALIZING buffer
sessions.
> 
> The NIXL adapter gains **`PreparedRead`** / **`NixlPeer`**: READ
descriptor lists are prepared once, reposted each update, and all
trainer-rank pulls in a group are posted before waiting. Arena reuse is
tied to READ completion via group `(index, generation)` signals; the
orchestrator participates with policy `ready` / `complete` notifications
over NIXL.
> 
> Inference follows the trainer’s **`staging_buffer_count`** (no GPU
free-memory sizing heuristic). Optional
**`weight_broadcast.overlap_transfer_and_replay`** allocates exactly
**two** largest-group arenas on trainer and inference so the next group
can be received while the current one is replayed; default remains one
arena.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0dc85f865aa7850e5a123fbb2791a9670c631d44. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 23:04:08 +02:00
Matej SirovatkaandGitHub fc12ef2c66 feat(slurm): launch ModelExpress for NIXL transfers (#3340)
## Summary

- start a job-scoped Redis and ModelExpress service when
`slurm.launch_modelexpress = true`
- inject the trainer-head service address into trainer, inference, and
orchestrator processes, or use the configured host when
`slurm.launch_modelexpress = false`
- pin every NIXL process to the active InfiniBand HCA nearest its GPU,
so an eight-GPU node uses all eight rails
- add a pinned, idempotent installer for ModelExpress v0.3.0 and Redis
7.4.2
- remove stale job-scoped ModelExpress and Redis processes before
managed-service startup

This is the launch prerequisite for the stacked transfer optimization in
#3341. It does not change the NIXL transfer protocol itself.

## Design

With `slurm.launch_modelexpress = true`, the generated job removes stale
ModelExpress and Redis processes from an interrupted managed launch,
then starts both services on the trainer head before launching the three
prime-rl components. The resolved ModelExpress address is passed to
every component, and service logs stay in the run directory. With
`slurm.launch_modelexpress = false`, the launcher performs no service
cleanup, starts no service, and uses `weight_broadcast.host` and
`weight_broadcast.port` unchanged.

Rail selection remains local to each NIXL process. Unless
`UCX_NET_DEVICES` is explicitly configured, startup resolves the process
GPU's PCI path, selects the nearest active InfiniBand port, and
constrains UCX to that port. TP8 therefore uses one distinct local rail
per GPU instead of relying on UCX's cluster-dependent default choice.
`UCX_NET_DEVICES` remains an explicit site override.

The installer pins both service versions, verifies their checksums, and
reuses valid existing installations. Generated jobs fail directly if a
required binary or UCX capability is missing.

## Scope

- ModelExpress provides startup discovery for a fixed Slurm allocation.
- Elastic discovery, autoscaling, and fault tolerance are intentionally
out of scope.
- The local service adds two small CPU processes on the trainer head and
no GPU allocation.

## Validation

- `bash -n scripts/install_modelexpress.sh`
- ran `scripts/install_modelexpress.sh` twice and verified that the
pinned binaries are reused
- rebased onto `main` at `21a4a3245`; rendered and shell-checked managed
and external ModelExpress modes for single-node and multi-node NIXL
Slurm jobs, including main’s trainer/orchestrator completion markers
- verified stale-service cleanup is present only in managed ModelExpress
renders and absent in external-service renders
- Ruff 0.15.14: `uv run ruff format --check` and `uv run ruff check`
- `uv run python -m compileall` on changed Python modules
- `uv run pytest -q tests/unit/test_configs.py` (122 passed)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes multi-node SLURM launch and NIXL UCX/IB selection for weight
sync; misconfiguration or rail selection bugs could break or degrade
policy updates, but scope is limited to NIXL SLURM paths.
> 
> **Overview**
> Adds **job-scoped ModelExpress + Redis** startup for SLURM RL when
`[weight_broadcast] type = "nixl"` and **`slurm.launch_modelexpress`**
is true (default). Single- and multi-node sbatch templates verify the
**`third_party/ucx`** build, optionally start pinned
**modelexpress-server** / **redis-server** (new
**`scripts/install_modelexpress.sh`**), wait for readiness, and pass
**`--weight-broadcast.host`** into trainer, orchestrator, and the local
`rl` launcher. With **`launch_modelexpress = false`**, jobs use
configured **`weight_broadcast.host`** / **`port`** and skip
managed-service cleanup.
> 
> **NIXL networking** now picks **`UCX_NET_DEVICES`** per process from
the **InfiniBand port nearest each GPU** (unless already set), and
inference workers **rotate which trainer ranks they pull from** so
concurrent pulls spread across rails.
> 
> Docs and the start-run skill describe install steps and the new SLURM
flag. **Does not change the NIXL transfer protocol** (prerequisite for
stacked transfer work).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0d809b1e4d24121690faab3a22b1f7f832de4f53. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 22:43:22 +02:00
Mika SenghaasandGitHub 95734aa1dd feat: make ipo the default rl loss (#3418)
## Summary

- Remove the DPPO loss and make IPO the default RL loss.
- Rename the IPO trust-region setting from `ipo_threshold` to `eps`.
- Update token exports, metrics, docs, tests, and agent skills for IPO.

## Breaking

- Remove `[trainer.loss] type = "default"`, `DefaultLossConfig`, and
`default_loss_fn`. Omit `[trainer.loss]` or set `type = "ipo"`.
- Rename `ipo_threshold` to `eps`. Update all IPO loss configs to use
`eps`.
- Remove the DPPO-only `dppo_mask_low` and `dppo_mask_high` settings.
- Remove the DPPO-only `is_masked_low`, `is_masked_high`, and
`masked_advantage_*` trainer metrics. Use `is_masked` for the IPO
trust-region mask.

## Verification

- RL loss GPU tests: 10 passed.
- Nemotron-H KL pipeline GPU tests: 7 passed.
- Ruff check and format hooks passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Removes the default RL loss and changes default training dynamics for
every run that relied on implicit DPPO; configs using `type = "default"`
or DPPO fields will fail or need migration.
> 
> **Overview**
> Makes **Importance Policy Optimization (IPO)** the only built-in RL
loss and the default when `[trainer.loss]` is omitted. The DPPO-based
`default` loss (`DefaultLossConfig`, `default_loss_fn`, `dppo_mask_low`
/ `dppo_mask_high`) is removed.
> 
> IPO trust-region config is renamed from `ipo_threshold` to **`eps`**
(default `0.1`). `setup_rl_loss_fn` always routes non-custom configs to
`ipo_loss_fn`.
> 
> **Breaking for configs:** use `type = "ipo"` or omit the section;
`type = "default"` and DPPO knobs no longer exist.
> 
> Monitoring and exports align with symmetric IPO masking: docs/skills
point to **`is_masked/mean`** instead of DPPO `masked_advantage_*`
metrics; W&B filtering drops the old DPPO-only series; token export
computes mask flags from `|prob_delta| > eps`. Unit tests now exercise
IPO instead of the default loss.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2c4227527992519e8ff7e1d08c8866c5068febb1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-27 11:35:01 -07:00
Mika SenghaasandGitHub 0c58f007bc feat: record run invocation (#3409)
## Summary

- Write a shell-safe `command.txt` for every config attempt.
- Keep the outer command when a pinned child launch uses the same
attempt.
- Show each attempt's command in the dashboard Config view.
- Document the command artifact in the config and training runbooks.

<img width="2656" height="1506" alt="Screenshot 2026-08-26 at 11 34
20 AM"
src="https://github.com/user-attachments/assets/d5b4da3a-f6a9-4bdc-9c16-ae41c1d192c6"
/>

## Verification

- `uv run pytest tests/unit/utils/test_pathing.py -q`
- `uv run ruff check src/prime_rl/utils/pathing.py
src/prime_rl/entrypoints/rl.py src/prime_rl/entrypoints/sft.py
src/prime_rl/entrypoints/inference.py src/prime_rl/entrypoints/evals.py
src/prime_rl/dashboard/server.py tests/unit/utils/test_pathing.py
tests/integration/dashboard_smoke.py`
- `node --check src/prime_rl/dashboard/static/app.js`
- Ran reverse-text SFT through step 10 with `--max-steps 10`.
- Resumed reverse-text SFT from step 10 through step 11.
- Ran the dashboard browser smoke test against the per-attempt commands.
- Ran a two-node SFT SLURM dry-run and checked its pinned config
attempt.
- Ran a local SFT dry-run after the review changes and checked
`command.txt`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Adds run-metadata recording and dashboard read-only UI; no changes to
training, inference, or config resolution logic.
> 
> **Overview**
> Each launch now writes **`command.txt`** under `configs/attempt_<n>/`
with the full **`uv run <entrypoint>`** invocation (CLI overrides
included), using **`shlex.join`** for shell-safe quoting.
**`write_launch_artifacts`** replaces direct **`write_launch_toml`** on
**`rl`**, **`sft`**, **`inference`**, and **`evals`**; the command file
is created **only if missing** so a pinned child process reusing the
same attempt keeps the **outer** launcher command.
> 
> The dashboard **Config** tab surfaces that command (per attempt) with
a **copy** button; **`/api/runs/{run}/configs`** and
**`/api/runs/{run}/config`** expose **`command.txt`**. Docs and
training/config/dashboard skills describe the artifact and point
monitors to **`configs/latest/command.txt`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c9ce79c772d842af7556626a790e78faba20be75. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-26 12:05:54 -07:00
Mika SenghaasandGitHub d09bf96dbe feat: cancel superseded online eval episodes (#3402)
## Summary
- cancel queued and in-flight SFT eval episodes when the trainer offers
a newer checkpoint
- report scores from completed episodes and log the cancelled count and
fraction for each superseded checkpoint
- show the cancellation fraction in the local dashboard and W&B eval
sections
- allow `eval.cancel_on_new_checkpoint = false` to drain every epoch,
which can idle the trainer while slow evals finish
- document the online-eval behavior and configuration

## Verification
- `uv run ruff check
packages/prime-rl-configs/src/prime_rl/configs/evals.py
src/prime_rl/evals/evals.py src/prime_rl/monitors/wandb/overview.py
tests/unit/test_configs.py`
- `node --check src/prime_rl/dashboard/static/app.js`
- `uv run pytest tests/unit/test_configs.py -q` (122 passed)
- two-GPU SFT and online-eval run with NCCL broadcast (steps 0 and 1
reported partial scores with 6 of 8 episodes cancelled; step 2 completed
all 8 episodes; the launcher exited successfully)
- dashboard browser smoke test for the cancellation panel and run
metrics
- `PYTEST_OUTPUT_DIR=/tmp/prime-rl-eval-cancel-tests uv run pytest
tests/unit -m "not gpu" -q` (477 passed, 86 deselected; one unrelated
baseline Qwen3-VL fixture failure in
`tests/unit/orchestrator/test_qwen3_vl_e2e.py`)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes online eval scheduling and trainer–evals checkpoint handoff;
mis-cancellation could skew eval metrics or stall weight updates, but
behavior is configurable and scoped to online evals.
> 
> **Overview**
> Online SFT evals now **preempt unfinished epochs** when the trainer
publishes a newer checkpoint, so slow eval rollouts no longer block
loading the next weights. This is the default
(`eval.cancel_on_new_checkpoint = true`); set it to `false` to finish
every triggered epoch (the trainer may idle waiting).
> 
> The evals loop detects a superseding published step, calls
**`Dispatcher.cancel_eval_step`**, and **`EvalSink`** counts cancelled
groups toward partial epochs instead of treating `GroupCancellation` as
fatal. **`GroupCancellation`** carries the eval **`step`** and a
**`superseded`** reason. Weight reload hooks **`on_version_pending` /
`on_new_version`** run before consuming the epoch. Partial results still
log with **`eval/{env}/all/cancelled/count`** and **`cancelled/mean`**
(dashboard and W&B overview panels added).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
730dce804cc20fb3257c8c3a457bb22f95a82e94. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-26 11:32:01 -07:00
Mika SenghaasandGitHub 05967ffcd2 feat: preserve configs by attempt (#3405)
## Summary

- store launch TOML and resolved JSON files under `configs/attempt_<n>/`
- point `configs/latest` and `logs/latest` at the same launch attempt
- pin local and SLURM child processes to concrete attempt paths
- add config attempt selection to the dashboard
- default config and log selectors to `latest (attempt <n>)`
- keep the dashboard and checkpoint converter compatible with legacy
runs

## Breaking

- New runs no longer write configs to `configs/resolved/` or launch TOML
files directly under `configs/`. Update custom tooling to read
`configs/latest/resolved/` and `configs/latest/<entrypoint>.toml`. Use
`configs/attempt_<n>/` for a specific launch.

## Verification

Before this change, a resumed launch replaced the run-scoped config
files. After this change, both SFT and RL preserved attempt 1 and wrote
the resumed settings to attempt 2. Both `configs/latest` and
`logs/latest` resolved to `attempt_2`.

- SFT completed steps 1-5, then resumed from step 5 and completed steps
6-10
- RL completed steps 1-5, then resumed from step 5 and completed steps
6-10
- browser dashboard smoke passed for both resumed runs, including
attempt switching
- local, single-node SLURM, multi-node SLURM, and inference dry runs
produced matching attempt paths
- all generated SLURM scripts passed `bash -n`
- pathing unit tests passed: 11 tests
- Ruff checks and format checks passed

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes the on-disk run layout and all launch paths (local, SLURM,
evals); legacy fallbacks limit breakage, but custom tooling must move
from `configs/resolved/` to `configs/latest/resolved/`.
> 
> **Overview**
> Each launch now keeps its **launch TOML and resolved JSON** under
**`configs/attempt_<n>/`** (resolved files in **`resolved/`**), with
**`configs/latest`** aligned to the same attempt as **`logs/latest`**.
Resumes no longer overwrite prior launch configs.
> 
> Launchers allocate matching config and log attempts via
**`prepare_attempt_dirs`** / **`create_attempt_dirs`**, pin children
with **`PRL_ATTEMPT_CONFIG_DIR`** and **`PRL_ATTEMPT_LOG_DIR`**, and
SLURM templates receive concrete **`config_dir`** / **`log_dir`**
instead of shell attempt loops. **`evals`** writes attempt-scoped
configs like **`rl`** / **`sft`**.
> 
> The **dashboard** adds a config **attempt** selector and **`attempt`**
query params on config APIs; logs already supported attempts and now
default to **`latest (attempt <n>)`**. **`get_config_dir`** and
dashboard resolution keep **legacy** `configs/resolved/` runs working.
> 
> Docs, skills, **`convert_dcp_to_bf16`**, and tests/smoke cover the new
paths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
29cab3515b5c1b97eaa3aa53f9be3b947a11802c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-26 11:06:00 -07:00
Mika SenghaasandGitHub 21a4a32450 fix: hide unused sft val plots (#3404)
## Summary

- Expose whether an SFT run has a validation dataset in dashboard
metadata.
- Hide `val/loss` and `val/perplexity` plots when validation is not
configured.
- Keep both validation plots when the resolved SFT config includes
`val.data`.

## Verification

Before: `dashboard-sft-no-val-1-step` showed empty `val/loss` and
`val/perplexity` plots.

After:

- `dashboard-sft-no-val-1-step` shows only training loss, perplexity,
and epoch plots.

<img width="1607" height="1045" alt="Screenshot 2026-08-26 at 12 15
49 AM"
src="https://github.com/user-attachments/assets/d4ebe5bf-48fa-4f07-a626-0cb9f369dfa1"
/>

- `dashboard-sft-with-val-1-step` shows both validation plots and
reports `val/loss = 5.811`.

<img width="1607" height="1045" alt="Screenshot 2026-08-26 at 12 15
32 AM"
src="https://github.com/user-attachments/assets/4746e568-dea3-4660-9692-545bf2dfa5dd"
/>

Both runs completed one SFT step. A browser check confirmed the expected
plot titles and rendered validation data.

- Ran `node --check src/prime_rl/dashboard/static/app.js`.
- Ran `uv run --no-sync ruff check src/prime_rl/dashboard/server.py`.
2026-08-26 00:17:10 -07:00
Mika SenghaasandGitHub a070beecbd fix: show single-point metrics as dots (#3403)
## Summary

- Render a dot when a metric series has one data point.
- Keep line-only rendering after a second data point arrives.
- Apply the same behavior to auxiliary band series.

## Verification

Before: a metric series with one sample rendered no visible data. After:
the sample renders as a dot at its chart coordinate. The dot disappears
when a second sample arrives.

<img width="546" height="285" alt="Screenshot 2026-08-26 at 12 07 40 AM"
src="https://github.com/user-attachments/assets/4af1930a-4bc0-47d3-990f-4bf723b641d6"
/>

- Confirmed that one-point series enable markers and two-point series
disable them.
- Ran `node --check src/prime_rl/dashboard/static/app.js`.
2026-08-26 00:08:31 -07:00
Mika SenghaasandGitHub 7da7c4d108 fix: unify multi-node SFT launch logging (#3401)
## Summary

- run multi-node SFT training and online evals in one SLURM job
- reserve `num_train_nodes + num_infer_nodes` and assign inference nodes
first
- keep every node in the shared step until trainer and eval completion
sentinels exist
- keep trainer, inference, router, evals, and env logs in one
`logs/attempt_<n>` directory
- give standalone `evals` launches an attempt directory and update
`logs/latest`
- update configuration help, training docs, and run skills for the new
topology

## Breaking

- Multi-node SFT online evals now require one combined SLURM allocation.
The scheduler must allocate all trainer and inference nodes together.
Trainer nodes remain allocated until the final eval finishes.
- The launcher no longer writes `launcher/eval.sbatch`. Custom
multi-node SFT templates must launch inference and eval roles from the
main SFT template.
- The bundled `multi_node_sft_eval.sbatch.j2` template is removed. Use
`multi_node_sft.sbatch.j2` as the template source.

## Verification

Before this change, a multi-node SFT dry run generated two batch
scripts. The eval script wrote inference, evals, and env logs directly
under `$OUTPUT_DIR/logs`.

After this change, the same dry run generates only
`launcher/sft.sbatch`. A `2 trainer + 1 inference` configuration renders
`#SBATCH --nodes=3`. The script contains one attempt allocator and no
`TRAIN_JOB_ID`, log-path marker, or NCCL-host marker. It backgrounds
trainer and evals roles. Every node waits for the job-specific trainer
and eval completion sentinels. Online-eval and trainer-only renders both
pass `bash -n` and sentinel checks.

Local two-GPU end-to-end smokes passed:

- SFT completed one training step with NCCL broadcasts and evals at
steps 0 and 1.
- RL completed one training step and evals at policy versions 0 and 1.
- Standalone inference served a standalone two-example eval run.

The filesystem audit found relative `latest -> attempt_1` links for all
three runs. Every component log was nonempty UTF-8 text. No component
log existed outside its attempt directory.

Targeted config, CLI parser, and pathing tests passed: 282 tests. Ruff
checks and formatting checks passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking change for multi-node SFT online evals: cluster scheduling
and custom SLURM templates must launch inference and trainer in one job;
misconfiguration could strand nodes or break NCCL broadcast wiring.
> 
> **Overview**
> **Multi-node SFT with online evals** no longer submits separate
trainer and eval SLURM jobs. One allocation reserves `num_train_nodes +
num_infer_nodes`; the first `num_infer_nodes` run the inference pool,
router, env servers, and `evals`, and the rest run the trainer. NCCL
weight broadcast uses the trainer rank-0 hostname directly—no cross-job
`TRAIN_JOB_ID` or shared run-dir host marker.
> 
> The launcher only writes `launcher/sft.sbatch` (
**`multi_node_sft_eval.sbatch.j2` is removed** ). The unified template
backgrounds trainer and eval roles, waits on job-specific completion
sentinels so the job can drain the final eval after a clean trainer
exit, and uses one attempt-scoped log tree under `logs/attempt_<n>/`
(including `evals.log` and env logs). Standalone/local SFT sets
`PRL_LOG_DIR` for evals; the dashboard still lists legacy `logs/envs/`
files for older runs.
> 
> Docs, `SFTConfig` field descriptions, and training skills are updated
for the single-job topology and log paths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
997c8c1457c1ba95a013eb353abdcb754bc1a648. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-25 23:58:02 -07:00
parkerpettitandGitHub 9e3be00b39 feat(dashboard): add trace timeline viewer (#3390)
## Summary

- add a Prime-styled synchronized timeline for agent lifecycle phases
and model-call activity
- render VF-native root-to-leaf `Branch` paths instead of inferring
harness-specific subagent identities or hierarchy
- keep each environment agent as the main lane and show one flat row per
native zero-based branch index, ordered by its first unique activity
- retain shared-prefix calls on every branch path and mute them visually
to distinguish reuse from branch-unique execution
- show the trace reward on every branch training sample
- preserve exact call identity, including repeated calls, node-less
calls, and explicitly unknown timing
- show input, cached input, total input, output, reasoning, maximum
context length, total tokens, and cost in timeline tooltips and Overview
when reported
- keep large multi-agent tab strips horizontally scrollable and
integrate with Messages and Rendered transcript modes
- reject stale timeline responses after episode selection changes and
preserve unknown completed-phase end timing
- retain report navigation, transcript highlighting, rendered-token
mode, and dashboard view-command support

## Screenshot of multiagent episode (with subagent calls)
Codex harness
<img width="2400" height="2490" alt="image"
src="https://github.com/user-attachments/assets/1fe4a274-5cf2-49de-adf8-f328086d9f4a"
/>

RLM harness
<img width="2400" height="3260" alt="image"
src="https://github.com/user-attachments/assets/1ea0d693-a72e-495d-8133-c5b82770f2a0"
/>

## Validation

- `uv run --frozen ruff check .`
- `uv run --frozen ruff format --check .`
- `node --check src/prime_rl/dashboard/static/app.js`
- real interactive Codex multi-agent episode projects 29 native branches
across four environment-agent traces, with every branch containing
exactly its root-to-leaf model calls and all 46 actual calls covered
- real interactive RLM multi-agent episode projects 40 native branches
across four environment-agent traces, with every branch containing
exactly its root-to-leaf model calls and all 125 actual calls covered
- captured full-episode Playwright screenshots of both branch timelines
2026-08-25 17:53:01 -07:00
ef66401434 feat: traces -> hf dataset converter (#3382)
## Summary

- Replace `scripts/export_sft.py` with
`tools/convert_traces_to_hf_dataset.py`.
- Convert each branch of each agent trace into one dataset row.
- Export trainable and non-trainable agents without selection or
filtering.
- Add top-level outcome fields for downstream filters, including
`reward`, `stop_condition`, `has_error`, and `is_truncated`.
- Preserve task, run, agent, error, timing, usage, call, reward, metric,
and trace metadata.
- Push to a private Hugging Face Hub dataset by default, with `--public`
as an explicit opt-out.
- Use `--local` to write Parquet files with Hugging Face dataset-card
metadata.
- Preserve existing dataset-card content when local metadata is updated.

## Verification

### Eval → dataset → SFT

1. Generated eight GSM8K episodes without uploading the eval:

```bash
uv run --project /home/ubuntu/prime-rl eval gsm8k -n 8 -r 1 -c 8 \
    --no-push -o /tmp/trace-converter-e2e-20260825 \
    --run.name trace-converter-gsm8k --run.dir eval
```

All eight episodes succeeded. Mean reward was 1.0 and the error rate was
0.0.

2. Converted the trace file into a local Hugging Face dataset:

```bash
uv run --project /home/ubuntu/prime-rl python \
    tools/convert_traces_to_hf_dataset.py \
    /tmp/trace-converter-e2e-20260825/eval/traces.jsonl \
    --name /tmp/trace-converter-e2e-20260825/dataset --local
```

The converter wrote eight branch rows. The dataset loaded through
`load_dataset`.

3. Trained Qwen3-0.6B on the converted dataset:

```bash
uv run --project /home/ubuntu/prime-rl sft \
    --output-dir /tmp/trace-converter-e2e-20260825 --run.name sft \
    --max-steps 5 --model.name Qwen/Qwen3-0.6B \
    --data.type sft --data.name /tmp/trace-converter-e2e-20260825/dataset \
    --data.subsets '["default"]' --data.splits '["train"]' \
    --data.seq-len 2048 --data.batch-size 4 --data.micro-batch-size 1 \
    --deployment.gpus-per-node 2 --deployment.num-train-gpus 1
```

The run completed all five steps. Final loss was 0.7764, the NaN count
was zero, and peak GPU memory was 10.7 GiB. No Hub or Prime platform
uploads occurred.

### Additional checks

- Ran the Ruff check and format pre-commit hooks.
- Converted a separate saved file with 132 episodes and loaded all 132
branch rows with `load_dataset`.
- Verified that a non-trainable errored trace still emits its branch row
and top-level error fields.
- Verified that local updates preserve plain, valid-frontmatter, and
unclosed-frontmatter README content.
- Verified that default uploads pass `private=True`, while `--public`
passes `private=False`.

## Breaking

- `scripts/export_sft.py` is removed. Use `uv run python
tools/convert_traces_to_hf_dataset.py <traces.jsonl> --name
<dir-or-repo-id>`.
- The converter no longer accepts `--min-reward` or `--drop-truncated`.
Apply filters in a separate script.
- The converter pushes to the Hub by default. Use `--local` to write a
local dataset.
- New Hub datasets are private by default. Use `--public` to create a
public dataset.
- The `--push` flag is removed because Hub upload is now the default.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are limited to offline export tooling and CLI workflows; no
in-repo training or runtime code is modified in this diff.
> 
> **Overview**
> **Removes** `scripts/export_sft.py` and **adds**
`tools/convert_traces_to_hf_dataset.py` as the path from eval/train
`traces.jsonl` to Hugging Face datasets.
> 
> The new converter reads **one episode per line** (`WireEpisode`)
instead of per-trace wire rows, emits **one row per branch** for every
agent trace (no `--min-reward`, `--drop-truncated`, or empty-branch
skipping), and keeps **`messages`** plus JSON **`tools`** for SFT while
adding top-level filter fields (`reward`, `stop_condition`, `has_error`,
`is_truncated`, etc.) and JSON metadata for task, run, agent, errors,
timing, and usage.
> 
> **Output behavior changes:** Hub upload is the default via required
`--name`; use **`--local`** to write `<name>/<subset>/<split>.parquet`
and update **`README.md`** dataset-card configs for `load_dataset`.
**`--public`** controls visibility on new Hub repos; **`--push`** is
gone.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8834b7aea61f2e6e9ba467758b593cf6ffb7a29b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 16:14:03 -07:00
480 changed files with 38850 additions and 23799 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
# .git stays: docker-editable-pretend-versions.sh reads .git/modules via the bind mount.
.git
**/.git
outputs
**/.venv
**/__pycache__
+61 -9
View File
@@ -172,7 +172,7 @@ jobs:
- name: Checkout
uses: actions/checkout@v7
with:
ref: ${{ needs.prepare.outputs.ref }}
ref: ${{ needs.prepare.outputs.full_sha }}
fetch-depth: 0
submodules: false
@@ -192,6 +192,53 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
with:
# CVE-2026-93318: pin the BuildKit builder to the patched release so
# the version is deterministic on the self-hosted runners (otherwise
# the rolling moby/buildkit:buildx-stable-1 tag is used, and a
# persistent runner may keep a stale local copy of it).
driver-opts: image=moby/buildkit:v0.33.1@sha256:cec9f139f45e93c5c69c60f8b07cfad9f43f4ef6b6a6cd917527fea5ff2e3dea
- name: Set up uv
uses: astral-sh/setup-uv@v7
with:
version: "0.11.9"
enable-cache: false
- name: Resolve dependency image and package versions
id: dependency
env:
GH_TOKEN: ${{ github.token }}
SUFFIX: ${{ matrix.suffix }}
run: |
set -euo pipefail
key=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py fingerprint .)
# deps-v2: remediation epoch for CVE-2026-93318 — the fingerprint
# hashes only Dockerfile/lock inputs, not the workflow or BuildKit
# version, so pre-fix deps-${key} images would otherwise be reused
# as the runtime base instead of being rebuilt by the pinned v0.33.1
# builder.
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-v2-${SUFFIX}"
digest=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py resolve "$image")
echo "image=${image}" >> "$GITHUB_OUTPUT"
echo "digest=${digest}" >> "$GITHUB_OUTPUT"
bash scripts/docker-editable-pretend-versions.sh --github-output . >> "$GITHUB_OUTPUT"
- name: Build and push dependencies
id: dependencies
if: steps.dependency.outputs.digest == ''
uses: docker/build-push-action@v7
with:
context: .
file: ./Dockerfile.cuda
target: dependencies
outputs: type=image,push=true,compression=zstd,compression-level=3
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
# builders (cache writers since 2026-08-16) must not be re-imported.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: ${{ steps.dependency.outputs.image }}
- name: Build and push
id: build
@@ -199,15 +246,17 @@ jobs:
with:
context: .
file: ./Dockerfile.cuda
# zstd compresses the multi-GB venv layers several times faster than gzip at a
# comparable ratio. No `force-compression`, so base-image layers are reused as-is
# rather than needlessly recompressed. Pulling zstd layers needs containerd >= 1.5
# or Docker >= 23.
target: runtime
build-args: |
DEPENDENCY_IMAGE=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ steps.dependencies.outputs.digest || steps.dependency.outputs.digest }}
VERIFIERS_PRETEND_VERSION=${{ steps.dependency.outputs.verifiers }}
RENDERERS_PRETEND_VERSION=${{ steps.dependency.outputs.renderers }}
PYDANTIC_CONFIG_PRETEND_VERSION=${{ steps.dependency.outputs.pydantic_config }}
outputs: type=image,push=true,compression=zstd,compression-level=3
# The per-job builder is ephemeral; mode=max caches builder-stage
# layers so warm builds skip the dependency sync.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
# builders (cache writers since 2026-08-16) must not be re-imported.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
@@ -223,6 +272,8 @@ jobs:
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
DEPENDENCY_IMAGE: ${{ steps.dependency.outputs.image }}
DEPENDENCY_DIGEST: ${{ steps.dependencies.outputs.digest || steps.dependency.outputs.digest }}
PLATFORM: ${{ matrix.platform }}
SUFFIX: ${{ matrix.suffix }}
run: |
@@ -236,6 +287,7 @@ jobs:
echo "| **Image** | \`${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}-${SUFFIX}\` |"
echo "| **Commit** | \`${IMAGE_SHA}\` |"
echo "| **Digest** | \`${IMAGE_DIGEST}\` |"
echo "| **Dependencies** | \`${DEPENDENCY_IMAGE}@${DEPENDENCY_DIGEST}\` |"
} >> "$GITHUB_STEP_SUMMARY"
manifest:
-155
View File
@@ -1,155 +0,0 @@
name: Build Kernels
# Builds the `prime-kernels` wheel for x86_64 and aarch64 from the deps/prime-kernels submodule.
# Runs on every bump of that submodule to catch build breakage, and with `release_tag` to
# attach the wheels to a GitHub release — which is how they are consumed (see the `kernels`
# skill).
#
# `tag-and-release.yaml` calls this for every release, before it promotes the draft, so a
# published release always carries the wheels its `[tool.uv.sources]` pin can point at.
# `workflow_dispatch` does the same by hand, for backfilling an already published release.
#
# No GPU is needed: nvcc cross compiles for the architectures kernels.toml declares.
on:
pull_request:
paths:
- "deps/prime-kernels"
- ".gitmodules"
- ".github/workflows/build_kernels.yaml"
push:
branches: [main]
paths:
- "deps/prime-kernels"
- ".gitmodules"
- ".github/workflows/build_kernels.yaml"
workflow_dispatch:
inputs:
release_tag:
description: "Existing release tag to attach the wheels to (e.g. v0.7.0). Empty = artifacts only."
required: false
type: string
ref:
description: "Ref to build the kernels from. Empty = the ref the workflow was started on."
required: false
type: string
workflow_call:
inputs:
release_tag:
description: "Release tag to attach the wheels to. The release may still be a draft."
required: false
type: string
ref:
description: "Ref to build the kernels from. Empty = the caller's ref."
required: false
type: string
env:
# Keep in sync with the CUDA the prime-rl image is built against (Dockerfile.cuda);
# the job container image below must be edited alongside it (no env context there).
CUDA_TAG: cu128
jobs:
build:
name: Build wheel (${{ matrix.arch }})
# Uploading the wheels to a release needs write; on workflow_call the caller
# must grant it too (tag-and-release.yaml does).
permissions:
contents: write
strategy:
fail-fast: false
matrix:
include:
- runner: image-builder
arch: x86_64
- runner: image-builder-arm-2204
arch: aarch64
runs-on: ${{ matrix.runner }}
container: nvidia/cuda:12.8.1-devel-ubuntu24.04
steps:
- name: Install build tooling
run: |
apt-get update
apt-get install -y --no-install-recommends git curl ca-certificates build-essential gh
- name: Checkout
uses: actions/checkout@v5
with:
submodules: false
ref: ${{ inputs.ref }}
# deps/prime-kernels is the prime-kernels submodule and carries every kernel's sources.
- name: Init the kernels submodule
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
git submodule update --init -- deps/prime-kernels
- name: Install uv
run: |
curl -LsSf https://astral.sh/uv/install.sh | env INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR=/usr/local/bin sh
uv --version
# The wheel only imports under the exact torch it was compiled against, so build
# against the torch prime-rl resolves rather than whatever is newest today.
- name: Create build environment
env:
UV_TORCH_BACKEND: ${{ env.CUDA_TAG }}
run: |
TORCH_PIN=$(grep -A1 '^name = "torch"$' uv.lock | sed -n 's/^version = "\([^"+]*\).*"$/\1/p' | head -n1)
if [ -z "$TORCH_PIN" ]; then
echo "Could not read torch's version from uv.lock" >&2
exit 1
fi
echo "Building against torch==$TORCH_PIN"
uv venv --python 3.12 /tmp/build-env
VIRTUAL_ENV=/tmp/build-env uv pip install "torch==$TORCH_PIN" setuptools wheel ninja
# torch C++ extensions are bound to the torch and CUDA they were compiled against, so
# the wheel carries both in its local version.
- name: Stamp ABI into the version
run: |
TORCH_VERSION=$(/tmp/build-env/bin/python -c 'import torch; print(torch.__version__.split("+")[0])')
LOCAL="${CUDA_TAG}torch${TORCH_VERSION}"
sed -i -E "s/^version = \"([^\"]+)\"$/version = \"\1+${LOCAL}\"/" deps/prime-kernels/pyproject.toml
grep '^version' deps/prime-kernels/pyproject.toml
- name: Build wheel
env:
VIRTUAL_ENV: /tmp/build-env
CUDA_HOME: /usr/local/cuda
PRIME_KERNELS_REQUIRE: "1"
MAX_JOBS: "8"
run: uv build --wheel --no-build-isolation --out-dir dist deps/prime-kernels
- name: Inspect wheel
run: |
ls -lh dist/
/tmp/build-env/bin/python - <<'PY'
import pathlib, zipfile
wheel = next(pathlib.Path("dist").glob("*.whl"))
extensions = [n for n in zipfile.ZipFile(wheel).namelist() if n.endswith(".so")]
assert extensions, f"{wheel.name} contains no compiled kernels"
print(wheel.name, *extensions, sep="\n ")
PY
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: prime-kernels-${{ matrix.arch }}
path: dist/*.whl
if-no-files-found: error
- name: Attach to release
if: inputs.release_tag != ''
env:
GH_TOKEN: ${{ github.token }}
# gh must not resolve the repo from the checkout: inside the container the
# workspace is owned by another uid, which git rejects as dubious ownership.
GH_REPO: ${{ github.repository }}
TAG: ${{ inputs.release_tag }}
run: |
gh release upload "$TAG" dist/*.whl --clobber
# The `[tool.uv.sources]` pin has to name the wheel exactly, ABI suffix and all.
WHEEL=$(basename dist/*.whl)
URL="https://github.com/${GITHUB_REPOSITORY}/releases/download/${TAG}/${WHEEL}"
echo "\`{ url = \"$URL\", marker = \"platform_machine == '${{ matrix.arch }}'\" },\`" >> "$GITHUB_STEP_SUMMARY"
+15 -10
View File
@@ -6,6 +6,10 @@ on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
unit-tests:
name: Unit tests
@@ -15,15 +19,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run tests
@@ -75,7 +80,7 @@ jobs:
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
from prime_rl.utils.validation import validate_shared_ckpt_config
from prime_rl.utils.validation import propagate_shared_fields
# `verifiers` (+ its `datasets` dep) is a declared slim dep: the v1 config types
# (EnvConfig, Task, ...) extend verifiers.v1, which is pure-pydantic and pulls no
+157 -45
View File
@@ -5,20 +5,103 @@ on:
branches: [main]
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
changes:
name: Select tests
runs-on: ubuntu-latest
if: github.event_name != 'pull_request' || github.event.pull_request.draft == false
permissions:
pull-requests: read
outputs:
unit: ${{ github.event_name != 'pull_request' || steps.filter.outputs.unit == 'true' }}
integration: ${{ steps.matrix.outputs.tests }}
eval: ${{ github.event_name != 'pull_request' || steps.filter.outputs.eval == 'true' }}
steps:
- uses: dorny/paths-filter@v4
id: filter
if: github.event_name == 'pull_request'
with:
filters: |
unit:
- &runtime
- '.github/workflows/gpu_tests.yaml'
- '{pyproject.toml,uv.lock,.python-version,.gitmodules}'
- 'deps/**'
- 'packages/**/pyproject.toml'
- 'packages/prime-rl-configs/src/prime_rl/configs/{trainer,shared,__init__}.py'
- 'packages/prime-rl-configs/src/prime_rl/utils/**'
- 'src/prime_rl/*.py'
- 'src/prime_rl/{trainer,multimodal,transports,utils}/**'
- 'tests/{__init__.py,conftest.py,utils.py}'
- 'tests/integration/{__init__.py,conftest.py}'
- 'tests/unit/{train,inference}/**'
- 'src/prime_rl/inference/**'
sft:
- *runtime
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
- 'src/prime_rl/dashboard/**'
- 'tests/integration/dashboard_smoke.py'
- 'packages/prime-rl-configs/src/prime_rl/configs/{sft,eval,monitors}.py'
- 'src/prime_rl/entrypoints/{sft,dashboard}.py'
- 'src/prime_rl/monitors/**'
- 'src/prime_rl/eval/{online,runner}.py'
- 'tests/integration/test_reverse_text_sft{,_lora}.py'
- 'configs/ci/integration/reverse-text-sft{,-lora}/**'
rl:
- *runtime
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
- 'src/prime_rl/dashboard/**'
- 'tests/integration/dashboard_smoke.py'
- 'packages/prime-rl-configs/src/prime_rl/configs/{rl,orchestrator,inference,env_server,algorithm,eval,monitors}.py'
- 'src/prime_rl/entrypoints/{rl,trainer,inference,orchestrator,env_server,dashboard}.py'
- 'src/prime_rl/{inference,orchestrator,monitors}/**'
- 'src/prime_rl/eval/{online,runner}.py'
- 'tests/integration/test_reverse_text{,_lora,_moe,_rl_opd,_rl_sft}.py'
- 'tests/integration/test_alphabet_sort.py'
- 'configs/ci/integration/reverse-text{,-lora,-moe,-rl-opd,-rl-sft}/**'
- 'configs/ci/integration/alphabet_sort.toml'
eval:
- *runtime
- 'packages/prime-rl-configs/src/prime_rl/configs/{eval,orchestrator,inference,env_server,algorithm,monitors}.py'
- 'src/prime_rl/{eval,orchestrator,monitors}/**'
- 'src/prime_rl/entrypoints/{eval,env_server}.py'
- 'tests/integration/test_gsm8k_eval.py'
- 'configs/ci/integration/gsm8k-eval.toml'
- name: Build integration matrix
id: matrix
env:
# Main and manual runs retain the full suite.
RUN_ALL: ${{ github.event_name != 'pull_request' }}
SFT: ${{ steps.filter.outputs.sft || 'false' }}
RL: ${{ steps.filter.outputs.rl || 'false' }}
run: |
tests=$(jq -cn --argjson all "$RUN_ALL" --argjson sft "$SFT" --argjson rl "$RL" '[
if $all or $sft then "reverse_text_sft", "reverse_text_sft_lora" else empty end,
if $all or $rl then
"reverse_text", "reverse_text_rl_opd", "reverse_text_rl_sft",
"alphabet_sort", "reverse_text_lora", "reverse_text_moe"
else empty end
]')
echo "tests=$tests" >> "$GITHUB_OUTPUT"
unit-tests:
name: Unit tests
runs-on: vm
needs: changes
runs-on: prime-rl-2xh200
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
timeout-minutes: 45
if: github.event_name == 'push' || github.event.pull_request.draft == false
if: needs.changes.outputs.unit == 'true'
steps:
- name: Install Git
run: |
@@ -29,12 +112,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run unit tests
@@ -50,43 +137,20 @@ jobs:
integration-tests:
name: Integration tests (${{ matrix.test }})
runs-on: ${{ matrix.runner }}
needs: changes
runs-on: prime-rl-2xh200
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
timeout-minutes: 60
if: github.event_name == 'push' || github.event.pull_request.draft == false
if: needs.changes.outputs.integration != '[]'
strategy:
fail-fast: false
# Bound per-PR fan-out: at most 5 integration jobs at a time (plus unit-tests),
# i.e. 6 h200 pods per PR. Tune together with the ARC scale set maxRunners.
max-parallel: 5
matrix:
include:
- test: reverse_text_sft
runner: vm
pytest_args: "tests/integration/test_reverse_text_sft.py"
- test: reverse_text_sft_lora
runner: vm
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
- test: reverse_text
runner: vm
pytest_args: "tests/integration/test_reverse_text.py"
- test: reverse_text_rl_opd
runner: vm
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
- test: reverse_text_rl_sft
runner: vm
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
- test: alphabet_sort
runner: vm
pytest_args: "tests/integration/test_alphabet_sort.py"
- test: reverse_text_lora
runner: vm
pytest_args: "tests/integration/test_reverse_text_lora.py"
- test: reverse_text_moe
runner: vm
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py"
test: ${{ fromJSON(needs.changes.outputs.integration) }}
steps:
- name: Install Git
run: |
@@ -97,12 +161,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run integration tests
@@ -117,7 +185,7 @@ jobs:
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
VLLM_WORKER_MULTIPROC_METHOD: spawn
run: uv run pytest -vvs ${{ matrix.pytest_args }}
run: uv run pytest -vvs tests/integration/test_${{ matrix.test }}.py
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v7
@@ -126,3 +194,47 @@ jobs:
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
eval-tests:
name: Integration tests (gsm8k_eval)
needs: changes
if: needs.changes.outputs.eval == 'true'
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
submodules: false
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run eval tests
env:
USERNAME_CI: CI_RUNNER
WANDB_MODE: offline
HF_TOKEN: ${{ secrets.HF_TOKEN }}
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
GITHUB_REF_NAME: ${{ github.ref_name }}
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
run: uv run pytest -vvs tests/integration/test_gsm8k_eval.py
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: gsm8k_eval-logs
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
+4
View File
@@ -9,6 +9,10 @@ on:
# This will trigger the workflow for pull requests to any branch
types: [opened, synchronize, reopened]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
ruff:
name: Ruff
+2 -24
View File
@@ -113,21 +113,8 @@ jobs:
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
# Wheels are attached while the release is still a draft, so it is never published without
# them — `[tool.uv.sources]` pins prime-kernels at a release asset, and an install that
# resolves to a wheel-less release would fall back to compiling CUDA from source.
kernels-from-auto-tag:
needs: auto-tag-on-main
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
permissions:
contents: write
uses: ./.github/workflows/build_kernels.yaml
with:
release_tag: ${{ needs.auto-tag-on-main.outputs.tag }}
ref: ${{ needs.auto-tag-on-main.outputs.tag }}
release-from-auto-tag:
needs: [auto-tag-on-main, kernels-from-auto-tag]
needs: auto-tag-on-main
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
runs-on: ubuntu-latest
permissions:
@@ -219,17 +206,8 @@ jobs:
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
kernels-from-tag:
needs: resolve-release
permissions:
contents: write
uses: ./.github/workflows/build_kernels.yaml
with:
release_tag: ${{ needs.resolve-release.outputs.tag }}
ref: ${{ needs.resolve-release.outputs.tag }}
publish-release:
needs: [resolve-release, kernels-from-tag]
needs: resolve-release
runs-on: ubuntu-latest
permissions:
contents: write
+3 -2
View File
@@ -5,6 +5,7 @@
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
- **Don't touch `optimization_dtype` / `reduce_dtype`**: never change these model config fields (or their defaults in `trainer.py`) unless the user explicitly asks. They're load-bearing numerical knobs — flipping bfloat16/float32 silently changes training dynamics.
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
- **Context parallelism**: a module that needs CP state holds a `CPContext` (`models/base.py`) as `self.cp_context`, defaulting to `CPContext()`, which is the non-CP case; `PreTrainedModelPrimeRL` supplies that default. `setup_context_parallel` in `utils/cp.py` builds one `CPContext` and assigns it to every module that has the field, so each module holds the same frozen object.
- **Zen of Python**: remember the Zen of Python when writing code.
```
Beautiful is better than ugly.
@@ -42,9 +43,9 @@ Namespaces are one honking great idea -- let's do more of those!
## Skills
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs). When you make changes to the codebase, check if any skills need to be updated to stay accurate.
Skills live in `skills/` and are symlinked to `.claude/skills/` (Claude Code) and `.agents/skills/` (Codex). They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs).
You are responsible for maintaining the skills folder. When a workflow fails and you fix it – whether with help from the user or through trial and error – you must update the skills to make implicit knowledge explicit. You are also responsible for keeping the skills up to date whenever you or anyone else modifies the code.
If a repository skill could benefit from an update, suggest the specific change, explain why it would help, and ask the user for approval before making it. Wait for approval before creating, modifying, renaming, or deleting skills, including their supporting files and symlinks. If the user has already explicitly requested or approved the skill change, proceed without asking again. Requests to change code, fix workflows, update documentation, or open a PR do not implicitly authorize skill changes. You may read and follow skills without changing them.
## Testing
-1
View File
@@ -1 +0,0 @@
@AGENTS.md
+113 -105
View File
@@ -1,21 +1,27 @@
# syntax=docker/dockerfile:1
# ^ `COPY --exclude` (used to split the venv into parallel-compressible layers) needs
# Dockerfile syntax >= 1.19; `docker/dockerfile:1` resolves to the latest stable 1.x.
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
ARG DEPENDENCY_IMAGE=dependencies
FROM ghcr.io/astral-sh/uv:0.11.9@sha256:6b6fa841d71a48fbc9e2c55651c5ad570e01104d7a7d701f57b2b22c0f58e9b1 AS uv
FROM ubuntu:24.04@sha256:a853f94d226358a79c740cfc7bce0c289748f3fe3488d921d038ccd752c61b60 AS python-builder
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates python3.12 python3.12-venv \
&& rm -rf /var/lib/apt/lists/*
COPY --from=uv /uv /uvx /usr/local/bin/
ENV UV_PYTHON_PREFERENCE=only-system UV_LINK_MODE=copy
# Every pyproject.toml + uv.lock, so the dependency sync below caches
# independently of source edits.
FROM nvidia/cuda:12.8.1-base-ubuntu24.04 AS manifests
# .git is ~735 MB, changes every commit, and would land in the registry cache.
COPY --exclude=.git . /ctx
FROM python-builder AS manifests
COPY . /ctx
RUN mkdir -p /manifests \
&& cd /ctx \
&& find . -name .git -prune -o -type f -name pyproject.toml -exec cp --parents {} /manifests/ \; \
&& cp uv.lock /manifests/
# Build stage - multi-arch base (supports amd64 + arm64)
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 AS builder
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04@sha256:8b2705ea7a8653ad3451b46ab835eced92d77b44e671b9cf3ad4f95fbb2efe5e AS builder
LABEL maintainer="prime intellect"
LABEL repository="prime-rl"
@@ -72,18 +78,12 @@ RUN git clone --depth 1 --branch v${UCX_VERSION} https://github.com/openucx/ucx.
&& make install \
&& rm -rf /tmp/ucx
# Download the latest installer
ADD https://astral.sh/uv/install.sh /uv-installer.sh
# Set install dir to location accessible to non-root users
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
COPY --from=uv /uv /uvx /usr/local/bin/
ENV PATH="/usr/local/bin:$PATH"
# Build .venv against the system CPython, so the venv's recorded interpreter
# matches the runtime interpreter and no bin/python relink is needed at runtime.
ENV UV_PYTHON_PREFERENCE=only-system
ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
# Explicity set venv dir inside /app so to ensure it gets copied over during
# the runtime stage's `COPY /app`
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
# Install Python dependencies
@@ -91,67 +91,44 @@ WORKDIR /app
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# Third-party deps only — source edits don't bust this layer. First-party
# editables install in the source-layer sync below. No build-context bind
# mount here: .git would bust the cache every commit.
# The runtime dependency image contains no first-party source or editable installs.
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
--no-install-package renderers \
--no-install-package prime-pydantic-config
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra flash-mla --extra disagg --extra quack --extra kernels --locked --no-dev \
--no-install-local
COPY pyproject.toml /app/pyproject.toml
COPY uv.lock /app/uv.lock
COPY README.md /app/README.md
COPY src/ /app/src/
COPY packages/ /app/packages/
COPY deps/ /app/deps/
COPY configs /app/configs
COPY examples /app/examples
COPY k8s /app/k8s
COPY benchmarks/scripts /app/benchmarks/scripts
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
# Use submodule git metadata from the build context when present. Docker copies
# only the submodule .git pointer files into /app/deps, so we temporarily link
# /app/.git/modules to the read-only context before resolving versions.
ARG VERIFIERS_PRETEND_VERSION
ARG RENDERERS_PRETEND_VERSION
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
--mount=type=bind,source=.,target=/build-context,readonly \
if [ -d /build-context/.git/modules ]; then mkdir -p /app/.git && ln -s /build-context/.git/modules /app/.git/modules; fi \
&& \
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
&& \
if [ -L /app/.git/modules ]; then rm /app/.git/modules && rmdir /app/.git 2>/dev/null || true; fi \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" /app/deps/verifiers/pyproject.toml \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
# (#2883); rebuilding against our UCX is the documented fix. Only needed for
# the disaggregated P/D path — default off so training-only / single-node
# inference builds are unaffected. Enable via `--build-arg INCLUDE_NIXL_FROM_SOURCE=1`.
ARG INCLUDE_NIXL_FROM_SOURCE=0
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
# ships its own UCX which segfaults on prefill→decode KV transfer (#2883);
# rebuilding against our UCX is the documented fix. The rename is required: an
# unrenamed source build is `nixl_cu12`, and the `nixl` shim imports nixl_cu13
# (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 \
VIRTUAL_ENV=/app/.venv uv pip install pip \
&& 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 \
LD_LIBRARY_PATH=/opt/ucx/lib:/opt/ucx/lib/ucx \
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/app/deps \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu12-*.whl \
&& rm -rf /tmp/nixl /app/deps/nixl_cu12-*.whl; \
/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 \
&& 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
@@ -161,19 +138,14 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
# (uses pinned nvidia-* wheels) needs them. Keeps nvcc/nvvm/ptxas + headers +
# libcudart/libnvrtc/libcudadevrt for JIT compile+link.
FROM builder AS cuda-trim
RUN find /usr/local/cuda-12.8/targets/*/lib \
RUN find /usr/local/cuda-13.0/targets/*/lib \
\( -name 'libcublas*' -o -name 'libcusparse*' -o -name 'libcufft*' \
-o -name 'libcusolver*' -o -name 'libcurand*' -o -name 'libnpp*' \
-o -name 'libnvjpeg*' -o -name 'libnvblas*' \) -delete \
&& find /usr/local/cuda-12.8 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
# CUDA 13 runtime libs source
FROM nvidia/cuda:13.0.1-runtime-ubuntu24.04 AS cuda13
RUN mkdir -p /cu13 && cp -d $(find /usr/local \
-name 'libcudart.so.13*' -o -name 'libnvrtc.so.13*' -o -name 'libnvrtc-builtins.so.13*') /cu13/
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
# Runtime image
FROM nvidia/cuda:12.8.1-base-ubuntu24.04
FROM nvidia/cuda:13.0.1-base-ubuntu24.04@sha256:f8ef28f579ea42a44b415d2c5d46f788e6a9b395c6c83f2929416e1fc192c143 AS dependencies
ENV DEBIAN_FRONTEND=noninteractive
@@ -203,24 +175,43 @@ RUN apt-get update && apt-get install -y \
libibverbs1 \
ibverbs-providers \
librdmacm1 \
libhwloc15 \
&& ln -sf /usr/bin/python3.12 /usr/local/bin/python \
&& apt-get clean autoclean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# CUDA 12.8 toolkit (TileLang's runtime nvcc JIT)
COPY --from=cuda-trim /usr/local/cuda-12.8 /usr/local/cuda-12.8
RUN ln -sfn /usr/local/cuda-12.8 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
# AWS EFA userspace stack: libfabric + the aws-ofi-nccl NCCL net plugin,
# installed as one version-matched unit via AWS's official installer rather
# than picking versions by hand. Do not substitute a host-mounted copy of
# these libraries instead of building them in -- symbol-version mismatches
# between a host's rdma-core and a container's can silently break the NCCL
# plugin. Run directly in this stage (not a separate one COPY'd in after):
# the installer's own apt-get/dpkg step upgrades system rdma-core packages
# (libibverbs, ibverbs-providers, librdmacm) in place to versions libfabric
# actually links against -- copying only /opt/amazon out of an isolated
# stage leaves that system-wide upgrade behind, so libfabric ends up paired
# with whatever older rdma-core this image's own apt install pulled in and
# fails to load (symbol version mismatch on libefa.so.1). --skip-kmod:
# containers share the host kernel and must never build/load a kernel
# module themselves; the EFA driver is expected to already be present on
# the host. --skip-limit-conf: ulimits config doesn't apply inside a build.
ARG EFA_INSTALLER_VERSION=1.47.0
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates tar gzip \
&& curl -fsSL "https://efa-installer.amazonaws.com/aws-efa-installer-${EFA_INSTALLER_VERSION}.tar.gz" \
-o /tmp/aws-efa-installer.tar.gz \
&& tar -xzf /tmp/aws-efa-installer.tar.gz -C /tmp \
&& cd /tmp/aws-efa-installer \
&& ./efa_installer.sh -y --skip-kmod --skip-limit-conf \
&& cd / && rm -rf /tmp/aws-efa-installer.tar.gz /tmp/aws-efa-installer \
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/*
# CUDA 13.0 toolkit (TileLang's runtime nvcc JIT)
COPY --from=cuda-trim /usr/local/cuda-13.0 /usr/local/cuda-13.0
RUN ln -sfn /usr/local/cuda-13.0 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
ENV CUDA_HOME=/usr/local/cuda
ENV PATH="/usr/local/cuda/bin:${PATH}"
# CUDA 13 runtime libs for deep-gemm
COPY --from=cuda13 /cu13/ /opt/cuda13/lib64/
RUN echo /opt/cuda13/lib64 > /etc/ld.so.conf.d/cuda13.conf \
&& ldconfig \
&& ldconfig -p | grep -q libcudart.so.13 \
&& ldconfig -p | grep -q libnvrtc.so.13
ARG USER_ID=1000
ARG GROUP_ID=1000
@@ -232,19 +223,12 @@ RUN userdel -r ubuntu 2>/dev/null || true; \
echo "appuser ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
# Install uv for development use
ADD https://astral.sh/uv/install.sh /uv-installer.sh
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
COPY --from=uv /uv /uvx /usr/local/bin/
USER appuser
ENV PATH="/usr/local/bin:$PATH"
WORKDIR /app
# Copy the application from the builder, splitting the venv's largest trees into their
# own layers. BuildKit compresses and pushes layers in parallel, so shipping the whole
# ~20 GB venv as one layer serialized the export behind a single compressor. Splitting
# also lets nodes pull the image in parallel. Keep the excludes below in sync with the
# per-tree copies above, or the data lands in the image twice.
# The volatile /app remainder goes last so a source edit re-pushes one layer,
# not all of them.
# Split the largest dependency trees so compression and pulls can run in parallel.
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/nvidia /app/.venv/lib/python3.12/site-packages/nvidia
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/torch /app/.venv/lib/python3.12/site-packages/torch
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/vllm /app/.venv/lib/python3.12/site-packages/vllm
@@ -252,17 +236,17 @@ COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packa
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so /app/.venv/lib/python3.12/site-packages/
COPY --from=builder /opt/ucx /opt/ucx
# Copy and set up entrypoint script
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
RUN chmod +x /app/docker-entrypoint.sh
COPY --from=builder --chown=appuser:appuser \
--exclude=.venv/lib/python3.12/site-packages/nvidia \
--exclude=.venv/lib/python3.12/site-packages/torch \
--exclude=.venv/lib/python3.12/site-packages/vllm \
--exclude=.venv/lib/python3.12/site-packages/flash_attn \
--exclude=.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so \
/app /app
--exclude=lib/python3.12/site-packages/nvidia \
--exclude=lib/python3.12/site-packages/torch \
--exclude=lib/python3.12/site-packages/vllm \
--exclude=lib/python3.12/site-packages/flash_attn \
--exclude=lib/python3.12/site-packages/flash_attn_2_cuda*.so \
/app/.venv /app/.venv
RUN /app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]' \
&& if [ "$(uname -m)" = "x86_64" ]; then \
/app/.venv/bin/python -c 'from importlib.metadata import version; version("flash-mla")'; \
fi
# Place executables in the environment at the front of the path
ENV PATH="/app/.venv/bin:$PATH"
@@ -273,6 +257,30 @@ ENV LD_LIBRARY_PATH="/opt/ucx/lib:/opt/ucx/lib/ucx${LD_LIBRARY_PATH:+:${LD_LIBRA
ENV HF_HUB_ETAG_TIMEOUT=500
ENV HF_HUB_DOWNLOAD_TIMEOUT=300
# Use entrypoint for setup (ulimit, etc) but default to sleep infinity for K8s
FROM python-builder AS application-builder
WORKDIR /app
COPY pyproject.toml uv.lock README.md /app/
COPY src /app/src
COPY packages /app/packages
COPY deps /app/deps
COPY configs /app/configs
COPY examples /app/examples
COPY benchmarks/scripts /app/benchmarks/scripts
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
COPY scripts/docker_application.py /build/docker_application.py
ARG VERIFIERS_PRETEND_VERSION
ARG RENDERERS_PRETEND_VERSION
ARG PYDANTIC_CONFIG_PRETEND_VERSION
RUN --mount=type=cache,target=/root/.cache/uv \
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
&& uv run --no-project --python /usr/bin/python3.12 /build/docker_application.py /app /out/app
# COPY --link and numeric ownership let source builds reuse dependency blobs without unpacking them.
FROM ${DEPENDENCY_IMAGE} AS runtime
ARG USER_ID=1000
ARG GROUP_ID=1000
COPY --link --from=application-builder --chown=${USER_ID}:${GROUP_ID} /out/app /app
# Preserve the executable Git mode; --chmod disables BuildKit's linked-copy optimization.
COPY --link --chown=${USER_ID}:${GROUP_ID} scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
ENTRYPOINT ["/app/docker-entrypoint.sh"]
CMD ["sleep", "infinity"]
+14 -35
View File
@@ -35,33 +35,29 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
2. Performant: built to train 1T+ MoE models on 1000+ GPUs with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) for training and [vLLM](https://github.com/vllm-project/vllm) for inference, with FP8 inference, PD disaggregation, EP and CP parallelism, and more.
3. Native integration with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments through the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars), including built-in support for SWE and agentic environments.
4. End-to-end post-training: SFT, RL training, and evals.
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
5. Multi-node deployment with Slurm support.
6. Multimodal support for VLMs such as Qwen3.5.
7. Hackable, modular, and extensible by design.
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.2/).
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.3/).
## Models support
The trainer works with both Hugging Face and Prime custom `ModelForCausalLM` out of the box. For selected families (especially large MoE) we also ship highly optimized training code under `src/prime_rl/trainer/models/`, including expert parallelism (EP) for MoE layers and context parallelism (CP) for long sequences (see the table), and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels).
With `[model] impl = "auto"` (the default), the trainer selects that custom stack when the Hugging Face config type is registered.
The trainer runs the PrimeRL model implementations under `src/prime_rl/trainer/models/`: dense Llama, Qwen3 and Qwen3.5, plus the families in the table below, with expert parallelism (EP) for MoE layers, context parallelism (CP) for long sequences, and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels). Other architectures fail at trainer setup.
| Family | Example IDs | MoE | EP | CP |
|--------|-------------|-----|----|-----|
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | yes | ✅ | ✅ |
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ❌ |
| Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
| 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 (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ✅ | ✅ |
| Other HF causal LMs | Qwen3 dense, Mistral, … (`impl = "hf"`) | varies | ❌ | ✅ |
| GPT-OSS (`gpt_oss`) | `unsloth/gpt-oss-20b-BF16`, … | yes | ✅ | ✅ |
## Setup
@@ -113,15 +109,6 @@ uv sync --all-extras
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`
```bash
uv pip install "flash-attn-3 @ git+https://github.com/Dao-AILab/flash-attention.git@main#subdirectory=hopper" --no-build-isolation
```
</details>
<details>
@@ -148,22 +135,16 @@ uv run python -c "import flash_attn"
uv run sft @ configs/debug/fake/sft.toml
```
4. Check that you can run the RL trainer (*this requires 1 GPU*)
```bash
uv run trainer @ configs/debug/fake/rl.toml
```
5. Check that you can run the inference server (*this requires 1 GPU*)
4. Check that you can run the inference server (*this requires 1 GPU*)
```bash
uv run inference --vllm.model Qwen/Qwen3-0.6B
```
6. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
5. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
```bash
uv run rl @ configs/basic/reverse-text/rl.toml
uv run rl @ examples/basic/reverse-text/rl.toml
```
</details>
@@ -195,19 +176,16 @@ Follow this guide to learn the basics of prime-rl. You can train your own models
2. [**Wordle**](examples/basic/wordle/README.md): Train `Qwen3-1.7B` to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
3. [**Alphabet Sort**](examples/basic/alphabet-sort/README.md): Train `Qwen3-4B-Instruct-2507` to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
4. [**Wiki Search**](examples/basic/wiki-search/README.md): Train `Qwen3-4B-Instruct-2507` to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
5. [**Hendrycks Sanity**](examples/basic/hendrycks-sanity/README.md): Run a sanity check experiment on `DeepSeek-R1-Distill-Qwen-1.5B` using a filtered subset of MATH where the model already partially solves 20-80% of problems. Useful for algorithm ablations.
5. [**Hendrycks Sanity**](examples/basic/hendrycks-sanity/README.md): Run a sanity check experiment on `Qwen3-1.7B` using a subset of MATH filtered to problems that `DeepSeek-R1-Distill-Qwen-1.5B` partially solves (20-80%). Useful for algorithm ablations.
### Advanced Training: 32 - 2048 GPUs:
Follow this guide to train large models on hard reasoning and agentic tasks.
These guides are designed to be run from a Slurm cluster but can also be adapted to k8s deployments.
These guides are designed to be run from a Slurm cluster.
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
3. [**Nemotron-3-Super**](examples/advanced/nemotron-3-super/): Train the `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
4. [**MiniMax-M2.5 SWE**](examples/advanced/minimax-m2.5/): Train `MiniMax-M2.5` on agentic SWE tasks.
5. [**INTELLECT-3.1**](examples/advanced/intellect-3.1/): Reproduce our `INTELLECT-3.1` training run.
6. [**High-throughput GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation, the `llm-d` router, and FP8.
3. [**GLM-5**](examples/advanced/glm-5.3/): Large-scale `GLM-5`/`GLM-5.3` training with P/D disaggregation, the `llm-d` router, and FP8.
## Docs
@@ -215,7 +193,8 @@ Check out the [docs](docs) directory for in-depth guides on how to use prime-rl.
- [**Overview**](docs/overview.md) - Architecture, install, and a copy-pasteable end-to-end RL run
- [**Configuration**](docs/configuration.md) - TOML composition, CLI overrides, env vars, validation
- [**Training**](docs/training.md) - RL, SFT, evals, checkpointing, observability, rules of thumb
- [**Training**](docs/training.md) - RL, SFT, checkpointing, observability, rules of thumb
- [**Eval**](docs/eval.md) - Standalone evals against any inference server, online evals, resume, platform upload
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA
@@ -6,43 +6,46 @@
"lora_rank": null,
"seq_len": 65536,
"ac": "Recompute",
"selective_targets": null,
"attention": "flash_attention_2",
"output": "benchmark_result.json",
"output": "benchmarks/baselines/benchmark-1xa6000-Qwen--Qwen3-0.6B-rl-full-1gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
"dry_run": false,
"timeout": 1500,
"timeout": 600,
"max_steps": 4,
"micro_batches": 2,
"ep": 1,
"cp": 1,
"fused_lm_head_token_chunk_size": 1024,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "c88d08fdf",
"timestamp": "2026-06-24T22:50:40+00:00",
"commit_sha": "7007d2ef",
"timestamp": "2026-08-29T02:35:31.543870+00:00",
"success": true,
"error_reason": null,
"time_taken": 276.12556480802596
"time_taken": 295.5118532651104
},
"metrics": {
"mfu": {
"mean": 20.802552047875178,
"std": 0.16199364988631793,
"min": 20.664358307416567,
"max": 20.98082222151257
"mean": 16.701924322664684,
"std": 0.0999595293790186,
"min": 16.586575698092034,
"max": 16.763194274056005
},
"throughput": {
"mean": 2484.411208996455,
"std": 19.346608946709658,
"min": 2467.9069802355616,
"max": 2505.7016937694384
"mean": 1994.6806480062144,
"std": 11.937986005933869,
"min": 1980.9047701633856,
"max": 2001.998007610024
},
"step_time": {
"mean": 52.79691480938345,
"std": 0.4071756223542672,
"min": 52.35017399210483,
"max": 53.14720633160323
"mean": 65.74198961785685,
"std": 0.3962098986964774,
"min": 65.49867434287444,
"max": 66.19917749473825
},
"peak_memory": {
"gib": 11.728515625,
"pct": 24.742767157118376
"gib": 11.591145833333334,
"pct": 24.45296844104
}
}
}
}
@@ -6,43 +6,46 @@
"lora_rank": null,
"seq_len": 65536,
"ac": "Recompute",
"selective_targets": null,
"attention": "flash_attention_2",
"output": "benchmark_result.json",
"output": "benchmarks/baselines/benchmark-4xa6000-Qwen--Qwen3-0.6B-rl-full-4gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
"dry_run": false,
"timeout": 1500,
"timeout": 600,
"max_steps": 4,
"micro_batches": 2,
"ep": 1,
"cp": 1,
"fused_lm_head_token_chunk_size": 1024,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "c88d08fdf",
"timestamp": "2026-06-24T22:55:54+00:00",
"commit_sha": "7007d2ef",
"timestamp": "2026-08-29T02:28:40.728120+00:00",
"success": true,
"error_reason": null,
"time_taken": 291.91085167229176
"time_taken": 317.33935201819986
},
"metrics": {
"mfu": {
"mean": 17.217465998339005,
"std": 0.02905058130694137,
"min": 17.19503698271855,
"max": 17.250282374540514
"mean": 15.880248465863398,
"std": 0.005915779562921215,
"min": 15.873443653590638,
"max": 15.884167926432548
},
"throughput": {
"mean": 8225.003435798719,
"std": 13.877833769765575,
"min": 8214.288808538377,
"max": 8240.68023789224
"mean": 7586.197539502296,
"std": 2.826043462792163,
"min": 7582.946793757898,
"max": 7588.069915881657
},
"step_time": {
"mean": 63.90305413212627,
"std": 0.11015530079183487,
"min": 63.77801387012005,
"max": 63.985770548693836
"mean": 69.21047159920757,
"std": 0.022114607283211834,
"min": 69.19065106380731,
"max": 69.234325167723
},
"peak_memory": {
"gib": 6.298828125,
"pct": 13.288163877053583
"gib": 8.55078125,
"pct": 18.038939985655993
}
}
}
}
-113
View File
@@ -1,113 +0,0 @@
#!/usr/bin/env python3
"""
Time the routed-expert compute three ways: the fused MoE kernel (bf16 and mxfp8) against
the grouped-mm path a `model.moe_fused_kernel=false` run takes.
Forward and backward are timed separately, because only the forward is a kernel — the
backward is prime-rl's own closed-form bf16 gradients or, for mxfp8, autograd through the
grouped-mm reference. A speedup on the forward can be spent again on the backward.
uv run benchmarks/scripts/bench_fused_moe.py
uv run benchmarks/scripts/bench_fused_moe.py --tokens 16384 --num-experts 128
"""
from __future__ import annotations
import argparse
import torch
from prime_rl.trainer.models.layers.moe import _FusedMoE, _load_fused_moe_kernel, _run_experts_fused_reference
MODES = ("grouped_mm", "fused_bf16", "fused_mxfp8")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--tokens", type=int, default=8192, help="routed tokens (batch * seq)")
parser.add_argument("--dim", type=int, default=2048, help="model dim; must be a multiple of 256")
parser.add_argument("--hidden-dim", type=int, default=768, help="expert intermediate size; multiple of 128")
parser.add_argument("--num-experts", type=int, default=64)
parser.add_argument("--top-k", type=int, default=8)
parser.add_argument("--iters", type=int, default=20)
parser.add_argument("--warmup", type=int, default=5)
return parser.parse_args()
def make_inputs(args: argparse.Namespace) -> tuple[torch.Tensor, ...]:
torch.manual_seed(0)
randn = lambda *shape: torch.randn(*shape, device="cuda", dtype=torch.bfloat16)
x = (randn(args.tokens, args.dim) * 0.2).requires_grad_(True)
w1 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
w3 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
w2 = (randn(args.num_experts, args.dim, args.hidden_dim) * 0.05).requires_grad_(True)
logits = torch.randn(args.tokens, args.num_experts, device="cuda", dtype=torch.float32)
top_scores, selected = torch.softmax(logits, dim=-1).topk(args.top_k, dim=-1)
return x, w1, w2, w3, selected, top_scores.requires_grad_(True)
def run_forward(mode: str, inputs: tuple[torch.Tensor, ...], num_experts: int) -> torch.Tensor:
x, w1, w2, w3, selected, top_scores = inputs
if mode == "grouped_mm":
return _run_experts_fused_reference(x, w1, w2, w3, selected, top_scores, num_experts)
return _FusedMoE.apply(x, w1, w2, w3, selected, top_scores, num_experts, mode == "fused_mxfp8")
def time_mode(mode: str, inputs: tuple[torch.Tensor, ...], args: argparse.Namespace) -> tuple[float, float, float]:
"""Median forward ms, median backward ms, peak MiB."""
forward_ms, backward_ms = [], []
grad_out = torch.randn(args.tokens, args.dim, device="cuda", dtype=torch.bfloat16)
start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
torch.cuda.reset_peak_memory_stats()
for i in range(args.warmup + args.iters):
for tensor in inputs[:4] + (inputs[5],):
tensor.grad = None
torch.cuda.synchronize()
start.record()
out = run_forward(mode, inputs, args.num_experts)
end.record()
torch.cuda.synchronize()
if i >= args.warmup:
forward_ms.append(start.elapsed_time(end))
start.record()
out.backward(grad_out)
end.record()
torch.cuda.synchronize()
if i >= args.warmup:
backward_ms.append(start.elapsed_time(end))
median = lambda values: sorted(values)[len(values) // 2]
return median(forward_ms), median(backward_ms), torch.cuda.max_memory_allocated() / 2**20
def main() -> None:
args = parse_args()
if not torch.cuda.is_available():
raise SystemExit("no CUDA device")
kernel = _load_fused_moe_kernel()
for mxfp8 in (False, True):
reason = kernel.unsupported_shape_reason(args.dim, args.hidden_dim, mxfp8=mxfp8)
if reason is not None:
raise SystemExit(f"shape unsupported by the fused kernel: {reason}")
inputs = make_inputs(args)
print(
f"tokens={args.tokens} dim={args.dim} hidden_dim={args.hidden_dim} "
f"experts={args.num_experts} top_k={args.top_k} "
f"({args.iters} iters, {args.warmup} warmup, median)\n"
)
print(f"{'mode':<12} {'fwd ms':>9} {'bwd ms':>9} {'total ms':>9} {'speedup':>9} {'peak MiB':>10}")
baseline = None
for mode in MODES:
forward, backward, peak = time_mode(mode, inputs, args)
total = forward + backward
baseline = baseline or total
print(f"{mode:<12} {forward:>9.3f} {backward:>9.3f} {total:>9.3f} {baseline / total:>8.2f}x {peak:>10.0f}")
if __name__ == "__main__":
main()
+8 -10
View File
@@ -23,6 +23,7 @@ import torch
from pydantic import Field
from prime_rl.utils.config import BaseConfig, cli
from prime_rl.utils.pathing import get_file_monitor_dir
MAX_LORAS = 4
@@ -70,11 +71,6 @@ class BenchmarkConfig(BaseConfig):
Field(description="Activation checkpointing type"),
] = "Recompute"
selective_targets: Annotated[
list[str] | None,
Field(description="Selective activation checkpoint targets when ac=Selective"),
] = None
attention: Annotated[
Literal["sdpa", "flash_attention_2", "flash_attention_3", "flash_attention_4"],
Field(description="Attention implementation"),
@@ -160,8 +156,6 @@ def build_command(config: BenchmarkConfig, output_dir: Path) -> list[str]:
cmd.append("--model.ac")
elif config.ac == "Selective":
cmd.extend(["--model.ac", "--model.ac.mode", "selective"])
if config.selective_targets:
cmd.extend(["--model.ac.targets", json.dumps(config.selective_targets)])
elif config.ac == "Offload":
cmd.append("--model.ac-offloading")
@@ -214,13 +208,16 @@ def aggregate_metrics(metrics_path: Path) -> dict:
Each metrics.jsonl line is one monitor.log call (``{"step": N, ...}``);
merge the lines per step, drop the first (warmup) step, and compute
mean/std/min/max per metric like the old --bench JSON export did.
mean/std/min/max per metric like the old --bench JSON export did. Rows
keyed by wall time rather than step (``step: null``) are not per-step and
are skipped.
"""
per_step: dict[int, dict] = {}
with open(metrics_path) as f:
for line in f:
row = json.loads(line)
per_step.setdefault(row["step"], {}).update(row)
if row.get("step") is not None:
per_step.setdefault(row["step"], {}).update(row)
steps = sorted(per_step)[1:] # Exclude first warmup step
columns = {
@@ -262,7 +259,8 @@ def run_benchmark(config: BenchmarkConfig) -> None:
return
# The SFT entrypoint writes to output_dir/<run.name>, the RL trainer to output_dir directly
metrics_path = output_dir / "bench" / "metrics.jsonl" if config.type == "sft" else output_dir / "metrics.jsonl"
run_dir = output_dir / "bench" if config.type == "sft" else output_dir
metrics_path = get_file_monitor_dir(run_dir) / "metrics.jsonl"
start_time = time.perf_counter()
try:
+11 -9
View File
@@ -2,17 +2,19 @@
Configurations for running prime-rl.
- **[`basic/`](basic)** — small, 2-GPU (1 trainer + 1 inference) configs for the core
environments, sized to run on a single dev machine. Each mirrors the matching
[`examples/basic/`](../examples/basic) tutorial and is smoke-tested for one step.
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
- **[`advanced/`](advanced)** — frontier-model training configs without launch walkthroughs:
`minimax-m2.5` (swe), `nemotron-3-super` (swe), `deepseek-v4-flash` (sft + a standalone
vLLM serving pre-flight). For the tutorialized equivalents, see
[`examples/advanced/`](../examples/advanced).
- **`ci/`** — integration and nightly configs used by CI.
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
(two reverse-text train sources + one eval source, one env server per source). Not
guaranteed functional or up to date.
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and
`eval/` (`uv run eval` smokes against Prime Inference, one per shape: `single-turn`
(gsm8k), `multi-turn` (terminal-bench-2 fix-git in sandboxes against a local vLLM deployment with the adaptive band), `resume`, `multi-env`).
Not guaranteed functional or up to date.
```bash
uv run rl @ configs/basic/<env>/rl.toml
uv run sft @ configs/basic/<env>/sft.toml # where present
uv run rl @ configs/debug/algo/<algo>.toml
uv run sft @ configs/debug/fake/sft.toml
uv run eval @ configs/debug/eval/<shape>.toml
```
@@ -0,0 +1,35 @@
# Standalone vLLM serving pre-flight: does this cluster's vLLM serve the real DeepSeek V4 Flash
# checkpoint at all, independent of the trainer? Uses vLLM's own native DeepSeek V4 support, not
# this repo's trainer port. Run directly on one allocated 8xH200 node (no [slurm] block):
#
# uv run inference @ examples/advanced/deepseek-v4-flash/inference.toml
#
# Then check /health and a /v1/chat/completions request from another shell on the same node, and
# confirm a coherent response before trusting the model for a real run.
#
# Reference: https://recipes.vllm.ai/deepseek-ai/DeepSeek-V4-Flash
# Mandatory for the fp8 checkpoint, not an optimization: without it the UE8M0-scaled fp8 weights
# route to a CUTLASS kernel that crashes on boot. That crash was observed during SM120 bring-up and
# has not been re-tested on Hopper, but the vLLM recipe sets the flag on every NVIDIA configuration.
# The mHC pre-norm GEMM does not need it on H200: measured there, the TileLang fallback matches the
# reference to 1.3e-06 relative at every token count, including the >= 1024 block-M kernel.
use_deep_gemm = true
[server]
port = 8000
[vllm]
model = "deepseek-ai/DeepSeek-V4-Flash-0731"
tensor_parallel_size = 8
enable_expert_parallel = true
gpu_memory_utilization = 0.85
max_model_len = 8192
# Required, not a tuning choice. Every DeepSeek V4 attention class sets
# `use_fp8_ds_mla_layout = True`, and the sparse-MLA layout then asserts
# "DeepseekV4 fp8_ds_mla layout only supports fp8 kv-cache" against the `auto` default. The vLLM
# recipe sets it on every vendor and every architecture.
kv_cache_dtype = "fp8"
# Recipe-derived rather than measured here: every NVIDIA configuration in the vLLM recipe pairs
# the fp8 KV cache with this block size.
block_size = 256
@@ -0,0 +1,60 @@
# Real-data SFT for deepseek-ai/DeepSeek-V4-Flash-0731 at full depth (all 43 layers, no
# `debug.num_layers` truncation) on 4 train nodes. Trainer only: no online eval, no inference
# node, and so no weight broadcast. Tested on 8xH200.
#
# uv run sft @ examples/advanced/deepseek-v4-flash/sft.toml --run.name ds-v4-sft-torch-4node
#
# Note: on 4 8xH200 nodes, this config is near the memory limit, using ~94%+ GPU memory.
#
# `dist_timeout_seconds = 14400` is needed on any run that has to build the HF -> prime-rl
# conversion cache, which takes far longer than the 3600s default.
#
# To buy memory back for quicker testing on fewer nodes, set `offload = "full"` under `[model]`,
# which keeps the fp32 masters, moments and gradients in CPU RAM and disables gradient clipping;
# the lighter `offload = "optimizer"` is already the default here.
#
# There is no `[ckpt]` block. The trainer saves unconditionally at the last step, and a 43-layer
# checkpoint (fp32 master weights plus two fp32 AdamW moments) is ~3 TiB. Add one with
# `ckpt.output_dir` pointed at a volume that can hold it if you need the trained weights.
dist_timeout_seconds = 14400
max_steps = 20
[model]
name = "deepseek-ai/DeepSeek-V4-Flash-0731"
ep = 8
# Torch all-to-all, not DeepEP. At full depth DeepEP dies on the first backward with
# "RuntimeError: Autograd not support dtype: Byte", raised from `Tensor.float()` in
# `DeepEPTokenDispatcher.combine` while the activation-checkpoint recompute replays through a
# `__torch_dispatch__` mode that hands back a uint8 tensor. Reproduced deterministically on 4
# nodes against the same weights and conversion cache this config trains on.
[model.moe.dispatch]
type = "torch"
[model.ac]
freq = 1
[model.ac_offloading]
max_inflight_activations = 5
[data]
name = "PrimeIntellect/Reverse-Text-SFT"
seq_len = 2048
batch_size = 32
[optim]
lr = 1e-5
[monitors.wandb]
project = "deepseek-v4-flash"
name = "deepseek-v4-flash-sft"
# `num_infer_nodes` defaults to 0, so this allocates 4 nodes and runs only the trainer.
[deployment]
type = "multi_node"
num_train_nodes = 4
[slurm]
job_name = "ds-v4-sft"
partition = "all"
@@ -6,9 +6,6 @@ level = "debug"
[model]
name = "PrimeIntellect/MiniMax-M2.5-bf16"
[weight_broadcast]
type = "nccl"
[deployment]
type = "multi_node"
num_train_nodes = 4
@@ -24,7 +21,6 @@ interval = 100
project = "minimax-swe"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
ep = 8
cp = 4
@@ -36,7 +32,6 @@ fused_lm_head_token_chunk_size = 1024
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[trainer.optim]
type = "adamw"
@@ -9,8 +9,8 @@ PYTORCH_CUDA_ALLOC_CONF = "expandable_segments:True"
[slurm]
job_name = "nemotron-3-super-swe"
partition = "prod"
# Nemotron-H needs the mamba-ssm kernels; sync that group, then clear this run's orphaned sandboxes.
pre_run_command = 'uv sync --all-extras --all-packages --group mamba-ssm ; timeout 120 prime sandbox delete --label "nemotron-3-super-swe" -y || true'
# Sync the env (the gpu extra brings Nemotron-H's mamba-ssm kernels), then clear this run's orphaned sandboxes.
pre_run_command = 'uv sync --all-extras --all-packages ; timeout 120 prime sandbox delete --label "nemotron-3-super-swe" -y || true'
[deployment]
type = "multi_node"
@@ -22,12 +22,6 @@ num_infer_replicas = 4
project = "nemotron-3-super"
name = "nemotron-3-super-swe"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
@@ -38,11 +32,9 @@ keep_last = 1
name = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
# Hybrid-Mamba model: ring CP is unsupported, so use ulysses (capped at 8 by n_groups).
cp = 8
@@ -57,25 +49,24 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
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
@@ -89,7 +80,7 @@ truncate_history_thinking = false
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["nemotron-3-super-swe"]
[orchestrator.eval]
@@ -99,7 +90,7 @@ interval = 20
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["nemotron-3-super-swe"]
env.agent.timeout.rollout = 3600
@@ -111,4 +102,3 @@ max_model_len = 131072
tensor_parallel_size = 8
enable_prefix_caching = true
enable_expert_parallel = true
enable_return_routed_experts = true
-8
View File
@@ -1,8 +0,0 @@
# alphabet-sort (2 GPU)
Multi-turn task driven by a colocated user simulator, LoRA on `Qwen3-4B`. Dev mirror of
[`examples/basic/alphabet-sort`](../../../examples/basic/alphabet-sort).
```bash
uv run rl @ configs/basic/alphabet-sort/rl.toml
```
-46
View File
@@ -1,46 +0,0 @@
# Alphabet-sort on 2 GPUs (1 trainer + 1 inference) — a multi-turn task driven by a colocated
# user simulator, trained with LoRA on Qwen3-4B. Dev-sized mirror of examples/basic/alphabet-sort.
max_steps = 200
seq_len = 2048
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[monitors.wandb]
project = "alphabet-sort"
name = "alphabet-sort"
[trainer.model.ac]
freq = 1
[trainer.model.lora]
rank = 32
alpha = 64
[trainer.optim]
lr = 1e-5
[orchestrator]
batch_size = 128
group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 768
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # Checkpoint at the end of training
[inference]
-9
View File
@@ -1,9 +0,0 @@
# hendrycks-sanity (2 GPU)
Single-turn math sanity run (reward climbs slowly, meant to run long),
`DeepSeek-R1-Distill-Qwen-1.5B`. Dev mirror of
[`examples/basic/hendrycks-sanity`](../../../examples/basic/hendrycks-sanity).
```bash
uv run rl @ configs/basic/hendrycks-sanity/rl.toml
```
-37
View File
@@ -1,37 +0,0 @@
# Hendrycks-math sanity on 2 GPUs (1 trainer + 1 inference) — a single-turn math env meant to
# run long (reward climbs slowly). Dev-sized mirror of examples/basic/hendrycks-sanity.
max_steps = 5000
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[monitors.wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
[orchestrator]
batch_size = 128
group_size = 8
seq_len = 8192
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset.id = "math-env"
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
env.taskset.dataset_subset = "default"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.model]
seq_len = 16384
[inference.vllm]
max_model_len = 8192
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-9
View File
@@ -1,9 +0,0 @@
# reverse-text (2 GPU)
Smallest end-to-end RL loop — single-turn, `Qwen3-0.6B`. Dev mirror of
[`examples/basic/reverse-text`](../../../examples/basic/reverse-text).
```bash
uv run sft @ configs/basic/reverse-text/sft.toml # optional warmup
uv run rl @ configs/basic/reverse-text/rl.toml
```
-41
View File
@@ -1,41 +0,0 @@
# Reverse-text on 2 GPUs (1 trainer + 1 inference) — the smallest end-to-end RL loop
# (single-turn, 0.6B). Dev-sized mirror of examples/basic/reverse-text.
max_steps = 20
seq_len = 2048
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
[ckpt] # Checkpoint at the end of training
[inference]
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[orchestrator.renderer]
name = "prime-qwen3"
-36
View File
@@ -1,36 +0,0 @@
# SFT warmup for reverse-text on 2 GPUs (1 train + 1 infer for online evals).
# Dev-sized mirror of examples/basic/reverse-text/sft.toml.
max_steps = 100
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[ckpt] # Checkpoint at the end of training
[model]
name = "PrimeIntellect/Qwen3-0.6B"
[data]
name = "willcb/R1-reverse-wikipedia-paragraphs-v1-1000"
seq_len = 4096
batch_size = 32
[optim]
lr = 2e-5
[eval]
interval = 25
num_examples = 32
[eval.sampling]
max_completion_tokens = 1024
[[eval.source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
-8
View File
@@ -1,8 +0,0 @@
# wiki-search (2 GPU)
Multi-turn tool calling (search a wiki corpus via native V1 tools), LoRA on `Qwen3-4B`. Dev mirror
of [`examples/basic/wiki-search`](../../../examples/basic/wiki-search).
```bash
uv run rl @ configs/basic/wiki-search/rl.toml
```
-52
View File
@@ -1,52 +0,0 @@
# Wiki-search on 2 GPUs (1 trainer + 1 inference) — a multi-turn tool-calling task (the model
# searches a wiki corpus via MCP tools), trained with LoRA on Qwen3-4B. Dev-sized mirror of
# examples/basic/wiki-search.
max_steps = 200
seq_len = 4096
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[monitors.wandb]
project = "wiki-search"
name = "wiki-search"
[trainer.optim]
lr = 1e-5
weight_decay = 0.0
[trainer.model.lora]
rank = 8
dropout = 0.0
target_modules = [
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
]
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset.id = "wiki-search"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # Checkpoint at the end of training
[inference.vllm]
tool_call_parser = "hermes"
-9
View File
@@ -1,9 +0,0 @@
# wordle (2 GPU)
Multi-turn Wordle (~6-turn games), `Qwen3-1.7B-Wordle-SFT`. Dev mirror of
[`examples/basic/wordle`](../../../examples/basic/wordle).
```bash
uv run sft @ configs/basic/wordle/sft.toml # optional warmup
uv run rl @ configs/basic/wordle/rl.toml
```
-39
View File
@@ -1,39 +0,0 @@
# Wordle on 2 GPUs (1 trainer + 1 inference). The Wordle-SFT model plays a
# full ~6-turn game per rollout.
max_steps = 200
seq_len = 8192
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[monitors.wandb]
project = "wordle"
name = "wordle"
[ckpt] # Checkpoint at the end of training
[model]
name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 128
group_size = 8
[[orchestrator.train.source]]
name = "wordle"
env.taskset.id = "wordle"
env.player.harness.id = "null"
env.player.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer] # Default trainer config
[inference] # single inference GPU (no data parallelism)
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
[orchestrator.renderer]
name = "prime-qwen3"
-20
View File
@@ -1,20 +0,0 @@
# SFT warmup for wordle on 2 GPUs. Dev-sized mirror of examples/basic/wordle/sft.toml.
max_steps = 20
[deployment]
num_train_gpus = 2
[ckpt] # Checkpoint at the end of training
[model]
name = "PrimeIntellect/Qwen3-1.7B"
[data]
name = "willcb/V3-wordle"
seq_len = 1024
batch_size = 64
micro_batch_size = 1
[optim]
lr = 1e-5
@@ -17,6 +17,8 @@ lr = 1e-5
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
+14
View File
@@ -0,0 +1,14 @@
# CI eval smoke: gsm8k with the null harness in a local subprocess runtime against
# Prime Inference — the eval path end to end without a GPU or sandbox.
dashboard = false
[select]
limit = 4
[sampling]
max_completion_tokens = 8192
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
@@ -17,13 +17,13 @@ rank = 8
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.model.lora]
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -14,13 +14,13 @@ rank = 8
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.model.lora]
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -15,11 +15,10 @@ name = "samsja/mini-glm-moe"
[trainer.optim]
lr = 3e-6
[trainer.model]
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"
@@ -48,7 +50,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.select]
limit = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
@@ -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"
@@ -54,7 +56,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.select]
limit = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
@@ -9,8 +9,7 @@ step = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
optim_cpu_offload = false
full_offload = true
offload = "full"
[optim]
lr = 0.0
@@ -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]
+4 -2
View File
@@ -11,13 +11,15 @@ name = "hendrycks-sanity"
[ckpt]
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
name = "Qwen/Qwen3-1.7B"
[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]
@@ -33,7 +35,6 @@ env.agent.runtime.type = "subprocess"
[trainer]
[trainer.model]
impl = "custom"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
+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]]
+6 -2
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]
@@ -29,7 +31,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+6 -2
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]
@@ -29,7 +31,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+6 -2
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]
@@ -48,7 +50,9 @@ algo.teacher.base_url = "http://localhost:8001/v1"
[orchestrator.eval]
interval = 5
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+7 -3
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"
@@ -41,7 +43,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+7 -3
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"
@@ -41,7 +43,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+6 -2
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]
@@ -31,7 +33,9 @@ env.player1.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.select]
limit = 16
[orchestrator.eval.sampling]
max_completion_tokens = 512
+6 -2
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"
@@ -37,7 +39,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+7 -3
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"
@@ -46,7 +48,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
+7 -3
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"
@@ -46,7 +48,9 @@ env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.select]
limit = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
-139
View File
@@ -1,139 +0,0 @@
# Concurrency-controller debug run: GLM-4.5-Air on the v1 `scaleswe` SWE taskset,
# bash harness on a prime sandbox runtime, 1 train + 1 infer node, eval on 100
# SWE-Bench Verified instances. Concurrency is fully default: the controller
# derives its start from the measured KV budget and adapts from there — watch
# the concurrency/* gauges in W&B or the "Concurrency ..." lines in the
# orchestrator log.
#
# Inference serves FP8 via online per-tensor quantization of the bf16
# checkpoint; weight broadcasts re-quantize through the same path on every
# update. The trainer fits on one node via cp=4 (ulysses), full CPU optimizer
# offload with the stateless sign-SGD optimizer, plus the memory improvements
# from the GLM-5.1 prod run: LM-head token chunking, activation checkpointing
# (freq=1) + activation offloading (max_inflight=1), and skip-gather /
# skip-optimizer checkpointing. Router replay is enabled — GLM-4.5-Air is a
# glm4_moe model, which supports routed_experts.
#
# GRPO uses the linear length penalty with the input-token and turns
# coefficients set to 0.1.
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "debug-concurrency"
partition = "all"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "debug-concurrency" -y || true'
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
num_infer_replicas = 1
[monitors.wandb]
project = "swe-ablations"
name = "debug-concurrency"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
[resume]
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
optim_cpu_offload = false
full_offload = true
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "sign_sgd"
# --- Orchestrator ---
[orchestrator]
batch_size = 128
group_size = 8
max_off_policy_steps = 32
[orchestrator.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["debug-concurrency"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
num_examples = 100
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["debug-concurrency"]
env.agent.timeout.rollout = 3600
# --- Inference ---
[inference]
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
quantization = "fp8"
enable_return_routed_experts = true
+16
View File
@@ -0,0 +1,16 @@
# AIME 2026 at avg@16: every problem 16 times with the null harness (one chat
# completion per rollout) against Prime Inference. The math tasksets forbid the
# agent any network, and only the sandboxed runtimes enforce that policy, so the
# rollouts run in prime sandboxes (PRIME_API_KEY) rather than as subprocesses.
# Competition math needs room to reason, so the completion budget is generous.
#
# uv run eval @ configs/debug/eval/aime2026.toml
group_size = 16
[sampling]
max_completion_tokens = 32768
[[source]]
env.taskset.id = "aime26"
env.agent.harness.id = "null"
+21
View File
@@ -0,0 +1,21 @@
# Multi env: 16 terminal-bench-2 tasks under two harnesses, bash and rlm, in prime
# sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout each with
# a ten-minute budget, against Prime Inference on the default model. One env server
# per source; the sources share the taskset, so each carries its own name.
#
# uv run eval @ configs/debug/eval/multi-env.toml
[select]
limit = 16
[[source]]
name = "tb2-bash"
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 600
[[source]]
name = "tb2-rlm"
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "rlm"
env.agent.timeout.rollout = 600
+13
View File
@@ -0,0 +1,13 @@
# Single env, multi turn: 16 terminal-bench-2 tasks with the bash harness in
# prime sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout
# each, against Prime Inference on the default model.
#
# uv run eval @ configs/debug/eval/multi-turn.toml
[select]
limit = 16
[[source]]
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
+25
View File
@@ -0,0 +1,25 @@
# Single env, resume: gsm8k with a low pinned concurrency so the run can be
# interrupted partway. Relaunch with the same --run.name and --resume: the landed
# episodes are restored from the trace stream and only the owed rollouts run.
# Resuming a finished run restores everything and exits.
#
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug
# <Ctrl-C partway>
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug --resume
group_size = 2
[select]
limit = 8
[concurrency]
min_inflight = 2
max_inflight = 2
[sampling]
max_completion_tokens = 8192
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+17
View File
@@ -0,0 +1,17 @@
# Single env, single turn: gsm8k with the null harness (one chat completion per
# task, no sandbox) against Prime Inference.
#
# uv run eval @ configs/debug/eval/single-turn.toml
group_size = 2
[select]
limit = 8
[sampling]
max_completion_tokens = 8192
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
+15
View File
@@ -0,0 +1,15 @@
# Terminal-Bench 2 at avg@4: every task 4 times with the bash harness in prime
# sandboxes (PRIME_API_KEY authenticates sandbox creation) against Prime Inference.
#
# uv run eval @ configs/debug/eval/tb2.toml
group_size = 4
[[source]]
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
env.agent.retries.rules = [
{type = "ProviderError", max_retries = 2},
{type = "SandboxError", max_retries = 2},
]
-51
View File
@@ -1,51 +0,0 @@
# Minimal multi-env debug run: two reverse-text train sources + one eval source.
# The launcher spawns one env server per source at its derived address
# (tcp://127.0.0.1:5000-5002); the orchestrator connects to each.
max_steps = 10
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.renderer]
name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text-a"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text-b"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 5
num_examples = 64
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+1 -1
+1 -1
+94 -22
View File
@@ -6,6 +6,7 @@ This page covers the specialized features layered on top of the core training st
- [Custom Modeling](#custom-modeling)
- [Expert Parallelism Backends](#expert-parallelism-backends)
- [Runtime Fusions](#runtime-fusions)
- [Multimodal Training](#multimodal-training)
- [Supported Families](#supported-families)
- [Enabling VLM Mode](#enabling-vlm-mode)
@@ -15,54 +16,126 @@ This page covers the specialized features layered on top of the core training st
## Custom Modeling
`prime-rl` ships custom optimized model implementations for several MoE families. With `model.impl = "auto"` (default) the trainer picks the custom path when the HF config type is registered, falling back to plain HF otherwise. To force one:
```toml
[trainer.model]
impl = "custom" # or "hf" to force the HF path
```
The trainer only runs `prime-rl`'s own model implementations, selected from the HF config type. Besides dense Llama, Qwen3 and Qwen3.5, these cover the families below. Other architectures fail at trainer setup.
| Family | HF config types | EP | CP |
|---|---|---|---|
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ❌ |
| Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
| Laguna | `poolside/Laguna-XS.2` | ✅ | ✅ |
| MiniMax M2 | `MiniMax/MiniMax-M2` | ✅ | ✅ |
| Nemotron H | `nvidia/Nemotron-3-Nano-30B-A3B`, … | ✅ | ❌ |
| Trinity (AFMoE) | `arcee-ai/Trinity-Mini`, … | ✅ | ✅ |
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
| GPT-OSS | `unsloth/gpt-oss-20b-BF16`, … | ✅ | ✅ |
| DeepSeek V4 | `deepseek-ai/DeepSeek-V4-Flash-0731` | ✅ | ✅ |
The custom path enables you to set EP, CP, selective activation checkpointing, low-precision training (`[trainer.model.quantization]`), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
GPT-OSS uses FlashAttention 4 with learned attention sinks. Training requires SM90 or SM100/SM110 GPUs
and a BF16 checkpoint such as `unsloth/gpt-oss-20b-BF16`; the original MXFP4 checkpoints are not supported.
### Low-precision training
Set `[trainer.model.quantization]` to train dense linears and MoE expert GEMMs in low precision. Two backends are available via the `type` discriminator:
Dense linear precision and routed-expert precision are configured independently. `[trainer.model.quantization]` applies only to dense `Linear` modules:
- `type = "fp8"` — DeepGEMM FP8 blockwise (requires SM90+ / Hopper). Options: `enable_grouped_gemm` (FP8 MoE expert GEMM). Both default on.
- `type = "mxfp8"` — torchao MXFP8 microscaling (requires SM100+ / Blackwell). Options: `enable_grouped_gemm`, `enable_a2a` (MXFP8 expert-parallel all-to-all), and `recipe` (`mxfp8_rceil` default or `mxfp8_rceil_wgrad_with_hp`).
- `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 compute independently:
- `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"
recipe = "mxfp8_rceil"
enable_a2a = true
[trainer.model.moe.compute]
type = "mxfp8"
recipe = "mxfp8_rceil"
[trainer.model.moe.dispatch]
type = "torch"
transport = "mxfp8"
```
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
All MoE compute backends accept `apply_to`:
- `"all"` (default) applies the backend to all expert groups.
- `"85%"` applies it to the first 85% of model layers, rounded down. For a 48-layer model, this selects layers 0–39.
- `[0, 1, 2, 3]` selects explicit zero-based model layer indices; `[]` selects none.
Percentages must be between 0% and 100%; explicit indices must be within the model's layer count. Non-MoE blocks in hybrid models count toward layer indices and percentages. Each selected layer uses the backend for all its routed experts. Other expert groups use BF16 compute and BF16 token transport while retaining the configured dispatch backend and expert parallelism. Dense linear quantization is configured separately.
For example, this selects routed experts in Qwen3's first four model layers:
```toml
[trainer.model.moe.compute]
type = "mxfp8"
apply_to = [0, 1, 2, 3]
```
Backend shape checks and token alignment apply only to the selected compute path.
In RL runs, configure the same precision selection for rollouts. Inference module names can differ from the trainer's names, and inference precision is configured explicitly, not inferred from `apply_to`. Check the selected modules on both sides before comparing trainer and rollout logprobs.
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed.
### Expert Parallelism Backends
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
`[trainer.model.moe.dispatch]` selects how routed tokens are dispatched and combined:
- **`torch`** (default): TorchTitan's all-to-all collective. Works everywhere, no extra install.
- **`deepep`**: Utilizes DeepEP's custom all-to-all collectives. This provides better performance if EP dimension spans multiple nodes. We provide pre-built binaries for H100/H200 with cuda runtime 12.9 installed, you can install them by running `uv sync --all-extras`.
DeepEP requires some careful tuning to achieve optimal performance, tuning parameters are `deepep_num_sms` and `deepep_token_chunk_size`.
- **`torch`** (default): torch all-to-all with `transport = "bf16"` or, when MXFP8 expert compute is selected, `transport = "mxfp8"` on SM100.
- **`deepep`**: DeepEP custom dispatch/combine kernels. Set `num_sms` and optional `token_chunk_size` in the same table. Pre-built H100/H200 binaries use CUDA 13.0 and are installed by `uv sync --all-extras`.
```toml
[trainer.model.moe.dispatch]
type = "deepep"
num_sms = 20
token_chunk_size = 4096
```
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
### Runtime Fusions
`model.fusions` packs parameters that are always computed together into one tensor, turning several GEMMs into one. Both fusions are on by default:
- `gate_up` — each gated MoE expert's `gate_proj` and `up_proj` become one `[num_experts, 2 * intermediate_size, hidden_size]` weight, halving the routed-expert grouped GEMMs.
- `qkv` — an attention layer's `q_proj`, `k_proj` and `v_proj` (and their biases) become one linear layer.
```toml
[trainer.model.fusions]
enabled = ["gate_up", "qkv"] # [] disables
```
Fusions are runtime-only. Checkpoints keep the canonical parameter names and shapes, so a run can turn a fusion on or off at any point and still load its own checkpoints, and exported weights are unaffected. Only modules that support a fusion are packed; a requested fusion that no module supports logs a warning and is skipped. Fusions are skipped when LoRA is enabled.
Muon receives the packed layout as matrix partitions and orthogonalizes each logical matrix on its own, so a packed parameter trains exactly as the parameters it replaces would — including per-projection learning-rate scaling for grouped-query attention — while keeping a single momentum tensor.
The experimental `shard_fused_on_dim1 = true` shards fused 2-D weights along dim 1 under FSDP, which makes weight loading and checkpointing zero-copy: fused weights and their optimizer state are read and written in place rather than assembled into a full copy on each rank first. It requires `hidden_size` to be divisible by the FSDP shard mesh size.
## Multimodal Training
### Supported Families
@@ -81,7 +154,6 @@ Add `[model.vlm]` and bfloat16 dtypes:
```toml
[model]
name = "Qwen/Qwen3.5-4B"
impl = "custom"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
@@ -115,7 +187,7 @@ dropout = 0.0
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`). With LoRA on, the inference server registers the adapter under the model name and serves the base model as `<model>-base`.
## Disaggregated Prefill/Decode Inference
@@ -126,7 +198,7 @@ For large MoE serving, splitting prefill and decode onto separate vLLM groups ca
| Agentic (SWE, Lean) | 3:1 | Long growing contexts → prefill-heavy |
| Non-agentic (math, chat) | 1:2 | Short prompts, long generations → decode-heavy |
Example config: [`examples/advanced/glm-5.2/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.2/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.2/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2/infer).
Example config: [`examples/advanced/glm-5.3/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.3/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.3/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3/infer).
Monitor live queue depths to detect imbalance:
@@ -141,7 +213,7 @@ If prefill queues and decode is idle, add prefill nodes (and vice versa).
```bash
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
uv pip install --reinstall --no-deps deps/nixl_cu13-*.whl
```
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
+82 -54
View File
@@ -13,7 +13,7 @@ This page covers the math and the configurable algorithmic components: the algor
- [Async / Off-Policy Training](#async--off-policy-training)
- [Loss](#loss)
- [Loss Components](#loss-components)
- [Default RL Loss](#default-rl-loss)
- [IPO Loss](#ipo-loss)
- [Custom Loss](#custom-loss)
- [Advantage](#advantage)
- [Default Advantage](#default-advantage)
@@ -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"]
```
@@ -112,18 +112,18 @@ patterns = ["WARNING"]
def drop_warnings(rollout, *, patterns: list[str]) -> list[list[bool]]: ...
```
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and aborts after repeated zero-trainable batches), not at config time.
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and skips it), not at config time.
### 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 `TrainEnv` (`prime_rl.orchestrator.envs`) resolves the `sampling.source` model into the inference pool used for train episodes, and its resolved config builds one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
@@ -157,9 +157,9 @@ Algorithms operate on native verifier artifacts and annotate their message graph
- `async score_episode(episode)` — rollout-local scoring as one episode arrives.
- `async score_group(episodes)` — group-relative scoring after the cohort completes.
The pipeline drives these through `finalize_episode` and `finalize_group`. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
The pipeline calls `score_group` directly and `score_episode` through `finalize_episode`, which skips episodes with no trainable sampled tokens. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
The algorithm config states which loss component its action tokens feed (`action_loss_type`, a class variable on each config class). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). Writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.train.algo.advantage`.
## Async / Off-Policy Training
@@ -184,47 +184,61 @@ $$
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
$$
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
- `rl` — the configured RL loss (`[trainer.loss]`): IPO by default, or optionally [IcePop](#icepop-loss) or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens, so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens — for `rl`, the sum of its weights, which is the same count while weights are 0/1 — so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
### Default RL Loss
### IPO Loss
The default RL loss is a DPPO policy-gradient term combined with a KL regularizer similar to Kimi-K2.5. For each prompt $x_j$ we sample a group of $G$ rollouts $\{y_i\}_{i=1}^G$, score them to get $s_i$, then optimize:
The default RL loss is Importance Policy Optimization (IPO). It is an importance-weighted policy-gradient term. A symmetric trust region removes tokens whose absolute probability change exceeds $\epsilon$:
$$
\mathcal{L}(\theta) = -\,\mathcal{J}_{\text{PG}}(\theta) \;+\; \tau_{KL}\,\mathcal{L}_{KL}(\theta)
\mathcal{L}(\theta) = -\frac{1}{N}\sum_t
\mathbb{1}\!\left(\left|\pi(y_t)-\mu(y_t)\right| \le \epsilon\right)
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}.
$$
where the policy-gradient term is
$\mu$ is the policy that generated the rollout. $\pi$ is the current trainer policy. $\hat{A}_t$ is the token-level advantage. The trust region uses the sampled token probabilities, not their ratio.
$$
\mathcal{J}_{\text{PG}}(\theta)
= \frac{1}{\sum_{j,i} |y_i^{(j)}|}
\sum_{j,i,t}
\min\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}, \delta\right) \hat{A}^{(j)}_{i,t}
$$
and the KL regularizer penalizes drift between trainer and inference policies via the squared log importance ratio:
$$
\mathcal{L}_{KL}(\theta) = \frac{1}{\sum_{j,i} |y_i^{(j)}|}
\sum_{j,i,t} \log^2\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}\right).
$$
$\mu$ is the policy that generated the rollout (inference), $\pi$ is the current policy (trainer), $\hat{A}_{i,t}$ is the token-level advantage, $\delta$ is the importance-sampling clipping ratio, and $\tau_{KL}$ is the KL temperature. The `min` clamps the importance ratio from above so a stale rollout assigning very low probability to a high-reward token doesn't produce a runaway gradient.
The knobs (under `[trainer.loss]` with `type = "default"`):
The knobs under `[trainer.loss]` are:
| Knob | Default | What it does |
|---|---|---|
| `dppo_mask_low` / `dppo_mask_high` | 0.2 / 0.2 | Lower / upper thresholds for DPPO-style token-level masking. |
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
| `eps` | 0.3 | Maximum absolute probability change before a token is masked. |
| `adv_tau` | 1.0 | Temperature on the advantage term. |
Set `[trainer.loss] type = "default"` and configure via the knobs above. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
### IcePop Loss
IcePop is an opt-in RL loss that drops tokens whose trainer-to-inference
importance ratio falls outside a fixed acceptance band, introduced to stabilize
MoE RL in [Every Step Evolves: Scaling Reinforcement Learning for Trillion-Scale
Mixture-of-Experts Reasoning Models](https://arxiv.org/abs/2510.18855). Accepted
tokens retain the importance-weighted policy-gradient term:
$$
\mathcal{L}(\theta) = -\frac{1}{N}\sum_t
\mathbb{1}\!\left(\alpha \le \frac{\pi(y_t)}{\mu(y_t)} \le \beta\right)
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}.
$$
Enable it explicitly:
```toml
[trainer.loss]
type = "icepop"
ratio_low = 0.2
ratio_high = 5.0
```
| Knob | Default | What it does |
|---|---|---|
| `ratio_low` | 0.2 | Lower accepted trainer-to-inference probability ratio. |
| `ratio_high` | 5.0 | Upper accepted trainer-to-inference probability ratio. |
| `adv_tau` | 1.0 | Temperature on the advantage term. |
### Custom Loss
@@ -304,13 +318,23 @@ 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"
```
A **length-weighted baseline** (`length_weighted_baseline = true` on the `grpo`-family algorithms) replaces the plain group mean with $b = \sum_i L_i s_i / \sum_i L_i$, where $L_i$ is the number of trainable (policy-sampled, loss-masked) tokens of rollout $i$, summed across all its turns; it applies after the length penalty. With token-level loss normalization, long rollouts carry more gradient weight, so this baseline makes the per-token advantage zero-mean across the group's tokens rather than across rollouts.
**Prompt-mean loss aggregation** (`loss_aggregation = "prompt"` on `grpo` and `echo`; default `"token"`). By default every `rl` token in the batch weighs the same, so prompts whose groups produce long trajectories dominate the gradient. With `"prompt"`, the loss is MiMo-V2.6's prompt-mean (Eq. 1): the mean over prompt groups $q$ of $\frac{1}{T_q}\sum_{t \in q} \mathcal{L}_{rl,t}$, where $T_q$ is the group's total trainable tokens. MiMo uses it to keep response length from growing too fast. `score_group` gives each trainable token of the group the `rl` weight $1/T_q$, so each group's weights sum to 1 and $N_{rl}$ (the summed weights) is the number of groups in the step. Zero-advantage tokens are still dropped from the `rl` component, so a group with a zero-advantage rollout keeps less than its full weight of 1. All envs with an `rl` loss in a run must use the same `loss_aggregation`.
```toml
[orchestrator.train.algo]
type = "grpo"
loss_aggregation = "prompt"
```
### Hierarchical GRPO
GRPO gives each rollout its reward minus the average reward of comparable rollouts. In an ordinary single-agent group, every rollout answers the same task, so one group average is enough.
@@ -343,7 +367,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"]
@@ -369,7 +393,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
@@ -392,8 +416,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):
@@ -417,14 +441,16 @@ 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"
```
Scoring runs before curriculum admission, so a rollout that is later rejected still costs its reference compute.
By default, zero-advantage RL tokens are removed after a complete batch cohort has been collected and before its payload is packed for the trainer. This does not backfill the batch. Samples that still carry CE or reference-KL components are retained, while pure zero-advantage RL samples are not shipped. Removing an RL token also removes its trainer/inference mismatch-KL contribution. Set `orchestrator.train.filter_zero_advantages = false` to retain them.
The orchestrator filters samples with no training signal. This includes samples with zero advantage on all RL tokens. Samples that still carry CE or reference-KL components are retained. Filtering an RL token also removes its trainer/inference mismatch-KL contribution.
`orchestrator.constant_trainer_batch_size` defaults to `true`. The orchestrator filters samples before they count toward the batch target. It collects replacements, so rollout-based batches contain `orchestrator.batch_size` training traces. Set the option to `false` to filter after collection without replacement. This setting can improve orchestrator throughput, but it produces smaller trainer batches.
## Curricula
@@ -436,7 +462,7 @@ Three small implementations are included:
- `StandardSampler` is the default: it advances the task iterator and cycles finite tasksets in source order.
- `DifficultyPoolSampler` samples finite tasksets with replacement and tracks each task's latest valid mean group reward. Each named pool has an inclusive reward threshold and a relative per-task sampling weight; weight `0` disables sampling from that pool. Unseen tasks use neutral weight `1.0`, so pool observations affect sampling immediately without waiting for a full taskset pass.
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in post-batch zero-advantage filtering, rejection requests replacement work. Groups without an advantage stream are admitted.
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in token filter, it can reject a configurable advantage range. Groups without an advantage stream are admitted.
```toml
[orchestrator.train.source.curriculum.sampler]
@@ -528,6 +554,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
+45 -9
View File
@@ -2,7 +2,7 @@
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions) that aren't surfaced here.
## Table of Contents
@@ -171,7 +171,37 @@ env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
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.
Sampling parameters use Verifiers' shared normalization: `max_tokens` and `max_completion_tokens` name the same limit, and `extra_body` parameters merge like top-level parameters. Agent overrides apply after source defaults; an explicit null clears an inherited parameter. Resolved sampling is recorded on each trace.
For live-policy training, set distribution parameters (`temperature`, `top_p`, `top_k`) on the source's `sampling` block. Every agent in that source, including non-trainable roles, may override only `max_tokens`, `reasoning_effort`, and `chat_template_kwargs`. These rules are checked when loading the config; evaluation and frozen-model sources allow general agent sampling overrides.
```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.rules = [
{type = "ProviderError", max_retries = 3},
{type = "SandboxError", max_retries = 3},
]
timeout.episode = 7200
[orchestrator.eval.select] # evaluate 128 tasks of each taskset
limit = 128
```
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>.*`).
@@ -220,16 +250,16 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
- [**Wordle**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/wordle) — `Qwen3-1.7B` playing Wordle. Multi-turn SFT + RL; 2–4 H100s.
- [**Alphabet Sort**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/alphabet-sort) — `Qwen3-4B-Instruct-2507` sorting names alphabetically. Multi-turn LoRA RL without SFT warmup; one H100.
- [**Wiki Search**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/wiki-search) — `Qwen3-4B-Instruct-2507` answering trivia by searching a Wikipedia corpus. Multi-turn with tool use.
- [**Hendrycks Sanity**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/hendrycks-sanity) — `DeepSeek-R1-Distill-Qwen-1.5B` on a filtered MATH subset. Useful for algorithm ablations.
- [**Hendrycks Sanity**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/hendrycks-sanity) — `Qwen3-1.7B` on a filtered MATH subset. Useful for algorithm ablations.
**Advanced** (32–2048 GPUs, SLURM):
- [**Qwen3-30B-A3B**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-30b-a3b) — `Qwen3-30B-A3B` on math, SWE, and tool use.
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal.
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal; includes a variant that trains the 100B+ MoE on only two nodes.
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation and FP8.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale `GLM-5`/`GLM-5.3` inference with P/D disaggregation and FP8.
### Worked Example: Compose, Override, Dry-Run
@@ -247,8 +277,14 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
Then inspect the resolved config:
```bash
ls /tmp/reverse-dry/check/configs/resolved/
ls /tmp/reverse-dry/check/configs/latest/resolved/
# rl.json trainer.json orchestrator.json inference.json
```
Each per-process JSON reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/check/configs/resolved/trainer.json`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
Each per-process JSON contains the final, validated configuration that the run
uses. This is also what each standalone process reads. For example, the trainer
reads `configs/latest/resolved/trainer.json`.
`configs/latest/command.txt` records the shell-safe launch command and its CLI
overrides. Each launch also remains under `configs/attempt_<n>/`. To compare
configs, dry-run a known-good base and your overlay. Then diff the two attempts.
+4 -5
View File
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
| Workflow | Trigger | What runs | Where |
|---|---|---|---|
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | relevant changes in non-draft PRs; full suite on push to `main` or manual dispatch | `pytest tests/unit -m gpu`, plus RL/SFT integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_sft_lora`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `alphabet_sort`) with `max-parallel: 5`; separate hosted `gsm8k_eval` job | self-hosted `prime-rl-2xh200` k8s scale set (2xH200); `ubuntu-latest` for test selection and hosted eval |
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
@@ -117,7 +117,6 @@ Then run the full RL stack on reverse-text:
```bash
uv run rl @ configs/ci/integration/reverse-text-moe/start.toml \
--model.name samsja/mini-glm-moe \
--trainer.model.impl custom \
--inference.vllm.gpu-memory-utilization 0.7 \
--inference.vllm.max-model-len 2048
```
@@ -141,12 +140,12 @@ In the PR that adds the new model, you also need to provide a table covering the
## Adding a Custom VLM Implementation
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body — the Qwen3.5 dense (`models/qwen3_5/`) and MoE (`models/qwen3_5_moe/`) implementations are the reference. The pieces, in dependency order:
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body. The unified dense/MoE Qwen3.5 implementation in `models/qwen3_5/` is the reference. The pieces, in dependency order:
1. **Custom text model first.** The VLM body wraps a custom `*ForCausalLM` (see [Adding a New Model](#adding-a-new-model)), so the text side — including its state-dict conversion and KL-mismatch table — comes first.
2. **Composite VLM body.** A `*VLMModel` that holds the HF vision encoder and the custom text model, with a `prepare_inputs_embeds_and_position_ids` step: embed tokens, run the vision encoder, scatter image embeddings over placeholder tokens, and build MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
2. **Composite VLM body.** A `*VLMModel` that holds the vision encoder and custom text model, embeds tokens, runs vision, scatters image embeddings over placeholder tokens, and builds MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
6. **Context parallelism (optional).** CP-capable VLMs implement `set_context_parallel_attributes` and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
6. **Context parallelism (optional).** CP-capable VLMs hold a `CPContext` on all modules which need to be CP-aware and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
7. **Validation.** Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the `color-codeword` environment is the reference task).
+129
View File
@@ -0,0 +1,129 @@
# Eval
This page covers `uv run eval` — evaluating a model in one or more environments. For the online evals of a training run, see [Training](training.md#online-evals).
> **AI agents working in this repo:** the equivalent runbook is at [`skills/eval/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/eval/SKILL.md).
## Table of Contents
- [Launch](#launch)
- [Configuration](#configuration)
- [Resume](#resume)
- [Monitors](#monitors)
- [File](#file)
- [Prime](#prime)
- [Metrics](#metrics)
`uv run eval` runs one epoch of every configured source and exits. It reuses the orchestrator's eval pipeline: env servers are spawned per source, episodes are admitted under the concurrency controller, and every episode streams into the run's trace stream and metrics.
## Launch
By default the model is served by Prime Inference; authenticate with `PRIME_API_KEY` or `prime login`:
```bash
uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Inference
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
```
The default endpoint comes from `PRIME_INFERENCE_URL`, then the Prime CLI's `inference_url`, then the standard Prime Inference URL. An explicit `client.base_url` wins. API keys and environment-backed headers are resolved when clients are built; Prime CLI credential and team fallbacks apply only to Prime Inference hosts, including for a separate admin URL.
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
```bash
uv run inference --vllm.model Qwen/Qwen3-4B
uv run eval gsm8k -n 32 -r 4 -m Qwen/Qwen3-4B --client.base_url http://localhost:8000/v1
```
Single-source shorthands: `<taskset-id>` names the run's only source, `--env.<field> <value>` sets a field of that source's env block (`--env.agent.harness.id bash`, `--env.taskset.tasks '["fix-git"]'`), `-n`/`-s`/`-r` set `select.limit`/`select.shuffle`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). `<taskset-id>` cannot be combined with a TOML that defines `[[source]]` blocks; next to one, `--env.<field>` sets the shared [env block](#configuration) instead. `uv run eval -h` lists them.
Against a local vLLM deployment, set `min_inflight < max_inflight` in `[concurrency]` to dynamically adjust the number of concurrent episodes for maximum throughput. An external API exposes no vLLM `/metrics` to adapt to, so pin the concurrency there (`-c N`, i.e. `min_inflight = max_inflight`).
## Configuration
Multi-source runs use a TOML (`EvalConfig` in `packages/prime-rl-configs/src/prime_rl/configs/eval.py`). The eval block is flattened to the top level — `[[source]]`, `[client]`, `[concurrency]`, `[sampling]`, `[select]`, `group_size` — and each source takes the same `env` block as `[[orchestrator.eval.source]]`:
```toml
model = "Qwen/Qwen3-4B"
group_size = 4
[select] # every source inherits these
limit = 32
[client]
base_url = "http://localhost:8000/v1"
[concurrency] # adaptive against a local vLLM deployment
min_inflight = 8
max_inflight = 256
[sampling]
max_completion_tokens = 2048
[env] # every source inherits these
timeout.episode = 7200
retries.max_retries = 3
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "bash"
[[source]]
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
select.include.idx = ["0:30"]
```
Per-source `group_size` and `sampling` override the top-level defaults. The top-level `[env]` block holds the env knobs that every source inherits (see [Environments](configuration.md#environments)); a source's own `env` values win.
Each field a source sets in its `select` overrides the same field of the top-level `[select]`. `select` picks which tasks of the taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit` (see verifiers' [Selecting tasks](../deps/verifiers/docs/v1/tasksets.md#selecting-tasks)). Train sources take the same `select`.
Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
## Resume
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: saved episodes with `episode.ok` rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch), and only the rollouts still owed run. Failed episodes and the ones the interruption cut off run again. Saved records that fail schema validation stop the resume before the current stream is archived.
```bash
uv run eval @ eval.toml --run.name my-eval
# <interrupted>
uv run eval @ eval.toml --run.name my-eval --resume
```
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
A landed episode counts toward a selected task in the same source when their content hashes (`task.hash`) match. A task whose content changes runs again even if its public `task.key` stays the same. `select` and `group_size` may change between launches: each selected occurrence keeps up to `group_size` matching episodes, and only its missing rollouts run. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Each selected occurrence owns a separate group containing its restored and new rollouts, even when the same task is selected more than once, so pass@k and the dashboard see one group per selected occurrence. Use `--clean` to start over instead.
## Monitors
Monitors receive the run's metrics and episodes through one abstraction. The file monitor is on by default; `--monitors.wandb` logs the run to Weights & Biases; `--monitors.prime` streams it to the Prime platform.
### File
The file monitor writes the run's metrics and trace stream under `output_dir / run.name / monitors/file/` and feeds the local [dashboard](training.md#dashboard). Env servers stream every rollout to the eval process as it happens: the trace's header when it is minted, then one delta per committed turn (the new messages and the model call behind them), per phase change (boot, setup, agent, finalize, scoring), and a preview of each model request's uncommitted messages, so a tool result shows the moment the model is asked about it rather than with the reply. The file monitor appends those deltas to `monitors/file/traces/live/<trace_id>.jsonl` and deletes the file when the episode lands in the finished trace stream, so that directory is exactly the live set and finished traces stay where they always were. The dashboard's traces tab shows live rollouts in the episode table itself: a pulsing dot in the `#` cell marks the row, a phase badge says where the rollout is (boot, setup, running, finalize, scoring), the `dispatched → arrived` column shows the dispatch time with the elapsed time in brackets, and the turn, token and branch counts grow as deltas land. The status filter toggles live and completed rows, and a live row opens in the trace viewer, which follows the rollout turn by turn (the transcript stays pinned to the newest turn until you scroll up; folded entries stay folded; the pending messages of the request in flight render dimmed with an `awaiting model` chip). The table and an open live trace poll once a second and transfer nothing while the rollout is unchanged. The progress line in `eval.log` counts the live rollouts by phase (`2 inflight episodes ... - boot 1 · running 1`). Read a live trace from a shell with `uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`. The same stream exists for RL runs, covering train and online-eval rollouts alike.
The dashboard's overview tab reads the trace stream directly. It shows one env at a time; the filter menu picks the env and whether errored episodes join the distributions. A block bar has one cell per expected episode: landed episodes (errored ones in red; click one to open it), live rollouts as pulsing outlines (click one to follow it), and the rest empty, with the percentage beside it. The expected count is what the eval runner wrote to `monitors/file/plan.json` when it counted the epoch's tasks. Below the bar, a summary row gives the headline numbers: avg@k and pass@k, the error and truncation rates (yellow past 10%, red past 50%), mean turns and branches in one tile, mean episode time and tokens, and the total cost when the run has costs; hover a tile for its distribution. The env's own rewards and metrics follow, a beeswarm pane each, resizable like the training charts. The usage section is one pane splitting each episode's tokens into input and output, and the timing section is the same pane over the phases of a rollout (boot, setup, model, harness, finalize, scoring, and `other` for wall time no phase accounts for): an icicle bar shows the mean split, one strip per episode below shows the split per rollout, and a legend sits above. Hovering a phase highlights it across the pane; the strips show 40 episodes by default and all of them on `show all`. A metric every episode shares appears as a chip instead of a pane, and a metric with only a few distinct values, such as a binary reward, as a counted dot plot with the count and share of each value. Every dot is an episode (or a task): hover it for its value and click it to open the trace; hover the pane's background for the summary (min, p10, median, p90, max), with a faint boxplot behind the dots. Errored episodes stay out of the distributions until the filter includes them, where they read red. The metrics tab charts every key of the run's `metrics.jsonl`: the epoch's `eval/<env>/…` summaries and the time-keyed `inference/` and `concurrency/` rows the runner samples while the epoch is in flight.
### Prime
`--monitors.prime` streams each source's epoch as an evaluation on the Prime platform:
```bash
uv run eval gsm8k -n 32 -r 4 -c 8 --monitors.prime
```
The monitor opens one platform evaluation per env when its epoch starts, streams every episode to it as it lands, and closes it with the epoch's aggregates. The run leaves its platform identity in `monitors/prime/run.json` (the training run's id and URL, or one entry per eval epoch), and the dashboard's top bar shows a `view on platform` link from the moment the evaluation opens: a direct link for a training run or a single evaluation, a menu when a run has several.
## Metrics
Eval metrics mirror the training rollout hierarchy under the `eval/<env>` scope:
| Metric | Reading |
|---|---|
| `eval/<env>/all/<agent>/reward/mean` | mean reward over the epoch |
| `eval/<env>/all/<agent>/is_truncated/mean` | share of rollouts cut by the length limit |
| `eval/<env>/all/<agent>/is_timeout/mean` | share of rollouts stopped by a stage deadline (`<stage>_timeout`) |
| `eval/<env>/all/<agent>/has_error/mean` | share of rollouts that raised |
| `eval/<env>/all/seq_len/mean` | mean episode length in tokens |
Task-specific env metrics (e.g. `correct_answer`, `format`) appear under the same prefix. The console summary line per source (`Evaluated <env> ... Reward 0.8125`) reports the epoch mean.
+21 -3
View File
@@ -190,8 +190,10 @@ Both backends support the 2 most important things:
- P/D disaggregation - handling the prefill and decode stages separately
### Routing policies
The 2 policies you might want to configure are:
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - it hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica.
The policies you might want to configure are:
- `sticky_least_loaded` - the default policy. A new `X-Session-ID` is assigned to the least-loaded replica, then every later turn in that rollout remains on the same replica for KV cache reuse. The orchestrator releases sessions when rollouts complete, fail, or are cancelled, including traces discarded during retries. Failed release requests are logged without disabling future cleanup.
- `consistent_hash` - hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica, preserving KV cache reuse without considering current load.
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
@@ -285,7 +287,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Capture runs on vLLM's V2 model runner (forced automatically). Router replay is not supported with disaggregated P/D: vLLM does not capture routed experts across NIXL KV transfer.
```toml
[trainer]
@@ -298,3 +300,19 @@ enable_return_routed_experts = true
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
### Sampling Replay
Truncated sampling (`top_p < 1`, `top_k`) renormalizes the sampling distribution over a sampling mask of surviving token ids. The rollout logprobs reflect that (`logprobs_mode = "processed_logprobs"`), so the trainer must renormalize over the same mask — otherwise every importance ratio is biased and training collapses (DeepSeek V3.2's "Keep Sampling Mask", [arXiv:2512.02556](https://arxiv.org/abs/2512.02556) §3.1; Cognition's [SWE-1.7 post](https://cognition.com/blog/swe-1-7)). prime-rl handles this automatically: vLLM records the sampling mask at sampling time (`--return-sampling-mask`, native since vLLM 0.28) and the trainer renormalizes its logprobs over it.
```toml
[orchestrator.train.sampling]
top_p = 0.95
top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling mask)
```
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`. Frozen-source envs are exempt.
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run together with router replay. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
+1
View File
@@ -7,6 +7,7 @@
"overview",
"configuration",
"training",
"eval",
"inference",
"scaling",
"algorithms",
+49 -28
View File
@@ -86,35 +86,34 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
|---|---|
| `trainer.model.dp_replicate` | Number of dimensions to **replicate** instead of shard. Set to 2 to run 2-way DP replication × FSDP sharding within each replica — useful for very large clusters where pure FSDP communication dominates. |
| `trainer.model.reshard_after_forward` | If `true` (default), parameters are resharded after the forward pass to free memory; the backward pass re-gathers. Set `false` to keep params resident — faster but more memory. |
| `trainer.model.fsdp_cpu_offload` | Offload params + grads + optimizer state to CPU. Big memory win, large throughput hit. |
| `trainer.model.optim_cpu_offload` | Offload optimizer state to CPU between steps. Enabled by default. |
| `trainer.model.full_offload` | Offload gradients, FP32 masters, and optimizer state and run the optimizer (AdamW or SignSGD) on CPU during backward. Disabled by default. |
| `trainer.model.offload` | CPU offloading: `optimizer` (default) offloads optimizer state between steps; `full` offloads gradients, FP32 masters, and optimizer state and runs the optimizer (AdamW or SignSGD) on CPU during backward; `none` disables offloading. |
### Expert Parallelism
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput.
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is <= 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
`ep` defaults to `"auto"`. At startup it loads the model config to check whether the model is MoE. For MoE models it resolves to `min(world_size // dp_replicate, 8)`: the FSDP island size, capped at 8. For non-MoE models it resolves to 1 (no-op). `"auto"` does not look at `num_experts` or `cp`; the resolved degree must still be a multiple of `cp` and divide `num_experts`, so set it explicitly when it does not. Set `ep` to an explicit integer to override:
```toml
[trainer.model]
impl = "custom"
ep = 8 # explicit EP degree; must divide num_experts
ep_comm_backend = "torch" # or "deepep"
ep = 8 # explicit EP degree; must divide num_experts
[trainer.model.moe.dispatch]
type = "torch"
transport = "bf16"
```
`ep_comm_backend = "deepep"` uses DeepEP's custom dispatch/combine kernels for speed, with two extra knobs (`deepep_num_sms`, `deepep_token_chunk_size`) — tune on your hardware.
For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_size` in the same dispatch table. Routed-expert precision is selected separately with `[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, or `mxfp8`).
### Context Parallelism
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Prefer `ulysses`: it gets the most throughput and is the only style that works for hybrid linear-attention/Mamba models (Qwen3.5, NemotronH) and for VLMs. Each model class declares its supported styles in `cp_support`; an unsupported `cp_style`, or a model with no CP support at all, is rejected at setup.
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Hybrid Mamba layers head-shard independently (`cp_mamba`), which requires the CP degree to divide `mamba_num_heads` and `n_groups`.
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Nemotron-H redistributes its Mamba activations between sequence- and head-parallel layouts in the model-owned Mamba path; the CP degree must divide `mamba_num_heads` and `n_groups`.
```toml
[trainer.model]
impl = "custom"
attn = "auto" # auto = FA3 on Hopper, FA4 on Blackwell; or flash_attention_2/3/4
attn = "auto" # auto = FA3 on Hopper, FA4 on datacenter Blackwell, FA2 otherwise; or flash_attention_2/3/4
cp = 2 # CP degree
cp_style = "ulysses" # "ring"
```
@@ -127,31 +126,34 @@ cp_style = "ulysses" # "ring"
| `trainer.model.ac.mode = "selective"` | medium | small |
| `trainer.model.ac_offloading` | extra | a bit more |
AC and AC offloading are enabled by default (full mode). For the best memory/throughput tradeoff, switch to selective AC (custom impl only):
AC and AC offloading are enabled by default (full mode). Both AC modes retain stateful MoE routing updates and DeepEP communication that cannot safely replay. Selective AC uses the same transformer-block boundaries and additionally retains distributed communication, expensive matrix multiplications, grouped GEMMs, and supported attention kernels:
```toml
[trainer.model.ac]
mode = "selective"
targets = ["norm", "attn_proj"] # see Reference for the full list per architecture
```
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
Set `targets` to operator names (for example, `"aten::mm"`) or namespaces (for example, `"prime_rl_collectives"`) to replace the default selective targets. Correctness-required operations remain retained.
Activation offloading still applies to tensors saved by autograd, but tensors retained by the checkpoint policy remain on the accelerator.
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only losing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
### Optimizer Offloading
State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`. For full offload, set `model.optim_cpu_offload = false` and `model.full_offload = true`; this keeps BF16 compute weights on GPU and runs CPU optimizer chunks as gradients become ready during backward. Full offload only supports AdamW and SignSGD (`optim.type = "sign_sgd"`) and disables gradient clipping. SignSGD is stateless, so it halves the host RAM footprint versus AdamW (8 instead of 16 bytes per parameter: FP32 master + FP32 accumulated gradient, no moments).
State-only optimizer offload is enabled by default (`model.offload = "optimizer"`). For full offload, set `model.offload = "full"`; this keeps BF16 compute weights on GPU and runs CPU optimizer chunks as gradients become ready during backward. Full offload only supports AdamW and SignSGD (`optim.type = "sign_sgd"`) and disables gradient clipping. SignSGD is stateless, so it halves the host RAM footprint versus AdamW (8 instead of 16 bytes per parameter: FP32 master + FP32 accumulated gradient, no moments).
### LM Head Chunking
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization. It defaults to `1024` for RL training:
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization. It defaults to `8192` for RL training:
```toml
[trainer.model]
fused_lm_head_token_chunk_size = 1024 # default
fused_lm_head_token_chunk_size = 8192 # default
# fused_lm_head_token_chunk_size = "disabled" # vanilla LM head
```
Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. SFT training silently disables this (not supported yet). Only available with `model.impl = "custom"`.
Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. SFT training silently disables this (not supported yet).
## Memory-Tight Recipe
@@ -159,7 +161,6 @@ The kitchen-sink config for fitting large MoE on limited GPUs at acceptable thro
```toml
[trainer.model]
impl = "custom"
ep = 8
cp = 2
@@ -170,7 +171,7 @@ freq = 1
max_inflight_activations = 1
```
The defaults already cover: fused LM head chunking (`1024`), `torch.compile` (fullgraph=False), AC (full mode), AC offloading (`max_inflight_activations=5`), and optimizer CPU offload. Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
The defaults already cover: fused LM head chunking (`8192`), `torch.compile` (fullgraph=False), AC (full mode), AC offloading (`max_inflight_activations=5`), and optimizer CPU offload. Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
## SLURM
@@ -217,7 +218,8 @@ SFT multi-node:
```toml
[deployment]
type = "multi_node"
num_nodes = 2
num_train_nodes = 2
num_infer_nodes = 1 # required only for online evals
gpus_per_node = 8
```
@@ -225,11 +227,30 @@ gpus_per_node = 8
Full multi-node configs ship under [`examples/advanced/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced):
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/configs/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`glm-5.3/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale and P/D-disaggregated inference across the GLM-5 family.
- [`glm-4.5-air/swe-2-node.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-4.5-air/swe-2-node.toml) — train a 100B+ MoE on only two nodes: a single-node sign-SGD trainer (full optimizer offload) paired with one inference replica at batch size 64. An overlay on the shared `swe-budget.toml` base — launch with `uv run rl @ swe-budget.toml @ swe-2-node.toml`.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
### NIXL weight broadcast
Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transfer. Before the first SLURM run, install the NIXL/UCX build and the ModelExpress service binaries on the shared filesystem:
```bash
bash scripts/install_nixl_from_source.sh
uv pip install --reinstall --no-deps deps/nixl_cu13-*.whl
bash scripts/install_modelexpress.sh
```
The generated job starts a job-scoped ModelExpress server and Redis backend on the trainer head node and passes that address to every component. To use an existing service, set `slurm.launch_modelexpress = false` and configure `weight_broadcast.host` and `weight_broadcast.port`.
The launcher requires the CUDA and InfiniBand transports from `third_party/ucx`. Each NIXL process selects the active InfiniBand port nearest its GPU; an explicitly configured `UCX_NET_DEVICES` takes precedence. Inference ranks start their pulls at different trainer ranks so concurrent workers distribute traffic across all available source rails.
ModelExpress exchanges peer metadata during startup. Weight updates reuse prepared NIXL requests, post every trainer-rank read in a transfer group concurrently, and use versioned NIXL notifications for source readiness and buffer credits.
By default, the trainer and inference worker each allocate one transfer arena. Set `weight_broadcast.overlap_transfer_and_replay = true` to allocate two arenas on both sides and replay one weight group while receiving the next. The additional arena is the size of the largest transfer group per GPU; allocation errors are reported instead of silently disabling overlap.
### Custom Templates
For unusual partitions, module loads, or environment setup, supply your own Jinja2 template:
@@ -248,8 +269,8 @@ To benchmark a parallelism config before committing a multi-day run, run a short
# SFT trainer alone
uv run sft @ sft.toml --data.type fake --max-steps 4
# RL trainer alone (no inference involved)
uv run trainer @ train.toml --data.fake --max-steps 4
# RL trainer alone (no inference involved) -- launch it under torchrun, like the `rl` launcher does
uv run torchrun --nproc-per-node=8 src/prime_rl/trainer/rl/train.py @ train.toml --data.fake --max-steps 4
```
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `metrics.jsonl` to the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `monitors/file/metrics.jsonl` under the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
+80 -30
View File
@@ -1,6 +1,6 @@
# Training
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md).
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md). For standalone evals, see [Eval](eval.md).
> **AI agents working in this repo:** the equivalent runbooks are at [`skills/training/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/skills/training) — top-level routing in [`skills/training/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/SKILL.md), launch details in [`skills/training/start-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/start-run/SKILL.md), and check-in / restart procedures in [`skills/training/monitor-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/monitor-run/SKILL.md).
@@ -35,9 +35,9 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run rl` | Wraps the trainer, orchestrator, and inference server in one launch from a merged TOML. | The default for any RL run. Runs locally for single-node experiments; submits to SLURM for single- or multi-node when `[slurm]` is set (see [Scaling § SLURM](scaling.md#slurm)). |
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at a derived loopback address); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-server` per source. |
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. on their own host) and the launcher expects the server to already run there. |
## RL Trainer
@@ -58,9 +58,11 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| Knob | What it does |
|---|---|
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `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.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). |
| `trainer.model.freeze_moe_router` | Freeze MoE router gates (default `true` for RL, `false` for SFT). Router updates in RL shift the trainer's expert choices away from the ones inference sampled, amplifying the train-inference mismatch, so RL keeps the pretrained router. Set `false` to train it. |
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
@@ -81,11 +83,11 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| `--run.name <name>` | Run name, also the run directory name under `<output_dir>` (override the directory separately via `--run.dir`). Auto-generated as `<envs>--<model>--<short-id>` when unset, so every launch gets a fresh, readable run directory. Set an explicit name for a predictable path — required to resume the run later. |
| `--clean` | Wipe the run directory before starting. Useful when re-running a named run during iteration. |
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/latest/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
### 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 |
|---|---|---|
@@ -100,7 +102,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 \
@@ -117,6 +119,7 @@ Pulled from the console logs and mirrored to W&B.
- `reward/{all,env}/mean` — main signal. Should trend upward over hundreds of steps.
- `seq_len/{all,env}/mean` and `is_truncated/{all,env}/mean` — rollout length and truncation rate.
- `is_timeout/{all,env}/mean` — share of rollouts stopped by a stage deadline (`setup`/`agent`/`finalize`/`scoring` `_timeout`). Training counts a timed-out rollout as an error, so it stays out of the batch; eval scores it.
- `num_turns/{all,env}/mean` — for multi-turn envs.
- `empty_rollouts/{all,env}`, `errored_rollouts/{all,env}` — non-zero is fine in small numbers; sustained > 5% is a smell.
- `eval/{env}/{avg@k,pass@k}` — eval scores when `[orchestrator.eval]` is set.
@@ -125,7 +128,7 @@ Pulled from the console logs and mirrored to W&B.
- `mismatch_kl/{all,env}/{mean,std,max}` — KL between trainer's current policy and the (older) inference policy that generated the rollouts. A sustained, growing mean is the early-warning sign for off-policy collapse.
- `entropy/{all,env}/mean` — too low means mode-collapse; too high means the model isn't committing.
- `masked_advantage_{positive,negative}/mean` — fraction of DPPO-masked tokens, split by sign.
- `is_masked/mean` — fraction of tokens masked by the IPO trust region.
- `optim/grad_norm` — spikes precede divergence; check the loss config or lower the LR.
**Performance** (trainer + orchestrator step independently):
@@ -133,7 +136,9 @@ Pulled from the console logs and mirrored to W&B.
| Source | Metric | Reading |
|---|---|---|
| trainer | `time/wait_for_batch` | **high → orchestrator bottleneck** |
| orchestrator | `time/wait_for_ckpt` | **high → trainer bottleneck** |
| orchestrator | `time/wait_for_policy` | **high → trainer bottleneck** |
The trainer warns when batch wait time exceeds active trainer time. Add inference nodes when this warning persists. The orchestrator warns when policy wait time exceeds active orchestrator time. Add trainer nodes when this warning persists. The orchestrator also warns when it discards more than half of an episode window. This warning reports stale, errored, and no-signal counts.
## SFT Trainer
@@ -146,9 +151,19 @@ 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"
```
**Per-message loss selection.** An optional `message_loss_mask` column contains one boolean or integer 0/1 per message. For example, `[0, 0, 0, 1]` on a user/assistant/user/assistant conversation trains only the final assistant turn while retaining the full context. For prompt-completion rows, the mask covers the concatenated prompt and completion messages. Zero excludes a message; one preserves the normal role and renderer loss settings. A missing or null mask leaves those settings unchanged. The renderer applies selection without changing token IDs, including ownership of assistant closing tokens. Invalid mask lengths or entries raise an error.
To read a differently named column, set `data.columns.message_loss_mask = "selection"`.
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column in OpenAI function-calling format. Each row's value can be either a list of dicts or a JSON-encoded string of a list.
Renderer-backed SFT reads template controls from the typed `[renderer]` config in the SFT TOML. For example:
@@ -158,11 +173,30 @@ name = "qwen3"
enable_thinking = false
```
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).
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectories) for the full picture.
@@ -176,14 +210,18 @@ 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` / `num_examples` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
`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:
```toml
[eval]
interval = 25
num_examples = 32
[eval.select]
limit = 32
[[eval.source]]
name = "reverse-text"
@@ -198,17 +236,17 @@ num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
The launcher starts the inference server, one env server per eval source, and an online-eval process next to the trainer (it logs to `logs/attempt_<n>/eval.log`). NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the online-eval process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
#### Multi-Node (Decoupled Trainer and Inference Pool)
#### Multi-Node Trainer and Inference Pool
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two separate SLURM jobs**. `deployment.num_train_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and online-eval process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2 # trainer job
num_infer_nodes = 1 # eval job (inference pool + evals)
num_train_nodes = 2 # trainer nodes
num_infer_nodes = 1 # inference pool + online evals
[inference.vllm]
tensor_parallel_size = 8
@@ -217,7 +255,7 @@ tensor_parallel_size = 8
job_name = "my-run"
```
The launcher submits the eval job after the trainer allocation starts. The trainer publishes its rank-0 hostname in the shared run directory, and the eval job uses it to join the NCCL weight-broadcast group. Each weight transfer is synchronous, but eval rollout execution overlaps with later training steps. After the final transfer, the trainer job releases its nodes while the eval job finishes the final epoch and exits. Without `max_steps`, the eval job never sees a final broadcast and holds its allocation until walltime. Trainer and evals log to one shared W&B run — the trainer creates it, and the evals process finalizes it. Any trainer-to-inference node layout works because `num_train_nodes` and `num_infer_nodes` are independent.
The shared script passes the trainer rank-0 hostname directly to the online-eval process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, online-eval never sees a final broadcast, so the job remains active until walltime. Trainer and online-eval log to one shared W&B run. The trainer creates it, and online-eval finalizes it.
### SFT-Specific Knobs
@@ -246,7 +284,8 @@ Pulled from the console log and mirrored to W&B.
- `optim/grad_norm` — spikes precede divergence.
- `optim/lr` — LR schedule.
- For MoE: `max_vio/mean` (load-balancing violation), `routing_confidence/mean` — both are logged when non-zero.
- For MoE: `max_vio/mean`, `max_vio/max` — mean and max over the step's microsteps of the largest load-balancing violation across layers and EP groups, computed from expert token counts summed across each EP group. `routing_confidence/mean` — mean routing confidence.
- For MoE: `expert_load/{cv,max_mean,cold_frac}/{mean,max}` — expert load per layer over the whole step, from token counts summed across all ranks, as the mean and max over MoE layers. `cv` is std/mean of the per-expert token counts, `max_mean` the busiest expert's count over the mean, and `cold_frac` the fraction of experts receiving under 0.1x the mean. A trainable router that drifts shows up as a rising `cv`/`cold_frac` (MiMo-V2.6 §5.4).
**Performance:**
@@ -313,6 +352,13 @@ The exported directory loads directly into `uv run inference --vllm.model <dir>`
## Observability
### Config Files
Each launch writes its command, input TOML, and resolved JSON files to
`<run_dir>/configs/attempt_<n>/`. Resumed runs keep the earlier configs.
`command.txt` uses shell-safe quoting.
`configs/latest` points to the current attempt.
### Log Files
The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>/` — every launch (fresh or resumed) gets its own numbered attempt directory, and `logs/latest` symlinks to the current one. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
@@ -321,6 +367,7 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
├── orchestrator.log # single instance, single file
├── eval.log # `uv run eval` process, or the SFT online-eval process
├── inference.log # symlink → inference/node_0.log on multi-node
├── trainer/
│ ├── node_*.log # per-node trainer stdout (multi-node only)
@@ -331,25 +378,25 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
```
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/latest/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
```bash
tail -F <run_dir>/logs/latest/{trainer,orchestrator,inference}.log
tail -F <run_dir>/logs/latest/{trainer,orchestrator,eval,inference}.log
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
```
### Dashboard
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved configs, a rollout trace viewer with a per-token advantage/logprob view, merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with six views per run: an overview (the W&B overview sections, read from the file monitor's `metrics.jsonl`), metrics (every key in that file, one pane each, with a regex filter), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
### Weights & Biases
W&B is off by default (the file monitor, which writes `metrics.jsonl` and the per-step trace files to the run directory, is on by default):
W&B is off by default (the file monitor, which writes the metrics and the trace stream under the run's `monitors/file/` directory, is on by default):
```bash
uv run rl @ rl.toml --monitors.wandb # default project, random name
@@ -367,6 +414,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:
@@ -376,14 +424,16 @@ Or set it in TOML:
name = "my-experiment"
```
Every 10th step the orchestrator uploads the step's episodes (full conversations with rewards and advantages) to the run's sample viewer.
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.
Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted team. Currently internal-only.
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.
## Rules of Thumb
- **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.
+32 -12
View File
@@ -2,16 +2,36 @@
End-to-end usage examples for prime-rl, referenced from the top-level [README](../README.md).
- **[`basic/`](basic)** — walk-throughs for the core environments on 1–8 GPUs (baseline eval →
optional SFT warmup → RL → eval), each with its own README:
- `reverse-text` — smallest end-to-end loop (single-turn, 0.6B)
- `alphabet-sort` — multi-turn, user simulator, LoRA
- `wiki-search` — multi-turn tool calling, LoRA
- `wordle` — multi-turn (~6-turn games)
- `hendrycks-sanity` — single-turn math, long-running
- **[`advanced/`](advanced)** — larger, mostly multi-node runs on frontier models, one folder
per model: `qwen3-30b-a3b` (math/swe/tool), `glm-4.5-air` (search/swe/terminal), `glm-5.2`
(large-scale + PD-disaggregated inference), `minimax-m2.5` (swe), `nemotron-3-super` (swe),
`intellect-3.1` (swe).
New here? Follow [`basic/reverse-text/`](basic/reverse-text/README.md) first — it trains a small model end-to-end on 2 GPUs and introduces the launch → dashboard → checkpoint flow the advanced examples reuse.
Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
## advanced/ — frontier models, multi-node
Larger runs on frontier models, one folder per model, each with a launch README covering requirements, credentials, launch, monitoring, and resume:
- [`qwen3-30b-a3b/`](advanced/qwen3-30b-a3b/README.md) — `Qwen3-30B-A3B` RL on math (`i3_math`), SWE (`r2e-gym`), and agentic tool use (general-agent on Modal). 2 train + 2 infer nodes; the SWE config runs at 131k context with `ep = 8` + `cp = 2`.
- [`glm-4.5-air/`](advanced/glm-4.5-air/README.md) — `GLM-4.5-Air` (100B MoE) RL across search, SWE, and terminal domains at 131k context, with agents in sandboxes. 2 train + 4 infer nodes (SWE: 1 + 3).
- [`glm-5.3/`](advanced/glm-5.3/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
- `intellect-3.1/` — reproduce the `INTELLECT-3.1` run: 4 train + 12 infer nodes on SWE.
All advanced configs submit through SLURM (the `rl` entrypoint writes the sbatch job when the config has a `[slurm]` table) and are monitored with `uv run dashboard`. See the per-model README for the full walkthrough.
## basic/ — 1 to 8 GPUs
Walk-throughs for the core environments (baseline eval → optional SFT warmup → RL → eval), each with its own README:
- [`reverse-text/`](basic/reverse-text/README.md) — smallest end-to-end loop (single-turn, 0.6B): `eval.toml` → `sft.toml` → `rl.toml`
- [`alphabet-sort/`](basic/alphabet-sort/README.md) — multi-turn, user simulator, LoRA
- [`wiki-search/`](basic/wiki-search/README.md) — multi-turn tool calling, LoRA
- [`wordle/`](basic/wordle/README.md) — multi-turn (~6-turn games)
- [`hendrycks-sanity/`](basic/hendrycks-sanity/README.md) — single-turn math, long-running
## extra/ — beyond the core loop
Examples that don't follow the basic eval → SFT → RL walk-through pattern:
- [`dynamo/`](extra/dynamo/README.md) — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
- [`vlm/`](extra/vlm/README.md) — multimodal (VLM) SFT, dense + MoE LoRA configs
## Related config folders
- Frontier-model configs without launch walkthroughs (`minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`) live in [`configs/advanced/`](../configs/advanced).
+103
View File
@@ -0,0 +1,103 @@
# GLM-4.5-Air
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0). The SWE configs also ship budget variants: `swe-4-node.toml` (1 train + 3 infer) and `swe-2-node.toml` — train a 100B+ MoE on only two nodes. Both are thin overlays on a shared `swe-budget.toml` base: the base holds the recipe, the overlay the topology, batch size, and per-run identity.
| Config | Trains on | Evals on | Topology |
|---|---|---|---|
| [`search.toml`](search.toml) | `openseeker` + `redsearcher` (search QA, `rlm` harness + `search` skill) | `browsecomp` (500 examples) | 2 train + 4 infer nodes |
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 2 train + 4 infer nodes |
| [`swe-budget.toml`](swe-budget.toml) + [`swe-4-node.toml`](swe-4-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
| [`swe-budget.toml`](swe-budget.toml) + [`swe-2-node.toml`](swe-2-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 1 infer node |
| [`terminal.toml`](terminal.toml) | `tmax` (per-task Docker image, `rlm` ipython harness) | `swebench-verified` + `terminal-bench-2` (avg@4) | 2 train + 4 infer nodes |
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8` (plus expert parallelism on `swe.toml`). `search.toml`, `swe.toml`, and `terminal.toml` train with Muon on 2 trainer nodes. The budget variants instead fit the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer; `swe-2-node.toml` cuts the batch size to 64 (4 groups of 16) to match the throughput of its single inference replica. They don't parse standalone: compose them left-to-right over `swe-budget.toml` (`uv run rl @ swe-budget.toml @ swe-2-node.toml`). Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
## Requirements
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. Install the `prime` CLI separately and log in. Each config's `slurm.pre_run_command` then cleans up the run's orphaned sandboxes by label before launch:
```bash
uv tool install prime
prime login # or: prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend) and drop the `slurm.pre_run_command` cleanup line.
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
- `HF_TOKEN` — `zai-org/GLM-4.5-Air` is a gated model.
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
- `SERPER_API_KEY` — search envs only; forwarded into the agent sandbox for the `search` skill (`harness.forward_env`).
## Setup
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
uv sync --all-extras --all-packages
```
## Tweak before launching
- `[slurm] partition` is set to `all` — override with `--slurm.partition <your-partition>`, or edit the config.
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
## Start the run
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
```bash
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
--output-dir /shared/outputs/glm45air \
--run.name glm45air-swe
```
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. For SWE on a smaller budget, compose a budget variant over its base: `uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml` trains the 100B+ MoE on only two nodes. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
## Monitor with the dashboard
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
```bash
uv run dashboard /shared/outputs/glm45air # serves http://localhost:7788
```
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
```bash
ssh -L 7788:localhost:7788 <head-node>
```
Pick the run (`<run_name>` from the launch) and you get five views:
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
## Checkpoint, resume, export
Checkpoints land in `<run_dir>/checkpoints/step_<N>` every 50 steps (`keep_last = 1`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
```bash
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
--output-dir /shared/outputs/glm45air \
--run.name glm45air-swe \
--resume --max-steps 1000
```
Trainer checkpoints are DCP-sharded; export HF-format weights with:
```bash
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/glm45air/glm45air-swe/checkpoints/step_100
```
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
+9 -23
View File
@@ -5,10 +5,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-search"
partition = "all"
@@ -25,12 +21,6 @@ num_infer_replicas = 4
project = "search-ablations"
name = "glm45air-search"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
@@ -43,11 +33,9 @@ name = "zai-org/GLM-4.5-Air"
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
@@ -60,9 +48,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "muon"
@@ -70,9 +55,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
@@ -81,10 +68,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
@@ -100,7 +87,7 @@ name = "openseeker"
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.taskset.id = "openseeker"
@@ -124,7 +111,7 @@ name = "redsearcher"
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.taskset.id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
@@ -150,11 +137,11 @@ interval = 20
[[orchestrator.eval.source]]
name = "browsecomp"
num_examples = 500 # full set is 1266; cap eval at 500
select.limit = 500 # full set is 1266; cap eval at 500
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = 98304
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.agent.timeout.rollout = 3600
env.taskset.id = "browsecomp"
@@ -180,4 +167,3 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
enable_return_routed_experts = true
@@ -0,0 +1,41 @@
# Budget variant of swe.toml: train a 100B+ MoE on only two nodes (1 train + 1 infer replica) with
# the single-node sign-SGD trainer. Overlay for swe-budget.toml — this file only carries the
# deltas, so compose the two (left-to-right merge, see docs/configuration.md "TOML Composition"):
#
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml
#
# The batch size is 64 (4 groups of 16), matching the rollout throughput of the single inference
# replica. The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the
# budget variants can run side by side.
[slurm]
job_name = "glm45air-swe-2-node"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe-2-node" -y || true'
[deployment]
num_infer_replicas = 1
[monitors.wandb]
name = "glm45air-scaleswe-2-node"
[orchestrator]
batch_size = 64
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-2-node"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-2-node"]
env.agent.timeout.rollout = 3600
@@ -0,0 +1,42 @@
# Budget variant of swe.toml: the same recipe on four nodes (1 train + 3 infer replicas, the
# topology swe.toml used before the Muon switch) with the single-node sign-SGD trainer. Overlay for
# swe-budget.toml — this file only carries the deltas, so compose the two (left-to-right merge, see
# docs/configuration.md "TOML Composition"):
#
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-4-node.toml
#
# Batch size 256 (16 groups of 16) matches the rollout throughput of the three inference replicas.
# The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the budget
# variants can run side by side.
[slurm]
job_name = "glm45air-swe-4-node"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe-4-node" -y || true'
[deployment]
num_infer_replicas = 3
[monitors.wandb]
name = "glm45air-scaleswe-4-node"
[orchestrator]
batch_size = 256
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-4-node"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-4-node"]
env.agent.timeout.rollout = 3600
@@ -0,0 +1,100 @@
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Shared base of the budget variants of swe.toml
# (`swe-4-node.toml`, `swe-2-node.toml`): the pre-Muon recipe with the single-node sign-SGD
# trainer, composed as `uv run rl @ swe-budget.toml @ <variant>.toml`. Router replay is enabled
# (trainer.enable_router_replay replays the routed-expert decisions returned by inference via
# enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe model, which supports routed_experts.
#
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
#
# Inference serves the bf16 checkpoint as-is (no quantization). The trainer fits on one node via
# cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus the
# memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
# skip-gather / skip-optimizer checkpointing. Concurrency is fully default: the controller derives
# its start from the measured KV budget and adapts from there.
#
# The variant overlays on top of this base set the inference replica count and batch size, the
# per-variant SLURM job name / sandbox cleanup label / W&B run name, and the train/eval sources
# with their matching runtime labels.
max_steps = 1000
seq_len = 131072
[slurm]
partition = "all"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[monitors.wandb]
project = "swe-ablations"
[ckpt]
interval = 50
keep_last = 1
[resume]
# --- Trainer ---
[trainer]
enable_router_replay = true
[model]
name = "zai-org/GLM-4.5-Air"
[trainer.model]
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
offload = "full"
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
[trainer.optim]
type = "sign_sgd"
# --- Orchestrator ---
[orchestrator]
max_off_policy_steps = 32
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
type = "grpo"
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
# --- Inference ---
[inference]
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
+22 -37
View File
@@ -1,28 +1,24 @@
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
# a glm4_moe model, which supports routed_experts.
# runtime; eval on SWE-Bench Verified. Follows the research-prod air ablation base config
# (research-prod PR #198): 2 trainer nodes with the Muon optimizer (instead of the single-node
# sign-SGD setup), 4 one-node inference replicas serving the bf16 checkpoint with TP=8 + expert
# parallelism, batch size 256 / group size 16, and the linear length penalty with the input-token
# and turns coefficients set to 0.1. Router replay stays enabled (trainer.enable_router_replay replays the routed-expert
# decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe
# model, which supports routed_experts. Optimizer state is checkpointed so runs can resume.
#
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
# GRPO uses the linear length penalty. Each term is pass_rate-scaled and normalized by the
# group's own max before the GRPO baseline subtraction.
#
# 1 train + 3 infer nodes. Inference serves the bf16 checkpoint as-is (no quantization). The trainer
# fits on one node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
# skip-gather / skip-optimizer checkpointing.
# Two trainer nodes fit GLM-4.5-Air with Muon plus the memory improvements from the GLM-5.1 prod
# run (research-prod rlm5/prod.toml): activation checkpointing (freq=1) + activation offloading
# (max_inflight=1). LM-head token chunking (8192) and optimizer CPU offload run at their defaults.
# Concurrency is fully default: the controller derives its start from the measured KV budget and
# adapts from there.
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-swe"
partition = "all"
@@ -31,20 +27,14 @@ pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y ||
[deployment]
type = "multi_node"
num_train_nodes = 1
num_train_nodes = 2
num_infer_nodes = 1
num_infer_replicas = 3
num_infer_replicas = 4
[monitors.wandb]
project = "swe-ablations"
name = "glm45air-scaleswe"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
@@ -54,20 +44,15 @@ keep_last = 1
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
optim_cpu_offload = false
full_offload = true
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
@@ -76,23 +61,22 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "sign_sgd"
type = "muon"
# --- Orchestrator ---
[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
@@ -130,6 +114,7 @@ VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
gpu_memory_utilization = 0.85
max_model_len = 131072
tensor_parallel_size = 8
enable_return_routed_experts = true
enable_expert_parallel = true
+8 -22
View File
@@ -6,10 +6,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-terminal"
partition = "all"
@@ -26,12 +22,6 @@ num_infer_replicas = 4
project = "terminal-ablations"
name = "glm45air-terminal"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
@@ -44,11 +34,9 @@ name = "zai-org/GLM-4.5-Air"
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
@@ -61,9 +49,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "muon"
@@ -71,9 +56,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
@@ -82,10 +69,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
@@ -96,7 +83,7 @@ num_turns_weight = 0.1
[[orchestrator.train.source]]
name = "tmax"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.taskset.id = "tmax"
@@ -123,7 +110,7 @@ interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.agent.timeout.rollout = 3600
env.taskset.id = "swebench-verified"
@@ -144,7 +131,7 @@ env.taskset.id = "swebench-verified"
name = "terminal-bench-2"
group_size = 4 # avg@4
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.agent.timeout.rollout = 3600
env.taskset.id = "terminal-bench-2"
@@ -175,4 +162,3 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
enable_return_routed_experts = true
-87
View File
@@ -1,87 +0,0 @@
seq_len = 131072
[log]
level = "debug"
[monitors.wandb]
project = "glm5-pd-disag"
[weight_broadcast]
type = "nccl"
port = 29502
timeout = 12000
quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
num_train_nodes = 16
gpus_per_node = 8
num_infer_replicas = 2
[inference.deployment]
type = "disaggregated"
prefill_nodes_per_replica = 4
decode_nodes_per_replica = 4
[inference.vllm]
model = "zai-org/GLM-5-FP8"
tool_call_parser = "glm47"
gpu_memory_utilization = 0.80
enable_expert_parallel = true
enable_eplb = false
[slurm]
job_name = "glm5-pd-disag"
[ckpt]
interval = 100
[trainer]
dist_timeout_seconds = 7200
[trainer.model]
name = "zai-org/GLM-5"
impl = "custom"
attn = "flash_attention_2" # dsa is skipping flash attn anyway
fused_lm_head_token_chunk_size = 2048
ep = 8
[trainer.model.ac]
freq = 1
[trainer.model.compile]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "adamw"
lr = 1e-6
weight_decay = 0.1
[orchestrator]
batch_size = 4096
group_size = 16
max_off_policy_steps = 16
[orchestrator.concurrency]
initial_inflight = 4096
max_inflight = 8192
[orchestrator.model]
name = "zai-org/GLM-5-FP8"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm5-pd-disag", "swe-bench-verified"]
[inference]
# we need <0.85 bc glm5 layers are too large for 0.85
use_deep_gemm = true
+129
View File
@@ -0,0 +1,129 @@
# GLM-5 family at scale
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5.3-BF16` for training and serving alike, quantized to per-block FP8 online on the vLLM side — at 131k context: 16 trainer nodes on the custom MoE implementation (expert + context parallelism) and P/D-disaggregated FP8 inference. The [`swe-llmd.toml`](swe-llmd.toml) append fronts the same inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. It also offloads KV to a Mooncake distributed CPU pool (1TB per node by default).
| Config | What it runs | Topology |
|---|---|---|
| [`swe.toml`](swe.toml) | Base GLM-5.3 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), serves `GLM-5.3-BF16` with online per-block FP8 quantization behind the default `vllm-router`. | 16 train + 16 infer nodes |
| [`swe-llmd.toml`](swe-llmd.toml) | Append for `swe.toml`: swaps in the llm-d router (EPP scorer tuning) + Mooncake KV offload — launch as `rl @ swe.toml @ swe-llmd.toml`. | same |
| [`infer/pd.toml`](infer/pd.toml) | Inference-only pre-flight: P/D-disaggregated `GLM-5-FP8`. | 6 infer nodes |
| [`infer/pd-llmd.toml`](infer/pd-llmd.toml) | Inference-only pre-flight: `GLM-5.2-FP8` with llm-d + Mooncake. | 16 infer nodes |
## Requirements
- A Slurm cluster with 8-GPU nodes, a shared filesystem, and at least **32 nodes** (16 trainer + 16 inference) for the RL configs. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path. If you have fewer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` accordingly.
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d append).
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, install the `prime` CLI separately and log in:
```bash
uv tool install prime
prime login # or: prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend).
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
- `HF_TOKEN` — the GLM-5 family checkpoints are gated models.
- `WANDB_API_KEY` — both RL variants log to W&B (`[monitors.wandb]`).
### Install llm-d (llm-d append only)
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
```bash
bash scripts/install_llmd.sh
```
## Setup
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
uv sync --all-extras --all-packages
```
## Tweak before launching
- `swe.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`.
- `swe-llmd.toml` `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
- `swe-llmd.toml` `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
## Start the run
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
```bash
# GLM-5.3 RL behind the default vllm-router
uv run rl @ examples/advanced/glm-5.3/swe.toml
# with the llm-d router + Mooncake KV offload appended
uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
```
The inference configs are standalone pre-flights: they serve the FP8 checkpoint through the same entrypoint the trainer uses (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster` included — never call `vllm serve` directly), and are a fast way to check that this cluster can serve the model at all before committing it to a run:
```bash
uv run inference @ examples/advanced/glm-5.3/infer/pd.toml
uv run inference @ examples/advanced/glm-5.3/infer/pd-llmd.toml
```
## Monitor with the dashboard
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
```bash
uv run dashboard /shared/outputs # serves http://localhost:7788
```
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
```bash
ssh -L 7788:localhost:7788 <head-node>
```
Pick the run and you get five views:
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
## Checkpoint and resume
Both RL configs ship without `[ckpt]` — add a `[ckpt]` overlay (e.g. `interval = 100`) for periodic checkpoints. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
See [Scaling](../../../docs/scaling.md) for SLURM details and [Inference](../../../docs/inference.md) for the disaggregated-inference and router reference.
## SFT
The SFT configs live under [`sft/h200/`](sft/h200) — they are tuned for 8-GPU H200 nodes. Compose the base config with a data overlay:
```bash
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml
```
This will start a SFT run with the following configuration:
- The model is `zai-org/GLM-5.3-BF16`
- The data is `PrimeIntellect/INTELLECT-3-SFT-10K` (math split)
- 8 nodes at 131k context: CP 8, EP 8, full activation checkpointing with activation offloading, optimizer state offloaded to CPU
- DSA attention runs on the FlashMLA sparse forward and the cuDNN sparse backward (`model.dsa_backend = "cudnn_flashmla"`)
For a fake-data dry run, append [`fake.toml`](sft/h200/fake.toml) instead. You can use the same dashboard to monitor the SFT run.
### 12 nodes at 16k
For 16k-token samples, append [`16k-12-node.toml`](sft/h200/16k-12-node.toml) after the data overlay:
```bash
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml @ examples/advanced/glm-5.3/sft/h200/16k-12-node.toml
```
On 12 nodes the sharded model state fits in GPU memory without CP or any offloading. Each GPU runs one 16k sequence per step (batch 96), and transformer blocks compile with `fullgraph = true`. Full activation checkpointing stays on; peak memory is about 115 GiB per GPU.
@@ -2,7 +2,7 @@
# Step 3 / goal target. Topology mirrors the proven original glm5.1_llmd_inference
# (job 348 succeeded): 8 prefill nodes (4 replicas x 2) + 8 decode nodes (1 replica).
#
# Launch: uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
# Launch: uv run inference @ examples/advanced/glm-5.3/infer/pd-llmd.toml
output_dir = "/shared/outputs/glm5.2-16node-llmd"
@@ -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"
@@ -60,5 +63,4 @@ reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
@@ -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"
@@ -0,0 +1,19 @@
# 12-node, 16k-token overlay: enough GPUs that the model state fits without CP or offloading,
# so each GPU runs one 16k sequence per micro-batch and blocks compile with fullgraph.
# Compose after the data overlay, e.g. base.toml @ math-10k.toml @ 16k-12-node.toml.
[model]
cp = 1
offload = "none"
ac_offloading = "None"
[model.compile]
fullgraph = true
[data]
seq_len = 16384
batch_size = 96
micro_batch_size = 1
[deployment]
num_train_nodes = 12
@@ -0,0 +1,39 @@
clean = true
[env_vars]
HF_HOME = "/home/huggingface"
[model]
name = "zai-org/GLM-5.3-BF16"
attn = "flash_attention_2"
cp = 8
ep = 8
offload = "optimizer"
dsa_backend = "cudnn_flashmla"
[model.ac]
freq = 1
[model.ac_offloading]
max_inflight_activations = 5
[optim]
type = "sign_sgd"
lr = 5e-5
weight_decay = 0.01
[scheduler]
type = "linear"
warmup_steps = 50
decay_steps = 0
[renderer]
name = "glm-5.3"
[deployment]
type = "multi_node"
num_train_nodes = 8
[slurm]
job_name = "glm53-sft"
partition = "all"
@@ -0,0 +1,8 @@
[model.debug]
force_balanced_routing = true
[data]
type = "fake"
batch_size = 8
micro_batch_size = 1
seq_len = 131072
@@ -0,0 +1,7 @@
[data]
type = "sft"
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
splits = ["math"]
batch_size = 8
micro_batch_size = 1
seq_len = 131072
+47
View File
@@ -0,0 +1,47 @@
# llm-d append for swe.toml: fronts the P/D-disaggregated inference plane with
# the llm-d router (Endpoint Picker + Envoy) and offloads KV to a Mooncake
# distributed CPU pool. Everything else is inherited from the base config:
#
# uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
[run]
name = "glm5-llmd"
[monitors.wandb]
project = "glm5-llmd"
[slurm]
job_name = "glm5-llmd"
# Overlays replace arrays of tables wholesale, so the train source is spelled
# out again just to swap the sandbox runtime label.
[[orchestrator.train.source]]
name = "r2e"
env.taskset.id = "r2e-gym"
env.agent.harness.id = "rlm"
env.agent.runtime.labels = ["glm5-llmd"]
[inference.router]
type = "llm-d"
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
@@ -1,23 +1,29 @@
# Base GLM-5.3 RL config: P/D-disaggregated FP8 inference behind the default
# vllm-router. Serves the same GLM-5.3-BF16 checkpoint the trainer broadcasts,
# quantized to per-block FP8 online on the vLLM side. Append swe-llmd.toml to
# front the same plane with the llm-d router + Mooncake KV offload:
#
# uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
max_steps = 10000000
seq_len = 131072
output_dir = "/shared/outputs" # FILL IN: point at your shared filesystem
clean = true
[run]
name = "glm5-llmd"
name = "glm5"
[log]
level = "debug"
[monitors.wandb]
project = "glm5-llmd"
project = "glm5"
name = "base"
[weight_broadcast]
type = "nccl"
port = 29502
timeout = 12000
quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
@@ -35,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"
@@ -52,53 +61,43 @@ num_decode_replicas = 1
"max_num_seqs" = 96
[inference.router]
type = "llm-d"
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
type = "vllm-router"
[inference.vllm]
model = "zai-org/GLM-5.1-FP8"
# Serve the same GLM-5.3-BF16 checkpoint the trainer broadcasts; vLLM quantizes
# it to per-block FP8 online.
model = "zai-org/GLM-5.3-BF16"
dtype = "bfloat16"
quantization = "fp8_per_block"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[slurm]
job_name = "glm5-llmd"
job_name = "glm5"
partition = "all" # FILL IN: set to your cluster's partition
[trainer]
dist_timeout_seconds = 1800
enable_token_export = true
[trainer.model]
name = "zai-org/GLM-5.1"
impl = "custom"
name = "zai-org/GLM-5.3-BF16"
attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
ep = 8
dsa_backend = "cudnn_flashmla"
[trainer.model.quantization]
type = "fp8"
[trainer.model.moe.compute]
type = "deepgemm_fp8"
[trainer.model.ac]
freq = 1
[trainer.model.compile]
@@ -112,18 +111,20 @@ 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
[orchestrator.model]
name = "zai-org/GLM-5.1-FP8"
name = "zai-org/GLM-5.3-BF16"
[orchestrator.renderer]
name = "glm-5.1"
name = "glm-5.3"
clear_thinking = false
[orchestrator.train.sampling]
@@ -136,17 +137,9 @@ clear_thinking = false
name = "r2e"
env.taskset.id = "r2e-gym"
env.agent.harness.id = "rlm"
env.agent.runtime.labels = ["glm5-llmd"]
env.agent.runtime.labels = ["glm5"]
[inference]
# <0.80 because glm5 layers are too large for 0.85
use_deep_gemm = true
enable_fp32_lm_head = true
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
+3 -5
View File
@@ -6,9 +6,6 @@ level = "debug"
[model]
name = "PrimeIntellect/INTELLECT-3-Base"
[weight_broadcast]
type = "nccl"
[deployment]
type = "multi_node"
num_train_nodes = 4
@@ -24,7 +21,6 @@ interval = 100
project = "intellect-3.1"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
ep = 8
cp = 2
@@ -36,7 +32,6 @@ fused_lm_head_token_chunk_size = 1024
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[trainer.optim]
type = "muon"
@@ -46,6 +41,9 @@ weight_decay = 0.01
[orchestrator]
batch_size = 2048
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
initial_inflight = 4096
max_inflight = 4096
+125
View File
@@ -0,0 +1,125 @@
# Qwen3-30B-A3B
RL on the 30B-A3B MoE across three domains: math, SWE, and agentic tool use. The Thinking checkpoint trains math and SWE; the tool config trains the Instruct checkpoint with colocated tools on [Modal](https://modal.com). All configs use the custom MoE trainer implementation with expert parallelism (`ep = 8`), the AdamW optimizer, NCCL weight broadcast, and W&B logging. `swe.toml` adds `cp = 2` context parallelism for its 131k context; the other two run at 32k.
| Config | Trains on | Evals on | Runtime | Topology |
|---|---|---|---|---|
| [`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.
## Requirements
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
- **Sandboxes** (`swe.toml` only) — the SWE agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, install the `prime` CLI separately and log in:
```bash
uv tool install prime
prime login # or: prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on the source for a runtime your environments support (e.g. a local Docker backend).
- **Modal** (`tool.toml` only) — the tool agents run on Modal (`env.agent.runtime.type = "modal"`). Authenticate once:
```bash
uv run modal setup # or export MODAL_TOKEN_ID / MODAL_TOKEN_SECRET
```
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
- `HF_TOKEN` — optional; the Qwen checkpoints are public, but a token avoids rate limits.
`math.toml` needs none of the above beyond W&B: its agents run as local subprocesses on the env server.
## Setup
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
uv sync --all-extras --all-packages
```
## Tweak before launching
- None of the configs set a `[slurm] partition` — sbatch picks your cluster default. Override with `--slurm.partition <your-partition>`.
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
## Start the run
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
```bash
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
--output-dir /shared/outputs/qwen30b \
--run.name qwen30b-math
```
Swap `math.toml` for `swe.toml` or `tool.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
## Monitor with the dashboard
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
```bash
uv run dashboard /shared/outputs/qwen30b # serves http://localhost:7788
```
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
```bash
ssh -L 7788:localhost:7788 <head-node>
```
Pick the run and you get five views:
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
## Checkpoint, resume, export
Checkpoints land in `<run_dir>/checkpoints/step_<N>` — every 100 steps for `math.toml`/`swe.toml`, every 50 steps (`keep_last = 1`) for `tool.toml`. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
```bash
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
--output-dir /shared/outputs/qwen30b \
--run.name qwen30b-math \
--resume --max-steps 1000
```
Trainer checkpoints are DCP-sharded; export HF-format weights with:
```bash
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/qwen30b/qwen30b-math/checkpoints/step_100
```
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.

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