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.
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 -->
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 -->
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>
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 -->
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 -->
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 -->
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 -->
## 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 -->
`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 -->
## 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 -->
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>
**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 -->
## 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.
## 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>
## 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>
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>
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>
## 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`.
## 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 narrowed to one env from the same filter

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

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

### Info mark on a panel

### Train overview narrowed to one env

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


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

🤖 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>
## 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>
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 -->
## 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 -->
## 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>
## 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 -->
## 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 -->
## 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.
## 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>
## 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>
## 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>
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 -->
## 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.
## 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.
## 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 -->
## 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>
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).
## 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>
## 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 -->
## 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>
## 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`.



🤖 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>
## 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>
## 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>
## 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 -->
## 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>
## 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.
## 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>
## 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 -->
<!-- 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`.
## 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 -->
<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 -->
## 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>
## 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 -->
## 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>
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.

**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>
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 -->
## 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 -->
## 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.
## 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 -->
## 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`.
## 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 -->
## 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 -->
## 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.

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

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

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

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>
## 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
## 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>
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 -->
<!-- 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 -->
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>
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.

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 -->
## 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.
## 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
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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>
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>
## 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>
### 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 -->
## 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 -->
## 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 -->
## 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 -->
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 -->
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>
## 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.
<!-- 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>
<!-- 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 -->
## 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`
## 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 -->
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 -->
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>
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 -->
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>
## 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).
## 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>
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 -->
## 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 -->
## 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 -->
## 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 -->
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>
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>
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 -->
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>
## 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 -->
## 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>
## 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.
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>
#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>
## 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 -->
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>
## 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>
## 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 -->
## 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>
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 -->
## 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 -->
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>
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>
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 -->
## 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 -->
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>
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>
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>
## 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 -->
## 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>
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>
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>
## 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>
## 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 -->
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>
## 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 -->
## 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 -->
## 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 -->
## 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 -->
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>
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>
## 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>
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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>
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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 -->
## 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
428 changed files with 35432 additions and 17827 deletions
- **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.
@@ -38,7 +38,7 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
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
@@ -53,15 +53,13 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
> *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`
@@ -148,22 +137,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>
@@ -204,10 +187,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
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 +195,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
@@ -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.
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.
Selective activation checkpointing works with either implementation. The custom path additionally enables EP, CP, low-precision training, and grouped MoE kernels. Forcing `impl = "hf"` is mostly useful when debugging and disables those model-specific runtime features.
GPT-OSS uses FlashAttention 4 with learned attention sinks. Training requires SM90 or SM100/SM110 GPUs
and a BF16 checkpoint such as `unsloth/gpt-oss-20b-BF16`; the original MXFP4 checkpoints are not supported.
### 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 = "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"
```
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.
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. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
### 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
@@ -126,7 +206,7 @@ For large MoE serving, splitting prefill and decode onto separate vLLM groups ca
| 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 +221,7 @@ If prefill queues and decode is idle, add prefill nodes (and vice versa).
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.
@@ -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:
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 resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
@@ -159,7 +159,7 @@ Algorithms operate on native verifier artifacts and annotate their message graph
The pipeline drives these through `finalize_episode` and `finalize_group`. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.train.algo.advantage`.
-`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.
### 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$:
$\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.
$\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"`):
| `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
| `adv_tau` | 1.0 | Temperature on the advantage term. |
### Custom Loss
@@ -304,10 +318,10 @@ This is intentionally simple — it does the right thing for most envs. Write a
A **length penalty** (`length_penalty` on the `grpo`-family algorithms) can be layered on top to discourage rambling. The `linear` penalty subtracts a single `pass_rate`-scaled penalty from each reward before the GRPO baseline, combining output tokens (`num_output_tokens_weight`), input / context tokens (`num_input_tokens_weight`), and turns (`num_turns_weight`) — each normalized by the group's own max for that quantity, with `num_input_tokens_weight` and `num_turns_weight` defaulting to `0.1`.
```toml
[orchestrator.algo]
[orchestrator.train.algo]
type="grpo"
[orchestrator.algo.length_penalty]
[orchestrator.train.algo.length_penalty]
type="linear"
```
@@ -343,7 +357,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 +383,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 +406,8 @@ There is no config hook that points at user code — a new credit-assignment sch
@@ -417,14 +431,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 +452,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.
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.
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.
`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.
```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>.*`).
@@ -225,11 +251,11 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
**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 +273,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/
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.
@@ -141,12 +141,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).
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
```
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:
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`: the episodes that landed 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. Errored episodes and the ones the interruption cut off run again.
```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 the task with its `task.key`, so `select` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. 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. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. 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:
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.
@@ -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`. Standard deployments use the V2 model runner. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
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`; Gemma-family (softcapped) lm_heads fail loudly. Frozen-source envs are exempt.
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
@@ -94,27 +94,30 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is <= 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is at most 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
```toml
[trainer.model]
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
| `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
@@ -226,11 +232,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:
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:
@@ -249,8 +274,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.
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. their own k8s pod) and the launcher expects the server to already run there. |
## RL Trainer
@@ -58,9 +58,10 @@ 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). |
| `[[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 +82,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 +101,7 @@ The RL entrypoint supports several training algorithms, switched via `[orchestra
A new algorithm is a named class in code, not a config — see [Algorithms § Authoring an Algorithm](algorithms.md#authoring-an-algorithm).
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for `opd` (the frozen model scored against), `[orchestrator.algo.sampling.source]` for `sft` (the model it samples from) — each with `name` + `base_url`. `opsd` declares no frozen model: it self-distills against the live policy. The `rl` entrypoint only manages policy inference — start frozen-model servers yourself and point `base_url` at them:
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.train.algo.teacher]` for `opd` (the frozen model scored against), `[orchestrator.train.algo.sampling.source]` for `sft` (the model it samples from) — each with `name` + `base_url`. `opsd` declares no frozen model: it self-distills against the live policy. The `rl` entrypoint only manages policy inference — start frozen-model servers yourself and point `base_url` at them:
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
@@ -117,6 +118,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 +127,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.
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 +150,15 @@ Two accepted layouts:
- **Prompt-completion**: a HF dataset with `prompt` and `completion` columns ([TRL format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion)). The trainer masks out the prompt and computes loss only over the completion.
- **Messages**: a HF dataset with a single `messages` column containing a list of chat turns. The trainer interprets the whole conversation as one sample, applies role-based loss masking, and trains over all assistant turns.
If both columns are present, `messages` takes precedence.
If both columns are present, `messages` takes precedence. A dataset that stores these under other names maps them in `[data.columns]`; the trainer renames the columns at load time:
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column (OpenAI function-calling format) or `tool_defs` ([`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) rollout format). Each row's value can be either a list of dicts or a JSON-encoded string of a list — both are accepted, and `tool_defs` rows are auto-converted to OAI shape before being passed into the renderer.
```toml
[data.columns]
messages="conversation"
tools="schemas"
```
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column in OpenAI function-calling format. Each row's value can be either a list of dicts or a JSON-encoded string of a list.
Renderer-backed SFT reads template controls from the typed `[renderer]` config in the SFT TOML. For example:
@@ -158,8 +168,27 @@ 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:
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).
@@ -176,14 +205,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:
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 Trainer and Inference Pool
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 evals 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:
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 nodes
num_infer_nodes=1# inference pool + evals
num_infer_nodes=1# inference pool + online evals
[inference.vllm]
tensor_parallel_size=8
@@ -217,7 +250,7 @@ tensor_parallel_size = 8
job_name="my-run"
```
The shared script passes the trainer rank-0 hostname directly to the evals 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`, evals never sees a final broadcast, so the job remains active until walltime. Trainer and evals log to one shared W&B run. The trainer creates it, and evals finalizes it.
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 +279,7 @@ Pulled from the console log and mirrored to W&B.
-`optim/grad_norm` — spikes precede divergence.
-`optim/lr` — LR schedule.
- For MoE: `max_vio/mean` (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.
**Performance:**
@@ -313,6 +346,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,7 +361,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
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
@@ -368,6 +408,7 @@ Register a run on the Prime Intellect platform (Prime Lab) and stream training m
```bash
uv run rl @ rl.toml --monitors.prime
uv run sft @ sft.toml --monitors.prime # same flag on the SFT trainer
```
Or set it in TOML:
@@ -377,14 +418,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.
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:
- Frontier-model configs without launch walkthroughs (`minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`) live in [`configs/advanced/`](../configs/advanced).
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.
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:
- `[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.
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 |
- 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:
- `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)
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.
# 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
# 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,42 +61,30 @@ 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"
name="zai-org/GLM-5.3-BF16"
impl="custom"
attn="flash_attention_2"# ignored with GLM5
fused_lm_head_token_chunk_size=1024
@@ -97,6 +94,9 @@ ep = 8
[trainer.model.quantization]
type="fp8"
[trainer.model.moe.compute]
type="deepgemm_fp8"
[trainer.model.ac]
freq=1
@@ -112,18 +112,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 +138,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
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 |
`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:
- 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
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.