Merges upstream/main (eed0e44c) into trinity-dsv41 (PR #4057 + trinity LoRA warm
start, adapter reload timeouts, renderers fork). Submodule pins for verifiers,
prime-envs and prime-kernels follow upstream/main; renderers stays on the
trinity fork.
Following b417ea31 (#4293), the three n-gram files take upstream's side and
DeepSeek-V4.1's engram is ported onto the shared module:
- engram.py: DeepseekV41NGramHasher(NGramHasher) replaces EngramHasher. It
maps tokens through the compressed token map, cuts look-back at document
starts only (no EOS reset), pads with compressed_token_map[pad_token_id],
takes consecutive_primes_from(engram_vocab_size, skip=24*table, count=24)
as head sizes, and uses odd PCG64 multipliers seeded with
10007 * engram_layer_ids[table]. Table rows come from the config
(384006168 / 384016682) and are checked to hold every bucket.
DeepseekV41Engram is now only the gate (wkv, q/k weights).
- modeling: DeepseekV41Model.ngram = NGramEmbeddings(hasher, {1: 0, 14: 1},
head_dim=256, non-persistent layout, deduplicating lookup). The row is
hashed once and looked up outside the layers. layers[i].engram runs the
gate inside the AC-wrapped compiled block. PackedContext carries
cu_seqlens.
- conversion: HF layers.{i}.engram.embed.weight <-> model.ngram.tables.{i}.weight.
The gate keeps its HF name, so vLLM-side names are unchanged.
- layers/ngram.py: NGramTable/NGramEmbeddings gain persistent_layout and
deduplicate_lookup options.
- ngram_lookup.py: RowShardedLookup(deduplicate=True) sends unique ids
(torch.unique) and sums repeated-row grads in fp32. ngram_runtime warms up
the all-to-all before training.
- model.py: drops AllToAllEmbeddingParallel, the FSDP-ignored table path, the
hand-applied divide factor and the dp_replicate guard. freeze_engram_tables
is keyed on NGramTable. optim/__init__.py drops the "engrams." Muon rule.
- transports: the fp8 row-chunk NCCL export is keyed on NGramTables that no
ChunkedConvOp converts (utils.weights.get_row_chunked_tables). It handles
plain, 1-D Shard(0) and multi-dim meshes (replicate or size-1 FSDP dims).
filesystem.py rejects such tables by the same rule instead of
hasattr(rows_per_rank).
- dsv41_indexer.py: upstream moved fp8_indexer to DeepGEMM and removed
_triton_fp8_indexer_kernel, so V4.1's two-level indexer now vendors that
Triton kernel (KEY_ALIGNMENT 16) to keep scoring unchanged.
Equivalence against the pre-merge tree (HEAD 282af805):
- Hashed ids are bit-identical for two synthetic configs with packed
multi-document rows (incl. 1-token docs, 24 heads/table, many collisions).
Primes, offsets, multipliers and pad id are identical. The real config
gives identical 2x24 primes, multipliers and 384006168/384016682 rows.
- The table lookup + gate matches the old DeepseekV41Engram bitwise
(outputs and grads of the table, wkv, q/k and the streams), fp32 and bf16,
CPU and CUDA.
- A 6-layer V4.1 stack (attention/MoE stubbed), loaded from the same HF
state dict, matches bitwise in its output and all 58 HF-named grads.
- RowShardedLookup(deduplicate) on gloo with 2 and 3 ranks and uneven rows:
outputs bitwise equal to a local lookup and to the old _AllToAllLookup.
fp32 grads are bitwise equal to the old path. bf16 grads differ by about
1 bf16 ulp, because the old path accumulated into an fp32 master.
- The fp8 export on gloo (plain, 1-D, replicate x shard, size-1 x shard)
reassembles byte-identical to quantize_rows_ue8m0 of the full table.
Untested here (no SM90 GPUs, one free GPU): multi-GPU FSDP+RowShardedLookup
training, the NCCL export through PyNccl into vLLM, the vLLM RowChunkWriter,
and the GPU-only test_deepseek_v41.py (skipped on SM86).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
- The trace sidebar shows **input / output / total tokens** from the
trace's own `num_input_tokens` / `num_output_tokens` /
`num_total_tokens`, so input + output = total. Before, it summed
provider usage over every call: "input tokens" counted the re-sent
context once per turn, and "total input" and "total tokens" built on
that.
- The sidebar groups its rows by scope:
- **episode** (only when the episode has more than one trace): trace
count and the episode's input / output / total.
- **trace**: messages, turns, tool calls, branches, input / output /
total and cost.
- **branch N** (only for a multi-branch trace with one branch selected):
messages, turns, tool calls and the branch's input / output / total.
- Messages, turns and tool calls used to be per selected branch without
saying so. They now sit in the section for their scope.
- Timeline tooltips and the semantic inspector show the same input /
output / total rows.
- **Trace lanes** read the trace's fields.
- **Branch and context lanes** count each fed-in token once
(`new_input_tokens`, the same rule as verifiers'
`min_new_input_tokens`).
- **A single model call** shows its whole prompt (cached part included)
as input.
- The sidebar, timeline tooltips and semantic inspector no longer show
"total input", "cached input", "reasoning tokens", "max context length",
"cumulative processed" or "uncached input". Cached input added up the
cached prompt of every call, so it counted the shared context again on
each turn. The other rows read as parts of the total. Timeline lanes no
longer carry `total_input_tokens`, `cached_tokens` or
`reasoning_tokens`.
- Counts the record already carries are read from it instead of
recounted: the sidebar's trace turns and branches (`num_turns`,
`num_branches`), its episode tokens (`Episode.num_*_tokens`), the live
table's turns, branches and cost, the index row's turns and cost
(`Episode.num_turns`, `Episode.usage.cost`), and the timeline trace
lane's cost (`Trace.usage.cost`). The live table counted model calls as
turns; it now reports sampled turns, like the finished table.
- The trace toggle lists traces in the order their agents started, and
an episode opens on the earliest one. An agentic judge used to come
before the solver it graded. Trace indices stay as stored, so links and
citations still resolve.
## Verification
Ran a one-episode agentic-judge eval on SWE-bench Verified with the bash
harness. Solver compaction was set at 12K tokens, so the solver trace
split into 5 branches. Then opened it in a dashboard served from this
branch (Playwright, no page errors).
- **Live:** the solver trace carries the `num_*` fields while it runs.
The trace section and the branch section updated as the trace grew.
- **Finished:** the dashboard matches verifiers' `Episode` / `Trace` /
`Branch` models on every number:
| scope | input | output | total |
|---|---|---|---|
| episode | 42,707 | 28,557 | 71,264 |
| solver trace | 37,259 | 26,608 | 63,867 |
| solver branches 0–4 | 5,533 / 6,387 / 7,806 / 8,528 / 9,005 | 6,157 /
7,197 / 5,486 / 5,103 / 2,665 | 11,690 / 13,584 / 13,292 / 13,631 /
11,670 |
| judge trace | 5,448 | 1,949 | 7,397 |
- The old sidebar would have shown about 622K "total tokens" for the
same solver trace, because it counted the re-sent context on every turn.
- A branch's total here is input + output. On a compacted branch this
exceeds verifiers' `Branch.num_total_tokens` (final sequence length). On
the summary call, the server's chat template dropped the earlier turns'
reasoning from the prompt, so those tokens were counted when generated
but are no longer in the final sequence.
- `tests/unit/test_dashboard_timeline.py`: the two semantic-context
totals changed from 260 → 140 and 310 → 190. In those fixtures, the
second call's prompt is shorter than the first call's final sequence, so
it adds no new input.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how token totals and costs are computed across the dashboard
and live/index summaries; wrong field usage would misreport usage but
does not affect training or auth.
>
> **Overview**
> Dashboard token and activity numbers now align with persisted
**episode / trace / branch** scopes instead of re-summing per-call
provider usage (which inflated totals when context was resent each
turn).
>
> The sidebar groups **episode**, **trace**, and selected **branch**
rows and reads `num_*_tokens` (plus `branchTokens` / server
`new_input_tokens` for branch paths). Timeline and semantic views drop
cached/reasoning/max-context breakdowns; per-call tooltips treat
**input** as full prompt (cached included). Monitors (**index**,
**live**) stop recomputing turns, branches, and cost from calls and use
record fields instead. Trace tabs and default selection follow **agent
start order** via `traceOrder`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
59aadfaa0a65b69346ae0082c114601584f82813. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
The environment hosting entrypoint launches a broker and a pool of
episode workers. Calling that unit an "env server" obscures the source →
pool replica → broker/workers hierarchy. This follow-up to #4375 names
those roles consistently.
- Rename the command to `uv run env-worker-pool`, its schema to
`EnvWorkerPoolConfig` in `prime_rl.configs.env_worker_pool`, and the
orchestrator field to `env_worker_pool_replicas`.
- Rename `EnvServerPool` to `EnvWorkerPool`, `EnvServer` to `EnvWorker`
in `prime_rl.env.worker`, and `serve_env` to `run_env_worker_pool`.
Process titles distinguish `PRL::EnvBroker` and `PRL::EnvWorker`.
- Update the RL/eval launchers, the shared SFT/pretrain launcher, SLURM
templates, config helpers, CI paths, dashboard text, docs, and the
affected skills. Document per-source configuration, pool replicas, and
worker concurrency.
- Anchor the root virtualenv ignore rule so it does not hide
`src/prime_rl/env/` on case-insensitive filesystems.
`[serve]`, the wire protocol, pool sizing/dispatch behavior, and run
artifact paths are unchanged. This is a naming change; direct
worker-to-sink data delivery remains separate work.
## Breaking names
| Before | After |
| --- | --- |
| `env-server` | `env-worker-pool` |
| `prime_rl.configs.env_server.EnvServerConfig` |
`prime_rl.configs.env_worker_pool.EnvWorkerPoolConfig` |
| `OrchestratorConfig.env_server_replicas` |
`OrchestratorConfig.env_worker_pool_replicas` |
| `prime_rl.env.pool.EnvServerPool` | `prime_rl.env.pool.EnvWorkerPool`
|
| `prime_rl.env.server.EnvServer` | `prime_rl.env.worker.EnvWorker` |
| `prime_rl.env.serve_env` | `prime_rl.env.run_env_worker_pool` |
| `EnvClient.wait_for_server_startup` |
`EnvClient.wait_for_pool_startup` |
## Validation
- 447 focused CPU tests passed (env, configs, supported
orchestrator/eval/transport tests, dashboard artifacts and pathing);
four cases deselected. Tests requiring unavailable `torch`, `vllm`, and
TextArena dependencies were excluded.
- Temporary smoke script exercised static pools with 1/2 workers and
elastic pools capped at 1/unbounded: address discovery, task/error
round-trip through the broker and worker, process titles, graceful
shutdown, and IPC cleanup all passed. The smoke env deliberately raises
an episode error; it does not call inference.
- Both wheels build; wheel contents and the renamed console entrypoint
verified. Entrypoint help, touched TOML parsing, Ruff, and `pre-commit
run --all-files` pass.
- The deep-backlog ZMQ test timed out after 18 seconds on both unchanged
base `c0ad9e9f4` and this branch, so it was deselected. No GPU training
run.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking renames span the CLI, Python imports, and orchestrator config
fields; behavior is unchanged but existing scripts and TOML must be
updated.
>
> **Overview**
> Renames the environment-hosting stack so **source → broker → workers**
is explicit: the CLI becomes **`uv run env-worker-pool`**, config schema
**`EnvWorkerPoolConfig`** (`prime_rl.configs.env_worker_pool`), and
orchestrator **`env_worker_pool_replicas`** replace the old `env-server`
/ `EnvServerConfig` / `env_server_replicas` names.
>
> Runtime symbols align with that model—**`EnvWorkerPool`**,
**`EnvWorker`**, **`run_env_worker_pool`**, broker/worker process titles
(**`PRL::EnvBroker`** / **`PRL::EnvWorker`**), and
**`EnvClient.wait_for_pool_startup`**. RL/SFT/eval launchers, SLURM
templates, pathing helpers, CI filters, dashboard copy, docs, and skills
are updated to match; **`[serve]`**, the ZMQ wire protocol, and artifact
paths stay the same.
>
> **.gitignore** anchors **`/ENV/`** so a root `ENV` venv directory is
not confused with **`src/prime_rl/env/`** on case-insensitive
filesystems.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
47c74d92f30d54524ad2e0c79ae1dae0e42def31. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Bump `deps/verifiers` to the merged PrimeIntellect-ai/verifiers#3061.
Lines are scoped `[<episode>/<trace> <agent>]`, lifecycle lines are
timed, and INFO keeps to episode start/finish plus one `Finished
rollout` per agent run.
- Env servers colorize their console sink only on a terminal. The
launcher redirects an env server's stdout into
`logs/.../envs/<split>/<name>.log`, so the colorized format used to land
raw ANSI codes in that file. Without a terminal, the console sink now
uses the plain layout the file sink already used
(`setup_logger(colorize=...)`).
- Env server, pool and client log lines follow the verifiers style: an
active sentence, then `key=value` fields, then error details after ` -
`. For example, `EnvServerPool up (address=..., workers=1/inf,
pool=ElasticPoolConfig(...))` is now `Started env server pool
address=... pool=elastic workers=1 max_workers=inf multiplex=128`.
- Remove `log.vf_level`. Env servers and the in-process verifiers
loggers follow `log.level`, so `--log.level debug` turns on debug output
everywhere. Before, env servers used `vf_level` and the orchestrator and
eval runner capped verifiers at WARN.
- `InterceptHandler` records the real call site. Its frame walk started
at `emit()`, which is not in stdlib logging, so it stopped at once. At
DEBUG, every verifiers line then reported `logging/__init__.py::1762` as
its call site.
## Breaking
- `log.vf_level` and `$PRIME_VF_LOG_LEVEL` are removed. Set `log.level`
(or `$PRIME_LOG_LEVEL`) instead; it now also sets the verifiers and
env-server level. A config that still sets `vf_level` fails validation.
## Verification
- `pytest tests/unit/{env,utils,eval,orchestrator,monitors}` and
`test_configs.py`: all pass, except tests that need GPU extras
(`prime_kernels`, `fla`, `vllm`) this venv lacks.
- `uv run eval` on gsm8k, terminal-bench-2 `fix-git`, proposer-solver
and a forced retry, at INFO and at DEBUG (`--log.level debug`). The
env-server logs contain no ANSI codes, and DEBUG lines name their real
call sites (`[rollout.py::276]`, `[prime.py::270]`, ...).
- `uv run eval gsm8k -n 1 -r 1 --log.level debug`: the env-server log
has the verifiers DEBUG lines (`Starting rollout`, `Served turn`, ...).
- `uv run eval gsm8k -n 2 -r 1` after the env-server log rewrite. The
env-server log reads:
```
INFO Started env server pool address=tcp://127.0.0.1:40267 pool=elastic
workers=1 max_workers=inf multiplex=128
INFO Started env server taskset=gsm8k
address=ipc:///tmp/prl-env-pool-wh3dujah/0
INFO Stopped env server taskset=gsm8k
address=ipc:///tmp/prl-env-pool-wh3dujah/0
INFO Stopped env server pool address=tcp://127.0.0.1:40267
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Removes a config field (`log.vf_level`) and changes default verifiers
verbosity in orchestrator/eval (was capped at WARN, now follows
`log.level`), which can increase log volume at INFO/DEBUG.
>
> **Overview**
> **Unifies logging verbosity** by removing **`log.vf_level`** (and
**`$PRIME_VF_LOG_LEVEL`**). Orchestrator, eval, env servers, and
in-process **`verifiers`** now all follow **`log.level`** /
**`$PRIME_LOG_LEVEL`**; configs that still set `vf_level` fail
validation. **Docs** in `training.md` reflect the single knob and point
env log verbosity at `orchestrator.log.level`.
>
> **Env-server observability** is tightened: lifecycle and error lines
use a consistent *sentence + `key=value`* style across pool, server,
client, and delta paths. When stdout is redirected to run logs
(non-TTY), **`setup_logger`** writes the **plain** console format so
**`logs/.../envs/*.log`** no longer contain raw ANSI.
**`InterceptHandler`** walks frames correctly so verifiers **DEBUG**
lines show the real call site, not `logging/__init__.py`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9d379337fda67529fd4848b68513254aae37d600. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
- An RL run can now resume with a different set of train and eval
sources. You can add a source, remove one, or change one (its taskset,
ratio, sampler or gates). Before, a resume with changed train sources
failed to load the orchestrator checkpoint.
- A resume re-runs the train groups that were drawn before the
checkpoint but not yet trained. Before, those tasks were silently
skipped.
- Fix: live config values (`ratio`, `sampling`, `interval`) now carry
over to the same source on resume. Before, they could move to another
source.
Scope: the RL orchestrator only. SFT online evals and `uv run eval
--resume` keep no per-source state and do not change.
## Motivation
A long RL run often changes its data mix between restarts: a new env, a
dropped env, or a taskset with more tasks. Today a restart like that has
three problems:
1. **The checkpoint does not load.** `TrainSource` and `Curriculum`
raise when the envs or admission gates differ from the checkpoint. The
only way out is to start the curricula from scratch.
2. **The sampler position becomes wrong.** `StandardSampler` saves a
cursor into the taskset. When the taskset gains or loses tasks, the
cursor points at different tasks.
3. **Drawn tasks get lost.** The orchestrator samples ahead of the
trainer. Groups that were drawn but not trained at the checkpoint are
gone after the resume, and the resumed run draws past them.
A fourth problem is in the config merge. `merge_resumed_config` matched
source lists by position. When you moved or replaced a source, it took
another source's live values. When the number of sources changed, every
source lost its live values.
This PR is also the base for rollout checkpointing (#4296), which
continues the open groups from the checkpoint instead of re-running
them.
## What happens on resume
| Change between checkpoint and resume | Result |
|---|---|
| Add a train source | It starts with a fresh curriculum. |
| Remove a train source | Its curriculum state and its open groups are
dropped (with a log line). |
| A taskset gains tasks | The new tasks start at the lowest surviving
sampling count, so they join the current pass. They are not sampled
first to catch up. |
| Rows are added, removed or moved anywhere in a taskset | The other
tasks keep their state: the default `Task.key` no longer includes the
row index (PrimeIntellect-ai/verifiers#3101, from #4413). A change to a
task's other data, including a config-level `system_prompt`, makes it a
new task. |
| A taskset loses tasks | Their counts (`StandardSampler`), rewards
(`DifficultyPoolSampler`) and open groups are dropped. A task added back
at a later resume starts as a new task. |
| Change `ratio`, `sampling` or `interval` | The launch value wins. A
value the launch config did not change keeps its live value. |
| Change the sampler type | The sampler starts fresh, with a warning. |
| Add or remove an admission gate | A new gate starts fresh; a removed
gate's state is dropped. |
| Rename a source | Counts as removing one source and adding another.
Naming an unnamed source with its old resolved name (its env id) keeps
its state. |
| Add an eval source | It first runs at the next step that is a multiple
of its interval. Eval sources keep no checkpointed state. |
| Streaming (unbounded) taskset | It resumes at the same offset into the
stream: it reads and discards that many tasks. This resumes at the same
task only if the stream yields the same tasks in the same order. Its
open groups are dropped, because a stream cannot find a task by key. |
## Changes
**Sampling counts instead of a cursor**
(`curriculum/samplers/standard.py`)
- `StandardSampler` checkpoints `{task_key: sampling_count}` for a
finite taskset. It yields a least-sampled task, with ties broken by
source order. For an unchanged taskset, this is the same order as the
old cycle.
- On load, it reconciles the counts with the current taskset, as in the
table above.
- One pass scans the taskset once. With 100k tasks, 1M samples take 0.28
s and a load takes 0.08 s.
- A streaming taskset keeps the cursor, as an offset into the stream.
**State restored by name** (`train_source.py`, `curriculum/base.py`,
`samplers/pool.py`)
- `TrainSource` restores each curriculum by source name.
- `Curriculum` records its sampler type, and restores gates by name.
- `DifficultyPoolSampler` drops the rewards of removed tasks.
**Open groups re-run** (`train_source.py`, `train_sink.py`)
- `TrainSource` gives each draw a group id. The group stays open until
its samples ship or it finalizes without training: rejected by the
curriculum, no trainable samples left, all queued traces stale, or
pruned. A group cancelled at shutdown stays open.
- The checkpoint saves the open groups as (source, task key). A resume
re-runs them whole, in draw order, before it draws new tasks. Their
sampling counts do not go up a second time.
- `TrainSink` owns every close through one callback
(`on_groups_closed`): groups that end without shipping, and the groups
of a shipped batch (`TrainSink.shipped`, called after the trainer
received it).
- A re-run group goes through the curriculum again, with its new
rollouts. Today's sampler and gate tolerate this
(`DifficultyPoolSampler` overwrites the task's reward, `AdvRangeGate`
keeps no state); the `observe` and `admit` docstrings state it for new
ones.
**Config merge by source name** (`configs/diff.py`)
- `merge_resumed_config` matches sources by resolved name: `name`, else
the env id. This is the same key `TrainSource` uses.
**Task keys** (#4413): pins verifiers main (`57314c0ec`), whose default
`Task.key` excludes the generated row index. The curriculum tests reload
tasksets through `Taskset`, so inserted, removed and reordered rows get
new indices, as in a real reload.
**Docs**: `docs/training.md` (Resuming a Run: what a resume restores,
and changing sources on resume).
## Compatibility
- **Checkpoints from main load.** A cursor converts to counts. The
conversion assumes the taskset is unchanged since the checkpoint, and a
log line says so. A missing sampler type is inferred. Such a checkpoint
has no open groups, so nothing re-runs.
- **Main cannot load a checkpoint from this PR.** Main rejects the new
fields (`sampler_type`, `open_groups`). This matters only if you roll
back to main after resuming on this PR.
## Verification
**Resume e2e** (reverse-text, Qwen3-0.6B, one node on SLURM, about 7
minutes per attempt). Three sources took disjoint 10-task slices of
reverse-text, so each task was drawn several times and the counts mean
something.
1. Run A trained steps 1–4 on `rt-a` and `rt-b` (ratio 1:1), with a
checkpoint every 2 steps.
2. The restart resumed step 4 in the same run dir and trained steps 5–8.
It removed `rt-b`, added `rt-c`, and changed `rt-a` (ratio 1 → 2,
taskset 10 → 15 tasks).
| Check | Result |
|---|---|
| Restart loads and trains | Steps 5–8 trained 128 of 128 samples each;
checkpoints at steps 6 and 8. |
| Removed `rt-b` | Its curriculum and its 5 open groups were dropped. No
`rt-b` group was dispatched after the restart. |
| Added `rt-c` | Fresh curriculum; at step 8 all 10 tasks had count 1. |
| `rt-a`'s open group | The 1 open group re-ran first, on the same task.
|
| `rt-a`'s new tasks | The 5 new tasks started at count 1, the lowest
surviving count. At step 8, all 15 tasks were at count 3 or 4. |
| `rt-a`'s ratio | The resolved config held `ratio = 2.0`. New draws
were 30 `rt-a` to 10 `rt-c`, within the noise of a 2:1 coin over 40
draws. |
The restart logged:
```
Resuming curriculum state for env rt-a
Reconciled sampling counts with the taskset: 5 new task(s) start at count 1, 0 removed task(s) dropped
Env rt-c is not in the checkpoint, so its curriculum starts fresh
Dropped the checkpointed curriculum state of env rt-b, which is no longer configured
Dropped 5 open group(s) of env rt-b, which is no longer configured
Re-running 1 open group(s) from the checkpoint
```
The e2e did not cover a taskset that loses tasks, a changed sampler
type, or changed gates. Unit tests cover those.
**Unit tests**
- `tests/unit/orchestrator/test_curriculum.py`: static order equals the
old cycle. It also covers resumes with added and removed tasks, an added
and a removed env, a changed sampler type, a changed gate set, and a
cursor checkpoint from main.
- `test_curriculum.py` and `test_train_sink.py`: open groups re-run in
order without recounting. A rejected group closes, a group closes when
its batch ships (`TrainSink.shipped`) and not when the batch is taken,
and a group cancelled at shutdown stays open. Removed envs and tasks are
dropped. The rng restore check draws before the checkpoint, so it can
fail.
- `tests/unit/test_config_diff.py` and `test_config_update.py`: the
source merge by name (reordered, replaced, removed, updated and added,
and named with its old resolved name), and an eval source list changed
on resume.
- `pytest tests/unit/orchestrator tests/unit/env
tests/unit/test_configs.py tests/unit/test_config_diff.py`: 475 passed,
before the latest review round. The latest round is verified by CI.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches orchestrator resume, curriculum sampling, and live-config
merge—logic mistakes could mis-schedule tasks or lose training batches,
though extensive tests mitigate obvious regressions.
>
> **Overview**
> **Resuming mixed RL sources now tracks unfinished groups instead of
skipping them.** `TrainSource` issues per-draw `TaskRequest.group_id`s,
snapshots `(env, task key)` for anything still open when a checkpoint
saves, and replays those draws (with sampler state untouched) before
taking fresh tasks while streaming envs drop in-flight work they cannot
key. `TrainSink` closes groups whenever admission fails, batches ship
after `sender.send`, pruned traces clear, or staleness drops everything,
but shutdown cancellations stay open for another try, and the
orchestrator wires those closes back to `TrainSource` so resume
bookkeeping matches lived rollouts. **Curriculum state survives
reshuffles instead of hard failing merges.** `merge_resumed_config` now
aligns `train.source` lists by resolved env names, newly added sources
inherit launch fields, and eval source edits get regression coverage via
`EvalSource`. `Curriculum` checkpoints sampler types, reloads gates by
name, warns when the sampler class changes, and both `StandardSampler`
and `DifficultyPoolSampler` reconcile per-task counts/rewards with
edited tasksets (legacy cursor checkpoints convert with an explicit
log). **Docs/tests call out the new behavior**, so reviewers can expect
checkpoint compatibility notes and expanded unit suites around samplers,
train-source reopen ordering, train-sink closures, and source-list
merges.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6503dc5ed8ac24a15fb237c495fd426c01c63849. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Konstantin Dunas <git@hallerite.com>
## Summary
- Bump `deps/verifiers` to PrimeIntellect-ai/verifiers#3102. That PR
serializes derived trace and episode values as computed fields:
`reward`, `usage`, `is_truncated`, `num_turns`, `num_branches`,
`last_reply`, `has_error`, `is_format_violation`, span `duration` and
policy `drift`.
- Stream the new trace fields to live watchers (`SCALAR_FIELDS` in
`env/delta.py`).
- The episode index (`monitors/file/traces/index.py`) reads `reward`,
`is_truncated`, `num_turns`, `num_branches` and `usage.cost` from the
record, and timing from span `duration`. The copied `TRUNCATING_STOPS`
rule and the node and call walks are gone. The index record now leaves
out model calls.
- The dashboard timeline (`server.py`) and trace viewer (`app.js`) read
`reward`, `is_truncated` and `usage` from the trace instead of
recomputing them. The viewer still walks calls for max context length.
- `uv.lock`: `prime-sandboxes` 0.5.5 → 0.5.7. The bump pulls in that
floor from verifiers.
## Breaking
- Trace records written before this bump have none of these fields. In
the dashboard's trace viewer, such a trace shows no reward,
`is_truncated` reads false, and the usage totals and finished timing
phases are empty. Episode index rows that were already written keep
their values.
## Verification
- `pytest tests/unit`: dashboard, monitors, env delta and eval tests
pass. This includes the guard test that every serialized `Trace` field
is streamed. The only failures come from modules missing in the slim
test venv (`torch` and env tasksets).
- `test_episode_summary_excludes_copied_assistant_context_from_turns`
now builds a real `WireEpisode` and summarizes its record.
- I have not checked the trace viewer in a browser.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Backward-incompatible dashboard/index behavior for legacy traces
missing new serialized fields; bumps a core dependency version.
>
> **Overview**
> **Serialized trace fields are now the source of truth** for rewards,
usage, truncation, and counts across the file monitor index, live
deltas, and dashboard (API + UI).
>
> The episode **index builder** stops walking `nodes`/`calls`; it reads
`reward`, `usage.cost`, `is_truncated`, `num_turns`, and `num_branches`
from each trace, derives timing only from `duration`, and simplifies
truncation detection. **`SCALAR_FIELDS`** in `env/delta.py` now includes
these fields so live streams stay in sync.
>
> The **dashboard** timeline exposes `trace.reward` directly, the trace
viewer shows **aggregated `usage`** and `is_truncated` from the record,
**truncation-rate tiles** rely on `series.truncated` only, and timing
rendering is adjusted for open spans. **Tests** build a real
`WireEpisode` via `index_record`. **`uv.lock`** bumps
**`prime-sandboxes` to 0.5.7** (floor aligned with verifiers).
>
> **Breaking:** Older traces without these serialized fields may show
empty reward/usage and false truncation in the viewer; existing index
rows are unaffected.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
418d5b0572ebebb154c6d530acd70182fa8e5d2d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
- Bump `vllm-router` from v0.2.3 to
[v0.2.4](https://github.com/PrimeIntellect-ai/router/releases/tag/v0.2.4)
(x86_64 and aarch64 wheels).
- Relock `uv.lock`. Only the `vllm-router` entries change.
The release adds these router changes:
- Remove the DP rank from proxied GET worker URLs (router#65).
- Pass `video_url` and audio content parts through in chat messages
(router#67).
- Keep SLL sessions alive while a request is in flight (router#68).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Behavior changes live in the disaggregated inference router (proxy
URLs and chat forwarding), so disagg deployments should smoke-test
routing and multimodal requests after upgrade.
>
> **Overview**
> Pins **`vllm-router`** from **0.2.3** to **0.2.4** for both **x86_64**
and **aarch64** wheels in `pyproject.toml`, and refreshes **`uv.lock`**
(URLs, version pins, and wheel hashes only).
>
> Installs via the existing **`disagg`** extra; no changes in this
repo’s application code. The upstream release adjusts proxied worker GET
URLs (drops DP rank), forwards **`video_url`** and audio parts in chat
payloads, and keeps SLL sessions open for in-flight requests.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e75143a2329f0db54d803a44ba1e717d78ed742e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
The Mooncake master was started with `-default_kv_lease_ttl=3600000` (1
h). A lease protects a KV object from eviction, so with a 1 h lease the
store can't evict anything for the first hour. On a long run the pool
fills up, every new put fails, and the store stops caching.
The lease is now a `kv_cache_offload` field: `lease_ttl_s`, default 60
s. 60 s is long enough for the P/D handoff, where the old 5 s lease let
objects expire before decode read them. It is short enough that the pool
can keep recycling space. Under P/D the larger of the two roles' values
applies, since one master serves both.
## Evidence
2×8 H200 nodes, 8 TP1 engines with small GPU KV, shared Mooncake store
over RDMA, kv-stress agentic workload:
| | 1 h lease (main) | 30 s lease |
|---|---|---|
| Store state | 200 GiB pool full in ~6 min; 8.4M allocation failures
(`NO_AVAILABLE_HANDLE`) | ~780 of 859 GB used, 5.4M evictions, 0
allocation failures |
| Mooncake hit rate, concurrency ≥ 64 | 0.00 | 0.90 |
| Generated tok/s at concurrency 256 | 521 | 755 (+45%) |
The 30 s run also used 400 GiB per node instead of 200, so the pool size
isn't held constant. The 1 h run's 8.4M failed puts show the lease
blocking eviction regardless of pool size. Template rendering was
checked for the default (60000 ms), an override (30000 ms), and P/D with
different per-role values (the larger is used).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes Mooncake eviction timing for distributed KV offload; mis-tuned
values can break P/D handoff or cache recycling, but defaults are
evidence-backed and the field is explicit.
>
> **Overview**
> Replaces the hard-coded **1 hour** Mooncake master
`-default_kv_lease_ttl` with a tunable **`lease_ttl_s`** on Mooncake KV
offload config (**60 s** default). The SLURM `_mooncake_store` template
converts that to milliseconds and passes it to `mooncake_master`; under
disaggregated P/D it uses the **maximum** `lease_ttl_s` across
prefill/decode offload configs because one master serves both.
>
> This addresses pools that could not evict entries while leases were
long, leading to full stores, failed puts, and effectively **zero**
prefix-cache hits under stress—while keeping TTL long enough for
prefill→decode reuse.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7a2c2b2fe20e79d28d8aea8782e724b60ff2a4dc. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
- Each eval job of the regression workflow posts one Slack message for
its config when it ends. The message has the verdict, the model, the
gated metrics against the baseline, and a link to the workflow run.
- The post goes to the `SLACK_WEBHOOK_URL` repo secret. The step skips
when the secret is not set.
- Only nightly (`schedule`) and manual (`workflow_dispatch`) runs with
one repeat post. PR runs and multi-repeat baseline runs do not.
- The post happens in the eval job, not in the summary job. GSM8K
reports after about 12 min and does not wait for the 4 h
Terminal-Bench-2.1 job. The stuck Parallel / Invariance GPU job also no
longer delays the results.
- An eval that crashes, times out, or is cancelled posts "no repeat
finished". A job that hits `timeout-minutes` ends as cancelled, so the
step runs on `always()`.
- The comment on the eval job timeout says that agent evals cap their
rollout time in the config. It said they have no rollout timeout.
- `eval.py summarize --slack <path>` writes the webhook payload. The
comparison logic moves into `gate()`, which the Markdown table and the
Slack message share. The Markdown summary output is unchanged.
- `docs/development.md` mentions the Slack post.
Example message (from the last Terminal-Bench-2.1 PR run):
```
✅ Eval regression: Terminal-Bench-2.1: no regression
internal/deepseek-v4.1-flash-1017-ci · 82 tasks × 1 rollouts · workflow run
✅ Accuracy: 59.76% vs 65.85% ± 2.86% (Δ −6.10%, tolerance ±9.40%)
✅ Time to finish (s): 14453 vs 14475 ± 11 (Δ −22, tolerance ±3619)
✅ Error rate: 4.88% vs 1.95% ± 0.67% (Δ +2.93%, tolerance ±10.00%)
✅ Truncation rate: 0.00% vs 0.00% ± 0.00% (Δ +0.00%, tolerance ±1.00%)
```
## Verification
- I rendered the payload locally from the saved Terminal-Bench-2.1 PR
result, a GSM8K baseline repeat, and an empty result set.
- The Markdown summary of the new `eval.py` is byte-identical to the one
on `main`.
- The commit has `[skip ci]`, so this PR does not start the 4 h
Terminal-Bench-2.1 eval. A manual dispatch of GSM8K only on this branch
tests the Slack post.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Changes are CI notifications and reporting refactor only; no runtime
training/inference paths, with webhook posting gated and non-blocking
(`|| true` on summarize).
>
> **Overview**
> Nightly and manual regression **eval** jobs now **post one Slack
message per config** as soon as that matrix job finishes, instead of
waiting on the aggregate summary job. Posts use the `SLACK_WEBHOOK_URL`
secret (skipped if unset), run on **`always()`** so
timeouts/cancellations still notify, and are limited to **non-PR runs
with a single repeat** (baseline multi-repeat runs still report only in
the GitHub summary).
>
> **`eval.py`** gains shared **`gate()`** logic for baseline comparison,
a **`slack()`** webhook payload builder, and **`summarize --slack
<path>`**; Markdown gating output is intended to stay the same.
**`docs/development.md`** documents the Slack behavior, and the eval job
timeout comment now notes that agent eval configs cap rollout time per
config.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2b54672427872d136f30620afee1fb1b3ebf2931. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This PR gives the orchestrator's router-session releases their own HTTP
client and caps how many run at once. Before, a burst of releases could
leave the shared client permanently unable to send any request, so
releases silently stopped for the rest of the run. From then on the
router treated every finished rollout as still running, and placed new
rollouts on inference replicas based on that wrong picture of their
load.
**Background.** With the `sticky_least_loaded` router policy, each
rollout is a session pinned to one inference replica so later turns
reuse its prefix cache. The router places each new session on the
replica holding the fewest sessions. When an episode ends, the
orchestrator calls `/finish_session` so the router stops counting it. If
a release never arrives, the router keeps counting the session until its
time to live (TTL) expires, 2 h by default.
**Bug 1: a burst loses most of its releases.** All releases shared one
httpx client with 4 connections, a 10 s wait per attempt for a free
connection, and errors logged at DEBUG. When many episodes end at once
(for example, a sandbox outage failing thousands of episodes), thousands
of releases queue for those 4 connections:
```
episodes ending at once shared httpx pool (4 connections) router
release ─┐
release ─┼─► wait up to 10 s ─► [ conn ][ conn ][ conn ][ conn ] ─► /finish_session
release ─┘ for a connection
... (thousands)
```
Most time out waiting, which loses those releases. On its own this is
temporary: once the burst drains, releases work again.
**Bug 2: those timeouts permanently break the client.** httpcore 1.0.9
(the latest release) has a race in exactly that timeout. It is reported
upstream in encode/httpcore#1099 (open, unmerged), where a comment
reproduces this pool-timeout case on the same versions; the pydantic
fork fixed it in pydantic/httpx2#983.
```
time queued request R pool (4 slots)
─────────────────────────────────────────────────────────────────────────────────
0 s joins the queue, 10 s timer starts slots 1-4 busy
...
10 s (still asleep) request in slot 1 finishes;
pool creates connection C
(CONNECTING) and hands it to R
10 s timer fires before R wakes up:
R raises PoolTimeout and leaves
(C is never used) C stays in slot 1: never opened,
so never "closed", "idle" or
"expired", so never cleaned up
```
The pool opens a new connection instead of reusing the one that just
finished because the old client kept at most 1 idle connection, and
httpcore 1.0.9 counts every connection, busy or idle, against that
limit. So with 4 connections open, each one is closed the moment it
frees up.
Thousands of requests time out at nearly the same moment, so this fires
reliably and each occurrence costs one slot for good:
```
slot 1 busy ──► dead C ──────────────────────────────────────────────►
slot 2 busy ─────────► dead C ───────────────────────────────────────►
slot 3 busy ───────────────► dead C ─────────────────────────────────►
slot 4 busy ─────────────────────► dead C ───────────────────────────►
└─ from here on, every release waits 10 s
for a slot and fails with PoolTimeout
```
A fresh client works immediately, which is how the reproducer confirms
the pool, not the router, is at fault.
**Consequence.** The router keeps treating finished sessions as active
until its TTL removes them. It sends each new session to the replica
with the fewest sessions, so a replica holding many finished ones looks
busier than it is and receives less new work, while a replica holding
few receives more. The session counts look even across replicas, but the
actual work is not. If the table reaches `VLLM_ROUTER_SLL_MAX_SESSIONS`
(100,000 by default), new sessions are no longer pinned to one replica
and lose their prefix cache on every turn (we have not hit this; the
largest table we have seen peaked at about a third of the limit).
Training data and rewards are unaffected; this is purely a
routing-efficiency problem, and it was invisible because nothing was
logged above DEBUG.
**The fix.** A release now needs one of 32 tickets (a semaphore) before
it sends anything, and the release client has exactly 32 connections.
Releases that find no free ticket wait in `clients.py`, not inside
httpx, so httpx's pool wait and its race never come into play:
```
thousands of releases arrive at once (one per finished session)
│
▼
┌─ waiting for a ticket ───────────┐
│ (semaphore in clients.py) │──► waited 30 s, still no ticket?
│ R R R R R R ... │ give up: never sent, counted as failed,
└───────────────┬──────────────────┘ router removes the session after its TTL
│ takes 1 of 32 tickets
▼
┌─ httpx client, 32 connections ───┐
│ a ticket holder always finds an │──► POST /finish_session ──► router
│ idle connection, so it never │
│ waits inside httpx │
└───────────────┬──────────────────┘
│ request done (success or error)
▼
ticket returned; the next release in line goes
```
- Releases use a dedicated client with one connection per ticket, so
requests never wait inside httpx's pool.
- A `PoolTimeout` can then only mean a leaked connection, so the release
path replaces the client and the next releases go out on a fresh one.
- Failures log a WARNING each time their total doubles, so a burst logs
a handful of lines, and `sessions/released` / `sessions/release_failed`
report cumulative counts.
| Reproducer (httpx 0.28.1, httpcore 1.0.9) | Before | After |
|---|---|---|
| Burst of 6,000 releases, 10 ms server | 21 delivered (0.35%) | all
delivered |
| Single releases after each burst of 4,000 against a 2 s server | 0/3,
every burst | 3/3, every burst |
| Pool state after those bursts | 4 connections stuck `CONNECTING` | 32
`IDLE` |
Trade-offs a reviewer should know:
- If the router answers releases slowly (for example, under heavy load),
a release that waits more than 30 s for a ticket is dropped, so an
episode never waits longer than that to finish.
- Replacing a broken client fails up to 31 releases already in flight on
it; those sessions wait for the router TTL.
- Two other call sites keep the original 4-connection client unchanged:
weight-update admin calls (`AdminPlane`) and the Dynamo frontend's
startup checks. Each sends only a few requests at a time, so none ever
waits for a connection.
## Verification
Commit bbd2d3baa adds `tools/repro_session_release_pool_leak.py` and the
next commit removes it, so it stays in this PR's history without landing
on `main`. It copies the old and new release paths, runs them against a
local `/finish_session` server through the dispatcher's cancellation
pattern, and prints delivery, follow-up releases and pool state per
burst. It runs anywhere, without the repo's dependencies:
```
git show bbd2d3baa:tools/repro_session_release_pool_leak.py > /tmp/repro.py
uv run --no-project --with httpx==0.28.1 --with httpcore==1.0.9 --with anyio==4.13.0 \
--with tenacity==9.1.4 --with starlette --with uvicorn python /tmp/repro.py old # or: new
```
`--server-delay 0.01 --episodes 3000 --bursts 1` gives the first table
row; `new --undersized-pool` gives the pool 4 connections for 32
tickets, so its connections leak and the client replacement path
recovers it.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
- Bump `deps/verifiers` to the merged PrimeIntellect-ai/verifiers#3057.
A retried agent run keeps its trace id and counts `attempt`, and a
retried episode keeps its id.
- `DeltaStreamer` stores the attempt on each trace cursor. When a
trace's attempt changes under a known id, it sends a `discard` for that
id and then reopens the trace from scratch. `EpisodeAssembly`, the
orchestrator's live view and the file monitor already apply
discard-then-open as a replace, so they don't change.
- `attempt` joins `HEADER_FIELDS`, so the assembled trace carries it.
## Verification
-
`tests/unit/env/test_env_delta.py::test_retried_agent_run_replaces_its_trace`
(new): the client ends with one trace, `attempt == 2`, holding only the
retry's nodes.
- `pytest tests/unit/{env,orchestrator,monitors,eval}`: 203 passed.
`test_batch.py` and `test_prefill_logprobs.py` need the GPU extras
(`fla`, `vllm`), which this box's venv doesn't install.
- End to end, via `vf-run` and prime-rl `uv run eval`: gsm8k (null
harness, subprocess) and terminal-bench-2 `fix-git` (bash harness, prime
sandbox). Every run succeeds, and the log ids match the stored trace ids
with `attempt: 1`.
- Forced retry (bogus model, one agent retry plus one episode retry, so
4 attempts), via both entrypoints: the agent retry reuses the trace id,
and the episode retry keeps the episode id and starts a new agent run.
The stored episode and trace both have `attempt: 2` and carry all
errors. Through prime-rl, no stale live trace files remain.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes live episode delta semantics for retried agent runs;
correctness depends on clients already treating discard-then-open as
replace, but the behavior is localized to streaming assembly.
>
> **Overview**
> When an agent run is retried but keeps the same trace id, the live
stream now treats it as a **replace** instead of appending onto the
abandoned attempt.
>
> **`DeltaStreamer`** tracks **`attempt`** on each **`TraceCursor`**. If
a live trace’s **`attempt`** differs from what was already sent for that
id, it emits a **`discard`** delta, clears the cursor, and **`open`**s
the trace again from scratch (same path as when a trace disappears from
the live set). **`attempt`** is included in **`HEADER_FIELDS`**, so
assembled traces carry which retry they represent.
>
> A new unit test asserts that after a retry with **`attempt: 2`**, the
client ends with one trace whose nodes are only from the retry (not the
first attempt’s turns).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
362d57e790471ceba33d31041ee068f6fb3d4bf6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
- Add `tests/regression/configs/eval/pi-terminalbench2-1.toml`:
PI-TerminalBench2.1 (82 reviewed Terminal-Bench 2 tasks), one rollout
each, `internal/deepseek-v4.1-flash-1017-ci` (a dedicated CI deployment
with a 1k concurrency cap), bash harness in prime sandboxes.
- Every task is in flight at once. `env.taskset.ignore_timeouts = true`
drops the tasks' own agent and verifier timeouts. One 4 h agent budget
(`env.agent.timeout.rollout = 14400`) replaces them, so the eval ends in
about 4 h, inside the 6 h job limit.
- A rollout that runs out of time gets reward 0
(`env.agent.scoring.skip_on_timeout = true`) and does not count as an
error.
- Rollouts are not retried, so the gate sees the raw error rate. A retry
would also start a new 4 h budget late in the run.
- Run every config in `tests/regression/configs/eval/` in the `eval`
suite of `regression.yml`, not only gsm8k:
- `Eval / Plan` builds one job per config and repeat, named from a
display-name map in the plan step: `Eval / GSM8K`, `Eval /
Terminal-Bench-2.1`, or `Eval / GSM8K (2)` with several repeats. A
config missing from the map shows its file name.
- The new dispatch input `eval_config` runs one config, e.g. `-f
eval_config=pi-terminalbench2-1`.
- The new dispatch input `eval_max_parallel` caps how many eval jobs run
at once, e.g. `-f eval_max_parallel=2` for a baseline.
- `Eval / Summary` compares each config against its own baseline in
`tests/regression/baselines/eval/` and fails if any config regresses or
has no finished run.
- With `eval_set_baseline`, the bot PR refreshes the baselines of every
config that ran.
- The eval job timeout goes from 60 to 360 min, the GitHub-hosted
maximum.
- Cache `~/.cache/harbor` on the `prime-envs` commit. Harbor tasksets
download their task files from `prime-tasks` on each run otherwise.
- `eval.py summarize` takes `--name` for the heading of each config's
block.
- A baseline file can set a minimum tolerance per metric under
`"tolerance"`. `eval.py baseline` keeps it when it rewrites the file.
- Update the `regression.yml` row in `docs/development.md`.
- Add the PI-TerminalBench2.1 baseline in
`tests/regression/baselines/eval/pi-terminalbench2-1.json` and
`tests/regression/reports/eval/pi-terminalbench2-1.md`: accuracy 65.85%
± 2.86% (std), errors 1.95%, time to finish 4.0 h. It allows 10% errors
(`"tolerance": {"error_rate": 0.1}`): errors are rare sandbox and
harness failures, and five repeats under-sample their spread.
- The 5 repeats ([run
41763261279](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/41763261279))
ran without the cap and hit the 6 h job limit with 1–2 tasks still
running. I scored them as if the cap had applied: rollouts over 4 h or
unfinished get reward 0, and retried rollouts count as errors at their
first failure.
## Verification
- The PR run on d995db6e0
([41870729344](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/41870729344)):
GSM8K passed. TB2 scored 59.8% (baseline 65.9%, tolerance ±9.4%), and 4
tasks hit the 4 h cap with reward 0. Its 4 errors (4.9%: 2 sandboxes
terminated, 1 background job lost, 1 harness exit 137) failed the old
±2.2% error tolerance. `eval.py summarize` on that result with the 10%
tolerance passes, and GSM8K still gates at its 1% floor.
- `uv run eval @ tests/regression/configs/eval/pi-terminalbench2-1.toml
--dry-run` resolves `rollout = 14400` and `skip_on_timeout = true` in
the env config.
- The summary loop renders and gates correctly against the gsm8k result
of an earlier CI run. I tested both artifact download layouts (one
artifact, several). A config with no results fails with "No repeat
finished".
- On the shared `-ht` endpoint, the slowest TB2 rollouts took 4–5 h, and
4 of 5 repeats hit the 6 h job limit. One clean repeat scored 69.5% with
1.2% errors. The `-ci` endpoint decodes at about 68 tok/s per request at
128 concurrent requests, against about 17–20 on `-ht`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes regression CI orchestration and gating for long, API-dependent
evals; misconfiguration could block merges or miss regressions, but no
production runtime or auth paths are touched.
>
> **Overview**
> Adds **PI-TerminalBench2.1** to nightly eval regression (82 tasks, 4h
rollout cap, prime sandboxes) with baseline/report, and **generalizes**
`regression.yml` so every `tests/regression/configs/eval/*.toml`
runs—not only gsm8k.
>
> The eval suite now plans a **matrix of config × repeat** jobs (display
names like Terminal-Bench-2.1), with dispatch inputs **`eval_config`**
(single config) and **`eval_max_parallel`** (throttle parallelism). Eval
jobs get a **6h timeout**, **Harbor task caching** keyed on
`prime-envs`, and per-config artifacts under `results/$CONFIG/`. **Eval
/ Summary** compares each config to its own baseline and fails if any
regresses; baseline PRs refresh all configs that ran.
>
> **`eval.py`** gains `--name` for multi-config summaries,
**per-baseline minimum tolerances** (e.g. 10% floor on error rate for
TB2), and preserves existing `tolerance` when regenerating baselines.
Docs table updated for the new workflow behavior.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
60b69cd72b3d3d2f359ba8361abfa81b7295d8d2. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Why
The env server's rollouts reach inference through a session-affinity
router (vllm-router `sticky_least_loaded`), routed by `X-Session-ID`.
Until now that was the trace id for every call, so a recursive harness
pinned its whole tree to one data-parallel rank. nano-rlm runs up to
four agents of a tree at once, each growing toward its compaction
threshold. In RL runs serving DeepSeek-V4-Flash, single trees held up to
~1M tokens of live context on one rank, and a rank that collected a few
of them re-prefilled evicted prefixes. Under expert parallelism that
stalled every rank of its node.
verifiers#3075 (with PrimeIntellect-ai/nano-rlm#252) routes each
sub-agent as a session of its own, `<trace id>:<agent session>`. The
orchestrator releases a rollout's router sessions with `finish_sessions`
when its episode ends, but it only knew the trace ids.
## What
- `deps/verifiers` moves to `308619da`, the merge of verifiers#3075.
Beyond that PR, the bump brings in verifiers#3062 (CI endpoint) and
verifiers#3070 (custom-env format violations stay at zero reward). There
are no dependency changes, so the lock is unchanged.
- The dispatcher collects each streamed call's routing session
(`routing_session_id(trace, call.acp.agent_session_id)`) and releases it
with the trace's own when the episode ends, so sub-agent sessions do not
linger in the router until expiry and count toward its per-replica load.
Rollouts without sub-agents release exactly the trace id, as before.
Ran `ruff check` / `ruff format --check` (0.13.0) on the change and
checked against the verifiers branch that a dumped `ModelCall` carries
`acp.agent_session_id` and maps to `<trace>:<agent>`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes which session IDs are released to the inference router at
episode teardown; incorrect ids could leave sessions pinned or release
the wrong affinity, but the logic is additive and falls back to
trace-only when ACP is absent.
>
> **Overview**
> Rollouts that use a **recursive harness** now tear down every
inference router session they opened, not just the top-level trace id.
>
> While streaming env deltas, the dispatcher still records
`delta["trace"]`, and also collects **`routing_session_id(trace,
agent_session_id)`** from each call that carries **ACP** metadata. Those
ids are passed to **`finish_sessions`** when the episode finishes (same
path as before), so sub-agent sessions (`<trace>:<agent>`) do not stick
around on the sticky router and inflate per-replica load. Rollouts
without sub-agents behave unchanged—only the trace id is released.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
19ab0dc1c2fe5a7437f390db6f3d1b4ae9cbbc4d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
- Raise `P99_LAG_S` from 25 ms to 50 ms in
`tests/unit/monitors/test_monitor_load.py`.
- Raise `MAX_LAG_S` from 100 ms to 250 ms.
- Explain the headroom in the comment above the limits.
## Verification
Before: the test failed 5 times on `ubuntu-latest` after the current
monitor code landed. All failures were `count=1000` cases, with no code
change involved:
| Run | Branch | Assertion | Observed | Old limit |
|---|---|---|---|---|
| 41769341552 | main | prime p99 lag | 33.5 ms | 25 ms |
| 41696122236 | chore/bump-verifiers-renderers | prime p99 lag | 30.1 ms
| 25 ms |
| 41730705371 | fix/mega-moe-nccl-min | file max lag | 102 ms | 100 ms |
| 41552563666 | feat/episode-json | file max lag | 100 ms | 100 ms |
| 41555224772 | feat/episode-json | wandb max lag | 124 ms | 100 ms |
On a 30-core dev box, the same cases stay at p99 ≤ 9 ms and max ≤ 14 ms.
A simulated regression still fails under the new limits. I moved the
file monitor's episode write onto the event loop (`write()` instead of
`await asyncio.to_thread(write)`). Even on the dev box, this gave p99
lag of about 100 ms, max of about 200 ms, and p50 of about 13 ms. Both
the 100- and 1000-episode cases failed.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Test-only threshold and comment changes; no production monitor or
orchestrator behavior is modified.
>
> **Overview**
> **Relaxes event-loop responsiveness thresholds** in the slow monitor
load test (`test_monitor_load.py`) so it stops failing on shared GitHub
runners while still guarding against real stalls.
>
> `P99_LAG_S` goes from **25 ms → 50 ms** and `MAX_LAG_S` from **100 ms
→ 250 ms**. The comment above those constants now documents why: CI
alone can hit ~35 ms p99 and ~125 ms single stalls, and serializing
large episodes on the loop can push p99 toward ~100 ms even on fast
hardware.
>
> The assertions in `_assert_responsive` are unchanged—they still fail
if monitors block the asyncio loop beyond these limits (a deliberate
regression, e.g. blocking writes on the loop, still fails under the new
caps).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
932594fbd2cb137b9681c0c340b3dd38cba096bd. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Adds `uv run pretrain`, which trains a model from scratch on tokenized
shards written by datatrove. SFT and pretraining become two entrypoints
over one trainer, with shared launch, data and config code.
## Structure
- `entrypoints/launcher.py`: the launch logic (local, SLURM single and
multi node), moved out of `entrypoints/sft.py`, as `launch(config,
entrypoint)`. `sft.py` and `pretrain.py` are thin wrappers. The SLURM
templates take the entrypoint name, so a pretrain job runs `uv run
pretrain`/`prime_rl.trainer.pretrain.train` in the job. The resolved
config is `<entrypoint>.json`.
- `trainer/train.py`: the shared trainer loop (moved from
`trainer/sft/train.py`). `trainer/sft/train.py` and
`trainer/pretrain/train.py` are thin mains that pass their config class.
- `trainer/data.py`: the shared data machinery only
(`StatefulIterableDataset`, `CatDataset`, `setup_dataloader`, dataset
state/progress). `setup_sft_dataset` lives in `trainer/sft/data.py`,
`setup_token_dataset` in `trainer/pretrain/data.py`.
## Config shape
- `configs/supervised.py`: `SupervisedTrainerConfig(BaseTrainerConfig)`
holds what SFT and pretraining share (data/val base, deployment, SLURM,
online evals, resume, monitors). `SFTConfig` and `PretrainConfig` are
siblings and do not import each other.
- `PretrainConfig`: `data: DatatroveDataConfig` (`type = "datatrove"`;
`paths` required, `seed`, `document_masking`), optional `val:
PretrainValConfig` (held-out shard folders, `num_samples`). Defaults are
SFT's except `optim.lr = 1e-3` and a 10-step linear warmup, then
constant. The weights are initialized with the model's own init whenever
the run does not resume; there is no user flag for this.
## Usage
Tokenize with datatrove (a separate install) and set `eos_token` (for
Qwen, `<|endoftext|>`). Then:
```toml
[model]
name = "Qwen/Qwen3-0.6B" # only the architecture is read
[data]
paths = ["data/fineweb-edu"]
seq_len = 2048
```
`uv run pretrain @ pretrain.toml`. Details are in the Pretraining
section of `docs/training.md`.
## Data
`trainer/pretrain/data.py` reads all shard files as one token pool and
cuts it into `seq_len` windows. The order and offset are new each epoch
and seeded, and resume is exact, also onto another number of GPUs.
Attention and positions restart at every document. Empty documents are
dropped. Validation stops every rank at the same window. The trainer
warns at startup if the shards look like they have no document
separator.
## Tests
- Unit: window coverage, shuffled order, and window boundaries that move
between epochs; document masking; resume from 2 ranks onto 1 equals an
uninterrupted run; validation limits; config round-trip (`uv run sft`
rejects datatrove data); from-scratch init without a padding row (GPU).
- Integration: `configs/ci/integration/pretrain/{start,resume}.toml` +
`tests/integration/test_pretrain.py` (Qwen3-0.6B config from scratch, 2
GPUs, validation every 10 steps). The first resumed loss must continue
the start run's last loss. Added to the GPU workflow.
- Checked on 2 H100s: pretrain integration 6/6. `test_reverse_text_sft`
gives the same losses and grad norms as `main` (its `test_dashboard`
fails on that cluster on `main` too: playwright cannot install).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Introduces a new training entrypoint with from-scratch weight
initialization and non-trivial dataloader checkpoint semantics; changes
are mostly additive but touch shared supervised launch/training paths
used by SFT.
>
> **Overview**
> Adds **`uv run pretrain`**, a first-class path to train dense models
**from scratch** on datatrove **`*.ds` token shards** (next-token loss,
optional held-out validation), with **`model.name` supplying
architecture only** unless resuming from checkpoint.
>
> **Refactor for sharing with SFT:** launcher logic moves to
**`entrypoints/launcher.py`** (`launch(config, entrypoint)`); the
trainer loop consolidates in **`trainer/train.py`**; shared
packing/dataloader code moves to **`trainer/data.py`**; common config
base is **`SupervisedTrainerConfig`** in **`configs/supervised.py`**,
with sibling **`PretrainConfig`** (`DatatroveDataConfig`, higher default
LR, 10-step warmup) and slimmed **`SFTConfig`**.
>
> **Pretrain-specific behavior:** **`trainer/pretrain/data.py`** treats
shard folders as one token pool, shuffles windows per epoch with a
deterministic permutation (exact resume across GPU counts), optional
document-boundary masking, and startup warnings when shards lack
separators. **`setup_model`** gains **`init_from_scratch`** (custom init
+ clearing embedding **`padding_idx`**). SLURM templates, dashboard
resolved-config detection, checkpoint export, **`run_owner`**, Prime
monitors, docs, CI TOMLs, GPU workflow matrix, and integration/unit
tests follow the new entrypoint.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
665c1c55b12bd4bd7f10dffd3a04e18d323288ac. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Run the nightly GSM8K eval regression on
`internal/deepseek-v4.1-flash-1017-ci`, a dedicated CI deployment of
DeepSeek V4.1 Flash with a 1k concurrency cap. It was on
`internal/glm-5.3-high-throughput`, which backs up under load: on
2026-10-22, provider errors on that endpoint caused a false regression
(accuracy −1.44%, error rate 1.21%).
- Drop the pinned 256 in-flight episodes for the eval default of 128, so
a 5-repeat baseline (5 × 128) stays under the endpoint's cap.
- Refresh `tests/regression/baselines/eval/gsm8k.json` and
`tests/regression/reports/eval/gsm8k.md` from 5 repeats on the new
endpoint ([run
41725025527](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/41725025527)):
accuracy 96.95% ± 0.29% (std), 0% errors, 0% truncation, 701 s mean time
to finish. The old GLM baseline was 97.65% ± 0.18%.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Changes only affect regression eval config and stored baseline/report
data, not production training or inference logic.
>
> **Overview**
> Switches the nightly **GSM8K eval regression** from
`internal/glm-5.3-high-throughput` to
**`internal/deepseek-v4.1-flash-1017-ci`**, a CI-scoped inference
deployment meant to avoid load-related provider failures that had
triggered false regressions on GLM.
>
> In `tests/regression/configs/eval/gsm8k.toml`, the model name is
updated and the fixed **`[concurrency]` block (256 in-flight)** is
removed so the suite uses the eval default concurrency and stays within
the CI endpoint cap during 5-repeat baselines.
>
> **Refreshed regression artifacts** from [Actions run
41725025527](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/41725025527):
`tests/regression/baselines/eval/gsm8k.json` and
`tests/regression/reports/eval/gsm8k.md` now reflect ~**96.95%** mean
accuracy (vs ~97.65% on GLM), **0%** error/truncation rates, and roughly
**half** the prior wall/eval time and output-token length.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f46f648630d8e5ab3bc316cdcc383b49e9ca31db. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
- Move `deps/verifiers` to `v0.4.1` and raise the pin to
`verifiers[harbor]>=0.4.1` (also in `prime-rl-configs`).
- Move `deps/renderers` to `renderers-v0.2.0` and raise the pin to
`renderers[multimodal]>=0.2.0`. verifiers 0.4.1 requires it.
- Move `deps/prime-envs` to prime-envs main (797040d29), which requires
stable verifiers 0.4.1 (PrimeIntellect-ai/prime-envs#1060).
- Relock `uv.lock`.
Companion: PrimeIntellect-ai/prime-envs-private#383 (merged).
## Verification
- `pytest tests/unit -m 'not gpu'`: 1098 passed. 6 failed in
`qwen3_8_flash_next`, because `indexed_attention` does not support this
box's sm_120 GPU. The bump does not touch that code.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Wide dependency upgrade on verifiers/renderers and many RL
environments affects training and eval resolution, though the diff is
pins and lockfile only with no local code changes.
>
> **Overview**
> This PR **raises dependency pins** so the repo tracks stable
**verifiers 0.4.1** and **renderers[multimodal] 0.2.0** (the latter
required by verifiers 0.4.1). The main `pyproject.toml` moves from
`verifiers[harbor]>=0.4.0` and `renderers[multimodal]>=0.1.12`;
`prime-rl-configs` moves from a dev `verifiers>=0.3.2.dev158` pin to
`>=0.4.1`.
>
> **`uv.lock` is regenerated** to match: dev-style `verifiers`
specifiers across editable benchmark/env packages are normalized to
`>=0.4.1`, and the editable `verifiers` package now pins
`renderers[multimodal]>=0.2.0`. The lock also picks up **prime-envs**
changes—new workspace members such as **`group-wise-judge`**,
**`pi-automationbench`** (via git **`automation-bench`**), and
**`terminal-bench-science`**, plus minor version bumps on several
existing PI/SWE/search env packages (e.g. **`enterprise-ops-gym`
0.4.0**, **`pi-officeqa-pro-v2`**, **`swe-atlas-*` 0.3.0**).
>
> There are **no application source edits** in this diff; impact is
install/resolve behavior and whatever API or behavior changed in the
bumped libraries and env packages.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
926d820fb4b3768ebad0bb0d8c713f781423e04f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
GRPO length penalties now count only trainable branches for both the
ordinary linear penalty and the subagent-weighted variant. Discarded
compaction attempts no longer change output-token, input-token, or turn
penalties; shared prefixes count once. Raw usage metrics still record
all model calls.
Whole-trace admission continues to exclude non-training agents,
including agentic judges. Terminal format-violation attempts made
trainable by [Verifiers
#3059](https://github.com/PrimeIntellect-ai/verifiers/pull/3059) remain
eligible for the penalty.
Validation: 58 focused advantage and algorithm tests passed on CPU,
including discarded compaction, shared-prefix, serialization, and
subagent-weighting coverage. Ruff passed.
## Summary
- Move the ZMQ env server, client and worker pool from
`verifiers.v1.serve` into a new `prime_rl.env` package (`server`,
`client`, `pool`, `delta`, `encoding`, `types`). prime-rl is the only
consumer. verifiers keeps in-process abstractions only. The wire
protocol, delta streaming, and pool scaling logic are unchanged.
- Move the `[serve]` config block (`ServeConfig`, `StaticPoolConfig`,
`ElasticPoolConfig`) into `prime_rl.configs.env_server`. The fields and
defaults do not change. `serve.pool.max_workers` now must be at least 1
when set.
- Point the env-server entrypoint, the orchestrator (`EnvClient`), the
live-trace file monitor (`EpisodeAssembly`) and the payload hook at
`prime_rl.env`.
- Log through the prime-rl logger (`get_logger()`) in the env server
modules, in the prime-rl log style.
- Simplify for the one caller (`entrypoints/env_server.py`):
- `serve_env` takes the pool config directly (no `pool_serve_kwargs`)
and only plain config data.
- Every env server is an `EnvServerPool` broker over worker processes,
including a one-worker pool. Pool workers start through `serve_worker`.
- `log_setup` becomes `worker_setup`, since it also installs the episode
hook and sandbox labels.
- Remove unused address defaults, re-exports, `env_config_data`,
`EnvServer.run_server` and `_context`.
- Move the serve unit tests from verifiers to `tests/unit/env/`.
- Add `msgpack` as a direct dependency, because verifiers drops it.
- Remove the `env/` virtualenv rule from `.gitignore`. It hid
`src/prime_rl/env/`.
- Bump `deps/verifiers` to the merge of
PrimeIntellect-ai/verifiers#3054, which removes `verifiers.v1.serve`.
The new verifiers floors raise `prime-sandboxes` to 0.5.5 and
`prime-tunnel` to 0.1.17 in the lock.
- Update the process tree in the monitor-run skill: every env server is
a broker over spawned worker processes.
## Breaking
- `serve.pool.max_workers = 0` (elastic pool) is now rejected. Migrate:
set `max_workers = 1`.
- A pool capped at one worker (`num_workers = 1` or `max_workers = 1`)
no longer runs the env server in-process. It runs a broker over one
worker process, like every other pool. No config change is needed.
## Verification
- `tests/unit/env`, `test_configs`, `test_dashboard_artifacts`,
`tests/unit/{orchestrator,eval,transports}`: 523 passed against the
verifiers branch with `verifiers.v1.serve` deleted. Excluded:
`test_episode_records` and `test_modelexpress_boundary`, which fail at
import in the stale local venv (`prime_runs`, `modelexpress_rl`) and do
not touch this change.
- E2E with `deps/verifiers` checked out at verifiers#3054 (no
`verifiers.v1.serve`):
- `uv run rl @ examples/basic/reverse-text/rl.toml` (20 steps): train
reward 0.16 → 0.86, online eval reward 0.84 at step 20, 0% errors, no
tracebacks.
- `uv run eval @ examples/basic/reverse-text/eval.toml` (single-turn,
Qwen3-0.6B, 20 × 3 rollouts): finished with 0% errors. `EnvServerPool`
and per-worker `EnvServer` lines appear in the prime-rl log format.
- Smoke: `env-server` with `reverse-text` for static pools of 1 and 2
workers and elastic pools capped at 1 and unbounded. Each published its
address, answered `EnvClient` health, and shut down cleanly with its IPC
directory removed.
- The RL e2e was rerun after the pool-only change with the same result
(train 0.18 → 0.85, eval 0.83, 0% errors).
- After the submodule bump: `tests/unit/env` and
`tests/unit/orchestrator` pass (160 tests).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes the core rollout transport and multiprocess env-server
topology every train/eval run depends on, though the wire protocol and
streaming semantics are intended to stay the same and are covered by new
unit tests.
>
> **Overview**
> **In-process verifiers serving is replaced by a first-party
`prime_rl.env` stack** that owns the ZMQ wire protocol, msgpack
encoding, incremental trace deltas, async client, worker `EnvServer`,
and an `EnvServerPool` ROUTER broker with static or elastic scaling. The
orchestrator, env-server entrypoint, live-trace monitor, and training
payload hook now import from `prime_rl.env` instead of
`verifiers.v1.serve`.
>
> **Configuration moves to `prime_rl.configs.env_server`**:
discriminated `ServeConfig` with `StaticPoolConfig` /
`ElasticPoolConfig` (CLI `--serve.pool.type`), plus `max_concurrent` and
address binding. **`serve_env` is simplified** — it always runs through
the pool broker (including a one-worker cap), takes the pool object and
JSON `model_dump` env config directly, and uses **`worker_setup`**
(logging, hooks, sandbox labels) in the broker and every spawned worker.
>
> **Dependency and hygiene**: **`msgpack` is a direct prime-rl
dependency** (dropped from verifiers). Unit tests live under
`tests/unit/env/`. **`.gitignore` no longer ignores `env/`**, which was
hiding `src/prime_rl/env/`.
>
> **Behavioral breaks**: elastic **`serve.pool.max_workers` must be ≥
1** when set (0 is rejected). A pool capped at one worker is **no longer
in-process** — it is always broker + one worker process like larger
pools.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d3173c61a9781367b8c674601e51d51d9fd79b60. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
- Renderers: PrimeIntellect-ai/renderers#192 (V4.1 renderer) merged with
the trinity Hermes parser, on dphn/renderers trinity-dsv41.
- LoRA warm start: trainer-only now; upstream's startup broadcast ships
the loaded adapter as policy v0, so the orchestrator hook is dropped.
Parameter names follow upstream's single-slot LoRA layers.
- Adapter reload timeouts moved to orchestrator/clients.py.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
Companion to PrimeIntellect-ai/verifiers#3042 and
PrimeIntellect-ai/prime#1140 (released in `prime-runs` 0.1.6). The file
monitor and the Prime monitor encode each episode in short steps, so a
large episode no longer stalls the orchestrator's event loop for as long
as encoding it takes.
- **Pins.**
- The verifiers submodule moves to verifiers main, which includes
verifiers#3042: `to_json` encodes one node at a time and releases the
GIL every millisecond, and `record_run` records the run on every trace.
- `prime-runs` 0.1.6, already on main, contains prime#1140: the SDK
uploads `episode.to_json()` as it is when the episode and its traces
name the upload's run. The dispatcher's `record_run` makes that true for
RL episodes.
- Verifiers main also includes PrimeIntellect-ai/verifiers#3046, which
removes `vf-eval`'s platform push and verifiers' `prime-runs`
dependency. In `uv.lock` (uv 0.12.0), only the verifiers metadata
changes.
- **The file monitor writes `episode.to_json()`.**
- The stream line is byte for byte what
`orjson.dumps(episode.to_record())` gave before.
- The index row comes from `index_record(episode)`. It dumps everything
but the nodes' payloads, one trace at a time, and gives the same row.
- `ChunkedJsonl.append` takes a line in parts, so the newline is written
without copying a long line.
- **The load test's lag limits drop** from p99 100 ms and max 250 ms to
25 ms and 100 ms, so a regression shows. Across runs at production
sizes, the highest values were a p99 of 12.5 ms and a max of 22 ms.
- **A hosted orchestrator stamps the platform's run id.** A hosted
launch sets only `$RUN_ID`, not `$PRL_RUN_ID`, so the orchestrator
stamped episodes with a random id, and the SDK re-stamped every upload.
It now falls back to `$RUN_ID`, the Prime run id.
## Verification
**Headline: event-loop lag at 1,000 production-sized episodes (~8 GB of
JSON)**, monitor load test, dev box:
| | Main (before) | This PR |
|---|---|---|
| prime: lag p99 / max | 14 / 17 ms | **3.1 / 3.5 ms** |
| file: lag p99 / max | 47 / 93 ms | **4.8 / 15 ms** |
| file: `log()` max | 177 ms | 195 ms |
- **A second run:** inside the full unit suite, with more load on the
box, it measured prime 11 / 18 ms, file 5.2 / 22 ms, and file `log()`
max 224 ms.
- **Why the GIL release matters:** encoding node by node without it left
the file monitor at 15–18 / 31–66 ms, varying from run to run. A busy
encoder thread keeps the GIL until CPython's 5 ms switch interval forces
a handoff, and the event loop waits that out several times per wakeup.
**The stall no longer grows with the episode.** One thread encodes
episodes of 10 to 10,000 turns (1,000 tokens per turn) while a 5 ms
ticker on the event loop records the worst stall. Medians of 5 runs,
under the orchestrator's GC policy:
| Turns | Episode | Encode CPU, before / after | Worst stall, before |
Worst stall, after |
|---|---|---|---|---|
| 10 | 0.2 MB | 0.4 / 0.5 ms | 5.5 ms | 5.2 ms |
| 100 | 2.2 MB | 4.0 / 4.5 ms | 8.0 ms | 1.6 ms |
| 1,000 | 22 MB | 50 / 51 ms | 40 ms | 3.1 ms |
| 3,000 | 65 MB | 152 / 167 ms | 100 ms | 5.2 ms |
| 10,000 | 217 MB | 508 / 571 ms | 326 ms | 15 ms |
- **Before:** the stall grows linearly with the episode.
- **After:** it stays around 2–5 ms up to 3,000 turns, about the GIL
switch interval. The 10-turn case is that interval alone, since each
episode encodes in under a millisecond.
- **The rest at 10,000 turns:** the trace header's pydantic dump, which
holds every model call (one per turn). Alone it stalls 4.4 / 8.4 / 15 ms
at 1,000 / 3,000 / 10,000 turns. Agentic episodes in production have a
few hundred turns, so this part stays small. Encoding the calls one at a
time, like the nodes, would remove it.
- **CPU:** encoding costs up to ~12% more, from the extra calls and GIL
releases.
**Encoding:** `test_received_episode_encodes_as_its_record_did` sends a
two-trace episode over the real delta wire into a `WireEpisode`. Then:
- the file monitor's stream line equals `orjson.dumps(to_record())`,
byte for byte;
- its index row equals the row from the full record;
- after `record_run`, the SDK takes the episode's own `to_json()`, which
carries the same record as the old stamped line.
**Tests:** `pytest tests/unit -m "not gpu"`: 1,077 passed, 7 failed. The
same 7 fail on main on this dev box: an attention kernel without sm_120
support, and no ninja for the CPU Adam extension.
**CI:** on the CI runner, the file monitor at 1,000 production-sized
episodes measured event-loop lag p99 6.0 ms and max 12 ms, against 63 /
152 ms on main. Its slowest `log()` was 382 ms, under the 1 s limit.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes affect how every episode is persisted and indexed and how run
identity is chosen on hosted launches; behavior is contract-tested but
touches high-volume I/O on the training path.
>
> **Overview**
> Large episodes no longer block the orchestrator event loop during
trace logging. The **file monitor** writes stream lines with
**`episode.to_json()`** (incremental, GIL-friendly encoding from
verifiers) instead of a single **`orjson.dumps(to_record())`**, and
builds index rows via new **`index_record()`** so summarization skips
heavy node payloads without materializing the full record first.
**`ChunkedJsonl.append`** accepts **byte parts** so the newline is
appended without copying megabyte-scale lines.
>
> The orchestrator **`run_id`** now falls back to **`$RUN_ID`** when
**`$PRL_RUN_ID`** is unset, so hosted runs align with the platform id
and Prime uploads are not re-stamped with a random id.
>
> Monitor load tests use **stricter event-loop lag thresholds** to catch
regressions. A new unit test asserts on-disk bytes and SDK upload JSON
still match the legacy **`to_record()`** encoding.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f83e84906e5c9919df17e1ce7554580644ff00e7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
Prime uploads keep up with the orchestrator, and logging to Prime never
blocks it. Companion to PrimeIntellect-ai/prime#1136.
- **SDK pin.** `prime-runs[train]>=0.1.6`, which pulls `prime-traces`
0.0.12 from PyPI. These releases contain PrimeIntellect-ai/prime#1136:
gzip level 1, up to 8 upload requests in flight, an upload queue bounded
by records whose `submit` never blocks, and lazily built upload records.
- `uv.lock` is written with uv 0.12.0 (lockfile revision 3); only the
two SDK packages change.
- **No thread hop for Prime.** `PrimeMonitor` calls `run.log_metrics`
and `run.log_episodes` directly on the event loop, not through
`asyncio.to_thread`. A queue put that never blocks needs no thread, and
each hop had to win the GIL back from the uploader thread.
- **A production-sized load test.**
`tests/unit/monitors/test_monitor_load.py`:
- **Episode sizes:** episodes draw their size from a lognormal fitted to
a production RL run (median 6.4 MB, p90 17 MB; it also matches the mean
of 8.5 MB and the p99 of 35 MB), capped at 60 MB. 1,000 episodes is ~8
GB of JSON, close to one production step of 1,024 samples.
- **Memory:** episodes share 24 traces at log-spaced sizes, so the
test's own memory stays small.
- **Fake endpoint:** the fake Traces endpoint gzips at the SDK's level
and counts lines under a lock, because the client now sends several
requests at once.
- **File monitor check:** it streams every trace chunk, since 8 GB spans
two 5 GiB chunks.
- **No expected failure:** the prime monitor at 1,000 episodes is no
longer marked as one.
- **A separate `log()` limit of 1 s.** A `log()` call may await the
monitor's own work: the file monitor awaits its write, which encodes the
episode on a worker thread, while the event loop keeps serving other
tasks. The lag limits still cover the loop.
- **The p99 lag limit rises from 50 to 100 ms.** At production sizes the
file monitor encodes each episode in one call, which stalls the event
loop with a p99 of ~60 ms on CI. Main's code shows the same stall with
this test. #4366 makes the encoder work in short steps and tightens the
limits to 25 ms p99 and 100 ms max.
## Verification
**Headline: Prime monitor, 1,000 production-sized episodes (~8 GB of
JSON), main against this branch.** Main ran this branch's test, with the
fake endpoint gzipping at main's level 9.
| | main | This branch |
|---|---|---|
| Episodes delivered | 725 of 1,000 | **1,000 of 1,000** |
| Lost to a full upload queue | 27 | 0 |
| Lost when the 60 s drain ran out | 248 | 0 |
| Slowest `log()` | up to 5 s (blocked on the full queue) | **0.6 ms** |
| Event-loop lag p99 / max | not reached (failed on delivery) | 14 / 17
ms |
| Test time | 217 s | 28 s |
**Scale: 10,000 episodes of 2.2 MB (~22 GB)**, from a local copy of the
test with the count raised:
| Setup | Result |
|---|---|
| No network time | 0 dropped; `log()` max 1.4 ms; event-loop lag p99 14
ms, max 21 ms; 570 MB peak RSS |
| 100 ms + 100 MB/s per request, 1 request in flight | 2,595 delivered
within the 60 s drain |
| Same, 4 in flight | 9,822 delivered |
| Same, 8 in flight (the default) | **10,000 delivered**; event-loop lag
p99 12 ms; 860 MB peak RSS |
The upload rate is ~180 episodes/s (~400 MB/s of JSON). Encoding the
records is the limit.
**Full load-test grid at production sizes, this branch (dev box):** 9
passed.
| 1,000 episodes | Event-loop lag p99 / max | `log()` max |
|---|---|---|
| prime | 14 / 17 ms | 0.6 ms |
| file | 47 / 93 ms | 177 ms |
| wandb | 0.9 / 0.9 ms | 0.6 ms |
**CI:** on the CI runner, the file monitor at 1,000 episodes measured
event-loop lag p99 60 ms and max 157 ms, within this PR's limits (100 /
250 ms), and `log()` up to 299 ms (limit 1 s). With #4366 the same case
measures p99 6 ms and max 12 ms.
Other checks:
- `pytest tests/unit/train/sft/test_prime_monitor.py
tests/unit/utils/test_links.py
tests/unit/orchestrator/test_episode_records.py tests/unit/train/rl -m
"not gpu"`: 29 passed.
- `uvx uv@0.12.0 lock --check` passes.
## Merge order
1. ~~PrimeIntellect-ai/prime#1136~~ and
~~PrimeIntellect-ai/prime#1140~~: merged and released as `prime-runs`
0.1.6 and `prime-traces` 0.0.12.
2. **#4363 (this PR)**: ready to merge. It does not need
PrimeIntellect-ai/verifiers#3042.
3. PrimeIntellect-ai/verifiers#3042
4. #4366🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes the hot path for RL training telemetry (episode/metrics
enqueue) and bumps external SDK versions; misbehavior could drop or
delay uploads under load, though load tests now enforce delivery and
loop responsiveness.
>
> **Overview**
> **Prime logging no longer blocks the orchestrator event loop** by
pinning `prime-runs[train]>=0.1.6` (and `prime-traces` 0.0.12 in the
lockfile), which uses a non-blocking upload queue, concurrent uploads,
and lighter gzip.
>
> **`PrimeMonitor`** now calls `run.log_metrics` and `run.log_episodes`
directly instead of `asyncio.to_thread`, matching SDK behavior where
enqueue never blocks.
>
> The **monitor load test** is reworked to use **production-like episode
sizes** (lognormal ~6.4 MB median), shared trace templates for memory, a
thread-safe fake Traces API, and multi-chunk file delivery checks. The
**Prime monitor at 1,000 episodes is no longer expected to fail**;
responsiveness asserts split event-loop lag (p99 100 ms) from
per-`log()` duration (max 1 s).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
11ae62999764db49fb8233bece63fdb81b69bce6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
- Remove `prime` (the Prime CLI) from prime-rl's runtime dependencies.
No prime-rl code imports `prime_cli`. The CLI only tied prime-rl's lock
to the CLI's releases, and gave `prime-sandboxes` a second path into the
lock next to `verifiers`.
- `Dockerfile.cuda`: install the CLI as a uv tool in its own venv
(`/opt/uv-tools`, executable in `/usr/local/bin`), pinned by `ARG
PRIME_CLI_VERSION=0.19.2`. The platform keeps running `uv run --no-sync
prime env install '<id>'` unchanged. Since prime CLI 0.8.0, `prime env
install` installs into `$UV_PROJECT_ENVIRONMENT`, `$VIRTUAL_ENV`, or the
`.venv` next to the nearest `pyproject.toml`, so Hub envs still land in
`/app/.venv`.
- `scripts/install.sh`: run `uv tool install prime` for local use. The
docs already tell users to install the CLI this way.
- `uv.lock` drops `prime`, `prime-evals` and `gitignore-parser`.
`pyproject.toml` drops their now-unused `exclude-newer-package` entries.
Source overlays on older images keep working: the entrypoint syncs with
`--inexact`, so the CLI already in those images' `/app/.venv` stays in
place.
## Breaking
- `uv sync` no longer installs the `prime` command into the project
venv, so `uv run prime …` in a prime-rl checkout fails until the CLI is
installed. Migration: run `uv tool install prime`, then call `prime …`
directly.
## Verification
- Local check, `prime==0.19.2` installed with `uv tool install` and
absent from the target project venv: `uv run --no-sync prime env install
primeintellect/gsm8k` installed `gsm8k` into the project `.venv` and not
into the tool venv. A plain `prime env install` from the project root
did the same.
- Hosted e2e: pending (reverse-text from the Hub with `prime train`, on
an image built from this branch).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Packaging and install-path changes only; runtime training code is
untouched, with a documented migration for local CLI usage.
>
> **Overview**
> **Removes the `prime` CLI from prime-rl’s Python dependencies and
lockfile**, so CLI releases no longer force lock updates and transitive
packages like `prime-evals` and `gitignore-parser` drop out of
`uv.lock`.
>
> **Docker and local setup now install the CLI separately** via `uv tool
install`: the CUDA image pins `PRIME_CLI_VERSION=0.19.2` into
`/opt/uv-tools` with `prime` on `PATH`, and `scripts/install.sh` runs
the same after `uv sync`. Hub env installs (`prime env install` / `uv
run --no-sync prime env install`) are unchanged in intent—the CLI still
targets the project `.venv`, not the tool venv.
>
> **Breaking for devs:** `uv sync` no longer puts `prime` in the project
venv, so **`uv run prime …` fails until you run `uv tool install
prime`** and invoke `prime` directly.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
82cac44caaa77bd77c1b2796186e74264068b873. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
`max_vio` measures expert-level imbalance: the busiest expert's tokens
over the mean, with the top_k busiest experts dropped so that padding
experts don't dominate it (#1332). With expert parallelism an MoE layer
waits for the EP rank that receives the most routes, and `max_vio`
tracks that poorly: hot experts that share a rank add up, hot experts on
different ranks don't, and the dropped experts are often the ones that
make a rank busy. This PR logs the rank-level imbalance next to
`max_vio`.
## What it computes
`get_global_moe_stats` already sums each micro step's per-layer expert
counts over the EP group. From those counts, per micro step and layer:
- **rank imbalance**: routes received by the busiest EP rank over the
mean rank. EP rank r holds experts `[r*E/ep, (r+1)*E/ep)`, so the counts
are viewed as `[..., ep, E/ep]` and summed. Padding routes count, since
they run through the expert GEMMs like any other token.
Every rank of an EP group holds the same values. A layer waits for the
busiest rank of its EP group and, through its FSDP collectives, for the
slowest EP group. So the logged value is the max over DP groups at each
(micro step, layer), and the DP mean is logged next to it. Both ride in
the existing all-reduces: the DP max is stacked into the `max_vio` MAX
all-reduce and the DP mean into the `routing_confidence` SUM all-reduce.
There is no new buffer, recording path or collective, and no host sync
per micro step. Per-DP-group values are not logged, since that would
need a gather.
Logged in SFT and RL:
- `ep_imbalance/rank/{mean,max}`: max over DP groups, then the mean and
max over the step's layers and micro steps.
- `ep_imbalance/rank_dp_mean/{mean,max}`: the same with the DP mean.
- The console step line shows `EP Imbalance` (`ep_imbalance/rank/mean`).
## Measurement: SFT on DeepSeek-V4-Base
The run is DeepSeek-V4-Flash-Base in bf16: 43 MoE layers (the first 3
hash-routed), 256 experts, top-6. It trains on long-context chat data
packed into 524288-token rows. With cp = 8 and ep = 8, each EP group is
one CP group and trains one row per micro step, 64K tokens per rank. It
ran on 48 H200s (6 EP groups) with 4 micro steps per rank for 60 steps,
which gives 61,920 (EP group, micro step, layer) values.
| | mean | p50 | p90 | p99 | max |
|---|---|---|---|---|---|
| rank imbalance per EP group, micro step and layer | 1.30 | 1.27 | 1.50
| 1.72 | 3.38 |
| … hash-routed layers 0-2 | 1.15 | 1.15 | 1.18 | 1.28 | 2.04 |
| … learned layers 3-42 | 1.31 | 1.28 | 1.51 | 1.73 | 3.38 |
| `max_vio` per layer, same counts | 2.94 | 2.87 | 4.05 | 5.36 | 22.8 |
| `ep_imbalance/rank/mean` per step | 1.39 | 1.39 | 1.41 | 1.48 | 1.54 |
| `ep_imbalance/rank/max` per step | 1.90 | 1.87 | 2.01 | 2.71 | 3.38 |
| `ep_imbalance/rank_dp_mean/mean` per step | 1.30 | 1.30 | 1.31 | 1.32
| 1.34 |
| `max_vio/mean` per step | 5.79 | 5.58 | 6.47 | 8.79 | 9.73 |
- **Step time tracks the new metric more closely than `max_vio`
(suggestive, not causal).** Over steps 2-60, forward plus backward time
ranged from 185 to 208 s. It correlates r = 0.83 with
`ep_imbalance/rank/mean` and r = 0.65 with `max_vio/mean`. On the 32
steps with more than 99.8% of tokens real (no padding spikes), the
correlations are 0.73 and 0.59.
- **`max_vio` and rank imbalance are loosely related.** Per (layer,
micro step, EP group) r = 0.35. The learned-layer values with `max_vio`
between 2 and 5 (94% of them) span 1.10 to 1.72 in rank imbalance (p1 to
p99). The layer with the highest mean `max_vio` (4.5) has rank imbalance
1.23. The most imbalanced layer (1.65) has `max_vio` 3.4.
- **Per layer:** the hash-routed layers sit at 1.12-1.16 and the learned
layers at 1.16-1.65. In the hottest learned layers (1.45-1.65), the same
rank is the busiest in 97-100% of micro steps. Most of the imbalance is
static: a fixed per-layer permutation of experts over ranks, fit on
steps 1-30, brings steps 31-60 from 1.30 to 1.11.
- **The max over DP groups matters:** 1.39 against 1.30 for the DP mean,
with only 6 groups.
- **The tail comes from the run's older packing, not from the metric.**
That trainer revision padded rows with token 0, and the maxima (rank
imbalance 3.38, `max_vio` 22.8, and the slowest step) come from a single
row that was 57% padding. At head, packs pad by repeating their own
tokens (#4184), so that tail should not reproduce; the mean-level
numbers (1.30 per value, 1.39 per-step DP max) are properties of the
routing and carry over.
The counts were recorded with this change applied to the earlier trainer
revision that the run's packing needs. Every (row, layer) counts exactly
row length × 6 routes, so activation-checkpoint recompute does not
double count.
## Testing
- A manual 4-rank gloo run of `get_global_moe_stats` at head (two EP
groups of two, random counts; not committed) matches a brute-force
reference for `ep_imbalance/rank` (max over DP groups) and
`ep_imbalance/rank_dp_mean`, and `max_vio` and `routing_confidence`
match the previous formulas.
- SFT on 8 H200s with a small GLM MoE (8 experts, top-4, fake data, ep =
4, so two EP groups), on the previous revision: every key is logged, and
the DP mean comes out below the DP max (1.38 vs 1.48).
- The measurement above, with this change applied to an earlier trainer
revision that the run's packing needed.
- `ruff check`, `ruff format --check`.
## Summary
- The W&B monitor without an API key fails with its own error, like the
prime monitor:
```
RuntimeError: The W&B monitor found no W&B API key. Authenticate with
`wandb login` (or set WANDB_API_KEY), or turn the monitor off with
--no-monitors.wandb
```
Before, the error wrapped W&B's text: ``The W&B monitor could not start
(No API key configured. Use `wandb login` to log in.). Authenticate with
...``.
- Other W&B usage errors (for example a bad project name) keep the
generic message with W&B's own text.
Follows the review on #4244: a missing key fails the run with an error
that tells the user, or their agent, how to fix it.
## Verification
- New unit test
`test_wandb_monitor_without_credentials_fails_informatively`: it runs
the real `wandb.init` with no key, `HOME` and `WANDB_CONFIG_DIR` in an
empty directory, and matches the new message.
- `pytest tests/unit/utils/test_links.py`: 5 passed.
## Summary
Part of the monitors stack: #4228 → #4316 → #4317 → **#4244**. Stacked
on #4317.
- No net change against #4317. Following review, a prime or W&B monitor
without credentials still fails the launch, as it does from #4228 on.
Most runs start from an agent, which can easily miss a warning. The
error has the login steps and the `--no-monitors.*` flag, so the agent
can act on it, and turning a monitor off stays explicit.
- The earlier warn-and-continue change is reverted in 9c2e9cd73. This PR
can close without merging.
## Verification
- Without a Prime key, `launch_run` fails before the components start:
```
RuntimeError: The prime monitor found no Prime API key. Authenticate
with `prime login` (or set PRIME_API_KEY), or turn the monitor off with
--no-monitors.prime
```
- `pytest tests/unit/utils/test_links.py
tests/unit/train/sft/test_prime_monitor.py`: 19 passed.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes default launch behavior for observability (credentials no
longer gate local runs) while keeping strict failure for attached
platform runs and authenticated registration errors.
>
> **Overview**
> **rl**, **sft**, and standalone **eval** no longer abort when Prime or
W&B is enabled but no API key is present. Each monitor logs a one-line
warning (with `prime login` / `wandb login` or `--no-monitors.*`
guidance), runs in a **disabled** mode, and the rest of the launch
continues.
>
> The **rl/sft launcher** (and multi-node **run_owner**) catches Prime
registration’s missing-key error once, warns, sets
**`PRIME_RUNS_MODE=disabled`**, and skips **`RUN_ID`** so child
processes don’t repeat the warning. **PrimeMonitor** and **W&B** map
their SDK’s “no API key” errors to the same disabled path; disabled
monitors register **no** platform links, so the launch banner doesn’t
block on them.
>
> **Still fails at launch:** attaching via **`RUN_ID`** without a key
(empty platform page), Prime registration errors **with** a key
(team/allowlist), and other W&B **`UsageError`**s (e.g. bad project).
>
> Docs for **training** and **eval** are updated to describe
warn-and-continue instead of hard failure; unit tests cover the new
paths.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9c2e9cd736a132efed040e8ffdb66806c4f4e6d0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
Part of the monitors stack: #4228 → #4316 → **#4317** → #4244. Stacked
on #4316.
- Adds `tests/unit/monitors/test_monitor_load.py`: one test,
parametrized over monitor (file, prime, W&B) × episode count (10, 100,
1000).
- Each episode is agentic and heavy: 100 turns, 100k tokens, numpy
streams as the env-server wire delivers them (about 2 MB per upload).
- Interleaved with 2000 metric rows of 200 keys.
- The episodes share one trace object. Every monitor serializes each
episode separately, so the load is the same at a fraction of the memory.
- The test logs through `monitors.log` as the orchestrator does, under
the orchestrator's `GarbageCollector` (no automatic full collections).
An asyncio ticker measures how late the event loop wakes.
- The test checks that everything logged arrives:
- **File monitor:** every episode in the trace stream, and steps 1 to
2000 in `metrics.jsonl`.
- **Prime monitor:** the real SDK run and uploader threads against fake
Prime Traces and platform endpoints. The fake traces endpoint gzips like
the real client.
- **W&B monitor:** the real SDK in offline mode. W&B takes metrics only.
- The test fails when a monitor stalls the loop: p99 lag of 50 ms or
more, max lag of 250 ms or more, or one `log()` call of 250 ms or more.
- `prime-1000` is an expected failure (strict). The SDK uploader gzips
each episode at level 9, about 70 ms here, so 1000 episodes logged at
once fill its queue. `log()` then waits for room for up to 5 s on the
orchestrator's arrival path, and the SDK drops what stays queued. A TODO
in the test tracks the fix; PrimeIntellect-ai/prime#1129 is the first
part (gzip level 1).
- The test is CPU-only, needs no network and is marked `slow`. CI's unit
job runs it (it deselects only `gpu`). It takes about 110 s.
## Verification
`pytest -s tests/unit/monitors/test_monitor_load.py` on the dev box,
with main's `prime-traces` pin: 8 passed, 1 xfailed.
| Monitor | Episodes | Loop lag p99 | Loop lag max | `log()` p99 |
`log()` max |
|---|---|---|---|---|---|
| File | 10 / 100 / 1000 | 3.6 / 3.4 / 4.7 ms | 3.7 / 5.6 / 4.9 ms | 0.1
/ 5.0 / 5.3 ms | 7.9 / 9.9 / 7.8 ms |
| Prime | 10 / 100 | 5.2 / 7.9 ms | 6.0 / 10.5 ms | 0.4 / 0.4 ms | 10.1
/ 15.4 ms |
| Prime | 1000 | xfail: 7 of 1000 episodes dropped ("Upload queue full
after 5.0s"), one `log()` call blocked 5 s | | | |
| W&B (offline) | 10 / 100 / 1000 | 1.6 / 1.3 / 1.1 ms | 6.0 / 1.6 / 1.4
ms | 0.6 / 0.5 / 0.6 ms | 6.1 / 0.8 / 0.8 ms |
Without the orchestrator's GC setup, a full collection pauses the loop
for 220–260 ms in the 1000-episode cases.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Test-only change with no production code paths modified; it exercises
existing monitor integrations under load.
>
> **Overview**
> Adds **`tests/unit/monitors/test_monitor_load.py`**, a slow unit test
that drives **file**, **Prime**, and **W&B (offline)** monitors through
**`monitors.log`** the way the orchestrator does—heavy agentic episodes
(up to 1000 × 100 turns / ~100k tokens) interleaved with **2000** wide
metric rows, under the orchestrator **`GarbageCollector`** fixture.
>
> For each monitor × episode count (**10 / 100 / 1000**), it asserts
**complete delivery** (trace chunks / fake Prime endpoints / W&B metric
steps) and **event-loop responsiveness** (p99 lag **< 50 ms**, max
lag and single **`log()`** **< 250 ms**). **Prime @ 1000 episodes**
is **`xfail` (strict)** documenting **`prime_runs`** upload-queue
backpressure that can block **`log()`** for seconds and drop episodes.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bb9dbad7e881aebde4fe78a8bc4589263c8d914d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
Part of the monitors stack: #4228 → **#4316** → #4317 → #4244. Stacked
on #4228.
- The RL trainer logs its per-step metrics to the run's Prime run. It
builds on #4170 by @kevinjosethomas and stacks on #4228.
- The trainer sets up the prime monitor from `trainer.monitors.prime`
and attaches to the run that the `rl` launcher registered (`$RUN_ID`).
- The orchestrator still uploads the episodes and its own metrics.
- The trainer only flushes its uploads. The process that registered the
run finishes it once the trainer and the orchestrator exited (#4228).
- `monitors.prime` must be on or off in both components, like
`monitors.wandb` and `monitors.file`. `--orchestrator.no-monitors.prime`
alone is rejected, so the trainer never waits for a run the launcher did
not register.
- The shared `[monitors.prime]` reaches the trainer and the
orchestrator, like `[monitors.wandb]` and `[monitors.file]`.
`--no-monitors.prime` turns it off for both.
- A trainer started without the `rl` launcher has no run to attach to.
In online mode it fails with a hint, like the SFT online-eval process:
launch it with `rl`, or pass `--no-monitors.prime`.
- The trainer and the orchestrator keep their metric names. Both log
`time/step` and `time/save_ckpt`, as they do into the shared W&B run on
main. A rename is a separate change.
Compared with #4170, the trainer needs no `run.json` lookup, no
pending-metrics queue and no sidecar mode: it attaches through
`$RUN_ID`, like every other component since #4228.
## Breaking
- A standalone RL trainer (`torchrun src/prime_rl/trainer/rl/train.py
...`) needs `--no-monitors.prime`, or `PRIME_RUNS_MODE=disabled`.
## Verification
- Hosted RL, reverse-text, 10 steps, from the stack head:
[u68lwuthm9f7e87fxb2pnq5f](https://app.primeintellect.ai/dashboard/training/u68lwuthm9f7e87fxb2pnq5f)
COMPLETED. The hosted trainer attached to the platform's run;
`mismatch_kl/*`, `entropy/*`, `importance_ratio/*`, `loss/*`, `optim/*`
and `perf/mfu` are on Prime at every step 1–10, next to the
orchestrator's `train/*`.
- `uv run rl @ examples/basic/reverse-text/rl.toml --max-steps 5
--no-monitors.wandb`, local:
[ek4xpjtfdnghv2yuae0252au](https://app.primeintellect.ai/dashboard/training/ek4xpjtfdnghv2yuae0252au)
COMPLETED.
- `trainer.log` and `orchestrator.log` both show `(attached via
$RUN_ID)`.
- The Prime run has the trainer's metrics (`optim/grad_norm`,
`perf/mfu`, `loss/*`) next to the orchestrator's.
- Local RL, 3 steps, latest head:
[vconz7g0fm720wr9mtcrqyht](https://app.primeintellect.ai/dashboard/training/vconz7g0fm720wr9mtcrqyht)
COMPLETED, with the trainer's and the orchestrator's metrics at every
step.
- Colliding keys: in
[h9ia98nk6zc9ndruvpahy4gw](https://app.primeintellect.ai/dashboard/training/h9ia98nk6zc9ndruvpahy4gw),
Prime keeps the last write per key and step, so `time/step` and
`time/save_ckpt` show the trainer's values.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes default monitoring behavior for standalone RL trainer launches
and tightens cross-component Prime config validation; metrics upload is
best-effort but misconfiguration now fails fast at startup.
>
> **Overview**
> The RL trainer now streams **per-step metrics** (loss, MFU,
`optim/grad_norm`, timing, etc.) into the same **Prime platform run** as
the orchestrator, instead of Prime being orchestrator-only.
>
> Shared **`[monitors.prime]`** (and `--no-monitors.prime`) apply to
**both** trainer and orchestrator, with validation that Prime is enabled
or disabled on both—matching W&B and file monitors. The trainer
**attaches via `$RUN_ID`** from the `rl` launcher and only flushes
uploads; it does not register or finish the run.
>
> **Breaking:** a standalone `torchrun … train.py` run must pass
**`--no-monitors.prime`** (or disable Prime runs in env), or online mode
errors with a launch hint. Docs and the parallel-invariance regression
test were updated accordingly.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b577b5522d91179db8049d19d0631e04be8fd037. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
Part of the monitors stack: **#4228** → #4316 → #4317 → #4244. Base of
the stack.
- **One prime monitor.** `PrimeMonitor` and `PrimeMonitorConfig` replace
the train and eval pair. `[monitors.prime]` and `--no-monitors.prime`
are unchanged.
- **One monitors config.** `MonitorsConfig` (`wandb`, `file`, `prime`)
replaces `TrainMonitorsConfig` and `EvalMonitorsConfig`. The online-eval
process takes the trainer's monitors as they are. The RL trainer gets a
`monitors.prime` field, which it doesn't set up yet.
- **The process that supervises the launch registers the Prime run, and
every component attaches to it.** This is how a hosted launch works: the
platform pre-creates the run, passes `RUN_ID` to each pod, and sets the
final status from the JobSet.
- Local: the `rl` or `sft` launcher.
- SLURM, single node: the `rl` or `sft` launcher inside the job. The
submitting process registers nothing.
- SLURM, multi node: `python -m prime_rl.entrypoints.run_owner {rl,sft}
<config> srun ...` wraps the job's launch step. It fails the run when
the step exits non-zero, or when SLURM sends SIGTERM (cancel, time
limit).
- **The Prime run gets the whole launch config.** An `rl` launch
registers the full RL config (trainer, inference, orchestrator,
deployment), not only the orchestrator's. Multi-node SLURM jobs write
the full `rl.json` and `sft.json` for the run owner. The multi-node SFT
trainer runs its own `trainer.json`, as the RL components already do.
- The run's id becomes the run identity: `PRL_RUN_ID`, and with it the
W&B run id and the episodes' `run.id`. The launcher also exports it as
`RUN_ID`, which each component's prime monitor attaches to.
- A launch that fails marks the run FAILED with the failed component's
error, e.g. `RuntimeError: Trainer failed with exit code -9`. The SDK
leaves an attached run's failure to the process that registered it.
- A component started without a launcher still registers its own run.
- **SFT online evals log to the same run, like RL.** The online-eval
process uploads its eval metrics and every eval episode to the sft run.
Before, it opened one Prime evaluation per eval epoch.
- The process that registered the run finishes it once every component
exited, and fails it when a component fails. Attached components only
flush, so no component can finish the run while another still logs to
it. On hosted training the platform sets the final status from the
JobSet.
- A paused run no longer gets reported as crashed: the SDK's exit hook
is dropped after the flush.
- **Standalone `uv run eval`** still opens one Prime evaluation per
source and epoch.
- Without a Prime API key, it fails at launch with the `prime login`
hint, like `rl` and `sft`. The evaluations open later, when each epoch
starts.
- **Fewer helpers.**
- The links record is keyed by the monitor's config field (`prime`,
`wandb`), and `run_links` takes the `MonitorsConfig`.
- The platform record is written through `update_record`.
- `register` takes the config directly and turns the SDK's missing-key
error into the `prime login` hint.
- **The orchestrator's monitor producer is `orchestrator`**, the name
every other place uses (`orchestrator.log`, the W&B labels).
## Breaking
- SFT online evals no longer create Prime evaluations. Their results are
on the sft run's Prime page, and an sft run's `monitors/prime/run.json`
no longer lists `evaluations`.
- With the prime monitor on, `PRL_RUN_ID` (and so the W&B run id) of an
`rl` or `sft` launch is the Prime run's id instead of a random uuid.
- A custom multi-node SLURM template (`slurm.template_path`) must wrap
its launch `srun` in `python -m prime_rl.entrypoints.run_owner {rl,sft}
<config>`, as the bundled templates do. Without it, nothing registers
the shared run.
- A multi-node SFT job's `sft.json` is now the full config. The trainer
reads `trainer.json`; a custom multi-node SFT template must pass `{{
config_path }}` (the trainer's) to the trainer and `{{ run_config_path
}}` to the run owner.
- The Prime run's config of an `rl` launch is the full RL config instead
of the orchestrator config.
- An RL config can no longer turn `monitors.wandb` or `monitors.file` on
in one component only: `RLConfig` rejects it ("must match across
components"). Set the shared `[monitors.<name>]` instead.
- A hosted orchestrator no longer finishes its attached run; the
platform marks it COMPLETED from the JobSet, as it already did.
- The orchestrator's file-monitor producer is `orchestrator` instead of
`orch`. Its annotation stream moves from
`monitors/file/traces/annotations/orch` to
`.../annotations/orchestrator`, and its `metrics.jsonl` rows carry
`"producer": "orchestrator"`.
## Verification
Stack head (#4244 at `450707973`), 2026-10-30:
| Run | Prime | Result |
|---|---|---|
| Hosted RL, reverse-text, 10 steps (`prime train --pr 4244 --image-tag
v0.10.1.dev143`) |
[u68lwuthm9f7e87fxb2pnq5f](https://app.primeintellect.ai/dashboard/training/u68lwuthm9f7e87fxb2pnq5f)
| COMPLETED by the platform; trainer and orchestrator attached via
`$RUN_ID` |
| Hosted SFT, fake data, online evals every 5 steps |
[uvmvu17v6bks0kbip83xubnd](https://app.primeintellect.ai/dashboard/training/uvmvu17v6bks0kbip83xubnd)
| COMPLETED; online evals at steps 0, 5, 10 in the same run |
| Local `rl`, reverse-text, 5 steps |
[g4n7oc8hqhz2pfqfi5hj9nno](https://app.primeintellect.ai/dashboard/training/g4n7oc8hqhz2pfqfi5hj9nno)
| COMPLETED by the launcher; W&B run has the same id |
| Local `sft`, 10 steps, evals every 5 |
[dxz2k1etkdbh3go026y96td4](https://app.primeintellect.ai/dashboard/training/dxz2k1etkdbh3go026y96td4)
| COMPLETED by the launcher; eval metrics at steps 0, 5, 10 |
| Local `eval` |
[evaluation](https://app.primeintellect.ai/dashboard/evaluations/mqbd7zx0ub6m6xnua15uerpq)
| exit 0 |
On hosted runs the platform stores the submitted TOML as the run's
config; the full resolved config is registered for local and SLURM
launches only.
Run ownership:
- Local RL, 3 steps:
[qxnhsl4ngd9qocvlcqzbbquw](https://app.primeintellect.ai/dashboard/training/qxnhsl4ngd9qocvlcqzbbquw)
COMPLETED. The orchestrator only flushed; the launcher finished the run.
- `run_owner` with a step that exits 0:
[sppd7r2l1kdposmws2tarp8g](https://app.primeintellect.ai/dashboard/training/sppd7r2l1kdposmws2tarp8g)
COMPLETED.
- SIGTERM to `run_owner` while the step runs: the step received the
forwarded TERM and finished a 2 s teardown before the owner exited 143;
[rfev5w1qbxnxlko6dwd22apt](https://app.primeintellect.ai/dashboard/training/rfev5w1qbxnxlko6dwd22apt)
FAILED with `RuntimeError: SLURM terminated the job`.
- `uv run rl @ examples/basic/reverse-text/rl.toml --max-steps 3
--no-monitors.wandb`, local:
[vtcuhcp16vigkskxu02d763l](https://app.primeintellect.ai/dashboard/training/vtcuhcp16vigkskxu02d763l)
COMPLETED. Its `run_config` on the platform has `trainer`, `inference`,
`orchestrator` and `deployment`.
- Multi-node dry runs: `rl.json` loads as a multi-node `RLConfig` and
registers `trainer`, `inference`, `orchestrator`, `deployment` and
`slurm`. `sft.json` loads as a multi-node `SFTConfig`, and the script's
`TRAIN_CONFIG_PATH` is `trainer.json`.
- Multi-node RL and SFT dry runs
(`examples/advanced/qwen3-30b-a3b/math.toml`, `.../sft/h200/base.toml`)
render scripts that pass `bash -n`. `run_owner` loads the configs the
scripts point to.
- `run_owner rl <orchestrator.json> bash -s <<'STEP_SH' ... exit 3`: the
step saw `RUN_ID=PRL_RUN_ID=<id>`, the wrapper exited 3, and Prime shows
run `ekc8dcf8agutxcrizts1bkbe` FAILED with `RuntimeError: The SLURM job
step exited with code 3`.
- SIGTERM to a running `run_owner`: exit 143, and Prime shows run
`q4g9hv95qoqsl06yeacle2jd` FAILED with `RuntimeError: SLURM terminated
the job`.
- `test_slurm_run_owner_fails_the_run_with_its_step`: the owner
registers the run (not attached), exports its id, and fails the run only
when the step fails.
Latest head, local reverse-text:
| Run | Prime run | Status |
|---|---|---|
| `uv run rl @ examples/basic/reverse-text/rl.toml --max-steps 5
--no-monitors.wandb` |
[kbv529xg6xoop15a0yf7ijwq](https://app.primeintellect.ai/dashboard/training/kbv529xg6xoop15a0yf7ijwq)
| COMPLETED |
| `uv run sft @ examples/basic/reverse-text/sft.toml --max-steps 10
--eval.interval 5 --no-ckpt` |
[bwd98te1u76s82qqrloaty8i](https://app.primeintellect.ai/dashboard/training/bwd98te1u76s82qqrloaty8i)
| COMPLETED; trainer and online eval attached via `$RUN_ID` |
| `uv run eval @ configs/debug/eval/single-turn.toml` |
[evaluation](https://app.primeintellect.ai/dashboard/evaluations/os36zxdjeqhacgls2oz5xy6j)
| banner shows the evaluation link |
Earlier head, with episode counts and the failure path:
| Run | Prime link | Local = Prime episodes | Arrival → ingested (p50 /
max) | Status |
|---|---|---|---|---|
| `uv run sft @ examples/basic/reverse-text/sft.toml --max-steps 10
--eval.interval 5 --no-ckpt` | [training
run](https://app.primeintellect.ai/dashboard/training/neakqq9sbr4s4o0942oeb2ys)
| 96 eval (3 epochs × 32) | 1.0 s / 1.9 s | COMPLETED |
| `uv run rl @ examples/basic/reverse-text/rl.toml --max-steps 5
--no-monitors.wandb` | [training
run](https://app.primeintellect.ai/dashboard/training/fnog09c4s2updmlso4omjoh7)
| 707 train + 512 eval | 1.0 s / 1.8 s | COMPLETED |
| Failure path: the RL run above, with the trainer killed (`SIGKILL`)
mid-run | [training
run](https://app.primeintellect.ai/dashboard/training/eb0gmivb9a0glvrfj4b4bmoc)
| — | — | FAILED: `RuntimeError: Trainer failed with exit code -9` |
- **SFT run:** the trainer and the online-eval process both logged
`Logging metrics and episodes to Prime run neakqq9sbr4s4o0942oeb2ys
(...) (attached via $RUN_ID)`.
- **RL run:** the orchestrator attached through `$RUN_ID`. An episode
read back from Prime Traces carries `run.id = fnog09c4s2updmlso4omjoh7`,
so `PRL_RUN_ID` is the Prime id.
- **Failure path:** components attach to the launcher's run, and the SDK
skips a failed finish from an attached run. So the launcher marks the
run failed itself, with the component's error.
- **Unit tests:** `pytest tests/unit --ignore=tests/unit/train
tests/unit/train/sft/test_prime_monitor.py`: 810 passed, with main
merged.
- **Hosted:** not run on this head. #4318, which unblocked hosted RL on
main, has merged.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes run identity, Prime lifecycle ownership, and multi-node SLURM
wiring; custom templates or mixed monitor settings can break tracking or
fail validation.
>
> **Overview**
> **Unifies Prime and monitor configuration** so training uses one
platform run and one config shape everywhere.
>
> **Prime:** `PrimeTrainMonitor` / `PrimeEvalMonitor` and separate
train/eval monitor config types become **`PrimeMonitor`** and shared
**`MonitorsConfig`**. The **`rl`/`sft` launcher** (or multi-node
**`run_owner`**) **registers** the platform run via **`launch_run`**,
sets **`PRL_RUN_ID` / `RUN_ID` / W&B run id**, and **finishes or fails**
the run when the launch ends; worker processes **attach** and only
flush. RL registration sends the **full RL config**, not
orchestrator-only. **SFT online evals** now upload metrics and episodes
to that same training run instead of opening per-epoch Prime
evaluations; standalone **`uv run eval`** still opens one evaluation per
env/epoch.
>
> **Launch / SLURM:** Bundled multi-node templates wrap the job step in
**`python -m prime_rl.entrypoints.run_owner`**. Multi-node SFT writes
full **`sft.json`** for the owner and **`trainer.json`** for torchrun.
**`run_links`** takes **`MonitorsConfig`**; link records use **`prime`**
/ **`wandb`** keys.
>
> **Other:** RL validates **`monitors.wandb`** and **`monitors.file`**
are on or off consistently on trainer and orchestrator. Orchestrator
file-monitor **`producer`** is **`orchestrator`** (annotation path
rename). Docs/skills updated accordingly.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7e0c55fc313db82c95f6f80e0a24aa3e3b0bdefd. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Problem
On `main`, a compiled trainer run of a GatedDeltaNet model (Qwen3.5 /
Qwen3.8) with the W&B monitor on dies on the first forward:
```
torch._dynamo.exc.InternalTorchDynamoError: RuntimeError: dictionary changed size during iteration
```
It reproduces every time, with a single thread:
1. FLA's `tensor_cache` wraps `prepare_chunk_indices`, which
`causal_conv1d` calls from `GatedDeltaNet.forward`. Its
`cache_disabled()` does `sys.modules.get('fla.utils')`
(`fla/utils/decorators.py:61`), so Dynamo wraps all of `sys.modules`
while tracing.
2. Dynamo walks the live `sys.modules.items()` and runs an `isinstance`
check on every module.
3. `wandb.init` leaves a lazy `azure.storage.blob` placeholder in
`sys.modules`: wandb's `util.get_module` returns a `LazyModule` by
default. `azure-storage-blob` is in the lock through
`runai-model-streamer-azure`.
4. The `isinstance` check runs the placeholder's `__getattribute__`,
which imports `azure.storage.blob` for real. About 144 modules
(`azure.*`, `cryptography`, `isodate`, ...) land in `sys.modules`
mid-walk, and the trace aborts.
CI misses it: the GPU integration tests train Qwen3-0.6B or
mini-glm-moe, and the regression test runs without W&B.
## Fix
`apply_compile` first loads every lazy module in `sys.modules`, meaning
any `ModuleType` subclass that overrides `__getattribute__`. The
trainers set up monitors before `setup_model`, so W&B's placeholder
already exists when this runs.
The upstream fixes would be for Dynamo to iterate a snapshot instead of
the live view, or for FLA to keep its cache flag out of `sys.modules`.
Until then, this keeps the trace from triggering imports.
## Verification
- Minimal repro, single process, no trainer:
`torch.compile(backend="eager")` over `prepare_chunk_indices` compiles
fine, fails with the error above after
`wandb.util.get_module("azure.storage.blob")`, and compiles again once
`load_lazy_modules()` runs first.
- Qwen3.5-4B LoRA reverse-text RL with `compile` and W&B on, on 2× RTX
PRO 6000 (torch 2.13.0, wandb 0.27.0, FLA 413ad2c): crashed on the first
forward in 5 of 5 runs on `main`; completes with this change, with
Dynamo's 4 wraps of `sys.modules` passing.
Since #3916 (Qwen3.8) and the Qwen3.5 VLM unification, text-only Qwen3.5
(`qwen3_5`, `qwen3_5_moe`) and Qwen3.8 (`qwen4_exp`) composite
checkpoints no longer load in the trainer. These configs have
`language_model_only: true` and a `vision_config`, but their weights
hold only `model.language_model.*` (plus `lm_head`).
**Symptom.** On main, SFT on such a checkpoint fails while loading:
`RuntimeError: Missing key in checkpoint state_dict:
model.visual.blocks.0.attn.proj...`. Meta construction shows the cause:
the model has `model.visual.*` keys that the checkpoint does not contain
(153 for Qwen3.5-0.8B with the vision weights removed, 333 for a 4-layer
Qwen3.8).
**Root cause.** Both composite configs dropped `language_model_only`,
and `vision_config` falls back to a default. `ForCausalLM` sets `is_vlm
= hasattr(config, "vision_config")`, so it always builds the vision
tower.
**Fix (same for both models).** Keep `language_model_only` on the
config. This follows vLLM's `--language-model-only`; official Qwen
configs ship the field. When the flag is set:
- the composite model sets `visual = None` and its forward calls the
language model directly (the injected LM-head forward calls
`model.model(...)`, so the branch lives there);
- `is_vlm` and `supports_packed_multimodal_training` are False.
The flag is kept on the config, so saved configs keep it. Key names stay
`model.language_model.*`, so conversion and the weight names sent to
vLLM do not change. `docs/advanced.md` notes that vLLM does not read the
field, so text-only RL also needs `inference.vllm.language_model_only =
true`.
I did not derive that vLLM setting automatically. The config package
never reads model files (the model can be a Hub id), so doing it there
would mean loading the HF config inside config validation.
**Test.**
- Qwen3.8: the config fixture of `test_model.py` gets a
`language_model_only` case.
- Qwen3.5: a meta test checks that a `language_model_only` config has no
vision encoder and only `model.language_model.*` / `lm_head` keys.
GPU (H200):
- Qwen3.5-0.8B with the vision weights removed and `language_model_only:
true`: SFT fails on main with the missing-key error. With the fix, SFT
runs 8 steps.
- Qwen3.8, 4 layers, text-only: SFT on 4 GPUs, 8 steps, loss 12.88 ->
10.98. RL with vLLM `language_model_only = true` (4 trainer / 4
inference GPUs, NCCL broadcast) runs 6 steps, sending 133 layer state
dicts per step, mismatch KL 0.075-0.09.
- VLM checkpoints (Qwen3.5-0.8B and a tiny Qwen3.8) with `[model.vlm]`:
the vision encoder is still built, frozen and wrapped with FSDP.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes Qwen3.5/Qwen3.8 model construction and checkpoint loading
paths; behavior is scoped to the `language_model_only` flag with new
unit coverage, but mistakes could affect weight loading or VLM vs
text-only routing.
>
> **Overview**
> Fixes loading and training for **text-only** Qwen3.5 / Qwen3.8
composite checkpoints that still carry a `vision_config` but only
`model.language_model.*` weights (official `language_model_only: true`
in `config.json`).
>
> **Trainer behavior:** The flag is preserved on `Qwen3_5Config` and
`Qwen3_8FlashNextConfig` instead of being dropped. Composite
`ForCausalLM` models now treat VLM mode as `vision_config` present
**and** not `language_model_only`; the composite wrapper skips building
`visual`, forwards through the language model only, and clears `is_vlm`
/ packed multimodal support. `init_buffers_post_meta` uses
`get_language_model` so buffer setup still targets the decoder when the
wrapper is composite but text-only.
>
> **Docs:** Notes that vLLM ignores the HF field, so text-only RL must
set `inference.vllm.language_model_only = true`.
>
> **Tests:** Qwen3.5 meta test asserts no vision encoder and state dict
keys under `model.language_model.*` / `lm_head`; Qwen3.8 config fixture
adds a `language_model_only` variant.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f30d782233f0148685dbd5c42594ecb9a561bad7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Problem
Training `Qwen/Qwen3.5-4B` (and other small Qwen3.5 checkpoints with
`tie_word_embeddings: true`) learns nothing: from step 1 the trainer
logs **entropy = 12.4225 = ln(vocab_size)**, **grad norm 0.0000**, and
**mismatch KL ≈ 11**, every step.
Those checkpoints ship no `lm_head.weight`. `load_dcp_from_hf` pops
`lm_head.weight` from the state dict when `tie_word_embeddings` is set,
on the assumption that the model ties it. `Qwen3_5ForCausalLM` builds a
separate `VanillaOutputLinear` and never ties it, so the head stays at
its meta-device init (zeros). The result is uniform logits and zero
gradients through the head.
With full fine-tuning it also breaks inference: vLLM ties `lm_head` to
`embed_tokens`, so the trainer's startup weight broadcast writes the
zero head into the shared tensor, and the policy then emits token 0 at
logprob −ln(vocab) from the first rollout.
## Fix
- When `config.tie_word_embeddings` is set, share the input embedding's
weight with `lm_head` at construction. `inject_prime_lm_head` already
carries `old_lm_head.weight` over to the injected head, so the tie
survives injection, and `shard_norm_and_lm_head` already skips separate
sharding for tied models.
- `load_dcp_from_hf` now asserts that a tied model's `lm_head` is its
input embedding before dropping `lm_head.weight`, so any model that
misses the tie fails at startup instead of training silently with an
unloaded head.
## Verification
- `test_tied_word_embeddings_share_lm_head` builds a tied Qwen3.5 VLM
config on the meta device (no CUDA, runs in the CPU unit job): passes
with the fix, fails on `main`.
- Qwen3.5-4B through `setup_model` on one GPU: per-token logprobs match
HF transformers (mean |Δ| 0.012 nats vs 10.7 on `main`). With the fix
reverted, the new assertion fires at load; tied Qwen3-0.6B and
Qwen3.5-4B + LoRA load normally.
- 8-step reverse-text RL on Qwen3.5-4B, 2× RTX PRO 6000 (trainer
`compile` off):
- LoRA: `main` logs entropy 12.4225, mismatch KL 9–11, grad norm 0 at
every step; with the fix, entropy 2.5 → 1.7, staleness-0 mismatch KL ≈
0.003, reward 0.41 → 0.56.
- Full fine-tune: on `main` the policy outputs `!!!!` after the startup
broadcast and no batch is ever admitted; with the fix it trains and
staleness-0 mismatch KL stays 0.002–0.004 across weight updates.
- In a LoRA RL run on Qwen3.5-4B, 2× A6000: before, entropy 12.42,
mismatch KL 11.3, grad norm 0. After, entropy 0.08, mismatch KL 0.0001,
grad norm 0.007, and the run trains normally.
Co-authored-by: hallerite <git@hallerite.com>
The SFT and RL trainers saved each in-loop checkpoint before adding the
step to `progress.total_tokens` and `progress.total_samples`. A resume
from such a checkpoint starts the counters one batch behind an
uninterrupted run, and they stay behind. The final checkpoint, written
after the loop, was already correct.
- **SFT:** `progress/num_tokens` stays one batch behind for the rest of
the run. `progress/num_samples` recovers after the first resumed step,
because it is re-read from the dataloader.
- **RL trainer:** both counters stay one batch behind. They are printed
in the resume log line ("Resuming from step N (total_tokens=…,
total_samples=…)") and saved in every later checkpoint. RL's
`progress/total_tokens` metric comes from the orchestrator, which
already updates its totals before checkpointing, so the logged metric
was correct.
The fix counts the step before the checkpoint block in both trainers, as
the orchestrator does. Training, data order and the dataloader state are
unchanged; only the saved counters move.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Reorders when existing counters are updated relative to checkpoint
I/O; no change to training math, data, or checkpoint format fields.
>
> **Overview**
> **Both SFT and RL training loops now update `progress.total_tokens`
and sample counters immediately after the optimizer step, before any
in-loop checkpoint write.**
>
> Previously those totals were incremented only after checkpointing (and
related logging), so checkpoints captured counters that omitted the step
just finished. Resuming from such a checkpoint left **`total_tokens` one
batch behind** for the rest of the run; RL also kept **`total_samples`
behind**, affecting resume logs and every subsequent checkpoint. SFT’s
sample count could catch up on the first post-resume step because it is
refreshed from the dataloader, but token totals did not.
>
> The moved block is unchanged in logic—same DP all-reduce over local
tokens/FLOPs—only its position relative to `ckpt_manager.save` changes,
matching the orchestrator’s ordering. Training data, step order, and
dataloader state are unaffected.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e67f0253012f9b0bbc252804f1038fbdbdff2c11. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Follow-up to #4211. It keeps the custom-op structure, the CUDA-only
dispatch and the eager CPU path, and replaces the kernels with a fused
read kernel that is more accurate and moves less memory. It also fuses
the attention's `combine` into the MLP's `mix`.
**Changes**
- **Precision.** The projection GEMM runs on the unnormalized streams
with the norm gain folded into `[down; inject]`, in fp32 (one cuBLAS
`bmm` over the streams). Each stream's rstd scales its rows afterwards.
`n` and the up logits are never rounded to bf16: the mix kernel
recomputes the logits per tile in fp32 registers and normalizes in
registers. #4211 rounds `n`, the `(tokens, 328)` projection and the up
logits to bf16.
- **Fewer HBM passes.** Forward: an rstd kernel, the `bmm`, a small
gates kernel and the mix kernel. Only the output has size `(tokens,
hidden)`, and nothing of size `(tokens, 4 x 2560)` is written. Backward:
two Triton kernels recompute the logits in-tile (one for the gate
gradient, one for the stream and norm gradient), and cuBLAS computes the
weight gradients in fp32. It keeps #4211's 16,384-token chunks.
- **`mix(x, pending_combine)`.** The previous sublayer's `combine` (`x +
block_output * injection` per stream) runs inside the rstd pass, and its
backward runs in one kernel. The decoder layer uses this for the
attention -> MLP hand-off. That is one call site, and the layer's
interface does not change.
- `fused_hc_mix` keeps #4211's signature; `fused_hc_combine_mix` is new.
The kernels now live in `kernels/qwen3_8_hyper_connection/`
(`kernels.py`, `launch.py`, `ops.py`). On CPU, `mix` applies a pending
combine eagerly.
**Not included (possible follow-up):** handing each layer's last combine
to the next layer's first mix. It would save one more combine pass per
layer. But it puts the block output and the injection weights into every
checkpointed layer input under full AC: +1/4 of the streams, about 7 GiB
at 48 layers x 30k tokens per GPU.
## Numerics
32,768 tokens, bf16 inputs and weights (`hidden 2560, 4 streams, rank
320`), forward + backward. Mean relative error vs an fp64 evaluation of
the same math (`mean|err| / mean|ref|`, x1e-3). "eager" is
`HyperConnection`'s eager path in bf16; "eager compiled" is the same
under `torch.compile`.
`mix`:
| tensor | eager bf16 | eager compiled | #4211 | this PR |
|---|---:|---:|---:|---:|
| block input | 3.17 | 2.20 | 2.20 | 1.42 |
| injection weights | 1.48 | 1.48 | 1.48 | 1.47 |
| grad streams | 3.04 | 1.46 | 2.35 | 1.45 |
| grad norm weight | 3.78 | 1.48 | 2.89 | 1.47 |
| grad down | 5.02 | 4.08 | 4.08 | 3.32 |
| grad up | 5.03 | 4.09 | 4.09 | 3.29 |
| grad inject weight | 4.07 | 3.27 | 2.78 | 2.30 |
`combine + mix` (the #4211 column uses a compiled `combine`):
| tensor | eager bf16 | eager compiled | #4211 | this PR |
|---|---:|---:|---:|---:|
| block input | 2.63 | 2.03 | 2.03 | 1.76 |
| injection weights | 1.49 | 1.49 | 1.48 | 1.48 |
| combined streams | 1.84 | 1.41 | 1.41 | 1.41 |
| grad streams | 1.48 | 1.41 | 1.46 | 1.41 |
| grad block output | 2.68 | 2.15 | 2.17 | 2.15 |
| grad injection in | 2.85 | 2.28 | 2.30 | 2.29 |
| grad norm weight | 4.28 | 2.31 | 3.30 | 2.31 |
| grad down | 5.87 | 4.73 | 4.73 | 4.09 |
| grad up | 5.85 | 4.73 | 4.72 | 4.06 |
| grad inject weight | 4.66 | 3.71 | 3.26 | 2.86 |
This PR has the lowest mean error for every output and gradient, at 16k,
32k and 65k tokens. The only exception is the gradient of the incoming
injection weights, which ties with eager compiled (within 0.2%). The
largest error (`max|err| / max|ref|`) is below #4211's everywhere except
two `combine + mix` gradients at 65k tokens: the block output (3.65e-3
vs 3.61e-3) and the incoming injection weights (2.81e-3 vs 2.78e-3). The
test tolerance is #4211's: relative L2 error < 1e-2 vs the CPU fp32
eager reference.
## Isolated HC microbenchmark (1x H100 80GB)
Same shape, one call, CUDA events, median of 20. Cells are fwd / bwd /
fwd+bwd in ms; the last column is #4211's fwd+bwd time over this PR's.
| tokens | call | eager | eager compiled | #4211 | this PR | #4211 ÷
this PR |
|---:|---|---:|---:|---:|---:|---:|
| 16,384 | mix | 3.88 / 9.55 / 13.43 | 1.05 / 3.62 / 4.67 | 0.97 / 2.51
/ 3.48 | 0.89 / 2.58 / 3.47 | 1.00x |
| 16,384 | combine + mix | 4.66 / 11.07 / 15.73 | 1.18 / 4.03 / 5.21 |
1.21 / 3.13 / 4.34 | 1.05 / 2.84 / 3.88 | 1.12x |
| 32,768 | mix | 7.68 / 18.94 / 26.61 | 2.06 / 7.16 / 9.22 | 1.83 / 4.97
/ 6.80 | 1.64 / 5.25 / 6.89 | 0.99x |
| 32,768 | combine + mix | 9.18 / 21.95 / 31.13 | 2.55 / 8.01 / 10.55 |
2.31 / 6.20 / 8.51 | 1.95 / 5.69 / 7.63 | 1.12x |
| 65,536 | mix | 15.25 / 37.01 / 52.27 | 3.99 / 13.57 / 17.56 | 3.53 /
9.88 / 13.41 | 3.08 / 10.50 / 13.58 | 0.99x |
| 65,536 | combine + mix | 18.24 / 43.02 / 61.26 | 4.98 / 15.32 / 20.30
| 4.51 / 12.35 / 16.86 | 3.70 / 11.42 / 15.12 | 1.11x |
| tokens | call | saved after forward (GiB): eager / compiled / #4211 /
this PR | peak over fwd+bwd (GiB): eager / compiled / #4211 / this PR |
|---:|---|---|---|
| 16,384 | mix | 1.97 / 0.72 / 0.09 / 0.10 | 3.84 / 1.65 / 1.42 / 1.25 |
| 16,384 | combine + mix | 2.29 / 1.04 / 0.40 / 0.42 | 4.15 / 1.97 /
1.73 / 1.57 |
| 32,768 | mix | 3.95 / 1.45 / 0.18 / 0.20 | 7.67 / 3.29 / 2.18 / 1.74 |
| 32,768 | combine + mix | 4.57 / 2.07 / 0.80 / 0.83 | 8.29 / 3.92 /
2.81 / 2.36 |
| 65,536 | mix | 7.89 / 2.89 / 0.35 / 0.40 | 15.33 / 6.58 / 3.00 / 2.60
|
| 65,536 | combine + mix | 9.14 / 4.14 / 1.60 / 1.65 | 16.58 / 7.83 /
4.26 / 3.85 |
A plain `mix` takes about the same time as #4211's: the forward is 8-13%
faster, the backward 3-6% slower at rank 320. A `combine + mix` is
11-12% faster. Saved activations are higher because the projection is
kept in fp32: +0.6 KB per token per call, i.e. +13-18% for a plain `mix`
and +3-4% for `combine + mix`, whose saved tensors include the combined
streams. The transient peak is 0.17-0.45 GiB lower.
## RL trainer steps (1 node, 8x H100 80GB)
#4211's setup on H100 instead of H200: `Qwen/Qwen3.8-Flash-Next` config
with `model.debug.num_layers = 8`, `random_init`,
`force_balanced_routing`, n-gram table cut to 200K rows
(`ngram_vocab_size_base = 200000`), EP8, `moe.dispatch = "torch"`,
compiled, FSDP; "full AC" is `ac.mode = "full"` with the default
activation offloading. Fake packed samples
(`data.fake.generate_samples`, batch 16, i.e. 2 micro-batches per GPU),
the trainer's default env (`expandable_segments:True`). One warm-up run,
then 3 interleaved runs per arm. Median over steps 3-12 (AC on) or 4-12
(AC off), then over runs; range over runs in brackets.
| config | main (#4211) step | tok/s | peak | this PR step | tok/s |
peak | Δ tok/s |
|---|---:|---:|---:|---:|---:|---:|---:|
| 32k tokens per GPU, full AC | 6.46 s | 81.2k (81.0-81.5k) | 66.6 GiB |
6.35 s | 82.5k (82.5-82.6k) | 66.7 GiB | +1.7% |
| 16k tokens per GPU, no AC | 2.79 s | 93.8k (93.8-94.0k) | 71.9 GiB |
2.78 s | 94.2k (94.1-94.5k) | 72.3 GiB | +0.4% |
- Entropy and mismatch KL match main to 4 decimals on every step in both
configs.
- With full AC the forward runs twice, and that is where the gain comes
from. Without AC the difference is within noise, and the peak is 0.4 GiB
higher. The fp32 projection accounts for about 0.16 GiB of that (16
calls x 16k tokens x 0.6 KB).
- Step 1 (with compilation) is unchanged: 25 s vs 25 s (AC on).
- The isolated HC numbers transfer to the step only partly: HC is a
small share of a Qwen3.8 layer.
## Tests
-
`tests/unit/train/models/qwen3_8_flash_next/test_model.py::test_fused_hyper_connection_matches_eager`
(gpu): fused CUDA bf16 vs eager CPU fp32, forward and backward,
with/without injection, with/without a pending combine. It runs at three
shapes (`4 x 2560` rank 320, `4 x 1024` rank 128, `3 x 200` rank 24)
with the backward chunk set to 256 tokens, so several chunks run and the
last one is partial. All 12 cases pass on H100 (the whole file: 24
passed).
- `-m "not gpu"` unit tests pass, except `test_cpu_adam`, which fails
the same way on main in this environment. ruff 0.15.14 check + format
clean.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Training forward/backward math for Qwen3.8 hyper-connections is
replaced with new fused CUDA kernels and a cross-sublayer fusion path,
though behavior is guarded by expanded GPU parity tests against eager
fp32.
>
> **Overview**
> Replaces the single-file Qwen3.8 hyper-connection CUDA path with a
**`kernels/` / `launch` / `ops`** package and a **rewritten fp32 read**:
projection runs as one fp32 stream `bmm` with norm gain folded into
`[down; inject]`, gate logits are recomputed in Triton tiles instead of
storing bf16 intermediates, and backward uses new gate/stream/write
kernels with H100-tuned launch configs.
>
> Adds **`fused_hc_combine_mix`** (custom op `qwen3_8_hc_write_read`) so
the previous sublayer’s **combine** (`streams + block_output * inject`)
runs inside the rstd pass before the next **mix**.
**`HyperConnection.mix`** accepts optional **`pending_combine`**; the
decoder applies this on the **attention → MLP** hand-off so the explicit
attn `combine` is dropped from the layer forward. **`fused_hc_mix`**
keeps the same public signature; imports move to **`...ops`**.
>
> Unit tests broaden **`test_fused_hyper_connection_matches_eager`**
(multiple shapes, pending combine, chunked backward).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2e60a99efec8a5cb40cba760dfb666ae5d6f53cd. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Folds the trainer's multimodal code into one module, keeps one VLM
registry, and removes VLM config fields that nothing reads.
## What changes
- **One module.** `src/prime_rl/multimodal/` (5 files),
`trainer/multimodal.py`, `utils/vlm.py` and `setup_processor` (from
`model.py`) become `src/prime_rl/trainer/vlm.py`: `get_vision_encoder`,
`get_language_model`, `get_layer_prefix`, `load_image`,
`setup_processor`.
- **Image processing lives on the model.** Each VLM class exposes
`materialize_images(refs, processor)`; the RL trainer calls
`model.materialize_images`, so a new VLM family brings its own. Qwen3.5
and Qwen3.8 Flash Next each define `materialize_qwen_vl_images` in their
own `vision.py` (the packages stay self-contained), which runs the
Qwen-VL image processor and checks placeholder lengths against vLLM; the
family-agnostic data-URL decoding is `load_image` in `trainer/vlm.py`.
- **Deleted:** `ForwardPolicy`, `MaterializedMM`, the
`MultimodalAdapter` Protocol and its registry, and the Kimi K2.5 /
Qwen3-VL image paths. No Kimi K2.5 or Qwen3-VL trainer model exists, so
`get_model` already rejected them.
- **One VLM registry.** `_CUSTOM_VLM_MAPPING`
(`trainer/models/__init__.py`) is the only one; `VLM_REGISTRY` and
`is_vlm_architecture` are gone. The vision encoder, language model and
NCCL layer prefix come from the model layout: `model.model.visual` and
`model.model.language_model`, with `model.model` for text models (Muse
Glimmer, Qwen3.8 Flash (`qwen4_exp`) and GLM-5.3 Flash (`glm5_next`)
resolve the same way; they load no vision tower).
- **Qwen3.5 VLM owns its positions and CP.** The model builds MRoPE
positions whenever `image_grid_thw` is given; `forward()` always passes
`position_ids`, used only for text-only rows. RL and SFT defer CP to the
model for every batch with images. `setup_context_parallel` refuses `cp
> 1` for a VLM without `cp_context`.
- **Config (breaking).** `[model.vlm]` keeps only
`freeze_vision_encoder`; `vision_encoder_attr` / `language_model_attr`
and `orchestrator.model.vlm` are removed (the orchestrator detects
images from message content). `vlm` moves to the trainer `ModelConfig`
and the shared `[model.vlm]` propagates only to `trainer.model.vlm`. The
VLM bfloat16 `optimization_dtype` / `reduce_dtype` validator is removed.
Old keys fail with "Extra inputs are not permitted".
Migration: delete `vision_encoder_attr` / `language_model_attr` and any
`[orchestrator.model.vlm]` block.
## Behavior
Training is unchanged for every trainable VLM (Qwen3.5 dense and MoE):
same MRoPE positions, same CP shards, same component lookup. Configs
with fp32 dtypes and `[model.vlm]` are no longer rejected.
## Checks
- `pytest -m "not gpu" tests/unit/orchestrator
tests/unit/test_configs.py tests/unit/train tests/unit/utils` after
merging main (1810d5b9a): 651 passed. `ruff check` / `ruff format
--check`: clean. No dependency changes.
- CPU, main vs this branch, tiny Qwen3.5 VLM through the trainer
`forward()`: embeddings, positions and logits reaching the decoder are
bit-identical for an image batch at cp=1 and ulysses cp=2, and for a
text-only batch.
- GPU, 1×H200, VLM SFT Qwen3.5-0.8B, 6 steps on image+text samples at
cp=1 and ulysses cp=2: main and this branch match to 1e-4 on every step.
| run | loss step 1 → 6 | grad norm step 1 → 6 |
|---|---|---|
| main and branch, cp=1 / cp=2 | 12.4225 → 12.1251 | 24.88 → 28.88 |
RL with images is not GPU-validated here: the nightly multimodal RL
config stops on main and on this branch with the orchestrator error that
#3949 fixes. #3949 and this PR share no files.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking VLM config and a broad trainer refactor (FSDP, NCCL
broadcast, CP, RL micro-batch prep), though trainable Qwen3.5 paths were
validated for numerical parity.
>
> **Overview**
> **Breaking config:** `[model.vlm]` now only has
`freeze_vision_encoder`. Remove `vision_encoder_attr` /
`language_model_attr` and any `[orchestrator.model.vlm]` block. Shared
`[model.vlm]` propagates to the trainer only. SFT no longer requires
`optimization_dtype` / `reduce_dtype` bfloat16 for VLM runs.
>
> **Architecture cleanup:** Deletes `prime_rl/multimodal/`,
`utils/vlm.py` (`VLM_REGISTRY`, per-family attr overrides), and
`ForwardPolicy` / `MultimodalAdapter` (including Kimi paths). VLM
helpers live in **`trainer/vlm.py`** (encoder/LM lookup, `load_image`,
`setup_processor`). Vision and LM modules are resolved from a fixed
layout: `model.model.visual` and `model.model.language_model`.
>
> **RL image prep:** Each custom VLM exposes **`materialize_images(refs,
processor)`** (Qwen3.5 / Qwen3.8 implement `materialize_qwen_vl_images`
in their `vision.py`). The RL data path calls `model.materialize_images`
instead of a global adapter registry.
>
> **Forward / CP:** Trainer **`forward()`** always passes
`position_ids`; Qwen VLMs build MRoPE only when `image_grid_thw` is set.
Context parallelism defers sharding to the model for any batch with
`mm_kwargs`, and **`setup_context_parallel`** errors if a VLM lacks
`cp_context` with `cp > 1`.
>
> Docs and example TOMLs are updated to match.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bba40041de2751cc3239e14ca91888cab52c7fe3. 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: Hubert <163992334+hubert-marek@users.noreply.github.com>
Co-authored-by: Hubert Pyskło <hubert@uni.minerva.edu>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This PR computes the mHC pre-pass projection and per-token sum of
squares with DeepGEMM's `tf32_hc_prenorm_gemm`, the kernel vLLM uses for
DeepSeek V4's mHC, and keeps the existing fused Triton op for the
collapse and the backward. The forward drops from 5.5 ms to 0.6 ms at
31k tokens per GPU on H200 under `matmul_precision = "highest"`.
- Under `"highest"` the forward projection now runs in TF32, as [vLLM's
does](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/model_executor/kernels/mhc/tilelang.py#L22-L72)
(v0.32.0), instead of IEEE fp32. With bf16 weights and bf16 streams, as
in training, TF32 holds both inputs exactly, so only the fp32
accumulation differs.
- The backward still follows `matmul_precision`.
- DeepGEMM takes at most 32 outputs in multiples of 8, so the 4-output
`DeepseekV4HyperHead` keeps the in-kernel projection.
- The weight is upcast to fp32 for DeepGEMM, since FSDP hands it over in
bf16.
- The split count is bucketed to 1, 4 or 16 as in vLLM, so DeepGEMM
compiles at most three variants of the GEMM (21 without bucketing on
H200).
#4216 fused this input side so the fp32 normalized streams are no longer
stored, saving 8 to 10 GiB of activations per layer at 64k tokens. Its
timings and numerics checks ran at `"high"`, where it was faster than
before. Under `"highest"`, which production RL uses to match inference,
its `tl.dot` runs as an IEEE fp32 loop on CUDA cores, so the forward
ended up slower than the compiled code it replaced, which projected
through cuBLAS. This PR keeps #4216's memory savings and removes that
slowdown.
| mHC input side, 31k tokens, H200, fp32 weights | `"highest"` fwd /
fwd+bwd | `"high"` fwd / fwd+bwd |
|---|---|---|
| before #4216 (compiled) | 2.01 / 6.77 ms | 1.69 / 5.67 ms |
| #4216 | 5.50 / 9.70 ms | 1.39 / 4.47 ms |
| this PR | 0.60 / 4.79 ms | 0.60 / 3.67 ms |
With bf16 weights, as FSDP passes them in training, this PR measures
0.61 / 4.87 ms under `"highest"` and 0.69 / 3.59 ms under `"high"`.
End to end, we ran a trainer-only proxy on one 8x H200 node: a DeepSeek
V4 Flash checkpoint cut to 6 layers, cp 8, ep 8, FP8, `"highest"`,
262,144-token micro batches, 8 per step, 20 steps, each arm against a
baseline on the same node. Medians over steps 4 to 20:
| node | main fwd+bwd per step | this PR | change |
|---|---|---|---|
| H200 node A | 17.45 s | 16.52 s | -5.3% |
| H200 node B | 17.35 s | 16.45 s | -5.2% |
Entropy matches the baseline and peak memory drops from 125.0 to about
121.4 GiB. That is about 19 ms per layer per micro batch, so the full
43-layer model should save about 0.8 s of its roughly 16 s per micro
batch on H200, about 5%.
## Verification
- `uv run pytest
"tests/unit/train/models/test_deepseek_v4_kernels.py::test_fused_mhc_pre_matches_reference"`
on H200: all 36 pass, the fp64 reference test for 4 and 24 outputs, fp32
and bf16 weights, and hidden sizes 96, 128 and 512, which reach DeepGEMM
split counts 1, 4 and 16.
- In the end-to-end runs, DeepGEMM's JIT cache holds
`sm90_tf32_hc_prenorm_gemm`, so the new path runs inside the model.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Builds on #3890 (by @zhengluo-nv) to test ModelExpress weight broadcast
end to end; their PR is untouched. This branch is #3890 rebased on main
plus:
- **MX client pin**: follows #3890's 957eda8 (cherry-picked):
`modelexpress==0.8.0.dev20261022` from PyPI, the nightly built from
ai-dynamo/modelexpress `446feec` (main after #886; includes TrainerMesh
#835, transfer-plan reuse #882, coarser replay descriptors #885 and
quantized bounded streaming #889). The same commit fixes a stable mesh
`idempotency_key` and passes `roles` when pausing engines for an MX
update. The benchmarks below ran at `f24c721`.
- **MX server**: `scripts/install_modelexpress.sh` builds the matching
`modelexpress-server` at `446feec` (+ Redis), bootstrapping Rust and
`protoc` when the host has none.
- **`uv run rl`**: starts a run-scoped MX server + Redis when
`weight_broadcast.type = "modelexpress"` (logs in `logs/modelexpress/`).
- **SLURM**: the multi-node template launches the MX server on the
trainer head node for `modelexpress` as it already did for `nixl`.
Dropped `--database-path`, which the current server no longer accepts.
The template flag `uses_modelexpress_server` covers both transports,
since both rendezvous through the MX server; the UCX checks stay
`nixl`-only.
- **Receiver conversion fix**: the vLLM worker builds its PrimeRL-to-HF
conversion chain from the PrimeRL config class instead of vLLM's
`hf_config`; the transformers class lacks PrimeRL-only fields such as
DeepSeek-V4's `layer_types`, so `init_broadcaster` failed for that
model.
- **Weight-version labels**: `/update_weights_from_modelexpress` sets
the engine weight version like `/update_weights` does on main, and MX
updates record pause/transfer/resume times for the watcher gauges.
- **CI**: new `tests/integration/test_reverse_text_modelexpress.py`
(reverse-text, Qwen3-0.6B, 1+1 GPU) added to the `gpu.yml` integration
matrix, with an MX server build step for that job.
- **Docs**: the ModelExpress docs moved from `scaling.md` to their own
page, `docs/model-express.md`.
## Results
### MX nightly `0.8.0.dev20261022` (server `446feec`) on main,
2026-10-26
Same setup as the `f24c721` table below: bounded staging (2 x 4 GiB),
vLLM default `gpu_memory_utilization` (0.9), 10 steps, default
`max_staleness`. Medians in seconds over warm updates 2-9. "Inference
pause" is the orchestrator's per-update wait
(`watcher/last_update_weights_time`); "startup sync" is the v0 transfer,
which includes MX's cold transfer planning.
| Model | Transport | Trainer weight send | Inference pause | Startup
sync | Max mismatch KL |
|---|---|---:|---:|---:|---:|
| Qwen3-30B-A3B (1+1 nodes, TP=2) | NCCL | 5.99 | 4.34 | 4.3 | 0.034 |
| Qwen3-30B-A3B (1+1 nodes, TP=2) | **MX** | **4.14** | **2.25** | 20.4
| 0.028 |
| GLM-4.5-Air (2+1 nodes, TP=8) | NCCL | 14.56 | 7.20 | 6.4 | 0.0033 |
| GLM-4.5-Air (2+1 nodes, TP=8) | **MX** | **9.05** | **3.53** | 24.7
(77 s on the trainer) | 0.0036 |
- MX cuts the inference pause about 2x and the trainer send 30-40% vs
NCCL; mismatch KL matches NCCL.
- Cold planning on the first update dropped from 59 s / 108 s at
`f24c721` to 20 s / 25 s (likely ai-dynamo/modelexpress#885).
- NCCL is also faster on today's main than in the `f24c721` table, so
compare within this table.
### MX `f24c721`, bounded staging (2 x 4 GiB), vLLM default
`gpu_memory_utilization` (0.9)
Run 2026-10-21. *Trainer* = `time/broadcast_weights` median (steps
3-10); *Inference* = inference pause per update
(`watcher/last_update_weights_time`) median; *MX warm* = one inference
GPU's MX update after the first.
| Model | Inference dtype | Transport | Trainer (s) | Inference (s) | MX
warm (s) | Pulled / GPU | Mismatch KL |
|---|---|---|---:|---:|---:|---:|---|
| Qwen3-30B-A3B, TP=2 | BF16 | NCCL | 9.76 | 5.66 | - | - | 0.020-0.033
|
| Qwen3-30B-A3B, TP=2 | BF16 | MX bounded | 9.38 | **2.77** | 1.67 |
40.6 GB | 0.019-0.042 |
| Qwen3-30B-A3B, TP=2 | FP8 per-block (online) | MX bounded | 10.19 |
**3.42** | 1.97 | 40.6 GB | 0.061-0.153 |
| GLM-4.5-Air, TP=8, 2 trainer nodes | BF16 | NCCL | 15.51 | 9.05 | - |
- | 0.002-0.004 |
| GLM-4.5-Air, TP=8, 2 trainer nodes | BF16 | MX bounded | 13.36 |
**3.88** | 2.13 | 89.5 GB | 0.002-0.003 |
| DeepSeek-V4-Flash, TP=8 + EP, 4 trainer nodes | BF16 | NCCL | 26.93 |
24.93 | - | - | 0.011-0.034 |
| DeepSeek-V4-Flash, TP=8 + EP, 4 trainer nodes | BF16 | MX bounded |
fails | fails | - | - | - |
- With #882 the bounded transfer plan is built once (59 s for Qwen3-30B,
108 s for GLM-4.5-Air on the first update) and reused after: warm
updates spend 0.00 s planning, ~1.5-1.9 s on the wire and 0.05-0.08 s
installing (1.4 s with FP8 re-quantization).
- Bounded staging holds 8 GiB per inference GPU, so vLLM runs at its
default memory setting. Full staging OOMs on Qwen3-30B at 0.9 and on
GLM-4.5-Air even at 0.6.
- #889 makes FP8 bounded streaming work; mismatch KL matches NCCL with
FP8 inference.
- MX still pulls more than each GPU's shard: 40.6 GB for a 30.6 GB shard
at TP=2 and 89.5 GB for a ~26.5 GB shard at TP=8. Slices that need more
than `MX_RESHARD_MAX_SEGMENTS_PER_COPY` (64) reads are pulled whole and
resliced on the GPU.
- The first update of a run takes 60-110 s while MX plans the transfer.
- DeepSeek-V4-Flash fails in MX's layout capture: MX records the vLLM
load layout by replaying `load_weights` on meta tensors, and vLLM's
DeepSeek-V4 `load_weights` runs `process_weights_after_loading`
(`finalize_mhc_broadcast_weights`), which copies tensor data
(`NotImplementedError: Cannot copy out of meta tensor; no data!`).
DeepSeek-V4-Flash runs here train BF16 with SignSGD (MXFP8 needs
Blackwell) and serve BF16 (online `fp8_per_block` crashes vLLM's
DeepSeek-V4 CUDA-graph capture on H200), so it has no FP8 row.
- Trainer-side times were higher for NCCL too on this day (9.8 s vs 5.9
s on 2026-10-10); compare rows within one table.
- The trainer log floods with `metadata_stream.cpp ... Socket Bind
failed ... Address already in use`: every trainer rank on a node binds
NIXL's metadata listener to the same port. Transfers still work.
### MX `8512b8c`, 2026-10-10
| Inference dtype | Transport | Trainer (s) | Inference (s) | Mismatch
KL |
|---|---|---:|---:|---|
| BF16 | NCCL | 5.86 | 4.34 | 0.019-0.034 |
| BF16 | MX, full staging (`gpu_memory_utilization` 0.6) | 4.57 | 2.32 |
0.016-0.036 |
| BF16 | MX, bounded 2 x 1 GiB | 92.87 | 89.28 | - |
| FP8 per-block (online) | NCCL | 8.74 | 6.99 | 0.070-0.160 |
| FP8 per-block (online) | MX, full staging (0.6) | 5.65 | 3.84 |
0.070-0.144 |
Qwen3-30B-A3B, 1 trainer node + 1 inference node (TP=2). Bounded staging
at `8512b8c` re-planned the transfer on every update (~88 s of CPU
planning per update; ~2 s on the wire) and MX refused it for FP8.
GLM-4.5-Air with full staging OOMed at `gpu_memory_utilization` 0.6.
Single-node CI test (`test_reverse_text_modelexpress`, Qwen3-0.6B, 1+1
GPU) passes on `8512b8c`, `f24c721` and the `0.8.0.dev20261022` nightly
(server `446feec`): reward 0.14 -> 0.80, mismatch KL < 0.008, ~0.5 s per
update.
## Reproduce
Run from this branch after `bash scripts/install_modelexpress.sh`. Save
the base config and the overlays below to files, then compose them: `uv
run rl @ qwen3-30b-a3b.toml @ <overlay>.toml`.
<details><summary><code>qwen3-30b-a3b.toml</code> (1 train + 1 inference
node, TP=2)</summary>
```toml
max_steps = 10
seq_len = 2048
[model]
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[slurm]
job_name = "wb-qwen30b"
partition = "all"
[trainer.model]
attn = "flash_attention_3"
[trainer.model.ac]
[trainer.optim]
lr = 1e-7
[orchestrator]
batch_size = 64
[orchestrator.train]
group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
# Node-local compile caches: concurrent DP servers race on a shared NFS cache.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[inference.vllm]
max_model_len = 2048
tensor_parallel_size = 2
```
</details>
<details><summary><code>glm-4.5-air.toml</code> (2 train + 1 inference
node, TP=8)</summary>
```toml
max_steps = 10
seq_len = 2048
[model]
name = "zai-org/GLM-4.5-Air"
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 1
[slurm]
job_name = "wb-glm45air"
partition = "all"
[trainer.model]
attn = "flash_attention_3"
[trainer.model.ac]
[trainer.optim]
lr = 1e-7
[orchestrator]
batch_size = 64
[orchestrator.train]
group_size = 8
[orchestrator.renderer]
name = "glm-4.5"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
# Node-local compile caches: concurrent DP servers race on a shared NFS cache.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[inference.vllm]
max_model_len = 2048
tensor_parallel_size = 8
```
</details>
<details><summary>Transport overlays</summary>
```toml
# nccl.toml
[weight_broadcast]
type = "nccl"
```
```toml
# modelexpress-default.toml: full staging at vLLM's default gpu_memory_utilization (0.9).
# Qwen3-30B OOMs on the first weight update.
[weight_broadcast]
type = "modelexpress"
```
```toml
# modelexpress.toml: full staging with room for the staging copy.
# Qwen3-30B fits; GLM-4.5-Air still OOMs.
[weight_broadcast]
type = "modelexpress"
[inference.vllm]
gpu_memory_utilization = 0.6
```
```toml
# modelexpress-bounded.toml: bounded staging, ~90 s per update with MX defaults.
[weight_broadcast]
type = "modelexpress"
staging_buffer_bytes = 1073741824
staging_buffers_count = 2
```
```toml
# modelexpress-bounded4g.toml: bounded staging as in the f24c721 table.
[weight_broadcast]
type = "modelexpress"
staging_buffer_bytes = 4294967296
staging_buffers_count = 2
```
```toml
# fp8.toml: online per-block FP8 inference, as in the GLM-5 recipes. Combine with a transport overlay.
[inference.vllm]
quantization = "fp8_per_block"
gpu_memory_utilization = 0.6
```
</details>
<details><summary><code>local-env.toml</code> (cluster workaround,
2026-10-21)</summary>
The shared `/home` filesystem was slow enough that env-server harness
processes hung importing from `~/.cache/uv`. This overlay keeps them on
node-local disk:
```toml
[orchestrator.env_vars]
UV_CACHE_DIR = "/tmp/uv-cache-envs"
PYTHONDONTWRITEBYTECODE = "1"
UV_NO_SYNC = "1"
```
</details>
## Before merging
- [ ] Not checked, out of scope for this PR: `weight_broadcast.type =
"nixl"` against the bumped MX client (0.3.0 -> 0.8.0.dev20261022) and
server.
- [ ] GPU CI green on GitHub, including the new
`reverse_text_modelexpress` job (builds the MX server from source, ~4
min uncached).
- [ ] Agreement with #3890 on landing this as one PR.
- [ ] Ideally, a stable MX release to pin instead of a nightly.
## Compatibility
| Area | Status |
|---|---|
| Qwen3 MoE, GLM-4.5 MoE (BF16, online FP8) | works |
| Trainer across 2 nodes | works (GLM-4.5-Air) |
| DeepSeek-V4 | fails in MX layout capture (needs an MX fix) |
| GLM-5 (DSA) | untested |
| Expert-parallel inference | untested (only DeepSeek-V4 used it) |
| P/D disaggregated inference | not supported |
| LoRA, speculative decoding, SFT online evals | rejected by config
validation |
| Pipeline parallelism, resume, MXFP8 inference | untested |
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes the trainer–inference weight sync path and multi-node launch,
but MX is opt-in, guarded by config validation, and covered by new
integration tests.
>
> **Overview**
> Adds **`modelexpress`** as a first-class `[weight_broadcast]`
transport so FSDP trainers can push full weight updates to vLLM over
ModelExpress (RDMA/NIXL) without an NCCL collective with inference.
>
> **Config and validation:** New `ModelExpressWeightBroadcastConfig`
(staging mode, bounded receiver buffers, gRPC port). RL/SFT/trainer
validators treat MX like other in-memory transports for
`inference_world_size`, and reject incompatible setups (LoRA, Dynamo
discovery, speculative decoding, SFT online evals).
>
> **Runtime wiring:** Trainer `ModelExpressWeightSender` and
orchestrator `ModelExpressWeightReceiver` use the public
`modelexpress_rl` clients; vLLM gets a `ModelExpressWeightUpdateWorker`,
`/update_weights_from_modelexpress`, and optional staging args on
`/init_broadcaster`. The orchestrator admin plane initializes workers
and installs versioned weights under a lock, leaving inference paused on
failure.
>
> **Launch:** `uv run rl` and SLURM templates start a run-scoped
ModelExpress server + Redis when using `modelexpress` or `nixl`
(`uses_modelexpress_server`); the installer pins server build
**`446feec`** and bootstraps Rust/`protoc` when missing. The GPU extra
bumps the MX client to **`0.8.0.dev20261022`**.
>
> **Tests and docs:** GPU CI runs `reverse_text_modelexpress` (builds
the server in-job); unit tests guard the public client boundary.
ModelExpress setup/limitations live in **`docs/model-express.md`**.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
62072b9c947b2f02228fee25e9b2dfc528ef6b5e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Signed-off-by: Zheng Luo <zheluo@nvidia.com>
Co-authored-by: Zheng Luo <zheluo@nvidia.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Resuming a run with the default `model.offload = "optimizer"` did not
restore the optimizer's param groups.
- With CPU state offload, `AppState.load_state_dict` relies on DCP
writing the loaded tensors in place, so it never calls
`optimizer.load_state_dict`.
- The param groups' values are not tensors, so they kept the values of
the zero-grad step DCP runs to build its template.
- dion's Muon keeps its step count in the param groups. After a resume
it restarted at 1, so the AdamW part (embeddings, norms, biases) redid
its bias correction as if training had just started.
- torch AdamW is not affected, because its step lives in the
per-parameter state.
The fix copies the loaded param-group values back after the in-place
load.
Measured on Qwen3-0.6B reverse-text SFT, FSDP 8, Muon, checkpoint at
step 10, resumed run vs uninterrupted run:
- Before the fix: the losses split at step 12, and the resumed run
drifts to about 2% lower loss by step 20. The same drift shows on main
and with every Muon variant.
- After the fix: bitwise equal on steps 11-20 (loss and grad norm), with
`offload = "optimizer"` and with `offload = "none"`.
Added a GPU regression test to `tests/unit/train/test_state_offload.py`.
It runs dion's Muon behind `CPUOffloadOptimizer`, saves with DCP, loads
into a fresh model, checks that the param groups' step is restored, and
checks that 2 more steps give bitwise-equal weights. The test fails on
main (`[1, 1] != [3, 3]`) and passes with the fix.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Small, targeted change to the CPU-offload checkpoint resume path with
a regression test; no auth or data-path impact.
>
> **Overview**
> Resuming with **`model.offload = "optimizer"`** restored tensor
optimizer state in place via DCP but left **param group metadata** at
the values from DCP’s template zero-grad step. That broke **dion Muon**,
which stores its **step count in param groups**, so AdamW bias
correction restarted after resume and training diverged from an
uninterrupted run.
>
> **`AppState.load_state_dict`** now merges loaded **`param_groups`**
entries (everything except **`params`**) onto each checkpoint optimizer
after the in-place tensor load and packed-state write-back.
>
> A GPU regression test saves/loads through DCP with
**`CPUOffloadOptimizer`** + Muon, asserts **`step`** is **`[3, 3]`**
after resume, and checks two more steps match the uninterrupted model
bitwise.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
09c622b11f7f671af25526dfab946da3dff3b556. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
This PR passes the CP group from the DeepSeek V4 indexer to
`fp8_indexer`, opting DeepSeek V4 into the CP balancing that #4278 added
for GLM-DSA. Each query scores every earlier compressed entry, so with
contiguous CP sharding the last CP rank does the most indexer work and
the other ranks wait for it at the next collective.
Rank r pairs with rank CP-1-r. The busier rank of each pair sends some
of its last query rows to its partner, which scores them and returns
only their top-k indices, so the selected indices are unchanged. Indexer
time per step on each CP rank, with CP = 8 and one long document per
row:
```
before after
rank 0 ### 24 ms ########## 78 ms
rank 1 ##### 41 ms ######### 74 ms
rank 2 ####### 55 ms ########## 76 ms
rank 3 ######### 69 ms ########## 76 ms
rank 4 ########### 84 ms ########## 76 ms
rank 5 ############ 97 ms ########## 76 ms
rank 6 ############## 110 ms ########## 78 ms
rank 7 ################ 124 ms ######### 71 ms
```
On one 8x H200 node (DeepSeek V4 Flash cut to 6 layers, cp 8, ep 8,
262k-token rows of one long document each), forward plus backward time
per step dropped 0.8 to 1.0% against same-node baselines, with entropy
unchanged within run-to-run noise. That is about 10 ms per CSA layer per
micro batch, or about 1.3% of a step for the full 43-layer model.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Follow-up to #4318: mark live fields in the annotation, not in `Field`.
Behaviour is unchanged. Config values and the live set stay the same.
```python
- batch_size: int = Field(128, ge=1, json_schema_extra=LIVE)
+ batch_size: Annotated[int, Live()] = Field(128, ge=1)
- sampling: TrainSamplingConfig = Field(TrainSamplingConfig(), json_schema_extra=FROZEN)
+ sampling: Annotated[TrainSamplingConfig, Frozen()] = TrainSamplingConfig()
- length_penalty: LengthPenaltyConfig | None = Field(None, json_schema_extra=LIVE)
+ length_penalty: Annotated[LengthPenaltyConfig | None, Live()] = None
```
Same change for `max_staleness`, `concurrency.*_inflight`,
`train.source[*].ratio`, `train.sampling.*` and
`eval.source[*].interval`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Refactor-only with parity tests; live-update rules and field sets are
intended to stay the same.
>
> **Overview**
> Live vs frozen config semantics are unchanged; only **how** fields are
marked moved off `Field(json_schema_extra=…)` to **`Annotated[T,
Live()]`** / **`Annotated[T, Frozen()]`**.
>
> `prime_rl.configs.diff` now exposes **`Live`** and **`Frozen`** as
frozen dataclasses and resolves markers from **`FieldInfo.metadata`**
instead of JSON schema extras. Orchestrator, algorithm, and related
configs use the new annotations for the same live knobs (`batch_size`,
`max_staleness`, concurrency, sampling, source ratios, eval intervals,
GRPO `length_penalty`, etc.). Training docs describe **`Annotated[T,
Live()]`**, and unit tests cover marker value equality plus existing
diff/resume behavior.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
098fb0002fa75c6c91d57a62d27976038a52818c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
This PR adds `data.fake.doc_len`, which packs generated fake RL samples
of one fixed length into each micro batch, cutting the last sample to
fill the row. Fake data could not model long agentic rollouts packed
into rows longer than one rollout (e.g. two 262k rollouts in a 524k
row).
```
one micro batch row of seq_len tokens
default: one document, ids 0 to 99
|---------------------------------------------------------------|
--data.fake.generate-samples: random lengths up to seq_len / 8
|-------|---|----------|-----|--|--------|-----|----|-------|---|
--data.fake.generate-samples --data.fake.doc-len N: every sample N tokens, last one cut
|------------------|------------------|------------------|------|
```
- `doc_len` requires `data.fake.generate_samples`, whose random ids span
0 to 119999; the default ids 0 to 99 send a hash-routed MoE layer's
tokens to only a few experts.
- We ran `--data.fake.generate-samples --data.fake.doc-len 262144
--model.seq-len 524288` on 8 GPUs (6-layer and full
DeepSeek-V4-Flash-architecture models) without issues.
- A unit test in b4a5eaaa6 checked the packing (`[300, 300, 300, 100]`
for a 1000-token row) and the validator; it passed and was removed in
the next commit.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This PR changes `perf/peak_memory` and the console `Peak Mem.` in the RL
and SFT trainers to report peak GPU memory from all sources, max over
ranks, and adds `perf/non_torch_memory` for the part held outside
PyTorch's caching allocator. Before, the metric was
`torch.cuda.max_memory_reserved()` on rank 0. It missed Mega MoE's
symmetric buffers, NCCL buffers, and the CUDA context, and it hid ranks
that ran out of memory before rank 0 did.
- The peak is the caching allocator's peak plus the current
out-of-allocator memory (`mem_get_info` minus `memory_reserved`),
assuming the latter is static over the step.
- Expect `perf/peak_memory` to step up against older runs; in the run
below it rose by about 8 GiB.
- The one extra all-reduce per step sits next to the existing
`global_counts` all-reduce, which every rank reaches.
One-node check on 8 B300s: the RL trainer alone on fake data, with a
DeepSeek-V4-Flash-architecture model cut to 2 layers, sequence length
262144, EP 8, CP 8, and PyTorch all-to-all MoE dispatch. This run used
neither DeepEP nor Mega MoE, so `non_torch_memory` here is the CUDA
context and NCCL buffers. Values are max over GPUs.
| step | old `peak_memory` | new `peak_memory` | `non_torch_memory` |
`nvidia-smi` max |
|---|---|---|---|---|
| 2 | 66.25 GiB | 74.03 GiB | 7.04 GiB | 74.03 GiB |
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
## Problem
Context parallelism splits every micro batch evenly over the `cp` ranks.
Each rank's MoE layers therefore see `seq_len / cp` tokens: in RL, and
in SFT too, since SFT requires `micro_batch_size = 1` under CP.
`model.moe.dispatch.max_tokens_per_rank` defaulted to the whole micro
batch and rejected anything smaller. With `seq_len = 262144` and `cp =
8`, the Mega MoE symmetric buffer was sized for 262,144 tokens per rank,
8x more than any rank holds. That size is aligned up to 263,040 tokens,
which exceeds DeepGEMM's shared L2 pool, so the trainer fails at init
(`num_shared_l2_pool_blocks <= kNumMaxSharedL2Blocks`). There was no way
to set a smaller value.
## Change
- `mega_moe_max_tokens_per_rank` now takes `cp`. It defaults to
`ceil(micro_batch_tokens / cp)` and rejects values below that.
- The RL and SFT validators pass `model.cp`.
- Docstrings, the runtime comment and error message, and
`docs/scaling.md` describe the new default.
- At `cp = 1` the default doesn't change.
## Testing
- Two new tests in `tests/unit/test_configs.py`: RL and SFT default to
`seq_len` at `cp = 1` and to `seq_len / 8` at `cp = 8`, and a value
below the CP share is rejected.
- `tests/unit/test_configs.py` + `tests/unit/train/models/test_moe.py`:
285 passed, 2 failed. The 2 failures are `test_load_configs` for the VLM
example configs (`examples/extra/vlm/rl-qwen3.5.toml`,
`rl-qwen3.8.toml`), and they fail the same way on `main`.
- GPU check: this change applied as a local patch on an earlier commit
(this file hasn't changed since).
- Setup: 8 nodes x 8 B300, a 43-layer DeepSeek-V4-Flash-sized model,
`seq_len = 262144`, `cp = 8`, MXFP8 Mega MoE.
- Result: `max_tokens_per_rank` resolved to 32,768 and 10 training steps
ran with no buffer overflow.
- Without the change, init fails as described above.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes MoE symmetric-buffer sizing at startup for CP and Mega MoE;
wrong sizing would deadlock or overflow at runtime, but behavior at
`cp=1` is unchanged and tests cover the new defaults.
>
> **Overview**
> Fixes Mega MoE init failures under **context parallelism** (`model.cp
> 1`), where `max_tokens_per_rank` defaulted to the **full** micro batch
even though each rank only processes `ceil(micro_batch_tokens / cp)`
tokens—often blowing DeepGEMM's shared L2 pool at large `seq_len`.
>
> **Config resolution** now divides by `cp`:
`mega_moe_max_tokens_per_rank(..., cp)` defaults to that per-rank token
count and rejects explicit values below it. **RL** also uses padded
micro-batch size via new `rl_micro_batch_multiple` (CP, or `cp * 32`
with MXFP8). **SFT** passes `model.cp` into the same helper. **RL
orchestrator padding** reuses `rl_micro_batch_multiple` instead of
duplicating MXFP8/CP logic.
>
> Docs (`scaling.md`), field docstrings, and runtime comments/errors are
aligned with the CP-aware default. Unit tests cover RL/SFT defaults at
`cp=1` vs `cp=8`, MXFP8 padding, and validation when the buffer is too
small.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2e73a1b33c5bac85eb217b9eaa392aa572fa11c7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Neo <mario.sieg.64@gmail.com>
Fixes#4201
`bind_process_to_gpu_numa_node` crashed with `FileNotFoundError` when
the GPU's PCI entry is missing from `/sys/bus/pci/devices/` (e.g. WSL2),
which made `model.offload = "full"` unusable there. A missing
`numa_node` file is now treated like `-1`, so it falls into the existing
warn-and-skip path.
## Test plan
- `uv run sft @ configs/debug/fake/sft.toml --model.offload full` on
WSL2 (RTX 4070 Laptop, 8 GB): crashed before, now logs `GPU 0
(0000:01:00.0) reports no NUMA node; skipping NUMA binding` and
completes all 5 steps (peak 6.0 GiB).
- `uv run pytest tests/unit -m "not gpu"`: 910 passed, 1 skipped.
- `pre-commit run`: ruff check and format pass.
## Summary
- Mark the orchestrator fields that a live config update may change with
`Field(json_schema_extra=LIVE)`. Every other field is frozen for live
updates. This replaces pydantic's `Field(frozen=True)` on about 50
fields.
- Add `FROZEN` for a sub-config that stays frozen with everything below
it. Only `train.sampling` and `train.algo` use it: they reuse the
per-source classes, but they are only defaults that seed the sources
when the config loads.
- `LIVE_INSIDE` is gone. `diff_config` and `frozen_raw_changes` walk
every sub-config and accept a change only at or below a `LIVE` field.
- The live set doesn't change: `batch_size`, `max_staleness`,
`concurrency.{initial,min,max}_inflight`, per-source `ratio`,
`sampling.{temperature,max_completion_tokens,extra_body}` and
`algo.length_penalty`, and per-source eval `interval`.
- A rejected update now names the changed field, e.g.
`train.algo.length_penalty`, not the frozen sub-config above it
(`train.algo`).
**Why:** pydantic's `frozen=True` does more than mark a field as fixed
for live updates. It also rejects assignment on the config object.
Hosted training sets `resume` on the parsed config (fft
`prime-rl-k8s/rl_k8s/values.py`: `component.resume = ResumeConfig()`).
So since #4273, every hosted RL dispatch fails validation. Marking the
live fields also makes a new field frozen by default, so an update can't
change a field that nothing applies.
## Verification
Hosted RL, `prime train examples/basic/reverse-text/rl.toml --image-tag
v0.10.1.dev131` (the main image for a1647464b):
- Before (main):
```
Error: Invalid config:
config: 1 validation error for OrchestratorConfig
resume
Field is frozen [type=frozen_field, input_value=ResumeConfig(step=None,
dir=None), input_type=ResumeConfig]
```
- After (this branch, `--pr`): AFTER_PLACEHOLDER
Unit tests:
- `pytest tests/unit --ignore=tests/unit/train`: 812 passed.
- `test_frozen_fields_accept_assignment` sets `resume` on an
`OrchestratorConfig`, as hosted training does. A live update that
changes it is still rejected.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches live config validation for all orchestrator control updates
and redefines freeze semantics project-wide; wrong LIVE/FROZEN tags
could allow forbidden mid-run changes or block valid updates, though
tests and the unchanged live field set mitigate that.
>
> **Overview**
> Replaces **pydantic `Field(frozen=True)`** on orchestrator config with
an explicit **opt-in live-update model**: only fields tagged
`Field(json_schema_extra=LIVE)` (from `prime_rl.configs.diff`) may
change via the control API; unmarked fields are frozen. **`FROZEN`**
marks group defaults (`train.sampling`, `train.algo`) that stay fixed
including nested LIVE markers. **`LIVE_INSIDE` is removed**;
`diff_config` and `frozen_raw_changes` walk configs with a simpler
live/frozen propagation.
>
> **Behavioral fixes:** Launchers can mutate post-parse config again
(e.g. hosted RL setting `resume`) without pydantic “Field is frozen”
validation failures. Rejected live updates report **leaf paths** (e.g.
`train.sampling.temperature`,
`train.source[0].algo.length_weighted_baseline`) instead of whole
sub-config keys. The allowed live set is unchanged (`batch_size`,
`max_staleness`, concurrency bounds, per-source `ratio` / sampling knobs
/ GRPO `length_penalty`, eval `interval`).
>
> Docs in `training.md` describe the LIVE marker; unit tests updated for
granular frozen paths plus assignment on frozen fields.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
09c62461d968a32114c321fd9f9f73a1a5b0ec94. 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>
Every trainer checkpoint of a full-weight PrimeRL model now writes
`mapping.json` next to the DCP `.metadata`, before the sharded state so
it is in place once `.metadata` appears: `{"prefix": "app.model.",
"tensors": {hf_name: {"from": prime_name, "index": [...]}}}`, where each
HF tensor is `prime[from][*index]`. `view_mapping` finds this by playing
the model's real `apply_prime_to_hf` on meta tensors with the saved
global shapes and reading each output back as a view of an input, so it
cannot drift from the trainer's conversion. No file is written, with an
info log, for plain transformers models, LoRA runs, or when some HF
tensor is not such a view (gpt-oss, concats, value transforms). This
lets ferry stream a checkpoint into vLLM using the mapping from the
trainer version that wrote it, instead of hand-exported copies that go
stale.
Qwen3.8 Flash Next runs two `HyperConnection`s per decoder layer. On
main, `mix` and `combine` are plain PyTorch inside the compiled layer.
`mix` materializes several `(tokens, 4 x 2560)` tensors (fp32 norm,
up-projection logits, sigmoid, product) and autograd keeps several of
them.
This PR adds `prime_rl::qwen3_8_hc_mix`, a custom op (Triton kernels +
cuBLAS GEMMs) that `HyperConnection.mix` uses for CUDA inputs; CPU keeps
the eager code.
- Forward: per-stream RMSNorm kernel, one GEMM for `[down; inject]`
(padded to 328 rows), the up GEMM, then one kernel for
`mean_s(sigmoid(z) * n)`. The inject weights are computed in `mix`, so
`combine` is only the weighted residual add.
- Autograd keeps `x`, the per-stream rstd and the `(tokens, 328)`
projection; backward recomputes `n` and the up logits.
- Both passes run over 16,384-token chunks, so `(tokens, 10240)`
intermediates exist for one chunk at a time.
RL trainer step, 1 node 8xH200, 8 layers, random init, balanced routing,
fake packed samples, compiled, full AC, FSDP (steady steps 3-6):
| config | step time | peak memory |
|---|---|---|
| 32k, ep8, torch dispatch | 12.0 s → 10.6 s (-12%) | 79.1 → 64.7 GiB |
| 131k, cp4 ep8, torch dispatch | 11.5 s → 9.8 s (-15%) | 96.0 → 80.8
GiB |
| 16k, ep8, `mega_moe` | 7.2 s → 6.3 s (-12.5%) | 51.7 → 47.5 GiB |
Isolated HC (131k tokens, 1x H200, compiled): fwd+bwd 73.2 → 55.8 ms,
saved activations 10.3 → 3.9 GiB.
Validation:
- Numerics (20k tokens, bf16, fwd+bwd): for the output and every
gradient, the fused error vs fp64 lies between main eager and main
compiled. Entropy and mismatch KL match main to 4 decimals on every
trainer step.
- No recompiles with changing packed sample boundaries; step 1 (with
compilation) takes 22-28 s vs 2-2.5 min on main.
-
`test_qwen3_8_flash_next.py::test_fused_hyper_connection_matches_eager`
(gpu): fused CUDA bf16 vs eager CPU fp32, fwd+bwd, with/without inject,
across chunk boundaries. `-m "not gpu"` unit tests and ruff pass on the
branch merged with current main.
Notes: the trainer runs used a 200K-row n-gram table (the full one does
not fit one node without #4217). The torch-dispatch runs had the #4236
activation-checkpointing patch (since closed) applied on both sides.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Custom Triton/cuBLAS autograd on a core per-layer path could diverge
numerically or break compilation, though CPU fallback and parity tests
mitigate this.
>
> **Overview**
> Adds a **CUDA-only fused path** for `HyperConnection.mix` via custom
op `prime_rl::qwen3_8_hc_mix` (Triton RMSNorm + stream-mean kernels,
fused down/inject GEMM, custom autograd with chunked 16k-token passes).
CPU/non-CUDA inputs still use the existing eager PyTorch implementation.
>
> **Behavior/API tweak:** `mix` now also produces **residual injection
weights** (when enabled) instead of stashing normalized states for
`combine`. `combine` only applies the weighted residual add using those
precomputed weights—matching the fused forward and avoiding extra work
on the hot path.
>
> Adds a **GPU unit test** that checks fused bf16 CUDA forward+backward
against the eager reference (with/without injection, including small
chunk sizes).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
938a65781090efd0e28337742590793b85199b32. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
`rl` and `sft` each defined their own deployment config with the same
`gpus_per_node` and the same single-node and multi-node fields, and
their defaults and checks had drifted. This PR gives them one base.
## Changes
- `shared.py` gets `BaseDeploymentConfig`,
`BaseSingleNodeDeploymentConfig` (`type`, `num_train_gpus`,
`num_infer_gpus`) and `BaseMultiNodeDeploymentConfig` (`type`, required
`num_train_nodes`). The `rl` and `sft` classes subclass them and keep
their own validators and extras: RL replicas and orchestrator placement;
SFT online-eval `num_infer_nodes`.
- SFT multi-node `num_train_nodes` is required, as for RL. A multi-node
SFT run without it no longer silently uses 2 nodes.
- `deployment.nodes_per_fsdp_group` is removed from `rl` and `sft`. It
only set `dp_replicate = num_train_nodes / nodes_per_fsdp_group` and
silently overwrote an explicit `dp_replicate`. Set
`trainer.model.dp_replicate` (`rl`) or `model.dp_replicate` (`sft`)
directly. No config in `configs/` or `examples/` uses it.
- SFT's `normalize_deployment` is removed. It silently dropped
`num_train_gpus` / `num_infer_gpus` under `type = "multi_node"`; they
are now rejected like any unknown field.
- The SFT `num_eval_gpus` / `num_eval_nodes` aliases are removed.
**Breaking:** `nodes_per_fsdp_group`, the `num_eval_*` aliases and
single-node fields under multi-node are rejected; SFT multi-node needs
`num_train_nodes`.
## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/train/sft tests/unit/utils -m "not gpu"`: 538 passed.
`test_configs` validates every TOML in `configs/` and `examples/`.
- Checked directly: SFT `{"type": "multi_node"}` without
`num_train_nodes` is rejected; `num_train_gpus` under multi-node is
rejected; `nodes_per_fsdp_group` is rejected; a valid multi-node config
builds.
- `ruff check`, `ruff format --check`, `uv lock --check`: clean.
## Overlaps
#3977 (reject launcher-owned fields) does not guard `dp_replicate` and
merges cleanly with this PR.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking deployment TOML/CLI fields and stricter multi-node validation
can fail existing configs; FSDP layout must be set explicitly via model
`dp_replicate` instead of deployment.
>
> **Overview**
> **Unifies `[deployment]` for RL and SFT** by moving shared single- and
multi-node fields into `shared.py` (`BaseDeploymentConfig`,
`BaseSingleNodeDeploymentConfig`, `BaseMultiNodeDeploymentConfig`). RL
and SFT only keep entrypoint-specific pieces (RL: infer replicas,
orchestrator placement; SFT: online-eval `num_infer_nodes`).
>
> **Breaking config cleanup:** `deployment.nodes_per_fsdp_group` is
removed for both entrypoints—along with the logic that overwrote
`trainer.model.dp_replicate` / `model.dp_replicate`. Set `dp_replicate`
on the model block directly. SFT multi-node now **requires**
`num_train_nodes` (no silent default of 2). SFT drops `num_eval_gpus` /
`num_eval_nodes` aliases, removes `normalize_deployment` (single-node
GPU keys under multi-node are rejected like other unknown fields), and
uses the shared base for `num_infer_gpus` without the eval alias.
>
> **Docs:** `docs/scaling.md` no longer documents `nodes_per_fsdp_group`
in the RL multi-node example.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
93ce58250e5bf5ae06c0933e9f7afc5d36b089a9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Update the orchestrator config while a run is going. With
`--orchestrator.control`, you resubmit the full config through the
control API; the orchestrator checks it and applies it at the next step
boundary. Running episodes keep their settings and nothing is cancelled.
```bash
curl localhost:8041/v1/config # {revision, step, config}
curl -X POST localhost:8041/v1/actions -d '{"type": "update_config", "config": {...}}'
```
## How it works
- **What can change:** pydantic's `Field(frozen=True)` is the single
source of truth. Every field that no component applies is frozen;
`diff_config` compares the new config with the running one and rejects
changes to frozen fields. Live today: `batch_size`, `max_staleness`,
`concurrency.{min,max,initial}_inflight`, per-source `ratio`, per-source
`sampling.{temperature,max_completion_tokens,extra_body}`, per-source
eval `interval`.
- **Who applies it:** components inherit `Reconfigurable` (no-op
`reconfigure(update)` by default) and override it to read the new
values; the orchestrator calls `reconfigure` on each of them for every
applied update.
- **Responses:** 202 with the list of changes; 422 with `frozen` paths
and/or validation `errors`; 409 if an update is already queued or the
run is pausing. Pause is unchanged.
- **Record:** each applied update is logged and written to
`updates/rev_<k>.json`.
- **Resume:** live updates survive `--resume`. The checkpoint stores the
launch config and the live config. Per field, a value you changed in the
new launch config wins; otherwise the live value is restored.
- **Sampling:** a group keeps the sampling settings of the step it
started at, so rollouts are trained with the temperature they were
sampled with.
Frozen for now: `group_size`, algorithm and curriculum params, eval
sampling, `dispatch_per_minute`, logging, adding or removing sources.
Touches the same orchestrator classes as draft #3652.
## Testing
- Unit tests (CPU) for the config diff, resume merge, control API and
the main handlers pass.
- Live RL runs of `examples/basic/reverse-text/rl.toml` on two
single-node GPU setups: updates to temperature, `batch_size`,
`max_inflight` and `max_staleness` applied at step boundaries; frozen
and invalid changes returned 422; a queued second update returned 409;
pause still works; resume restored the live config, and a changed launch
config took precedence. Training stayed healthy throughout.
- The live runs surfaced a stale-token metric `KeyError`, fixed
separately in #4268 (this branch is rebased on it).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes training dynamics at runtime (batch size, staleness, sampling,
concurrency) and resume merge semantics; mistakes could cause off-policy
or inconsistent batches, though validation and frozen-field guards limit
scope.
>
> **Overview**
> Adds **live orchestrator reconfiguration** when
`--orchestrator.control` is enabled: `GET /v1/config` returns the
running config with revision/step, and `POST /v1/actions` with
`update_config` queues a full config replacement that applies at the
**next shipped step** (422 for frozen/invalid fields, 409 if another
update or pause is pending). Control actions now include a `changes`
list and config updates use state `applied`.
>
> Introduces `prime_rl.configs.diff` (`diff_config`,
`frozen_raw_changes`, `merge_resumed_config`) and marks orchestrator
fields with **`Field(frozen=True)`** plus selective **`LIVE` /
`LIVE_INSIDE`** markers (e.g. per-source sampling temperature,
`batch_size`, `max_staleness`, concurrency bounds, env mix `ratio`, eval
intervals, GRPO **`length_penalty`**). RL entrypoint validators use
**`model_copy`** when mutating frozen orchestrator sub-configs.
>
> Orchestrator **checkpoints store launch vs applied config +
revision**; on `--resume`, live values restore unless the new launch
TOML changed that field. Applied updates are logged to
`configs/.../updates/rev_<k>.json`. **`Reconfigurable`** components
(`TrainSink`, `TrainSource`, `TrainEnvs`, concurrency, eval cadence,
GRPO algo) pick up new settings without cancelling in-flight work;
dispatch uses **`sampling_at(step)`** so groups keep the
temperature/settings from when they started.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e65dda5837b4814f8ddecb8a8fc626aed0bda1d4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Run the heavy steps of the eval epoch close in worker threads
(`asyncio.to_thread`), matching `finalize_train_batch`:
- copying the effective episodes (`vf_episodes`);
- `stamp_batch`;
- building the `eval/{env}/...` metric dict.
- Move the success log line into a sync `log_eval_batch`, run in a
thread like `log_train_batch`. Only the `monitors.*` calls stay on the
event loop.
- Apply the same change to the standalone eval runner
(`prime_rl.eval.runner`).
These steps walk every trace's node graph in pure Python. For a large
eval epoch they froze the event loop for tens of seconds. During that
time the orchestrator could not dispatch, collect completions or answer
the weight-broadcast handshake.
## Verification
A bench builds one synthetic eval epoch from real recorded agentic
episodes. It feeds the epoch through the real `EvalSink` and
`Orchestrator.finalize_eval_batch`. A 10 ms ticker measures event loop
lag during the close.
| epoch size | before: max loop lag | after: max loop lag |
|---|---|---|
| 1024 episodes | 5.9 s | 10 ms |
| 4096 episodes | 26.9 s | 18 ms |
The total close time does not change (~23–27 s at 4096 episodes); it now
runs off the loop. The result is the same with the orchestrator's
`GarbageCollector` settings (21 ms).
`pytest tests/unit/orchestrator tests/unit/eval` passes.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches eval logging and metrics on the hot orchestration path; logic
is refactored rather than changed, but threading adds concurrency
surface around shared batch objects during finalize.
>
> **Overview**
> **Moves CPU-heavy eval epoch finalization off the asyncio event loop**
in both the orchestrator and standalone eval runner, following the same
pattern as `finalize_train_batch`.
>
> `finalize_eval_batch` now uses `asyncio.to_thread` for building
effective `vf_episodes`, `stamp_batch`, assembling the `eval/{env}/...`
WandB metric dict (including failure/cancelled fields in the runner),
and the console success/warning line via new sync helpers
`log_eval_batch`. **Only** `monitors.log` / `log_eval_epoch` /
`log_annotations` stay awaited on the loop.
>
> Docstrings note that aggregation walks trace node graphs and can take
seconds on large epochs. Behavior and metrics are unchanged; the goal is
to avoid multi-second event-loop stalls that blocked dispatch,
completions, and weight-broadcast handshakes during eval close.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
04e5a39262ebf86a040ffe8876eef7b6df7c98ce. 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>
This PR moves Qwen3.8-Flash-Next's hashed n-gram (PLE) tables into a
shared module, `layers/ngram.py`, as top-level FSDP units looked up
eagerly outside the AC-wrapped compiled layers. This fixes the multi-GPU
full-AC crash with `reshard_after_forward = false` (supersedes #4269)
and replaces the trainer's n-gram special cases by class, name and FQN
with `NGramTable` type checks. Weight transfers treat the tables like
any other non-layer weight.
- Under full AC the lookup runs once per step instead of twice, without
`bincount`'s hidden host sync.
- Without AC, the PLE graph breaks go from 8 to 0 per rank, with fewer
recompiles at cp=1 and cp=2.
- **Breaking:** prime-format Qwen3.8 checkpoints and conversion caches
from before this PR no longer load. HF checkpoints are unaffected.
On a synthetic Qwen3.8 (8 linear-attention layers, two 205M-parameter
tables), 20-step SFT runs over 1 and 8 GPUs, AC on and off,
`reshard_after_forward` on and off, ep 1 and 8, and cp 1 and 2 all match
main within run-to-run noise, except full AC with `reshard_after_forward
= false`, which crashes on main and trains here. Weight transfers,
checkpoint resume and an RL run with vLLM also match main. Step time is
unchanged and peak memory grows by up to 0.5 GiB. Not covered: real
Qwen3.8 weights.
#4217 should freeze tables by the `NGramTable` type.
### DeepSeek-V4.1
#4057 should rebase onto this PR and port its engram onto the shared
module instead of adding a second n-gram implementation. The rebase
conflicts in `layers/ngram.py` (both PRs add it) and in
`embedding_parallel.py` and `qwen3_8_flash_next/ngram_embedding.py`
(deleted here). Take this PR's side of all three:
`consecutive_primes_from` replaces `is_prime`, and the all-to-all lookup
becomes an `NGramLookup` strategy. The conversion chain maps the HF
`layers.{i}.engram.embed.weight` to `ngram.tables.{i}.weight`, as
Qwen3.8's does here, so names on the vLLM side do not change.
```
class DeepseekV41NGramHasher(NGramHasher):
__init__(config) = super().__init__(max_ngram_size=4, heads_per_ngram=8, rows_multiple_of=1)
map_tokens(ids) = compressed_token_map[ids] # normalized vocabulary, 99092 ids
segment_starts(...) = document starts only # no EOS reset
pad_token() = compressed_token_map[2]
head_sizes(table) = consecutive_primes_from(16_000_000, skip=24 * table, count=24)
table_multipliers(table) = odd PCG64 draws, seed 10007 * engram_layer_ids[table]
DeepseekV41Model:
ngram = NGramEmbeddings(
DeepseekV41NGramHasher(config),
table_indices={1: 0, 14: 1}, head_dim=256,
) # 384006168 and 384016682 rows, as in the checkpoint
layers[i].engram = gate consumer, inside the AC-wrapped compiled layer
add: a deduplicating RowShardedLookup (its torch.unique and fp32 grad sum),
an NGramTable option for non-persistent layout buffers (its HF checkpoint has none)
re-key: the fp8 row-chunk export and freeze_engram_tables on NGramTable
drop: AllToAllEmbeddingParallel, the FSDP-ignored table path and hand-applied divide factor,
isinstance(DeepseekV41Engram) in setup_fsdp, the Muon name rule, hasattr(rows_per_rank) in transports
```
### Test commits
- A/B harness and results: the `test(ngram)` commits, results in
`779a296` and `3e703da`, removed in `3ec67f6`.
- Review-round harness and results: `056a84c`, removed in `93969d0`.
- 4-GPU lookup tests: passed at `54b65ef`, removed in `93969d0`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
## Summary
Router-replay rows, the score-centering top-k head and sampling masks
travel today from the env servers to the orchestrator inline, and the
orchestrator packs them into the trainer batch. At high concurrency with
long contexts, the orchestrator node then holds terabytes of per-token
arrays that only the trainer reads. Now they never leave the env servers
inline: the train env servers keep them, and references are the only way
they reach the trainer. There is no config and no inline path:
- **Env servers keep the arrays** (`transports/payload.py`). vLLM still
returns them inline, so the env server keeps full control over the
response. When a train episode finishes, each env-server worker
(verifiers' `set_episode_hook`, `PayloadHook.keep`) encodes every
trainable branch's arrays (`encode_branch_arrays`), keeps the blob,
serves it over HTTP (`GET <url>/<id>`, a stdlib threaded server per
worker on the env server's bind host, loopback by default, `DELETE` to
free). It leaves the URL and, per branch, the blob id, the kept fields
and the routing shape in `trace.info["prime_rl_payload"]`. Env-server
workers import no torch through this path. Episode streams never carry
the arrays (verifiers#2934).
- **The orchestrator packs references, never arrays.** A sample carries
a `PayloadSlice` (url, id, kept token count, fields); truncation
shortens the count. A micro batch lists one reference per sequence, so
samples with and without arrays pack together; samples with and without
routing do not (`orchestrator/trajectories.py`,
`orchestrator/batch.py`). Padding dummies reference only routing rows.
- **Trainer ranks fetch and assemble.** Before each step, every rank
fetches its micro batches' blobs in parallel and assembles them
(`pack_token_arrays`, `pad_token_arrays`: cut each to its sample,
concatenate in packing order, pad; a sample without arrays gets empty
rows), so the tensor conversion is unchanged (`trainer/rl/data.py`,
`transports/payload.py`).
- **Strict accounting, no sweep.** Every kept array is deleted exactly
once (`DELETE <url>/<id>`), by whoever holds it last: the **trainer**,
once every rank fetched a step's arrays (after the world all-reduce that
agrees on failed fetches, one rank per data rank deletes); the
**orchestrator**, for whatever it receives but never ships: the train
sink for filtered and dropped traces and groups, untrained branches,
pruned samples, samples that staleness masking voids, and batches and
queues discarded at shutdown; the eval sink for every eval episode; the
dispatcher for episodes that returned after their group was dropped; the
**env server**, for episodes it kept that never reached the
orchestrator, including runs the client abandoned after the reply
(`PayloadHook.discard`, called by verifiers' delivery contract).
- **Missing arrays fail loudly.** Each fetch retries before giving up,
and bypasses HTTP proxies. A step where no micro batch's arrays can be
fetched anywhere stops the run. A micro batch whose arrays still cannot
be fetched is dropped from the loss on every rank that trains it (one
all-reduce), never trained on zeros, and counted in
`payload/dropped_micro_batches` (summed over data ranks). Its routing
keeps the model's shape and repeats real rows, so the forward pass still
routes like real data.
- **Every env server keeps its arrays; eval deletes them.** prime-rl's
`env-server` entrypoint always installs the hook, with no config. Eval
never trains, so `EvalSink.add` deletes the arrays of every eval episode
it receives, in the orchestrator and in the standalone `eval` entrypoint
(`orchestrator/eval_sink.py`).
- **Env-server replicas on every inference node.** On multi-node SLURM
runs with inference nodes, every inference node runs a replica of every
launcher-managed env server, bound to the node address. Each replica
publishes its address to `envs/<split>/<name>.<node>.address`. The
orchestrator connects to all replicas and sends each run to the replica
with the fewest runs in flight (`orchestrator/envs.py`). So env-server
memory and CPU spread over all inference nodes, even for a single env.
The launcher sets `orchestrator.env_server_replicas` to the number of
inference nodes.
Builds on PrimeIntellect-ai/verifiers#2934 (merged): episode streams
without training arrays, and `set_episode_hook` with its keep/discard
contract. `deps/verifiers` points at its merge commit on verifiers
`main` (`60290d436`).
## Breaking
- **Env server placement.** On multi-node SLURM runs with inference
nodes, launcher-managed env servers now run as one replica per inference
node instead of one server next to the orchestrator. Env-server logs
move to `logs/envs/<split>/<name>.<node>.log`. No option restores the
old placement. To pin a source's env server elsewhere, run it yourself
and point the source at it with `serve.address`.
- **Train env servers must run prime-rl's `env-server` entrypoint.**
Episode streams no longer carry training arrays, so a train source
served any other way (`serve.address` pointing at a plain verifiers
server) delivers none. Runs that need sampling masks or top-k heads stop
with an error saying so.
- **Per-server limits apply per replica.** `serve.max_concurrent`, the
worker pool and sandbox limits of a launcher-managed env server now
apply to each replica, so a source's total rises with the number of
inference nodes. Migration: divide a limit that must hold run-wide by
the number of inference nodes.
- **Persisted batches can't be replayed.** With the filesystem rollout
transport, a step file now holds references, and the trainer deletes the
arrays once it has fetched them. A trainer that re-reads an old step
file after a restart finds the arrays gone and drops every micro batch
(`payload/dropped_micro_batches`).
- **The `sampling_support/size` metric is removed.** Traces reach the
orchestrator without sampling masks, so nothing feeds it.
## Verification
Qwen3-30B-A3B-Thinking on `i3_math` with router replay (48 layers × 8
experts, uint8) and IcePop score centering (top-128 head), batch 128 ×
group 8, up to 1,024 rollouts in flight, 16k-token completions, H200.
**Inline (`main`) vs by reference**, 1 trainer + 1 inference node each,
same config otherwise, 10 steps, measured on an earlier revision of this
branch:
| | inline | by reference |
|---|---|---|
| Reward (mean of steps 1–10) | 0.427 | 0.388 |
| Mismatch KL | 4.0e-4 | 4.0e-4 |
| Step time (orchestrator / trainer) | 381 s / 380 s | 378 s / 375 s |
| Orchestrator peak RSS | 14.5 GiB | **2.7 GiB** |
| Dropped micro batches | – | 0 |
Per-step reward varies by ±0.07 at this batch size, so the reward gap is
within about two standard errors; the trainer sees byte-identical arrays
(unit test below) and the mismatch KL is unchanged.
**Env-server replicas**, 2 trainer + 4 inference nodes, 27 steps each.
one env server vs one replica per inference node:
| | one env server | replica per inference node |
|---|---|---|
| Env-server peak RSS | 90.6 GiB on one node | 25.6–25.9 GiB on each of
4 nodes |
| Peak memory used, inference nodes | 220 GiB on the env-server node,
122–164 GiB elsewhere | 144–158 GiB on every node |
| Orchestrator peak RSS | 3.2 GiB | 3.3 GiB |
| Payload fetch per trainer step (mean / max) | 1.26 s / 2.30 s | 0.74 s
/ 2.20 s |
| Reward (mean of steps 1–27) | 0.398 | 0.415 |
| Mismatch KL (mean) | 3.9e-4 | 3.9e-4 |
| Step time (orchestrator / trainer) | 118 s / 117 s | 124 s / 122 s |
| Dropped micro batches | 0 | 0 |
The replica run continued to its 60-step limit and exited cleanly. Each
replica's memory peaks early (≤ 25.9 GiB) and stays flat at ~22–23 GiB,
so eager deletes keep up. Over 60 steps: no dropped micro batches,
payload fetch 0.67 s mean, orchestrator peak RSS 3.3 GiB, reward mean
0.417. In both runs, most env-server memory is the math runtime's
per-episode subprocesses and the pool workers; the kept arrays are about
10 GiB in total.
**Transport**, measured on an earlier revision of this branch: deltas
into the orchestrator 8.8 GiB → 120 MiB per step, trainer batch 2.6 GiB
→ 78 MiB per step.
**Tests:** `tests/unit/transports/test_payload.py`: real verifiers
traces go through the env-server hook, `trace_to_samples`, packing
(truncation, padding, multi-sample bins) and the HTTP fetch, and each
fetched micro batch holds exactly its branches' encoded arrays in
packing order. Samples with and without routing never share a micro
batch. Explicit heads, masks with sampler logprobs, plain masks and a
sample without arrays survive truncation, mixed packing, padding and the
trainer's tensor conversion. Also covered: the routing of a micro batch
whose fetch failed (truncated sample included), a `keep` that fails
midway, a branch whose arrays don't encode, the bind host (wildcard
included), and the store and `discard`.
`tests/unit/orchestrator/test_train_sink_payloads.py`: the train sink
deletes exactly the arrays of filtered, dropped, stale, pruned and
discarded samples and leaves only the shipped ones; the eval sink
deletes those of eval episodes; the dispatcher deletes those of episodes
that returned after their group was dropped.
`tests/unit/orchestrator/test_env_replicas.py`: least-loaded routing
over replicas. `pytest -m "not gpu" tests/unit` after merging `main`:
1003 passed; after the last fixes, the affected suites (orchestrator,
transports, trainer, configs, eval) pass 498.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Changes the training data path (HTTP payload fetch, strict delete
accounting, micro-batch drop on fetch failure) and multi-node env-server
placement; misconfiguration or network issues can silently drop training
signal or fail steps.
>
> **Overview**
> **Training arrays (router replay, sampling masks, top-k heads) are
kept on env servers and passed by reference** instead of riding inline
through the orchestrator and rollout transport. The `env-server`
entrypoint installs `PayloadHook`, which encodes branch arrays over HTTP
and stamps `trace.info["prime_rl_payload"]`; samples carry
`PayloadSlice`, the packer threads `payloads` through micro batches, and
trainer ranks **fetch** blobs before each step then **release** them
after a DP-wide sync. Dropped or never-shipped arrays are deleted from
train/eval sinks, the dispatcher on cancel, and when fetches fail micro
batches are zeroed out of the loss (with
`payload/dropped_micro_batches`).
>
> **Multi-node runs spread env-server load**:
`orchestrator.env_server_replicas` (auto-set to inference node count)
launches one env server per inference node; the orchestrator connects to
all replicas and routes episodes **least-loaded first**. SLURM templates
move env-server startup off the orchestrator node; address files use
`<name>.<replica>.address`.
>
> Orchestrator batching no longer inlines slice/pack logic for routed
experts and masks—that moves to `transports/payload.py`. Live monitor
deltas keep full delta dicts; the `sampling_support/size` metric is
removed.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d65bfc0373f6432226d9f2506ff702b7b4fe3590. 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 orchestrator stamps each shipped `TrainingSample` with a per-token
`staleness` stream (int16). The stamping runs in a worker thread, off
the event loop. The value is the version the batch trains on minus the
policy version that sampled the token, and it uses the same fallback as
the existing staleness metrics. `-1` marks tokens without a staleness:
context tokens, frozen-sourced rollouts and padding.
- `MicroBatch` carries the stream as an optional appended field
(`MICRO_BATCH_DTYPES["staleness"] = int16`). Packing backfills samples
without a stream with `-1`, and padding pads with `-1`.
- The trainer folds the mismatch KL into log2 staleness bins (`0`, `1`,
`2-3`, `4-7`, …, `64+`) with `torch.bucketize`. It logs them as
`mismatch_kl_by_staleness/{bin}/{mean,std,max}`. The fold reuses the GPU
moments of `TensorStats`, so no extra collective runs. Empty bins are
left out.
- `TensorStats.add` gets `fold_all=False` to skip the `/all` aggregate,
which here would only repeat `mismatch_kl/all`.
- Docs: added the metric to `docs/training.md`, to the staleness section
of `docs/algorithms.md`, and to the stability table of the `monitor-run`
skill.
Bin `0` holds only the numerical trainer–inference mismatch, because the
trainer computes its logprobs with the same weights that sampled those
tokens. The rise across bins is the drift that staleness adds.
## Verification
- Unit tests: `tests/unit/orchestrator/test_batch.py` and
`test_train_sink.py` (CPU), plus `tests/unit/train/test_tensor_stats.py`
(1×H200, 3 passed).
- E2E: `examples/basic/reverse-text/rl.toml` (Qwen3-0.6B, 1 node, 1
trainer + 1 inference GPU) for 15 steps with `orchestrator.max_staleness
= 8`. The run completed. Every step logged the binned keys, and each
step's bins match the orchestrator's `staleness/token/mean`. The slow
first step (compile) let the dispatcher queue v0 rollouts, so staleness
climbs by one per step until fresh rollouts replace the queue:
| step | `staleness/token/mean` | `mismatch_kl/all` | `0` | `1` | `2-3`
| `4-7` |
|---|---|---|---|---|---|---|
| 1 | 0.00 | 5.5e-04 | 5.5e-04 | | | |
| 2 | 1.00 | 6.5e-04 | | 6.5e-04 | | |
| 3 | 2.00 | 1.1e-03 | | | 1.1e-03 | |
| 5 | 4.00 | 7.2e-03 | | | | 7.2e-03 |
| 9 | 6.27 | 4.1e-02 | | | | 4.1e-02 |
| 12 | 4.26 | 1.1e-02 | | | 4.4e-03 | 1.1e-02 |
| 14 | 3.79 | 8.5e-03 | | | 4.4e-03 | 1.1e-02 |
Within one step (12, 14), the `4-7` bin carries about 2.5× the KL of the
`2-3` bin.
- Ship-path cost, replaying one real agentic batch (2048 episodes, 2142
samples, 193.5M tokens, about 95 turns per rollout) through `TrainSink`
and `finalize_train_batch`: stamping takes 0.84 s in a worker thread, of
which `token_staleness` is 0.59 s. The whole ship takes 21.4 s. The
int16 stream adds 2 bytes per token to the wire.
- With the stream as int8, I re-ran the same e2e config: 15/15 steps,
and each step's bins again match `staleness/token/mean`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Observability and batch metadata only—no loss or staleness masking
behavior changes; wire format adds an optional appended field with `-1`
backfill for compatibility.
>
> **Overview**
> Adds **per-token staleness** on the orchestrator→trainer path and
**binned mismatch-KL metrics** so you can separate numerical
trainer–inference drift from off-policy staleness.
>
> At batch ship time, `TrainSink` stamps each `TrainingSample` with
`staleness` (trained policy version minus the version that sampled the
token; `-1` for non-sampled/padding tokens) via new `token_staleness()`.
The optional `int16` stream is packed through `MicroBatch` (backfill
`-1`, padding `-1`) and decoded in the RL data loader.
>
> The trainer buckets mismatch KL with `torch.bucketize` into log₂ bins
(`0`, `1`, `2-3`, …, `64+`) and logs
`mismatch_kl_by_staleness/{bin}/{mean,std,max}` on sampled tokens only.
`TensorStats.add` gains `fold_all=False` so bin folds skip a redundant
`/all` rollup; W&B filtering treats the new prefix like other
mismatch-KL keys.
>
> Docs and the monitor-run skill document the metric; unit tests cover
packing, ship-time stamping, and grouped stats.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f8a91257dde322e805bdd517b71108ae329fa0d2. 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>
GPU tests move from `tests.yml` into a new `gpu.yml` that runs on PRs
only on request: applying the `gpu-ci` label runs the full GPU suite on
the PR's current commit. Before, every push to a ready PR re-ran the GPU
suite whenever the diff hit a broad path filter, which about 64% of
recent `main` commits did.
- The label is one-shot: the workflow removes it, so re-apply it to run
again after new pushes or to retry.
- A new trigger cancels the PR's queued or in-flight GPU run.
- Approvals do not trigger GPU CI, so a PR merged without the label is
first GPU-tested by the run on `main` after it merges.
- Every merge to `main` still runs the full GPU suite, now each in its
own run, in parallel with any already in progress. Before, `main` ran
one at a time and a newer merge replaced the one waiting, so a burst of
merges was tested together. Per-merge runs pin a failure on one commit
but use more GPU time during bursts. To go back, key push events on a
fixed name instead of `run_id` in `gpu.yml`'s concurrency group.
`tests.yml` keeps its CPU jobs and the path-gated `gsm8k_eval`.
- Fork PRs and PRs with merge conflicts can't run GPU CI. For a fork PR,
a maintainer can push the branch here and label it.
- Dispatching `tests.yml` no longer runs GPU jobs (dispatch `gpu.yml`),
and the README "Tests" badge no longer reflects GPU results.
- `AGENTS.md` tells agents how GPU CI is triggered, and to add the label
only when the user asks.
Possible future extension point: scoped labels like `gpu-ci:unit` could
run a subset of the GPU tests, with each GPU job checking for its own
label.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Adds token-weighted importance-ratio diagnostics to IPO and IcePop
(including IcePop + SC), separately for all RL tokens and tokens
accepted by the sampled-action mask. This makes large accepted weights
visible even when average mismatch KL looks stable.
Logs ratio and log-ratio mean/std/min/max, plus exceedance indicators at
5, 10, 100, and 10,000 (their means are token fractions). Ratios are
measured before the loss's cap. Diagnostic ratios saturate at 1e30 to
keep moments finite; unclipped log ratios and a saturation indicator
preserve visibility into larger values. Uses the existing distributed
TensorStats reducer; no percentile estimates or changes to
loss/gradients.
Validation: all 26 loss tests passed on the devbox GPU, including
gradient parity, extreme ratios, ignored tokens, and empty accepted
sets. Ruff check/format passed. The separate TensorStats suite could not
collect with the devbox's installed Verifiers version
(`agent_config_fields` missing); the reducer itself is unchanged.
Fuses the input side of DeepSeek-V4's manifold-constrained
hyper-connections (mHC) into one Triton op. **Main win: the
hyper-connections stop storing a 64 KiB/token fp32 copy of the streams,
which saves ~8 GiB of activations per decoder layer at 64k tokens and
lets a 131k-token layer fit where main runs out of memory.** It also
applies unchanged to GLM-5.3-Flash (`glm5_next`), which uses
`DeepseekV4HyperConnection`.
## What changes
On main, each `DeepseekV4HyperConnection` (two per layer) and the
`DeepseekV4HyperHead` compute, in plain PyTorch: an fp32 RMS norm over
the flattened `(T, 4 × hidden)` streams → an fp32 `F.linear` to 24
outputs (4 for the head) → the gates → the pre-collapse `(pre *
x).sum(2)`. The fp32 normalized copy is written, re-read by the GEMM,
and kept for backward.
`prime_rl::dsv4_mhc_pre` (`kernels/deepseek_v4/dsv4_mhc_pre.py`)
replaces that with one custom op:
- The RMS norm is folded into the projection (`mixes = (x @ fn.T) *
rstd`), so the normalized streams are never built.
- Autograd keeps only `x`, `mixes` `(T, 24)` and `rstd` `(T,)`.
- Backward: one `dx` kernel; `d fn` uses fixed split-token partials, so
it is deterministic.
- Sinkhorn and the write-back keep the existing `dsv4_mhc.py` kernels.
TF32 follows the same rule as the fp32 `F.linear`.
## Savings (1× H200, `torch.compile`, bf16, main → this PR)
| | tokens | fwd+bwd | activations saved for backward | backward peak |
|---|---|---|---|---|
| **DeepSeek-V4-Flash decoder layer** (MoE), no AC | 64k | 350 → 344 ms
(−2%) | 42.3 → 34.3 GiB (**−8 GiB**) | 54.9 → 44.9 GiB (**−10 GiB**) |
| same | 131k | OOM → 748 ms | OOM → 68.6 GiB | OOM → 82.1 GiB (**now
fits**) |
| hyper-connection pair alone, no AC | 64k | 31.2 → 23.4 ms (1.33×) |
11.0 → 4.0 GiB | 21.0 → 9.6 GiB |
| hyper-connection pair alone, full AC | 64k | 38.6 → 30.0 ms (1.29×) |
0 → 0 | 21.5 → 9.6 GiB |
| **GLM-5.3-Flash** hyper-connection pair, no AC | 128k | 63.1 → 45.9 ms
| 22.1 → 8.1 GiB | 42.1 → 19.1 GiB |
| GLM-5.3-Flash layer 3 (sparse MLA + MoE), full AC | 64k | — | — | 57.8
→ 48.9 GiB (**−9 GiB**) |
So per layer the speed gain is small (the hyper-connections are a small
share of layer time); the value is memory: about −8 to −10 GiB of
activations/peak per layer at 64k, more at longer context.
## Validation
- Numerics (8,229 tokens, bf16, `matmul_precision="high"`, fwd+bwd vs
fp64): the `post`/`comb` gates are ~10× closer to fp64 than main (main
rounds the fp32 normalized streams to TF32); every other output and
gradient is within 5% of main's error.
- `test_deepseek_v4_kernels.py::test_fused_mhc_pre_matches_reference`
(GPU, passes on H200): outputs and grads of `x`, `fn`, `scale`, `base`
vs fp64, for 4 and 24 outputs, across token and hidden block boundaries.
- `-m "not gpu"` unit tests and ruff pass on the branch merged with
current main.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches core hyper-connection math and training gradients via new
Triton autograd; numerics are tested but behavior differs slightly from
materialized fp32 norm (TF32 matmul rules preserved).
>
> **Overview**
> Replaces the eager PyTorch **mHC input path** (fp32 RMS norm on
flattened streams, `F.linear`, pre-collapse) in
`DeepseekV4HyperConnection` and `DeepseekV4HyperHead` with a single
Triton fused op **`fused_mhc_pre`** (`dsv4_mhc_pre.py`).
>
> The kernel folds RMS norm into the projection (`mixes = (x @ fn.T) *
rstd`) so the large fp32 normalized stream buffer is never materialized.
It returns **`collapsed`** and **`logits`**; callers still derive
**`post`** / **`comb`** (Sinkhorn) from logits via existing `dsv4_mhc`
kernels. A custom op **`prime_rl::dsv4_mhc_pre`** implements forward and
backward (including split-token weight grads).
>
> Adds GPU test **`test_fused_mhc_pre_matches_reference`** (outputs and
grads vs fp64 reference across token/hidden block sizes).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
56879eefdb125b430f2a2d660639992f390ea6a5. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
MoE routing stats (`max_vio`, `routing_confidence`) are now reduced once
per step instead of once per micro step.
On main, `get_global_moe_stats` runs every micro step, and each call
does 1 EP all-reduce and 2 DP×CP all-reduces. Now each micro step only
snapshots this rank's routing counters (`take_moe_routing_stats`, no
collective). After the micro steps, one EP all-reduce over the stacked
snapshots and one MAX + one SUM over DP×CP give the same per-micro-step
values as before. RL folds them into `TensorStats` as before; SFT takes
the same mean/max over micro steps.
The logged metrics and their definitions do not change. `expert_load/*`
still uses this rank's unreduced counts summed over the step.
Validation:
- CPU (gloo, 4 ranks, EP group of 2, 4 micro steps, fake MoE blocks):
per-micro-step `max_vio` / `routing_confidence` and the summed
`tokens_per_expert` match main's `get_global_moe_stats` exactly; models
without MoE blocks still return no stats.
- `pytest tests/unit -m "not gpu"`, `ruff check`, `ruff format --check`
on the branch merged with current main.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Refactors when MoE routing collectives run but preserves the same
metric definitions; validated against the prior per-micro-step path on
CPU distributed tests.
>
> **Overview**
> **MoE routing metrics are cheaper per training step** by deferring
distributed reductions until after all gradient-accumulation micro steps
finish.
>
> Each micro step now only calls **`take_moe_routing_stats`** to pack
this rank’s per-layer token counts and routing-confidence sums and reset
the MoE buffers—**no collectives**. **`get_global_moe_stats`** takes the
stacked snapshots, does **one EP all-reduce** on the batch, derives
per-micro-step `max_vio` and `routing_confidence`, then **MAX/SUM over
DP×CP** as before. RL logs those vectors through `TensorStats` after the
micro loop; SFT aggregates mean/max across micro steps once at step end.
**`get_load_balance_stats`** is removed; validation still clears routing
counters via **`take_moe_routing_stats`**.
>
> **`expert_load/*`** still uses this rank’s unreduced counts summed
across micro steps; metric definitions are unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b4e2a96539e449aed0a7ef50b33c62aca1b49301. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Bump verifiers to PrimeIntellect-ai/verifiers#2980. With it,
`Episode.to_record()` returns the per-token node streams as numpy
arrays.
- The file monitor's orjson (`OPT_SERIALIZE_NUMPY`) writes them in one
pass, so the file monitor needs no code change.
- The bump adds `orjson` to the verifiers dependencies. `uv.lock` is
relocked for it.
- The prime monitors keep passing the episodes to the SDK. From
PrimeIntellect-ai/prime#1109 on, the SDK encodes the numpy streams with
orjson.
- `test_episode_records.py` checks the upload path with the SDK's own
encoders: the trace line, the samples batch and the training viewer
table.
**Pinned until release:** PrimeIntellect-ai/prime#1109 is merged but not
released yet, so `prime-runs` and `prime-traces` are pinned to its merge
commit on prime main (`adf8d25`), with a TODO to replace the pins with
the PyPI release and raise the `prime-runs` minimum. `deps/verifiers` is
on verifiers main with PrimeIntellect-ai/verifiers#2980 (f166cd5). With
the released SDK, the prime monitors' uploads fail with `TypeError`.
## Verification
Real data: one 2,048-episode training batch with 193M tokens, replayed
through the real `TrainSink` and `Orchestrator.finalize_train_batch`
with a no-op sender.
| | Before | After |
|---|---|---|
| File monitor serialization, single-threaded, per batch | 103.3 s |
18.1 s |
| `FileMonitor.log_episodes` during arrival, per batch | 113.4 s | 19.9
s |
| Ship with the file and prime serializers running in background threads
| 1015.7 s | 114.2 s |
- Ship time runs from taking the batch to shipping it. The last row is a
worst case: each monitor's real per-episode serializer loops in its own
thread, as with a backlog. These threads hold the GIL in long C calls
and starve the ship's pure-Python steps. Without them, the ship on this
base takes ~42 s.
- In the last row, before is `main` with the released SDK, and after is
this stack with PrimeIntellect-ai/prime#1109. GC time in the ship drops
from 103.7 s to 0.6 s, and the longest pause from 4.52 s to 0.01 s.
- The prime serializer thread still costs 147 ms per episode after. Of
that, 12 ms is the encode and the rest is the SDK's level-9 gzip, which
releases the GIL.
- The prime SDK trace line drops from 114.7 ms per episode (`main` and
the released SDK) to 12.2 ms (this stack with
PrimeIntellect-ai/prime#1109) on 512 episodes, with the same content.
- `pytest tests/unit/orchestrator tests/unit/utils
tests/unit/train/sft/test_prime_monitor.py
tests/unit/test_dashboard_artifacts.py` with the
PrimeIntellect-ai/prime#1109 SDK: 181 passed. With the released SDK,
`test_received_episode_uploads_plain_json` fails with `TypeError: Object
of type ndarray is not JSON serializable`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Temporary git pins on core upload/training SDK packages change
resolution and reproducibility until PyPI catches up; behavior change is
limited to serialization of episode traces but affects all prime monitor
uploads.
>
> **Overview**
> **Pins `prime-runs` and `prime-traces` to the Prime main commit that
ships PrimeIntellect-ai/prime#1109** (orjson-based trace/record encoding
for numpy per-token streams), via `tool.uv.sources`, an override on
`prime-traces`, and a refreshed `uv.lock`. TODOs call out swapping these
git pins for the next PyPI releases.
>
> **Aligns upload-path tests** in `test_episode_records.py` with the
SDK: trace lines use `prime_traces._encode_record`, and sample JSON uses
`prime_runs._http.encode_json`, with an explicit check that encoded
`token_ids` remain plain JSON lists—not the old `json.dumps` /
`to_mapping` stand-ins.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d5b8db34167db201053542308821278e1a3eff54. 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 native image training to Qwen3.8 Flash Next (`qwen4_exp`) through
Prime-RL’s existing multimodal pipeline.
- Adds the checkpoint-compatible vision encoder and composite model,
merges image features into placeholders, and constructs packed MRoPE
positions.
- Preserves raw token IDs for PLE hashing; CP shards merged embeddings,
token IDs and positions after vision encoding.
- Keeps vision parameter names and checkpoint conversion intact,
including frozen-vision and text-only dummy-forward handling.
- Includes #4259’s validated linear patch projection, learned-position
interpolation and rotary-trig alignment. No fused-head or
hyperconnection experiments.
- Provides Qwen3.5/Qwen3.8 image RL examples using the included
`primeintellect/color-codeword@0.1.0` environment and native `null`
harness, with disjoint training/evaluation slices and comments showing
where to substitute your multimodal environment. Qwen3.8 uses CP8.
Rebased onto main `088570f8` (2026-10-26). Main now supplies #4252’s PLE
memory fix, #4264’s FLA 0.6.0 update and #4279’s new QSA
kernels/activation-checkpoint plan handling.
### Validation
Nebius H200, PyTorch 2.13.0+cu130, exact release kernel wheel
`v0.1.0-b52bd9d`, job **6812**:
- **47 passed:** Qwen3.8 model/meta/checkpoint and VLM checks, Qwen3.5
VLM regressions, activation-checkpoint policies and kernel selection
tests.
- Four fixed-input old/new attention controls include the production
24-query-head / 2-KV-head / 256-dimension geometry, packed/batched
shapes and 2,051 selection slots. Outputs and gradients remain close to
the FP32 reference (roughly 0.21–0.24% relative L2); the new output and
Q/K/V gradients are bitwise identical across three repeats.
- Old/new selector sets match exactly in all three paired controls,
including packed bounds and a CP query offset. The new selector’s order
is repeatable.
- These are component numerical checks, not a full-model KL measurement
or a full-size trainer update. Two-GPU packed-image CP2 + full AC +
compilation also passes forward/backward on both ranks (job 6817), with
finite gradients and outputs matching the unsharded reference within
atol=0.02, rtol=0.03.
- Example follow-up: both previously failing `test_load_configs` cases
pass (**2 passed**). Both configs also load 1,024 shuffled image
training tasks and 128 disjoint evaluation tasks, and resolve
`ColorCodewordEnv` with `NullHarness`. Browser-only fields were replaced
with the native harness's compaction setting. Both examples inherit the
default Prime runtime (no subprocess override); train/eval runtime
resolution was verified. Whitespace checks pass.
- Ruff lint/format and whitespace checks pass. Vision implementation and
vision tests are unchanged from the previously validated PR head. The
examples retain CP8 for Qwen3.8 and use main’s renamed max_staleness
field (8).
Earlier frozen-model validation of the three vision changes used one
eight-image prefix and all 4,545 generated targets, with saved inference
expert replay and stable attention ordering. Exact full-vocabulary KL
fell **0.002570 → 0.001602** with FLA 0.5.2 and **0.002430 → 0.001249**
with FLA 0.6.0. These results predate this main rebase and do not
establish training-wide gains.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> New vision encoder and MRoPE/CP paths affect large-scale RL training
numerics and distributed behavior; mitigated by extensive unit tests but
not full production KL validation in this PR.
>
> **Overview**
> **Adds native vision-language training for Qwen3.8 Flash Next**
(`qwen4_exp`) on top of Prime-RL’s existing multimodal stack, alongside
doc and example updates for Qwen3.5/Qwen3.8 image RL and SFT.
>
> The trainer gains a composite **VLM model**: vision encoder
(`model.visual`), image-token scatter into language embeddings, **packed
MRoPE** positions from `mm_token_type_ids` / `image_grid_thw`, and
**context-parallel sharding after** vision merge. PLE still hashes raw
placeholder `input_ids`; checkpoint conversion **keeps** `model.visual`
weights instead of dropping them. `QwenVLAdapter` registers `qwen4_exp`.
>
> **Docs** list Qwen3.8 in model/VLM tables, add a `qwen3.8` renderer,
and revise multimodal limits (FP32 trainer + BF16 vLLM is OK; monitor
mismatch KL metrics).
>
> **Examples**: new `rl-qwen3.5.toml` and `rl-qwen3.8.toml` (4×8 H200
trainer + 4 inference replicas, `color-codeword`, GRPO/IPO); expanded
`examples/extra/vlm/README.md`.
>
> **Tests** cover VLM forward/backward, router replay, MRoPE packing,
and composite checkpoint roundtrip.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b12f244d24b0e86afa8a3746e9f3c1cfdebc3113. 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: Cursor <cursoragent@cursor.com>
Co-authored-by: Codex <codex@local>
## Summary
With IcePop score centering on, `validate_score_centering_data` ran on
the CPU, on the training loop's main thread, for every micro batch:
- boolean masking of the `[seq, 128]` head ids and values;
- a full sort of the ids to find duplicates;
- `exp`, sums and support checks.
The loop waits on the GPU at the end of every micro batch, so this time
added straight to step time. It took ~2.4 s per 262k-token micro batch
at `OMP_NUM_THREADS=1`.
This PR runs the same checks on the GPU, on the copies the step already
makes, with no host sync, and checks the result once per step.
## Changes
- `score_centering_data_errors` runs the six checks per token on the
step's GPU tensors. It returns one flag per check without syncing.
- `raise_score_centering_data_errors` syncs once, after the last micro
batch and before gradient scaling, clipping and `optimizer.step()`. It
raises the same message the CPU validation raised for the first failing
micro batch.
- `topk_valid` is computed on the GPU instead of the CPU.
- `validate_score_centering_data` keeps its signature. It reuses the
same checks, and the trainer still calls it on the CPU only when top
logprobs are missing.
**Behavior change:** an invalid micro batch now fails the step after the
forward/backward instead of before its forward. Gradients from bad
sampler evidence are still never applied. In between, out-of-vocabulary
head ids can't index out of bounds: the LM head maps them through
clamped, range-masked local indices.
## Benchmarks
Validation alone, on a synthetic micro batch (262,144 tokens, 128-wide
head, vocab 129,280):
| | per micro batch |
|---|---|
| CPU, `OMP_NUM_THREADS=1` (before) | 2,424 ms |
| CPU, `OMP_NUM_THREADS=16` (before) | 351 ms |
| GPU (this PR) | ~2 ms of kernels, 0.36 ms on the host, ~450 MiB of
temporaries |
End to end, on an 8-layer DSv4-Flash slice: 1×8 B300, CP=8, 4 micro
batches per rank, forward/backward averaged over steps 8–10:
| | s / micro batch |
|---|---|
| score centering on, before | 5.65 |
| score centering on, this PR | 1.84 |
| score centering off | 1.66 |
The remaining ~0.18 s per micro batch is the score-centering loss path
itself.
## Testing
- `tests/unit/orchestrator/test_batch.py` checks that the GPU path
raises the same error as the CPU validation for each corruption case
where top logprobs are present, on CPU and CUDA. On GPU, `test_batch`,
`tests/unit/train/rl/test_loss.py` and `test_fused_lm_head` pass. ruff
check and format pass.
- The old and new validation raise identical messages on 9 corruption
types, on clean data, and on a corrupted row outside the loss mask.
#4232 doesn't touch this validation. The two PRs only conflict
textually, in `train.py`'s top-k block.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Training-step timing and failure timing change for IcePop score
centering; invalid batches still abort before `optimizer.step()` but
after backward. Logic must stay equivalent to the prior CPU checks on RL
tokens only.
>
> **Overview**
> Moves IcePop **score-centering** sampler-evidence checks off the CPU
micro-batch hot path and onto **GPU tensors**, deferring a **single host
sync** until after all micro-batches finish forward/backward.
>
> **`data.py`** factors the six RL-token checks into
`score_centering_data_errors` (per-check flags, no sync) and
`raise_score_centering_data_errors` (one sync, same `ValueError`
messages via `SCORE_CENTERING_DATA_ERRORS`).
`validate_score_centering_data` still runs on CPU when top logprobs are
missing.
>
> **`train.py`** drops per-micro-batch CPU
`validate_score_centering_data`; with logprobs present it appends GPU
flags each micro-batch and calls `raise_score_centering_data_errors`
before gradient scaling/`optimizer.step()`. `topk_valid` is computed on
CUDA with the other top-k tensors.
>
> **Behavior:** bad sampler data now fails the step **after** that
micro-batch’s backward (gradients still not applied); missing-logprob
batches still fail immediately on CPU.
>
> **Tests** assert the deferred GPU path raises the same errors as CPU
validation (CPU/CUDA).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9c23f38ed2a789fe77b7fd3764819041a6b38da5. 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>
Balances `prime_rl::fp8_indexer` (the DSA indexer) across contiguous CP
ranks. Everything outside the indexer keeps main's contiguous split.
With a contiguous split and causal selection, rank P-1 does the most
indexer work and sets the critical path. With `cp_group_name` set (GLM
DSA passes its CP group when CP > 1):
- Rank r pairs with rank P-1-r.
- Each rank sums a cost per query chunk and all-gathers the sums (one
small collective, one host sync per call).
- The heavier rank of each pair sends its trailing whole chunks to its
partner: fp8 q, `w * q_scale`, `ks`, `ke`. The partner already holds the
all-gathered keys. It scores those chunks with the same per-chunk
`_select_topk` and sends back int32 indices.
- Without `cp_group_name`, the op is unchanged from main.
Cost per row: `(ke - ks) + TOPK_COST_PER_KEY · (ke + S_k_aligned)`,
`TOPK_COST_PER_KEY = 0.13`. It is fitted to main's per-rank op times at
26 layouts (CP4/CP8, 128K-1M, 2.2% mean error). A keys-only cost gains
about 0% on packed 256K+ rows and sometimes loses 5-15%.
## Numbers
Op, slowest rank, median ms (H200, GLM-5.3 indexer 32x128 heads,
top-2048; synthetic agentic packed rows, "median"/"worst" row of a step,
plus one long doc; ideal = total work / P):
| layout | main | this PR | ideal |
|---|---|---|---|
| 256K CP8 median row | 30.1 | 27.8 (-8%) | 25.5 |
| 256K CP8 worst row | 79.6 | 59.4 (-25%) | 47.5 |
| 512K CP8 median row | 99.1 | 85.7 (-14%) | 81.3 |
| 512K CP8 single doc | 361.6 | 215.3 (-40%) | 206.6 |
| 1M CP8 median row | 324.4 | 273.8 (-16%) | 265.5 |
| 1M CP8 single doc | 1401 | 823 (-41%) | 801 |
| 128K CP8 median row | 16.4 | 16.4 (0%) | 11.2 |
- Over a whole step of packed rows the indexer op time drops 7-9% at
256K, 13% at 512K and 16-17% at 1M.
- SFT step, `glm_moe_dsa` cut to 8 layers (4 full indexers), CP8 EP8,
AC, 256K: one doc per row 7.62 s -> 7.43 s (-2.4%); packed fake rows
-1.5% (within the 5% noise). Peak memory unchanged.
- Full GLM-5.3 estimate (21 full indexers in 78 layers): about 0.2-0.9%
of the step for packed 256K-1M rows, and 1.3-7.3% for one long 256K-1M
doc.
## Validation
- `torch.equal` against main's op on every rank, at all 26 layouts, CP4
and CP8, four cost settings (same row chunks as the unbalanced path, so
each top-k sees the same logits).
- `test_fp8_indexer.py` and the new plan test pass on H200 (DeepSelect
release build, DeepGEMM 2.5.0).
- `pytest -m "not gpu" tests/unit`, `ruff check`, `ruff format --check`
on the branch merged with current main.
## Notes
- Needs equal-length CP shards, which is true on main. Only GLM DSA opts
in.
- `TOPK_COST_PER_KEY` was fitted on H200.
This PR stops DeepSeek V4 training from recompiling `torch.compile`
graphs whenever a rank first sees a new row length, document layout or
unusually short row. Each recompile stalled every rank for 30 to 200 s,
at whatever step that micro batch arrived.
Step times in seconds; every number past step 1 that is above steady
state is a recompile:
| step | 4 micro batches, `main` | 4, this PR | 1 micro batch, `main` |
1, this PR |
|---:|---:|---:|---:|---:|
| 1 | 733 | 455 | 335 | 371 |
| 2 | 9.1 | 9.4 | 195 | 104 |
| 3 | 33.5 | 6.3 | 85 | 1.9 |
| 4 | 5.0 | 5.0 | 129 | 1.8 |
| 8 | 6.3 | 6.3 | 30 | 2.1 |
| 10 | 152 | 4.5 | 1.7 | 1.7 |
| 5, 6, 7, 9 | 5.4-6.3 | 5.5-6.4 | 1.7-2.1 | 1.8-2.0 |
One 8xB300 node, prod's RL trainer config (CP 8, MXFP8, Muon, full AC,
compile), DeepSeek-V4-Flash truncated to 8 layers, replayed prod tokens
padded to a multiple of 256. Entropy and grad norm track `main` step by
step.
Sources of recompilation and their fixes:
1. Row length varies per rank. FSDP2 hands each layer a view of its
input that drops tensor marks, so the input is passed by keyword and
named in `dynamic_sources`; other row-length inputs are marked directly.
2. Compression layout tensors change size with document lengths. They
are marked dynamic.
3. `max_entries_per_doc` is a Python int. It joins `DYNAMIC_INT_ARGS`.
4. Single-document rows got their own graph. `first_entry_of_doc` is
marked unbacked.
5. The torch MoE dispatcher's argsort recompiled below 32767 routed
tokens. It is now a custom op, which helps every MoE model.
One recompile round remains at the first new row length, once per
restart (the 104 s at step 2), from a dynamo guard on the memory layout
behind FSDP's view. These fixes are DeepSeek V4 specific except the
argsort; a general per-model mechanism is left to a later PR.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Bumps `deps/verifiers` from `e7c847821` (current `main`) to `32c1f14fc`,
the tip of verifiers `main`. There is no newer release tag than
`v0.4.0`, so this pins to main.
New upstream commits:
- `fix(harbor): create artifact directory before grading`
(PrimeIntellect-ai/verifiers#2986)
- `Update bundled harnesses and Code Mode settings`
(PrimeIntellect-ai/verifiers#2988)
Scope:
- Only `deps/verifiers` changes; `prime-envs`, `renderers`,
`prime-kernels` and `pydantic-config` pins are untouched.
- Diff is harness/taskset level (claude_code, codex, pi, prime_agent,
rlm, hermes_agent, harbor taskset, etc.). Worth a smoke run of a harness
eval before merge.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Pins verifiers to moving `main` and changes eval harness/taskset
behavior; a harness smoke eval is advisable before merge.
>
> **Overview**
> Updates the **`deps/verifiers`** git submodule from `e7c847821` to
**`32c1f14fc`** (current upstream `main`; no newer release than
`v0.4.0`). Other dependency pins (`prime-envs`, `renderers`,
`prime-kernels`, `pydantic-config`) are unchanged.
>
> Upstream adds a **Harbor** fix to create the artifact directory before
grading, plus refreshed **bundled harnesses** and **Code Mode** settings
(e.g. claude_code, codex, pi, prime_agent, rlm, hermes_agent, harbor
taskset). Expect harness/taskset-level diffs only inside the submodule.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
cea64f3bdaa814b7dd74e89e61e218c6976a662e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
`tools/convert_dcp_to_bf16.py` crashes on models whose prime-rl class
can't generate, such as `NemotronHForCausalLM` (it doesn't inherit
`GenerationMixin`). For those models transformers never sets
`model.generation_config`, so `save_model_assets` raised
`AttributeError` at `if model.generation_config:`.
The crash happened after the safetensors shards and index had been
written, so the export was left without `generation_config.json`, the
tokenizer files or the chat template, and torchrun exited non-zero.
`tools/convert_dcp_to_fp8.py` reuses `save_model_assets` and had the
same crash.
The fix reads the attribute with `getattr(model, "generation_config",
None)`, so models that can't generate skip writing a generation config.
Behaviour is unchanged for every other model.
Found while planning an HF export of Nemotron 3.5 Super SFT checkpoints.
Open PR #4168 contains the same one-line change inside a larger
CPU-export rework; this PR lands just the fix on its own.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
With IndexShare (GLM-5.3: 21 of 78 layers run the indexer), each index
tensor is passed into the next shared layers. Every checkpointed block
saves it again, and `OffloadActivations` made a new pinned CPU copy for
every save. So the same `[S, 2048]` int32 indices were copied to the
host up to 4 times, and copied back to the GPU up to 4 times. The same
happens to the full-sequence RoPE `cos`/`sin`, which every layer saves.
This PR makes a tensor that has already been offloaded reuse its CPU
copy:
- **Forward:** a contiguous activation whose storage, offset, numel and
dtype match an earlier offload reuses that CPU copy, if the GPU storage
is still alive (`StorageWeakRef`). No new D2H copy is made.
- **Backward:** the first unpack of a shared copy moves it to the GPU
once. Later unpacks reuse that GPU tensor. It is released after the last
unpack.
The dedupe key leaves out the version counter on purpose. In compiled
blocks, the indexer's saved output (version 128, from the chunked
in-place writes) and the view passed to the next layer (version 0) share
storage but report different versions. A saved tensor that is mutated
between two saves would already fail autograd's saved-tensor version
check without offloading.
## Measurements
1x8 H200. GLM-5.3 with all 78 layers (21 indexer + 57 shared layers, the
real IndexShare pattern) and EP8 + CP8. Random init, SFT on fixed-length
fake data, full AC + offload, compile on, bf16 params/grads, one
micro-batch per step. Routed experts were cut from 256 to 32 so the
model fits on one node. Top-8 routing, so per-token compute and
activation shapes are unchanged. Both arms: main 87ddbcf, and main with
this PR merged.
| seq (tokens/rank) | | node host peak | pinned/rank |
offloaded/micro-batch/rank | D2H+H2D time | step (median 2-6) | GPU peak
alloc |
|---|---|---|---|---|---|---|---|
| 64K (8K) | main | 196.1 GiB | 18.1 GiB | 15.4 GiB (317 copies) | 1.21
s | 8.63 s | 58.8 GiB |
| | #4277 | 160.2 GiB | 13.3 GiB | 10.6 GiB (106 copies) | 0.84 s | 8.25
s | 58.8 GiB |
| 128K (16K) | main | 331.9 GiB | 34.2 GiB | 29.0 GiB (317 copies) |
2.25 s | 17.20 s | 65.4 GiB |
| | #4277 | 251.9 GiB | 24.7 GiB | 19.4 GiB (106 copies) | 1.56 s |
16.40 s | 65.4 GiB |
| 512K (64K) | main | 1182.0 GiB | 138.8 GiB | 110.5 GiB (317 copies) |
9.55 s | 79.71 s | 105.6 GiB |
| | #4277 | 806.6 GiB | 92.7 GiB | 72.4 GiB (106 copies) | 5.50 s |
75.33 s | 105.6 GiB |
| 1M (128K) | both | host OOM | | | | | |
- Node host peak is MemTotal-MemAvailable over the run. Pinned is
`torch.cuda.host_memory_stats()` peak, which is about 1.25x the
offloaded bytes because the pinned allocator rounds up. Copy time comes
from a CUDA profile of one step on rank 0.
- The offloaded index tensors go from 78 to 21 copies, as expected: at
512K, 39.0 -> 10.5 GiB per rank. The rest of the saving is repeated
full-sequence saves such as RoPE `cos`/`sin`.
- The copies run on the compute stream (`use_streams = False`), so all
copy time is exposed (>99% not overlapped). The step time saving matches
the removed copy time: -4% at 64K, -5% at 128K, -5.5% at 512K.
- GPU peak is unchanged.
- At 1M (128K/rank), the PR arm still filled the node's 1.57 TiB of host
RAM and OOMed. Scaling the 512K numbers gives about 2.2 TB for main and
1.5 TB for this PR. Neither fits on a 1.6 TB node.
- Loss/grad-norm check, 128K with a nonzero init, 7 steps: step 1
matches exactly (loss 14.0931, grad norm 648). Later steps differ
between arms by no more than two runs of main differ from each other
(e.g. step 3: main 11.672 / 11.636, PR 11.651 / 11.635).
Overlap: #4238 (side-stream offload) and #3926 both rewrite
`act_offloading.py`. This change is small enough to port onto either.
Validation: `tests/unit/utils/test_act_offloading.py` (gpu) passes. The
new test checks that a tensor saved twice, once through a view, gets one
CPU copy, that the shared state is drained after backward, and that the
gradients are exact. `tests/unit/utils` and `tests/unit/test_configs.py
-m "not gpu"` (286 passed) and ruff also pass.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes autograd saved-tensor pack/unpack behavior on the training hot
path when activation offloading is enabled; correctness depends on
storage-based deduping without the version counter, though autograd
would already catch in-place mutations between saves.
>
> **Overview**
> **Activation offloading now reuses one CPU copy when autograd saves
the same underlying storage more than once** (e.g. index tensors and
full-sequence RoPE `cos`/`sin` passed through many checkpointed layers).
>
> On **forward**, contiguous activations that match an existing offload
by storage pointer, offset, numel, and dtype skip a new D2H copy if the
GPU storage is still alive (`StorageWeakRef`). On **backward**, the
first unpack performs a single H2D transfer; later unpacks of that
shared CPU buffer reuse the same GPU tensor until the refcount drops to
zero. The dedupe map is cleared when backward starts.
>
> A GPU unit test asserts that a tensor saved twice (including via a
view) produces one offloaded copy, `shared_copies` is empty after
backward, and gradients stay correct.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e1cbee6285ea7fc9e4947f235e4eb373ec7235d2. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
`fp8_indexer` now scores each query chunk with DeepGEMM's
`fp8_mqa_logits` (already a dependency; the same kernel vLLM uses for
DSA prefill) instead of our Triton kernel, which is deleted. The fp8
quantization, the `w * q_scale` fold, the 1 GiB chunking from #4235 and
DeepSelect's `select_topk` all stay. DeepSelect reads DeepGEMM's
padded-stride table in place (row stride `S_k + 256` floats, 1 KiB
aligned), with no copy.
- `chunk_rows = max(512, 1 GiB / row)`. DeepGEMM handles about 4 queries
per SM, so the 256-row chunks a 1M-key row gets under 1 GiB leave half
the SMs idle (519 vs 975 TFLOPS). The transient is 2 GiB past 512K keys.
- An empty key set now still pads to one 256-key tile. DeepGEMM rejects
zero keys, and DSV4 CSA has rows with no compressed entries.
## Numbers (H200, full `fp8_indexer` op, ms per indexer layer, last CP8
rank, one document, random inputs)
| shape | before #3958 (Triton + torch.topk) | main with #3958 (Triton +
DeepSelect) | this PR (DeepGEMM + DeepSelect) |
|---|---|---|---|
| GLM-5.3 128K (16K q x 128K k, top-2048) | 49.3 | 29.4 | **22.9** |
| GLM-5.3 256K (32K x 256K) | 189.5 | 107.5 | **89.2** |
| GLM-5.3 1M (128K x 1M) | 2996 | 1607 | **1364** |
| GLM-5.3 128K, CP rank 0 | 7.3 | 4.2 | **3.2** |
| GLM-5.3-Flash 128K (16K x 32K pools, top-512) | 14.8 | 9.5 | **5.9** |
| GLM-5.3-Flash 256K (32K x 64K) | 52.7 | 31.3 | **21.4** |
| GLM-5.3-Flash 1M (128K x 256K) | 745 | 398 | **331** |
- Over current main (with #3958) this is -15% to -38% per layer. Over
main before #3958 it is -53% to -60%.
- GLM-5.3 runs 21 full indexer layers per micro-batch (index share).
That saves ~0.14 s per micro-batch at 128K, ~0.4 s at 256K and ~5 s at
1M, forward only. The indices are a mandatory AC save, so nothing is
recomputed.
- Scoring alone: DeepGEMM runs at 900-1000 TFLOPS, Triton at ~740.
- Peak memory is the same as #3958 below 512K keys and +1 GiB at 1M (2
GiB chunks).
- Without DeepSelect (the `torch.topk` fallback), DeepGEMM is no faster
than main and uses +1 GiB: `torch.topk` copies the padded-stride table.
#3958, now in main, provides DeepSelect and the deep-select pin.
## Selection
The logits are not bitwise equal to the Triton kernel's. The only
difference is the order in which the 32 head terms are summed (DeepGEMM:
per-thread partial sums, then a warp-shuffle reduce; Triton:
sequential). The key scale is a power of two, so it adds no rounding.
- Top-k set overlap with main, 4096 sampled rows per shape: >= 99.99995%
of picks. At most 0.1% of rows differ, by one index (GLM 1M). This is
the same size as #3958's own tie differences against main.
- 512 rows of the raw logits vs Triton: 100% identical sets at
128K/256K, 99.9997% at 1M.
- Both kernels against float64 math on the same fp8 inputs give
99.97-99.98% overlap. The rounding change is ~100x smaller than what fp8
tensor-core accumulation already contributes.
- Trainer logits are now exactly 64x vLLM's prefill indexer logits for
the same inputs, because vLLM folds `softmax_scale * H^-0.5 = 1/64` into
the weights, an exact power of two. So this does not add train/inference
selection mismatch.
## Validation
- H200 with DeepSelect (wheel built from
PrimeIntellect-ai/prime-kernels#17) and without it:
`test_fp8_indexer.py` (7 passed / 5 passed + 2 skipped) and
`test_deepseek_v4_kernels.py` (all pass).
- Merged with current main (includes #3958 and the deep-select pin):
`test_fp8_indexer.py`, `test_glm5_next.py`,
`test_deepseek_v4_kernels.py` 47 passed on H200 with the released
DeepSelect wheel; `pytest -m "not gpu" tests/unit/orchestrator
tests/unit/test_configs.py tests/unit/train` 623 passed.
- New test: picks vs float64 scores of the kernel's own fp8-quantized
inputs, all queries within 2 keys of 512.
- `pytest -m "not gpu" tests/unit/orchestrator
tests/unit/test_configs.py
tests/unit/train/models/test_deepseek_v4_cpu.py`, `ruff check`, `ruff
format --check`.
- Not run: Blackwell (DeepGEMM has an sm100 kernel; untested here), real
activations (all numbers use random q/k/w), an end-to-end step.
## Overlaps
- #4057 and #4230 (DSV4.1, drafts) import `_triton_fp8_indexer_kernel`
in `dsv41_indexer.py`. They would call `deep_gemm.fp8_mqa_logits` per
chunk instead (q stays `[S, H, D]`, no permute).
- The CP rebalance PR (`perf/dsa-indexer-cp-balance`) moves the chunk
body into `_select_topk`. Whichever lands second puts the other's chunk
body there. Its per-key top-k cost constant should drop once top-k and
scoring are both causal (DeepSelect `end` + DeepGEMM).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes core DSA indexer scoring and top-k selection numerics (minor
rounding/tie behavior) on a performance-critical training path; behavior
is heavily tested but not bitwise-identical to the removed Triton
kernel.
>
> **Overview**
> **Replaces the custom Triton FP8 scoring kernel with DeepGEMM
`fp8_mqa_logits`** for DSA sparse token selection, while keeping UE8M0
quantization, folding `q_scale` into weights, 1 GiB logits chunking, and
DeepSelect/`torch.topk` top-k.
>
> Query chunks now use at least **512 rows** (`MIN_CHUNK_ROWS`) so
scoring better utilizes SMs on wide key rows. **Empty key sequences**
still pad to one 256-key tile so DeepGEMM never sees zero keys.
>
> Tests add a **float64-on-FP8-quantized-inputs** selection check
(within ~2 keys at the boundary) and update the forced-chunking test for
the new minimum chunk size.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9eb4aaa1af8ea342a57da15ede2c718f7fc7290c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Requests such as “run this on model factory” now route to the
`model-factory` skill at `skills/model-factory/SKILL.md` instead of the
local/SLURM launch workflow. The skill starts from checked-in example
TOMLs and uses portable paths and task-selected account settings.
- Covers Prime authentication and team selection, local versus
run-scoped `PRIME_API_KEY`, secret forwarding, and private Hugging Face
datasets for RL and volume-backed SFT.
- Explains custom branches/commits, restricted `--ref` access,
canonical-repository and private-fork constraints, source overlays,
image compatibility, submodules, and custom environment delivery.
- Covers monitoring, stop conditions, checkpoint retrieval, and
downloading stored traces with pagination, episode/step selection,
separate evaluation IDs, and upload-completeness checks.
Checked against the public [Model Factory
RL](https://docs.primeintellect.ai/hosted-training/hosted-rl), [Model
Factory SFT](https://docs.primeintellect.ai/hosted-training/hosted-sft),
and [trace
retrieval](https://docs.primeintellect.ai/traces/managing-traces) docs,
plus the [Prime CLI
source](https://github.com/PrimeIntellect-ai/prime/blob/main/packages/prime/src/prime_cli/commands/rl.py).
The guidance explicitly handles the docs/CLI mismatch on generic secret
forwarding and version-dependent SFT online eval support.
Validation: all five affected skill entrypoints pass the skill
validator; relative links, both agent discovery paths, and shell syntax
were checked. The Model Factory rename was revalidated for skill
metadata, links, discovery paths, and consistent naming. The embedded
config-validation snippet passes for the existing reverse-text RL and
SFT examples, and the trainer-only SFT adaptation validates. Relevant
CLI flags were checked through help without dispatching work. No Model
Factory GPU run or live trace download was performed.
Uses [DeepSelect](https://github.com/deepseek-ai/DeepSelect) for the DSA
indexer top-k in `fp8_indexer` on SM90/SM100/SM103. Everywhere else it
keeps `torch.topk`. `deep-select` is pinned in the `gpu` extra from
prime-kernels `v0.1.0-b52bd9d` (x86_64 + aarch64); the trainer logs
which top-k path is active.
- `select_topk` passes each row's causal end `ke` as DeepSelect's `end`,
so a row is read only up to its end. Output is unsorted int32 indices.
Rows shorter than top-k get the existing sentinel `S_k`; a NaN row
writes an out-of-range index that the existing range mask turns into the
sentinel.
- glm5_next no longer assumes invalid slots come last: the incomplete
pool's tokens go in the columns after the top-k ones, so DeepSelect's
unsorted order selects the same keys (new CPU test; on H200 all 16384
rows pick the same key sets as `torch.topk`). Rows with no keys keep
`torch.topk` (DeepSelect needs top-k > 0).
- `KEY_ALIGNMENT` 16 -> 256 keys: DeepSelect needs a 1 KiB row stride.
Padded keys are already masked to -inf.
- Exactness: DeepSelect picks the same logit values as `torch.topk` in
every row. Index sets differ only on ties at the k-th place, where
`torch.topk` is not defined either.
## Numbers (H200, top-k on fp32 indexer logits)
| shape | torch.topk | DeepSelect + `end` |
|---|---|---|
| GLM-5.3 cp4 last rank [32k x 131k], top-2048 | 54.4 ms | 10.9 ms |
| GLM-5.3 cp4 first rank, top-2048 | 51.5 ms | 3.6 ms |
| DS-V4 [64k x 16k], top-512 | 13.8 ms | 3.0 ms |
GLM-5.3 shape trainer (seq 131072, cp4 ep8, fp8, AC + offload, compile,
8 layers): step 15.4 s -> 15.0 s; about 1% of a full 78-layer step.
Entropy and mismatch KL identical to 4 decimals.
## Validation
- `tests/unit/train/models/test_fp8_indexer.py` on H200 with DeepSelect
(4 passed) and without it (2 passed, 2 skipped). The new test checks
equal value multisets in all rows and equal index sets where there is no
boundary tie.
- Determinism: the DeepSelect test also calls `select_topk` 3 more times
on the same tie-heavy integer logits (1024 x 16384, top-512 and
top-2048) and checks the raw unsorted output is `torch.equal` each time,
order included. 4 passed on H200 with the DeepSelect wheel
(`deep_select-1.0.0+bfa4507`).
- `pytest -m "not gpu" tests/unit/orchestrator
tests/unit/test_configs.py tests/unit/train`, `ruff check`, `ruff format
--check`, `uv lock --check` on the branch merged with current main.
- With the pinned release wheel on H200: `test_fp8_indexer.py`,
`test_glm5_next.py`, `test_deepseek_v4_kernels.py` (46 passed) and
`test_deepseek_v4.py` (8 passed).
- Not validated on SM100/SM103 (no Blackwell here).
## Before merge
- prime-rl's `prime-kernels` pin (v0.1.0-3101960) is not moved here.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes sparse attention token selection on supported GPUs; behavior
is validated against torch.topk except tie-breaking at the k-th slot,
but training numerics depend on that path.
>
> **Overview**
> Adds the **`deep-select`** wheel to the Linux **`gpu`** extra (x86_64
+ aarch64 from prime-kernels) and routes DSA FP8 indexer top-k through
**DeepSelect** on SM90/SM100/SM103, with **`torch.topk`** fallback
elsewhere. Startup logs which path is active.
>
> **`fp8_indexer`** gains **`select_topk`**, which passes per-row causal
**`ke`** into DeepSelect and bumps **`KEY_ALIGNMENT`** from 16 to
**256** keys so logits rows meet DeepSelect’s 1 KiB stride.
**`glm5_next` `KPoolIndexer`** no longer assumes top-k indices are
sorted with invalid slots last: selected pool tokens fill the first
**`token_budget`** columns in any order, and the incomplete-pool tail is
written to fixed columns after that (replacing **`scatter_`**
placement).
>
> New GPU tests compare DeepSelect to **`torch.topk`** (value multisets,
tie behavior, determinism) and assert **`KPoolIndexer`** output is
unchanged when mock indexer order is reversed.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
688290d32d4dec4db3811bc71c7ecda9a2351ae6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
FSDP can run an all-gather and a reduce-scatter at once next to a
persistent Mega MoE grid, so both NCCL kernels have to fit in the SMs
Mega MoE leaves free. With NCCL_MAX_CTAS equal to num_reserved_sms (the
documented 16/16), the two kernels overflow the reservation and deadlock
against the Mega MoE grids under full activation checkpointing.
The trainer now sets NCCL_MAX_CTAS to num_reserved_sms // 2 (8 by
default) before initializing torch distributed when it is unset, and
refuses to start when it is set above that. num_reserved_sms must be at
least 2.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes distributed startup env and validation for Mega MoE training;
mis-set NCCL_MAX_CTAS still fails fast, but default behavior shifts from
16 to 8 CTAs (5 under HSDP).
>
> **Overview**
> Fixes Mega MoE deadlocks when FSDP runs **two** NCCL collectives
(all-gather + reduce-scatter) alongside the persistent MoE grids, and
**three** under HSDP (`dp_replicate > 1`).
>
> **`NCCL_MAX_CTAS`** is now derived from how many kernels must fit in
`num_reserved_sms`: the trainer calls `default_nccl_max_ctas` via
`setup_moe_comm_env` **before** `setup_torch_distributed` in RL and SFT
when dispatch is `mega_moe`. If unset, it sets `NCCL_MAX_CTAS` to
`num_reserved_sms // 2` (or `// 3` under HSDP); startup fails if the env
var is above that cap. `reserve_sms_for_comm` and config/docs/benchmark
are aligned with the same concurrent-kernel model; `num_reserved_sms`
must be at least **2**. Manual `NCCL_MAX_CTAS=16` in docs/examples is
dropped in favor of the default.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
29a7a816fc025b3e35a37960d203771e6683b0d6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Bumps prime-kernels from `v0.1.0-3101960` to `v0.1.0-b52bd9d` (wheel
URLs, `deps/prime-kernels` submodule, `uv.lock`). Also adds
`prime_kernels::indexed_attention_plan` to `MANDATORY_SAVE_OPERATIONS`,
so full AC does not rebuild the plan in the recompute.
## What the new kernels bring (Qwen3.8-Flash-Next QSA; API unchanged)
- PrimeIntellect-ai/prime-kernels#22: `indexed_attention` as windowed
GQA Triton kernels. A new plan op groups 5 queries per window. 1.2-3.7x
per QSA layer fwd+bwd on H200 (16K: 116 -> 31 ms, 64K: 352 -> 191 ms,
CP8 rank 16K x 131K: 84 -> 65 ms) and lower peak memory. The dK/dV
backward is key-major with no atomics, so it is bitwise deterministic.
- PrimeIntellect-ai/prime-kernels#23: `select_indexed_blocks` uses
query-tiled scores and a radix select without atomics. 3.8-4.4x on
selection (64K: 32 -> 7.2 ms, CP8 at 1M: 2186 -> 516 ms). Scores and
selected sets are bitwise equal to before, and the output order is now
deterministic (ascending).
- The release also carries the DeepSelect wheel (#17), used by #3958;
this PR does not pin it.
## Plan save under full AC
The plan depends only on the indices and syncs to host for its sizes.
Without the save it is built twice per step (forward and recompute).
Profiled step (4-layer Qwen3.8, one QSA layer, full AC):
`_window_keys_kernel` launches 4 -> 2, so the plan is built once.
## Numbers (1 node, 8x H200, FSDP, 4-layer Qwen3.8 `q38-4l-small`, full
AC, SGD; median step after 2 warmup steps, 8 steps)
| tokens / rank | main (3101960) | new kernels, plan not saved | this PR
|
|---|---|---|---|
| 16K | 1.087 s | 0.908 s | 0.904 s |
| 64K | 3.754 s | 3.613 s | 3.593 s |
- Only 1 of the 4 layers is QSA, so the full-model gain is smaller than
the per-layer gain. Saving the plan saves about 20 ms per QSA layer at
64K.
- Loss per step matches main to about 1e-4 relative, the same run-to-run
noise main shows. The two new-kernel arms give bitwise-equal losses over
all 8 steps.
## Validation
- H200 with the release wheel: `test_qwen3_8_flash_next.py` +
`test_checkpointing.py` (16 passed). prime-kernels `smoke_test.py
prime-kernels` OK, prime-kernels `tests/` (6 passed).
- `pytest -m "not gpu" tests/unit/orchestrator
tests/unit/test_configs.py tests/unit/train` (620 passed), `ruff check`,
`ruff format --check`, `uv lock --check` (uv 0.13.5).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches training correctness under full activation checkpointing and
swaps prebuilt GPU kernel wheels; mis-saving the plan could change
numerics or performance on QSA paths.
>
> **Overview**
> Bumps **prime-kernels** from `v0.1.0-3101960` to **`v0.1.0-b52bd9d`**
on Linux x86_64 and aarch64 (`pyproject.toml` wheel URLs and matching
**`uv.lock`** hashes).
>
> Adds **`prime_kernels::indexed_attention_plan`** to
**`MANDATORY_SAVE_OPERATIONS`** in activation checkpointing so **full
AC** keeps the indexed-attention plan across forward and recompute
instead of rebuilding it (paired with the new kernels’ plan op).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
96d8822682f695e9cf11bfe77d88892c261fc048. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
`TrainSink.process_batch` crashes with `KeyError` on the stale-token
metric path (#4143, renamed in #4253) as soon as a queued trace has
tokens past `max_staleness`. Seen at step 18 of an async debug RL run.
`vf.Trace.branches` is a property that builds new `Branch` objects on
every access. The trainable masks were keyed by `id(branch)` from one
`iter_trainable_branches(trace)` call, then looked up with a branch from
a second `trace.branches` call. The ids never match, unless CPython
happens to reuse the freed address. When it does reuse one, the lookup
can silently return a different branch's mask.
Fix: key by `branch.index` and take the branch and mask from the same
`iter_trainable_branches` pass. Only the `staleness/token/masked` metric
was affected. Masking in `_drop_stale` already indexes a single
`branches` list.
Regression test: a partially stale trace ships its fresh token. On main
it fails with the `KeyError`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Narrows a metrics-only bug in batch assembly; actual stale-token
masking in `_drop_stale` was already correct.
>
> **Overview**
> Fixes a **`KeyError`** when `TrainSink.process_batch` records
**`staleness/token/masked`** for queued traces with tokens past
**`max_staleness`**.
>
> The metric path used **`id(branch)`** from one
**`iter_trainable_branches`** pass but looked up branches via
**`trace.branches[sample.branch_index]`**, which rebuilds new
**`Branch`** instances on each access so keys rarely matched (and could
silently map to the wrong mask). It now keys trainable masks by
**`branch.index`** and uses the **branch and mask from the same
iteration**, matching how **`_drop_stale`** already indexes a single
branch list.
>
> Adds **`test_partially_stale_trace_ships_fresh_tokens`** so a
partially stale trace still ships fresh tokens and reports the
masked-token rate without crashing.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
33d1543b2f5072d7052aa8beeeaa9cebc7055153. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Vectorize `_refine_by_swapping` in `orchestrator/batch.py`. For each
rank pair, NumPy now scores all candidate swaps at once. Before, a
pure-Python loop rebuilt the load list for each candidate.
- Keep the scoring `(max load, max - min load)` and the tie-break order
(rank pair, left position, right position). The result is the same
partition.
- Take loads relative to the current max load. This keeps the int64 math
in range when total FLOPs exceed int64.
## Verification
- Real data: one 2048-sample batch (744 bins, 8 train ranks), replayed
through `BatchPacker.pack` on CPU.
- `_refine_by_swapping`: 8.2 s → 0.06 s (50 swap passes).
- `BatchPacker.pack`: 17.7 s → 4.1 s.
- Equivalence: the old and new versions return identical partitions on
210 random cases (various sizes and rank counts) and on the real-data
input.
- Overflow: a k=2 case with 4e18 weights gives the correct result.
- `pytest tests/unit/orchestrator`: 132 passed.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes hot-path load-balancing logic for multi-GPU micro-batch
distribution; logic is complex but claimed equivalent and tested on
random and overflow cases.
>
> **Overview**
> **`_refine_by_swapping`** (used after Karmarkar–Karp in
`balanced_partition` for orchestrator batch packing) is rewritten to
score all candidate swaps between a rank pair with NumPy broadcasting
instead of nested Python loops that rebuilt load lists per candidate.
>
> Scoring still minimizes **(max partition load, max − min load)** with
the same tie-break order (rank pair, then left/right item index). Loads
are expressed **relative to the current max** so int64 arithmetic stays
in range when per-item weights (e.g. FLOP estimates) are huge. Applied
swaps now **incrementally update** partition loads instead of carrying a
full `new_loads` tuple.
>
> Behavior is intended to be **partition-equivalent** to the prior
implementation, with large speedups on real pack workloads.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b7eda0e3d676ae352b0d88604222efbe440b07f0. 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>
Qwen3.8 PLE computes the full sequence's convolution on every CP rank,
then discards nonlocal output rows. At long contexts this creates large
FP32 intermediates: a 4-trainer H200 run OOMed during backward
recomputation, requesting 8.99 GiB with 331 MiB free.
Compute only each rank's local output rows using global positions.
Preserve the existing differentiable gather, document-boundary masks,
kernel-tap order, FP32 multiplication/accumulation and final cast. The
full gathered input remains allocated. No optimizer or precision
settings change.
Validation on 4 H200s, Slurm 6251 (PyTorch 2.13.0+cu130, exit 0):
- Native PLE at CP1/CP4, 64/1,024/4,096 tokens, with/without native full
activation checkpointing and packed documents crossing shard boundaries.
All 48 forward outputs and all 48 input gradients were bitwise
identical.
- 328/336 parameter-gradient comparisons were bitwise identical. Only
convolution-weight gradients differed: maximum relative L2 error
3.81e-6; maximum absolute difference 0.00390625.
- Isolated CP4 convolution at expanded width 10,240, including
forward/backward and checkpoint recomputation. Peak PyTorch allocated
memory, maximum across ranks:
| Sequence tokens | Existing | Local rows |
| --- | ---: | ---: |
| 163,840 | 50.85 GiB | 15.69 GiB |
| 237,568 | 73.71 GiB | 22.72 GiB |
Full-model frozen scoring on 8 India H200s, CP4/EP8, eager/no-grad, no
optimizer: three overlapping archived prefixes from one real rollout,
identical inputs/images/masks and loaded parameters. The table reports
the native mismatch-KL estimator averaged over generated tokens with
`loss_mask=True`; each case is token-weighted, not an episode-average
estimate.
| Prefix tokens / images | Scored tokens | Existing, first pass | Local
rows | Unchanged-repeat range (3 passes) |
| --- | ---: | ---: | ---: | ---: |
| 14,546 / 1 | 1,111 | 0.031938 | 0.033646 | 0.026636–0.036309 |
| 18,141 / 2 | 1,489 | 0.030289 | 0.027104 | 0.029987–0.030289 |
| 59,165 / 17 | 14,241 | 0.022497 | 0.023918 | 0.022252–0.022627 |
Unchanged forwards also vary: sampled-logprob mean absolute differences
are approximately 0.066–0.079, comparable to candidate-vs-reference
differences. Natural routing was used because archived expert replay IDs
were unavailable. Parameter fingerprints matched across the scored
forwards; an initial fingerprint assertion compared FSDP shard and
compute representations and was subsequently diagnosed. Archived/current
HF config/index hashes and 213 sampled tensor fingerprints covering all
131 weight shards match, rather than a full bytewise weight audit. These
diagnostics do not establish KL equivalence or a 95% confidence
interval; a subsequent side-by-side comparison on identical real
full-model activations passed on all 24 rank×case combinations (8 GPUs ×
3 prefixes), with bitwise-identical PLE outputs and maximum absolute
difference 0. Explicit resharding also reproduced the initial parameter
fingerprints after every forward and at completion on all ranks (Slurm
2962). This isolates PLE parity from the unrelated end-to-end repeat
variation.
The memory table is for the isolated convolution, not full-model
training. Compiled parity and successful end-to-end training fit remain
unverified. Ruff check/format and `git diff --check` passed.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes numerically sensitive PLE conv indexing under context
parallelism; wrong global positions could alter outputs/gradients,
though the intent is parity with less memory.
>
> **Overview**
> Fixes **context-parallel (CP) memory blow-up** in Qwen3.8 **Position
Learning Enhancement** convolution: each rank still **gathers** the full
CP convolution input, but now runs the dilated 1D conv and FP32
accumulation **only for that rank’s global token positions** instead of
every row then discarding non-local slices.
>
> **Position indexing** starts at `cp_rank * local_token_count` when CP
is on; **output buffers** are sized to the local position count and
reshaped with **`local_shape`**, removing the old post-conv column
slice. Masking, kernel delays, and `gather_for_cp` behavior are
unchanged—intended to cut peak activation memory during checkpoint
recompute on long contexts.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a8c16eac513660b1cb3b1b96201cf438fda76c0f. 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: Codex <codex@local>
## Summary
Adds the text model of
[`zai-org/GLM-5.3-Flash`](https://huggingface.co/zai-org/GLM-5.3-Flash-BF16)
(`glm5_next`, 313B params / ~18B active). Based on #4036, which this
supersedes.
- **KDA linear attention** (3 of every 4 layers) on FLA's `chunk_kda`
with GLM's lower-bounded forget gate.
- **NoPE sparse MLA** in the remaining layers (absorbed form) on the
existing `sparse_mla` kernels, which now accept q/k without a RoPE tail.
- **DSA indexer with k-pool compression**: keys pooled per document in
groups of 4, FP8 scoring after a Hadamard rotation (as vLLM), top 512
pools plus the query's own incomplete pool. Frozen, as in GLM-5.
- **mHC** via `DeepseekV4HyperConnection`; **MoE** with
`ClampedSilu(10)`, built inline in the decoder layer like the other
models.
- Compile- and AC-safe `cu_seqlens` handling (one-document rows, FLA's
CP context, per-layer `cu_seqlens` copy for checkpoint replay).
- Composite `glm5_next` / text `glm5_next_text` configs; checkpoint-only
keys (`topk_method`, `moe_router_dtype`, vision keys, ...) pass through
so an HF export still loads in vLLM. Conversion stacks the experts,
moves the flat `hc_*` tensors onto the hyper-connection modules, and
drops the vision tower and the MTP layer.
- Merged with `main` (vLLM 0.32, transformers 5.19): transformers now
accepts GLM-5.3 Flash's layer types, so the compat shim is gone. It
renames the checkpoint's `deepseek_sparse_attention` to
`indexed_attention` on load, which the decoder layer now matches.
Context parallelism uses the Ulysses-only `cp_blocker` API (no head
constraint: KDA, the indexer and sparse MLA all-gather over the CP
group).
- **vLLM patch for KDA conv weight updates**: vLLM caches a `torch.cat`
copy of the q/k/v short-conv weights on the first forward, so weight
updates never reached inference.
`monkey_patch_glm5_next_kda_conv_weights` stores the three weights as
slices of one buffer and points the cache at a view of it; reload copies
in place, so every update lands. Remove when vLLM keeps them in one
merged parameter.
- **Example SWE RL config**
(`examples/advanced/glm-5.3-flash/swe.toml`): SWE-rebench-V2 at 128K
context on 2 trainer nodes (EP 8, CP 8) + 6 rollout nodes (TP 8).
Text only: the vision tower is not modelled. Multimodal support follows
in a separate PR.
## Validation
100+ RL steps on SWE-rebench-V2. mismatch_kl is stable, reward goes up.
Wandb run:
[link](https://forge.coreweave.com/wandb/primeintellect/glm53-flash/runs/7ce7b27d533a45d593f475c56bd2b486)
<img width="963" height="617" alt="Screenshot 2026-10-22 at 7 11 53 PM"
src="https://github.com/user-attachments/assets/47ec258f-bf31-4a56-99ad-54e7a996ddbd"
/>
<img width="1075" height="309" alt="Screenshot 2026-10-22 at 7 11 21 PM"
src="https://github.com/user-attachments/assets/ab4905f9-6037-420c-a1a0-b427ee7bbbb4"
/>
Also, initial tests of 20 RL steps on `math-env` (Hendrycks-Math train).
Two runs at `cp = 1` and at `cp = 2` (Ulysses). All steps have
`mismatch_kl` below 0.015:
Wandb run for cp = 1:
[link](https://forge.coreweave.com/wandb/primeintellect/glm53-flash/runs/00023e7a572141449318d5453de56e1a)
Wandb run for cp = 2:
[link](https://forge.coreweave.com/wandb/primeintellect/glm53-flash/runs/a17dba66002a4e99a28c7b2be54c22f7)
**Unit test**: config and checkpoint round trip for the text and
composite configs, including the pass-through keys.
## Follow-ups
Now that we have a baseline RL run, the additional changes from #4036
can be validated against the KL numbers above:
- fp32 hyper-connections and KDA decay (FSDP casts them to bf16 while
vLLM keeps them in fp32).
- FP8 trainer layout matching vLLM (attention stays bf16).
- Export tool without a generation config; int64 offsets in the grouped
FP8 weight cast (both model-independent fixes).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
With `enable_return_sampling_mask` on, vLLM generation throughput
dropped by about 45% (Qwen3-1.7B, H200). The cost was not the mask
transport. It came from GPU->CPU syncs inside the sampler step. Each
sync makes the engine thread wait for the current forward pass, which
removes vLLM's async-scheduling overlap. py-spy on the EngineCore showed
the busy loop 100% busy, with about 30% of it spent waiting in
`sampling_order.py:29` (`k.max().item()`). The sampler kernels
themselves cost about 1 ms per step.
Syncs removed:
- `apply_top_p_then_top_k` (on by default through `top_p_before_top_k`,
so it ran for every top-k/top-p request on a mask server, replayed or
not): `k.max().item()` and the tie-fallback `.any().item()`. The width
now comes from the host `top_k` array, set in a `Sampler._sample_random`
wrapper. Candidates are ranked by an int64 `(score, token id)` key, so
ties at the boundary resolve to the reference's stable order without a
data-dependent fallback. The result is bit-identical to
`reference_top_p_then_top_k`, including bf16-rounded logits with
boundary ties. The old fast path fell back to the full sort on those
logits.
- `capture_selected_supports` and `pack_support_logprobs`:
`torch.as_tensor(numpy, device=cuda)` (a pageable H2D copy that syncs)
becomes a pinned `non_blocking` copy.
Sampling semantics, masks, and logprobs are unchanged. There are no loss
changes.
## Numbers
Qwen3-1.7B, one H200 per server, 512 concurrent x 1024 tokens
(`min_tokens` = `max_tokens`), T=1, seeded; replay/top-k requests use
top_k=128, top_p=0.95. tok/s, two runs each. The columns come from
separate jobs. Untruncated requests have no syncs on either branch, so
that row shows the run-to-run noise (about 10%):
| request | main, masks off | main, masks on | this PR, masks on |
|---|---|---|---|
| untruncated, sampled logprob | 15.8-16.7k | 15.5-16.3k | 17.3-18.4k |
| top-k/top-p, no replay | 14.3-17.6k | 9.0-10.1k | 15.4-15.5k |
| replay | - | 8.2-9.6k | 14.4-14.9k |
On #4232's code, which deletes `sampling_order.py`, the same pinned
copies plus the matching fixes in `pack_sampler_rows` give:
- untruncated + 16 draws: 9.3-10.6k -> 17.1-17.4k (-6% vs untruncated)
- replay: 8.6-9.2k -> 14.4-16.9k
The rest of the replay gap on main is GPU time in the top-p-first
sampler: 4.1 ms vs vLLM's Triton top-k/top-p at 0.9 ms for 512 rows.
`apply_top_p_then_top_k` microbench, 512 x 151936 bf16-rounded logits:
old 9.5 ms (tie fallback to the full sort), new 4.1 ms, reference 8.4
ms.
With `VLLM_GPU_SYNC_CHECK=warn`, vLLM reports no syncs in
`execute_model`/`sample_tokens` for replay, top-k, and draws requests.
## Overlap
- #4232 (feat/sc-exact-support) deletes `sampling_order.py` and has the
same `as_tensor` syncs in `request_replay.py`/`paired_capture.py`, plus
four more in `pack_sampler_rows` (numpy-indexed CUDA tensors and
`as_tensor` copies). If #4232 lands first, only the two pinned-copy
lines here still apply, together with the `pack_sampler_rows` fixes on
that branch.
- #4213 (metrics) does not touch inference.
## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/inference -m "not gpu"`: 445 passed, 1 skipped. `ruff check`
and `ruff format --check` are clean.
- GPU (H200): `pytest tests/unit/inference/test_sampling_order.py`: 14
passed.
- Bench scripts: `/home/fares/scratch/smt/bench` (client.py,
val.sbatch).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes core top-k/top-p sampling and mask packing on every masked
request; behavior is intended to be bit-identical to the reference, but
the paths are performance-critical inference code.
>
> **Overview**
> Restores vLLM throughput when **sampling masks** are enabled by
eliminating **GPU→CPU syncs** in the hot sampling and mask-capture
paths, without changing sampling semantics or logprobs.
>
> **`apply_top_p_then_top_k`** no longer calls `k.max().item()` or a
tie-check `.any().item()`. Batch max top-k is supplied from host numpy
via a **`ContextVar`**, set in a **`Sampler._sample_random` wrapper**
during `patch_top_p_then_top_k`. The bounded path ranks candidates with
a composite **(score, token id)** key so boundary ties match the
reference stable order without a data-dependent fallback to full sort.
>
> **`capture_selected_supports`** and **`pack_support_logprobs`**
replace syncing `torch.as_tensor(numpy, device=cuda)` with **pinned,
non-blocking** host→device copies for boolean masks.
>
> Tests extend the patch test to preserve **`_sample_random`** under
monkeypatch.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1aee65607e72ec66d42e21b047356561fe3c007b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Scores the `fp8_indexer` queries in chunks so the fp32 logits stay
bounded.
On main, `fp8_indexer` builds the whole fp32 `logits[S_q, S_k]` before
`torch.topk`, so its transient memory grows with `S_q * S_k` (OOM at
256k without CP). This PR scores queries in chunks of at most 1 GiB of
logits (`LOGITS_CHUNK_BYTES`), runs `topk` and the range mask per chunk,
and writes one int32 `[S_q, topk]` output. Top-k is per row, so the
output is bitwise identical to main.
## Numbers (1 H200, GLM-5.3 indexer, top-2048, last CP rank, causal)
Peak is the memory the call allocates on top of its inputs.
| seq | CP | S_q x S_k | main peak / time | chunked peak / time |
|---|---|---|---|---|
| 128k | 8 | 16k x 128k | 8.8 GiB / 63.5 ms | 1.3 GiB / 49.6 ms |
| 256k | 8 | 32k x 256k | 33.5 GiB / 250 ms | 1.5 GiB / 191 ms |
| 128k | 1 | 128k x 128k | 69.8 GiB / 380 ms | 2.7 GiB / 315 ms |
| 256k | 1 | 256k x 256k | OOM (256 GiB) | 4.2 GiB / 1210 ms |
The GLM-5.3-Flash pooled shapes (top-512) show the same pattern.
Chunking is also 0-24% faster because `topk` runs on smaller blocks. AC
recompute still does not re-run the indexer (its output stays a
mandatory save).
## Validation
- `torch.equal` against main's implementation on H200 in 43 cases:
random, tie-heavy and 70%-zero keys; top-k 2048 and 512; 1, 3 and 7
packed segments; CP-last-rank and pooled shapes; `S_k < topk`; chunks
from 64 rows (ragged last chunk) to one chunk.
- New GPU test: 64-row chunks give the same picks as one pass on
tie-heavy keys. `test_fp8_indexer.py` and `test_checkpointing.py` pass
on H200.
- An empty key set (`S_k = 0`) no longer divides by zero when sizing the
chunks.
- Rerun on head `de24db8` (with the `S_k = 0` fix and the main merge), 1
node of 8 H200: `test_fp8_indexer.py` and `test_checkpointing.py` pass
(8 passed). The training-step check below ran on the same head.
- GLM-5.3 training step: `glm_moe_dsa` cut to 4 layers (3 full
indexers), seq 32k packed documents, fake data, same seed and weights, 3
steps, CP=1 and CP=2 (8 GPUs). In every indexer call, the PR's output
was compared with main's `fp8_indexer` on the same live activations. The
outputs were `torch.equal` in all 432 calls (CP=1 shape 32k x 32k, CP=2
shape 16k x 32k). This held with the default 1 GiB chunks (4 and 2
chunks) and with 64 MiB chunks (64 and 32 chunks). Loss and grad norm
match main. The trainer itself is not bitwise reproducible: two main
runs differ in about 95% of grad hashes. The PR's grad differences from
main are at that same noise level (step-1 median relative grad-norm
difference about 2e-6 at CP=1 and 2e-5 at CP=2, for main vs main and for
main vs PR).
- `pytest -m "not gpu" tests/unit/orchestrator
tests/unit/test_configs.py tests/unit/train`, `ruff check`, `ruff format
--check`, `uv lock --check` on the branch merged with current main.
Overlap: #3958 (DeepSelect top-k) changes the same `topk` lines.
Whichever merges second calls `select_topk` per chunk.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches the DSA sparse-indexing path used in training attention, but
output is intended to match the prior one-pass `topk` behavior; main
risk is subtle correctness or perf regressions at extreme sequence
lengths.
>
> **Overview**
> **`fp8_indexer` no longer materializes the full `S_q × S_k` fp32
logits tensor.** Queries are scored in row chunks sized so each chunk’s
logits stay under **`LOGITS_CHUNK_BYTES` (1 GiB)**; each chunk runs the
Triton kernel, **`topk`**, and causal/range masking, then writes into a
preallocated **`[S_q, topk]`** int32 result (default sentinel **`S_k`**
covers padding when **`S_k < topk`**).
>
> Chunk row count uses **`max(S_k_aligned, 1)`** so **`S_k = 0`** does
not break sizing. A GPU test forces tiny chunks via
**`LOGITS_CHUNK_BYTES = 1`** and asserts **`torch.equal`** with the
default path on tie-heavy keys.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
de24db80179522a741b8978462d401989e4180bc. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Activation offloading copies model weights to the CPU, not only
activations. With `torch.compile`, each compiled transformer block saves
its graph inputs for backward. For EP experts these include the local
tensor of the expert DTensor parameter, a plain `torch.Tensor` that
passes the `isinstance(nn.Parameter)` check. The offload hook then
copies the expert weights to pinned CPU memory and back in every micro
batch. On GLM-4.5-Air with EP=8 that is ~553 MB of weights per layer per
rank, versus a 64 MB layer input at 64k tokens / CP=8. FSDP already
frees and re-gathers that storage, so the copy is pure overhead.
`OffloadActivations` (and `maybe_activation_offloading`) now take the
model and skip any tensor that shares storage with a model parameter
(the local tensor for DTensor parameters). The check only runs for
tensors that would otherwise be offloaded. RL and SFT pass the model.
GLM-4.5-Air truncated to 12 layers (real weights), SFT, fake data, 1
node 8xH200, cp=8, ep=8, full AC, `max_inflight_activations=5`,
`offload="optimizer"`, mean of steps 3-6:
| seq_len | main, offload on | this PR | offload off |
|---|---|---|---|
| 64k: step time / host RAM peak | 7.7 s / 458 GB | 6.55 s / 393 GB |
6.2 s / 369 GB |
| 256k: step time / host RAM peak | 43.5 s / 473 GB | 42.4 s / 413 GB |
41.7 s / 369 GB |
Offload host RAM drops from ~90-104 GB to ~24-44 GB per node and the
offload step-time overhead drops by 70-75%; the savings scale with the
number of MoE layers. Losses and grad norms match main and offload-off
within run-to-run noise (~1e-3).
Validation: `tests/unit/utils/test_act_offloading.py` (gpu): a weight
view saved by `nn.Linear` stays on the GPU.
`tests/unit/{orchestrator,train,utils,transports}` +
`tests/unit/test_configs.py -m "not gpu"` and ruff.
#4238 is stacked on this PR.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes activation-offload behavior in the training forward/backward
path; fix is localized but affects memory and step time for MoE +
compile configs.
>
> **Overview**
> **Activation offloading no longer treats parameter storage as
activations**, which was copying large MoE expert weight tensors to
pinned CPU every micro-batch under `torch.compile` + EP (plain tensor
views of `DTensor` params bypassed the old `nn.Parameter` check).
>
> `OffloadActivations` and `maybe_activation_offloading` now take the
**model**, build a set of parameter storage IDs (using `to_local()` for
`DTensor`), and skip offload when a saved tensor shares that storage. RL
and SFT forward paths pass `model` into the context manager.
>
> Adds a GPU unit test that weight views saved for backward stay on GPU
and are not offloaded.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c12bb25c6e7dbea294252cec1c6c6d1eaedd9202. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Require **`flash-linear-attention>=0.6.0`** in `pyproject.toml` and
update `uv.lock` from FLA 0.5.2 (`a954753`) to the official **v0.6.0 Git
release commit `413ad2c`**, which includes [FLA
#1546](https://github.com/fla-org/flash-linear-attention/pull/1546).
That fix requires high-precision affine state-chain products during
context parallelism; the old pin uses default TF32 products despite FP32
state storage. Prime-RL's Qwen3.5 and Qwen3.8 share this GDN path.
The minimum version excludes older releases for GPU installs; it is not
an exact `==` pin. The lockfile retains the exact tested release commit.
The upstream Git source and all other resolved package records are
unchanged.
Validation on H200 / Torch 2.13 / CUDA 13:
- Minimum-version metadata audit, offline lock consistency, locked
all-extras install dry-run, dependency-record audit and whitespace
checks pass. Adding the lower bound changes no locked package records or
tested source.
- With CUDA hidden, all model registrations import, shared GDN meta
construction and the Nemotron Mamba sequence-ID helper pass; loaded FLA
modules come exclusively from the verified official release source.
- **Two-GPU shared-GDN forward/backward passed** for single, packed
cross-rank and compiled single-document controls. Outputs and gradients
are finite; CP2 versus same-release CP1 output relative L2 is 0–0.0093%,
and aggregate parameter-gradient relative L2 is at most 0.288%.
- **Complete-release full-model CP8/EP8 replay passed:** 31,488 tokens,
eight images, 4,545 generated targets, identical weights/inputs and
inference expert replay, with canonical QSA ordering in both engines.
Sampled-token mismatch K3 is **0.002477 → 0.002406 (2.9% lower)**. Six
scored repeats across all eight ranks are bitwise identical; peak
allocated forward memory remains **108.09 GiB**. The result also matches
the isolated upstream precision-policy control exactly.
A broader raw-logit control now computes exact full-vocabulary KL at
**all 4,545 generated targets**: **0.002570 → 0.002430 (5.5% lower)**,
with identical weights, expert replay and canonical attention ordering.
This is a different metric from the sampled-token K3 above. Paired text
controls also lower sampled K3 by 21.7% before the first image and 22.5%
after image removal; those are separate input cases, not an image-count
causal comparison.
The six-repeat full-model scoring above is eager/no-grad; the newer
raw-logit control is grad-enabled forward with AC, without backward.
Shared-GDN checks separately cover backward. These are frozen-prefix
numerical results, not training-wide KL or throughput measurements.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Upgrades a core training kernel dependency and can shift
forward/backward numerics on multi-GPU CP GDN paths, though the change
is an intentional precision fix rather than unrelated behavior.
>
> **Overview**
> **Bumps the Linux GPU extra’s `flash-linear-attention` dependency from
an unpinned install to `>=0.6.0` and refreshes `uv.lock` from 0.5.2 to
the v0.6.0 Git revision (`413ad2c`).**
>
> That release pulls in FLA’s high-precision affine state-chain products
for context parallelism, which matters for Prime-RL’s shared
**GatedDeltaNet** path (`build_cp_context` / `chunk_gated_delta_rule`)
used by Qwen-family models. The existing Git source URL in
`[tool.uv.sources]` is unchanged; only the resolved version/commit and
the declared minimum version move forward.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e40e631f8a1a9592871bfd0d82b79c366b62a892. 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: Codex <codex@local>
## Problem
`uv run eval` fails with `ModuleNotFoundError: No module named 'torch'`
on every install without the `gpu` extra: any macOS install, and a plain
`uv sync` on Linux. `eval --help` still works, because the entrypoint
imports the eval code only after it parses the config.
#3974 put `broadcast_pause` in `prime_rl/control/controller.py`. Only
the trainer calls it, but it needs `torch` and `torch.distributed`, and
the eval runner imports that module through
`prime_rl/control/server.py`.
CI did not catch this because no job runs without torch. The GSM8K eval
job used `uv sync --all-extras --all-packages`, and even without extras,
`--all-packages` installs torch through `bfcl-v3` → `bfcl-eval` →
`sentence-transformers` → `torch`.
## Changes
- Move `broadcast_pause` to `prime_rl/trainer/utils.py`, next to the
other `torch.distributed` helpers. `prime_rl.control` no longer imports
torch, so the eval runner keeps its top-level imports, and `uv run eval
--control` also works without torch.
- GSM8K eval CI job:
- installs only the base deps and the gsm8k env (`uv sync --locked
--package prime-rl --package gsm8k`), so it runs without torch;
- also runs on changes to `src/prime_rl/control/`, which the eval
imports.
- `tests/conftest.py` resets the trainer world only if a test loaded it.
It used to import `prime_rl.trainer.world`, which imports torch, at
startup, so pytest could not start without torch.
## Validation
On macOS, in a venv set up like the new CI job (torch not installed):
- `prime_rl.entrypoints.eval`, `prime_rl.eval.eval`,
`prime_rl.eval.runner` and `prime_rl.control.*` import without loading
torch.
- The eval control API, served with `prime_rl.control.server.serve`,
answers `GET` and `PUT /v1/concurrency`.
- `pytest tests/unit/control`: 12 passed. `pytest
tests/integration/test_gsm8k_eval.py --collect-only` collects both
tests.
- `uv run eval @ configs/ci/integration/gsm8k-eval.toml --dry-run`
resolves the config, including the gsm8k taskset.
The trainer side only moves the function and updates two imports. I did
not run it locally.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Trainer pause broadcast is a straight relocation with updated imports;
eval/CI changes reduce accidental heavy deps rather than altering
runtime training logic.
>
> **Overview**
> **Removes the accidental `torch` dependency from eval/control** so `uv
run eval` and control APIs work on installs without the GPU extra (e.g.
macOS or plain `uv sync`).
>
> `broadcast_pause` moves from `prime_rl.control.controller` to
`prime_rl.trainer.utils` (with RL/SFT trainers importing it there).
`prime_rl.control` no longer imports PyTorch, which matters because the
eval runner pulls in `prime_rl.control.server`.
>
> **CI** for GSM8K eval now syncs only `prime-rl` and `gsm8k` (avoiding
torch via `--all-packages`), and path filters treat changes under
`src/prime_rl/control/**` as eval-related.
>
> **Test harness:** `tests/conftest.py` resets trainer world only if
that module was already loaded, so pytest can start without importing
`torch` through `prime_rl.trainer.world`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
cd61451e7abd38d1df7f1e6ae0272da625c545b8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- **Problem:** with about 12k long agentic episodes in flight, the
orchestrator's event loop froze periodically. The freezes grew to 42 s
every ~100 s after 40 min, and to 190 s every ~400 s after 4 h. Nothing
ran during a freeze: no dispatch, no completions, and the trainer waited
for the weight-broadcast handshake. The cause is CPython 3.12's
automatic full (generation-2) collection. It holds the GIL, walks every
object the orchestrator holds, and runs each time the long-lived heap
grows by 25%.
- **Shared `GCConfig`:** the trainer's step-based `GCConfig` moves to
`prime_rl.configs.shared`, and the orchestrator uses it as
`[orchestrator.gc]` (`interval`, default 50 steps). The trainer config
is unchanged. `gc = null` keeps Python's default behavior.
- **`GarbageCollector`** (`orchestrator/gc.py`):
- At startup, it collects and freezes the startup heap.
- It turns off automatic full collections. Young collections keep
running.
- It runs one full collection every `interval` steps, right after a
batch ships, and logs how many objects it freed.
- Collections that hold the GIL for 1 s or longer are logged.
`gc/collections`, `gc/pause_max` and `gc/pause_total` join the pipeline
metrics.
- **Dispatcher cycle:** the dispatcher reads a failed request's
exception with `task.exception()` instead of re-raising it with
`task.result()`. The re-raise added the handler frame (which holds
`task`) to the traceback. That made a task ↔ exception cycle that kept
the partial episode alive until a full collection.
Companion: #4226 (merged) moved per-token streams to numpy arrays, which
removed most of the per-token Python objects.
## Verification
Replay on one compute node. The real `orchestrator` entrypoint ran
against a stub env server that replays 2048 recorded agentic episodes
from real data over the verifiers serve protocol. Each episode streams
turn by turn over 15–45 min. A stub trainer consumes batches over the
filesystem transport and runs the weight-broadcast handshake each step
(30 s per step). Settings: 12,288 episodes in flight, `batch_size =
256`, `seq_len = 262144`, 8 data ranks. Both variants ran side by side
for 88 min with the same external probe (GC callbacks, a GIL-stall
ticker thread, RSS).
| | before (`main`) | after (this PR) |
|---|---|---|
| Full collections | 66 automatic | 1 scheduled (step 50) |
| Longest full collection | 42.4 s | 37.2 s |
| Total time frozen in full collections | 1,248 s (24% of the run) | 37
s |
| Freezes over 10 s | 38 | 1 |
| Longest freeze outside full collections | — | 0.5 s |
| Broadcast handshake p90 / max | 32.4 s / 40.8 s | 0.15 s / 9.3 s |
| Steps shipped | 42 | 53 |
| Throughput after the first step | 63 steps/h | 69 steps/h |
| Tokens shipped | 1.21 B | 1.49 B |
| Peak RSS | 74 GB | 71 GB |
| Errors | 0 | 0 |
- On `main`, the automatic full collections grew from 1.5 s to 42.4 s as
the heap grew, about every 2 min. This matches the production pattern.
Each one freed only 0–153 objects.
- With this PR, no automatic full collection ran. The one scheduled full
collection freed 1,476 objects.
- A scheduled full collection still costs as much as an automatic one at
the same heap size (37 s here). This PR makes full collections rare and
predictable. It does not make them cheaper.
Unit tests: `tests/unit/orchestrator` 132 passed.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes orchestrator runtime behavior (GC timing and event-loop
pauses) and error-handling in the hot dispatch path; config is opt-out
via `gc = null` but defaults alter production GC behavior.
>
> **Overview**
> Addresses orchestrator event-loop freezes from CPython’s automatic
full garbage collections on large in-flight episode heaps by
**scheduling GC instead of letting it run unpredictably**.
>
> **`GCConfig`** is moved to shared config and wired into the
orchestrator as `[orchestrator.gc]` (default every 50 steps; `null`
restores Python defaults). A new **`GarbageCollector`** freezes the
startup heap, disables automatic generation-2 collections (young GC
still runs), runs a full `gc.collect()` on a fixed step interval after
batches ship, and reports pause metrics (`gc/collections`,
`gc/pause_max`, `gc/pause_total`) in the pipeline view.
>
> The **dispatcher** stops re-raising failed task exceptions via
`task.result()` and uses `task.exception()` instead, avoiding a
task↔traceback reference cycle that kept partial episodes alive until
rare full collections.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a4047fa0cd498865c601946a39383c49a3c84c3e. 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
- Rename the orchestrator config field `max_off_policy_steps` to
`max_staleness`. Update every config and example that sets it.
- Define two staleness levels and use them in code, metrics, and docs:
- **Token staleness**: the policy version a batch trains on minus the
policy version that sampled the token. Tokens without a policy label
(Dynamo engines) take their rollout's dispatch version, which is the
same rule the masking uses.
- **Rollout staleness**: the max token staleness of the rollout. It
splits into **in-flight** staleness (weight updates between the oldest
token and completion) and **in-queue** staleness (weight updates while
the rollout waits to ship).
- Replace `episode_staleness` and `token_policy_ages` with one
`rollout_staleness` helper that returns both levels.
- Rename the per-step metrics from `off_policy/*` to `staleness/*`:
- `staleness/token/mean`, `staleness/token/masked`
- `staleness/rollout/{mean,max}`
- `staleness/rollout/in_flight/{mean,max}`,
`staleness/rollout/in_queue/{mean,max}`
- `staleness/rollout/dropped`
- Remove the live `dispatcher/off_policy/{mean,max}` gauge. The
per-batch staleness metrics replace it.
- Change the console step log from `Max Off-Policy` to `Max Staleness`.
- Docs: add the token and rollout staleness definitions to
`docs/algorithms.md` (section renamed to "Async Training & Staleness").
List the staleness metrics in `docs/training.md`. Update `docs/ipo.md`,
the README, the `monitor-run` skill, and the dashboard producer regex.
## Breaking
- `orchestrator.max_off_policy_steps` is now
`orchestrator.max_staleness`. Configs that use the old name fail
validation. Migration: rename the key.
- Metric renames (update W&B panels and alerts):
| Old | New |
|---|---|
| `off_policy/{mean,max}` | `staleness/rollout/{mean,max}` |
| `off_policy/in_flight/{mean,max}` |
`staleness/rollout/in_flight/{mean,max}` |
| `off_policy/in_queue/{mean,max}` |
`staleness/rollout/in_queue/{mean,max}` |
| `off_policy/token/mean` | `staleness/token/mean` |
| `off_policy/token/max` | removed: equal to `staleness/rollout/max` |
| `off_policy/token/masked` | `staleness/token/masked` |
| `off_policy/dropped` | `staleness/rollout/dropped` |
| `dispatcher/off_policy/{mean,max}` | removed: use the per-batch
`staleness/rollout/*` |
- Value changes:
- Rollout staleness now comes from token policy labels, not from the
dispatch version. A rollout whose first token was sampled after a weight
update now reports a lower value.
- Token staleness now counts unlabelled tokens at their dispatch
version. Before, it skipped them.
- Frozen-sourced rollouts are left out of the staleness stats. Before,
they counted as 0.
## Verification
- `uv run pytest tests/unit/orchestrator`: 132 passed.
`test_token_policy_ages.py` is now `test_rollout_staleness.py` and
covers the token and rollout levels and the in-flight/in-queue split.
- `OrchestratorConfig(max_staleness=16)` validates, and
`OrchestratorConfig(max_off_policy_steps=16)` raises `ValidationError`.
- I did not run `tests/unit/test_configs.py` to completion. It fails
locally because the taskset packages (`reverse_text`, `gsm8k`,
`scaleswe`, …) are not installed. Every failure is a
`ModuleNotFoundError` for a taskset package.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking config and metric renames affect existing runs and
monitoring; staleness computation changes may shift reported values
without changing masking logic tied to `max_staleness`.
>
> **Overview**
> Renames the orchestrator knob **`max_off_policy_steps`** to
**`max_staleness`** everywhere (config schema, example/advanced TOMLs,
docs). Behavior is unchanged: it still caps how old a sampled token can
be before masking or dropping queued samples; rollouts are not cancelled
for staleness.
>
> **Staleness model and metrics** are tightened and renamed.
**`rollout_staleness`** replaces separate **`episode_staleness`** /
**`token_policy_ages`** helpers: rollout staleness is the **max token
staleness** (from engine `weight_versions`, with unlabeled tokens using
dispatch version), split into in-flight vs in-queue. Shipped-batch
logging and W&B-style keys move from **`off_policy/*`** to
**`staleness/token/*`** and **`staleness/rollout/*`**; live
**`dispatcher/off_policy/{mean,max}`** gauges are removed. Console logs
say **Max Staleness** instead of Max Off-Policy.
>
> Docs and ops surfaces (**`algorithms.md`**, **`training.md`**, IPO
ablation copy, **`monitor-run`** skill, dashboard orch key regex) use
the new vocabulary. **Breaking:** old config key fails validation;
dashboards/alerts must remap metrics (including removed
**`off_policy/token/max`** and dispatcher off-policy gauges). Reported
staleness values can shift slightly because rollout stats are
token-label-based and frozen-sourced rollouts are omitted from
aggregates.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c569e1512817bfd292ad14efc768ec7d1a76acf8. 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>
Stacked on #4249. Review that one first.
## Summary
On `main`, the RL loop copies every per-token metric to the host each
micro step: entropy, mismatch KL and per-token loss metrics, overall and
per env. It keeps them as CPU tensors for the step. At step end,
`Tensors.compute_stats` all-gathers each key, so every GPU holds every
token of the global batch per key, and then sorts it for the median.
Memory and time grow with the global batch size.
- **`TensorStats`** replaces `Tensors` in `trainer/utils.py`:
- `add` folds values into a running count, sum, sum of squares, min and
max per key on the GPU. With env ids it folds `{key}/{env}` per env and
derives `{key}/all` from those rows, so each metric is reduced once. It
uses masked reductions over a per-env membership mask, not boolean
indexing or scatter atomics, so a micro step never waits for the GPU on
its account. Values on the CPU, such as a custom loss's metric, move to
the GPU first.
- `compute_stats` runs one SUM and one MAX all-reduce for all keys, then
computes mean, std, min and max. The mean and std pool every value on
every rank, so each token (or sample) counts once. Before, it ran two
all-gathers and five host syncs per key.
- `flexible_all_gather` had no other caller and is removed.
- Per-sample and per-micro-step values (loss, `nll`, `is_masked`, MoE
stats) use the same path.
- **`get_global_moe_stats`** keeps its reduced values on the GPU. The
SFT loop keeps its MoE stat accumulators on the GPU to match.
- The env ids are copied to the GPU with the other micro-batch inputs,
before the forward pass.
- The per-micro-step debug line is lazy. It no longer reads three values
back from the GPU when debug logging is off.
## Breaking
- **No trainer metric reports `/median` any more.** After the W&B
filter, `main` logs a median only for `loss`, `nll`, `ref_kl`,
`max_vio`, `routing_confidence` and the per-token loss metrics such as
`score_centering/*`. Use `/mean` instead.
- **Keys without any value on any rank are left out** instead of logged
as NaN, for example `mismatch_kl/all` in a pure-ce step. The file
monitor already dropped those NaN values with a warning.
## Benchmark
**Metric path only.** 8xH200, 64k tokens per micro step, 10 per-token
keys like the RL loop's: entropy and mismatch KL, overall and for 4
envs. The run uses `main`'s `Tensors` and the train-loop code verbatim,
and gives the max over ranks.
| global tokens | accumulator | accumulate (s) | `compute_stats` (s) |
peak GPU (GiB) | peak host (GiB) |
|---|---|---|---|---|---|
| 100M | `main` | 0.64 | 0.26 | 2.52 | 0.68 |
| 100M | this PR | 0.42 | 0.01 | 0.01 | 0.14 |
| 400M | `main` | 2.16 | 0.68 | 10.10 | 0.65 |
| 400M | this PR | 1.19 | 0.05 | 0.01 | 0.00 |
| 1.6B | `main` | 8.66 | 2.79 | 40.28 | 2.06 |
| 1.6B | this PR | 4.72 | 0.13 | 0.01 | 0.00 |
On `main`, the extra GPU memory at step end is about 2.5 GiB per 100M
global tokens, on every rank, independent of the world size. This PR
keeps it constant. Both report the same mean and std (`entropy/all`:
5.005863 / 2.885920 against 5.005863 / 2.885921 at 1.6B).
**End to end.** The same one-node setup as #4249: Qwen3-0.6B, fake data
with aux streams, about 100M tokens per step, step 2.
| | step (s) | throughput (tok/s) | peak host / rank (GiB) | peak host /
node (GiB) |
|---|---|---|---|---|
| `main` | 341.4 | 295k | 16.2 | 90.4 |
| #4249 | 325.6 | 310k | 9.8 | 79.9 |
| this PR | 324.3 | 311k | 9.7 | 78.8 |
On one node at 100M tokens, the gather is small, so the end-to-end gain
is small. The memory win grows with the global batch, as in the table
above.
**Same metrics.** The benchmarks ran on this PR's first commit, which
still kept per-sample values for an exact median. On step 1 (same
weights), that commit logged the same 61 keys as `main` after the W&B
filter, with a max relative difference of 1e-7. The current commit logs
the same values, without the `loss`, `nll` and `ref_kl` medians.
Dropping that small per-sample gather does not change the timing and
memory numbers above.
## Relation to open PRs
- #4214 also moves these metrics off the per-micro-step host path and
batches the MoE all-reduces. It keeps every micro step's per-token
tensors on the GPU and gathers them at step end. The per-token part
overlaps with this PR. The MoE batching does not.
- #4213 adds per-token keys (`entropy_full_vocab/*`,
`mismatch_entropy`). With this PR each becomes one `add` call.
## Testing
- New `tests/unit/train/test_tensor_stats.py` (GPU) checks mean, std,
min and max, the per-env split, empty groups and scalar values against
torch on the gathered values. It also checks that a metric on the CPU is
reduced like one on the GPU.
- `tests/unit/train/rl/test_loss.py` passes on an H200.
- MoE smoke test on one H200: Qwen3-30B-A3B cut to 2 layers, random
init, fake data, 3 steps each for SFT and the RL trainer. Both log
`max_vio` and `routing_confidence`.
- `ruff check` and `ruff format --check` pass.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how all RL training metrics are aggregated and what gets
logged to W&B; behavior is intentional but breaks median keys and NaN
placeholders for empty metrics.
>
> **Overview**
> Replaces the RL trainer’s **`Tensors`** accumulator with
**`TensorStats`**, which folds per-micro-batch metrics on the GPU into
fixed-size running moments (count, sum, sum², min, max) and reduces them
with batched SUM/MAX all-reduces at step end. That removes per-step CPU
copies, the old **`flexible_all_gather`** path, and memory that scaled
with global token count.
>
> The RL loop now calls **`tensor_stats.add`** for loss, entropy,
mismatch KL (with env-aware keys via **`env_ids`** on CUDA), MoE stats,
and loss components; **`get_global_moe_stats`** leaves values on GPU.
Micro-step debug logging uses **lazy** evaluation so GPU readbacks
happen only when debug is enabled.
>
> **Breaking for dashboards:** trainer metrics no longer include
**`/median`**; empty keys are omitted instead of logged as NaN (e.g.
mismatch KL on CE-only steps).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9cf89bd817c7ed5b0e17ab44848f2bcfa8f5433c. 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
- `AnnotationWriter.export` keeps each micro batch's trainer logprobs
and entropies as float32 numpy arrays. Masked and non-finite positions
hold NaN.
- Before, it turned both streams into Python floats, one object per
token, and built Python lists per sequence span. Each value cost about
32 B (a 24 B float object plus an 8 B list slot). That is about 64 B per
token for the two streams. Every rank kept them for the whole step, and
`flush` then pickled them to rank 0, which held them for every token in
the global batch. Now they cost 8 B per token.
- The file monitor already serializes with `orjson.OPT_SERIALIZE_NUMPY`,
and orjson writes NaN as `null`. So the annotation records on disk keep
their format.
- Rounding to `float_decimals` now runs in numpy on the float32 value. A
value exactly halfway between two rounded values can round to the other
neighbour in its last digit.
## Benchmark
One 8xH200 node, RL trainer only, Qwen3-0.6B, fake data. Each step has
1536 packed micro batches of 64k tokens (about 100M tokens, 192 micro
batches per rank). The fake batches carry the aux streams real batches
do: reference logprobs, rl/ce/ref_kl component weights, a prompt loss
mask, 4 envs and trace ids, so annotations are exported. The numbers are
from step 2. Peak host memory is the per-step peak RSS (`VmHWM`) of the
largest rank, and the node peak sums all trainer processes.
| | step (s) | throughput (tok/s) | peak host / rank (GiB) | peak host /
node (GiB) |
|---|---|---|---|---|
| `main` | 341.4 | 295k | 16.2 | 90.4 |
| this PR | 325.6 | 310k | 9.8 | 79.9 |
- About 9 GiB per rank is the trainer's own baseline, so the annotation
path dropped from about 7 GiB to under 1 GiB on the largest rank (rank
0).
- The step time drops by 16 s (4.6%). The Python float conversion ran
inside the micro-step loop. With a 0.6B model the share of step time is
an upper bound, but the absolute time grows with the tokens per rank.
- The annotation streams on disk are the same. On 3000 records (23.7M
values), every null matches, and every value is within 1e-4 of `main`.
The stream size is 887 MB against 888 MB.
## Testing
- `tests/unit/orchestrator/test_episode_records.py`, `ruff check` and
`ruff format --check` pass.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Observability-only path with equivalent on-disk JSON; minor numeric
rounding differences possible at tie boundaries.
>
> **Overview**
> **Annotation export now stores per-token trainer logprobs and
entropies as float32 NumPy arrays** instead of Python lists of boxed
floats/`None`, cutting per-token memory and pickle cost during
distributed `flush`.
>
> `AnnotationWriter.export` builds the loss mask as a NumPy boolean
array, applies `_masked_floats` (replacing `_tensor_to_floats`) so
masked and non-finite positions are **NaN** (serialized as `null` via
existing `orjson.OPT_SERIALIZE_NUMPY`), and slices those arrays per
sequence span. The first token in each span is still cleared with
`np.nan` after the logprob shift. Rounding to `float_decimals` moves to
NumPy on float32 values, which can differ slightly from Python `round`
at half-way ties.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e02026a1af020f95406bc09e7e11813dcccbe714. 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>
`FlashAttention` stores `AttentionConfig.is_causal` but
`_compute_attention` always calls the kernel with `causal=True`, so a
model that sets `is_causal=False` gets causal attention without an
error.
- **Flash attention:** `_compute_attention` passes
`causal=self.is_causal`.
- **Sliding windows:** a non-causal module with a sliding window raises
`NotImplementedError`. The window is `(sliding_window - 1, 0)`, which
blocks every later token even with `causal=False`, and what a non-causal
window should span is not settled.
- **Ulysses context parallelism:** passes the module's `is_causal`.
After the all-to-all every rank holds the whole sequence, so non-causal
attention means the same thing as without context parallelism. Sliding
windows are handled as above.
Every model in the repo builds its attention with `is_causal=True`, and
Afmoe's attention, which has no such field, reads as causal through
`getattr(..., True)`, so no existing model changes. This makes
non-causal attention available to models that need it, for example
decision models whose full-attention layers read the whole prompt, or
diffusion language models.
## Testing
On an A100 (FlashAttention 2), `_compute_attention` on packed segments
matched per-segment `scaled_dot_product_attention` in outputs and
gradients for both settings, and the non-causal sliding-window check
raised. That test was dropped from the PR on review. The Ulysses path
was not run.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
`max_off_policy_steps` now bounds the age of each trained **token**
instead of each episode.
On main, the dispatcher cancels every train group whose dispatch version
is older than `(step-1) - max_off_policy_steps`, including finished
members, and the sink drops queued traces by the same rule. A group ages
out as a whole even when most of its tokens came from recent weights
(in-flight `keep`-mode updates).
With this PR:
- Each sampled token carries the policy step that sampled it (the
`weight_versions` spans from #4141, on main). Unlabelled tokens (Dynamo
only) take their episode's dispatch version, which is the old rule for
them.
- The sink masks tokens older than `(step-1) - max_off_policy_steps` out
of `mask`, `rl_weights`, `ce_weights` and `ref_kl_weights`, at the queue
sweep and at batch ship. Fresher tokens of the same sample keep training
with the sample's advantage and their own inference logprobs.
- A sample is dropped only when nothing is left to train; a trace only
when all its samples are dropped (`off_policy/dropped`).
- Rollouts are never cancelled for staleness. The dispatcher's stale
cancel, the `stale` cancel reason and the sink's whole-group void are
removed. On Dynamo, a stale group now runs to completion and is dropped
at the sink.
- New metric `off_policy/token/masked`: fraction of the batch's sampled
tokens masked for staleness.
- No loss changes: every loss in `trainer/rl/loss.py` is token-level and
reads the loss mask.
**Validation:** `pytest tests/unit/orchestrator
tests/unit/test_configs.py tests/unit/inference tests/unit/eval -m "not
gpu"` (512 passed), ruff. Not run end-to-end on GPU.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes off-policy enforcement in the orchestrator training path
(masking vs cancellation), which can alter throughput, batch
composition, and train–inference mismatch; loss code is unchanged but
what reaches the trainer does.
>
> **Overview**
> **`max_off_policy_steps` now limits staleness per sampled token**, not
per rollout or group. The train sink masks tokens older than `(step-1) -
max_off_policy_steps` out of `mask`, `rl_weights`, `ce_weights`, and
`ref_kl_weights` (using vLLM `weight_versions`; unlabeled Dynamo tokens
use the episode dispatch version). Fresher tokens in the same sample
still train; traces drop only when every sample has nothing left to
train.
>
> **Rollouts are no longer cancelled for staleness.** The dispatcher’s
pre–weight-update stale group drops, the `stale` `CancelReason`, and
whole-group voiding in the sink are removed; `on_version_pending` only
blocks scheduling across the swap. Queue sweeps and batch shipment apply
the token masks instead of episode-level drops.
>
> **Observability:** new `off_policy/token/masked` rate; docs/config
describe token-level behavior; cancellation metrics treat pipeline voids
as overload/shutdown rather than stale.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
24b8b5199a5fe1e834147e843a7e8d482de7b5a4. 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: Mika Senghaas <mail@mikasenghaas.de>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Engines label each sampled token with the policy step that produced it,
and the orchestrator logs per-token policy age.
- `/update_weights` takes `weight_version` and calls vLLM's
`update_weight_version` after loading. `/load_lora_adapter` takes a
`weight_version` query parameter and does the same. The orchestrator
sends the step on both (filesystem, NCCL and NIXL transports).
- vLLM 0.32 (on main) then returns `weight_versions` spans on every
`/inference/v1/generate` choice; renderers/verifiers on main already
pass them through to the trace.
- `token_policy_ages` turns the spans on a trace's assistant nodes into
per-token ages against the batch's training version. The orchestrator
logs `off_policy/token/{mean,max}` next to the episode-level
`off_policy/*`.
- The startup sync goes through `/update_weights` before the dispatcher
starts, so the boot step is labelled too. Only Dynamo engines (weight
updates via `/collective_rpc`) keep the `"default"` label; those tokens
are not counted.
**Validation**
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/inference -m "not gpu"` (445 passed), ruff, `uv lock
--check`.
- GPU (1×H200, Qwen3-0.6B, vLLM 0.32): a 4000-token generation paused
mid-way, `/update_weights` with `weight_version=5`, resumed. It returned
`[{"version": "default", "start": 0, "end": 1390}, {"version": "5",
"start": 1390, "end": 4000}]`; the next request returned `[{"version":
"5", "start": 0, "end": 8}]`.
Upstream: vllm-project/vllm#59582 (in 0.32). #4143 is stacked on this
PR.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Extends the weight-update and LoRA reload admin APIs to require
`weight_version` and invoke vLLM's `update_weight_version`; a mismatch
or missing field would break sync, but behavior is additive for
training.
>
> **Overview**
> Wires **vLLM 0.32 `weight_versions`** through the weight-sync path so
each sampled token is tagged with the policy step that produced it, and
the orchestrator can report finer-grained off-policy signal than
episode-level staleness.
>
> After full weight loads (`/update_weights`) and in-place LoRA reloads
(`/load_lora_adapter`), engines call **`update_weight_version`** with
the training step the orchestrator already passes on those admin calls
(filesystem / NCCL / NIXL and LoRA filesystem receive). Generate
responses then carry per-token version spans on traces.
>
> New helpers **`node_policy_versions`** and **`token_policy_ages`**
turn those spans into per-token ages vs the batch’s training policy; at
ship time the orchestrator logs **`off_policy/token/mean`** and
**`off_policy/token/max`** alongside existing episode **`off_policy/*`**
metrics. Tokens still labelled **`default`** (e.g. Dynamo engines that
skip this path) are excluded from the token metrics.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0025738a78f4cb1b11cdf03c56d5c2c8d1245569. 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: Mika Senghaas <mail@mikasenghaas.de>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Allow IcePop + score centering with truncated sampling: bounded top-k,
optionally combined with top-p. Follow-up to merged #4012.
Truncated sampling draws from a recorded support (full-distribution
top-p followed by a hard top-k cap by default, at most `top_k` tokens),
and the sampler probability is zero outside it. Capture the sampler
distribution over the whole support, replay it on the trainer, and
center exactly over it, with no tail approximation on replayed tokens.
Untruncated sampling keeps the existing head plus proportional-tail
approximation and `score_centering_topk`.
- **Config**: score centering accepts truncated sampling, with capture
width `top_k`. Truncated sampling without `top_k` now defaults to `top_k
= 128` (was 512); explicit `top_k` is still capped at 512. The default
applies to all truncated runs, not only score-centered ones.
- **Inference server**: when a request records a sampling mask, compact
logprobs drop filtered (-inf) candidates, so each row carries only the
support instead of `top_k` sentinel-padded entries.
- **Transport**: masked tokens' sampler logprobs travel on
`SamplingMask.logprobs` (new optional field, appended for wire
compatibility), so the support ids reach the trainer once. `TopLogprobs`
only carries heads of untruncated distributions. The orchestrator checks
that a masked token's top logprobs cover exactly its mask before
merging.
- **Trainer**: builds the centering head from mask and top logprobs,
validates normalization over the support and sampled-token membership,
and disables the tail term on replayed tokens.
- **Sampling-support metric**: log `sampling_support/size/mean` under
the existing train/eval and agent prefixes. It is the total number of
recorded support IDs divided by the number of tokens with nonempty
support. The existing rate aggregation preserves token weighting across
reporting windows without storing histograms or per-token scalars.
Positions without recorded support are excluded.
Support size measures the final truncated support. It does not measure
full-vocabulary retained mass or whether top-k prevented reaching top-p.
Those require pre-truncation probabilities, which this transport does
not carry.
- **Default sampling order**: `inference.top_p_before_top_k = true`
computes the nucleus on the full processed distribution before applying
a hard top-k cap. With `top_p = 0.99, top_k = 128`, nuclei smaller than
128 are preserved; larger nuclei are capped and may retain less than 99%
original mass. Stable tie-breaking keeps higher token IDs at the
boundary. This is the default whenever sampling-mask capture is enabled
and applies engine-wide (including eval) on V2. Set the flag to false to
restore vLLM ordering. Without mask capture the flag has no effect. The
final mask and processed logprobs still drive replay and SC.
Existing sampling-replay bounds and eval requirements still apply. The
default replay ordering implementation sorts the full vocabulary; it is
a correctness-first path, not a performance optimization.
Validation: 381 unit tests passed on the devbox across the orchestrator,
inference, trainer RL and config suites, covering config round-trips,
compact-logprob trimming, the mask/top-logprob merge and packing, exact
supported-distribution gradients and fused replay gradients. Two
`inject_prime_lm_head` tests crash the devbox GPU on main as well and
were deselected; example-config loading tests were excluded. Ruff
passes. No full-model training run was performed.
Sampling-order validation: 6 CPU/GPU sampler tests passed on the devbox
with PyTorch 2.13 and vLLM 0.32, including an independent nucleus
reference, ties, mixed per-row thresholds, V2 dispatch, and real GPU
sampling-mask capture. Six config/environment tests passed locally,
covering the omitted default, explicit true/false, V2 requirements, and
disabling the patch without capture. No full-model run was performed for
this ordering change. A sampler-only benchmark on RTX PRO 6000
Blackwell, vocab 151,552 (30 timed iterations after warmup, including
logits clone), measured native k→p vs new p→k: batch 1: 0.107/0.110 ms;
batch 32: 0.123/0.673 ms; batch 128: 0.198/3.516 ms. This does not
measure end-to-end rollout overhead.
Review-cleanup validation: seven focused cases pass for the renamed
`PRL_TOP_P_BEFORE_TOP_K` environment variable and token-weighted
support-size aggregation, including merged windows and zero-count
exclusion. Ruff check/format and `git diff --check` pass.
Sampler-evidence byte conversions are inline with explicit int32/float32
dtypes.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Rebased onto `main` at `82a5f506f`. Preserves main’s policy-client
sampling defaults while retaining request-scoped replay flags and
independent eval sampling. The focused train/eval sampling config
round-trip test, targeted Ruff check/format, and diff checks pass. All
rewritten commits are signed.
Cursor Bugbot follow-up: disabled `top_k = -1` now leaves the support
uncapped in both full-sort and bounded-candidate sampling paths,
including all-eval and mixed train/eval batches. Four focused CPU cases
cover a single eval row, all-eval batches, mixed batches, and bounded
sampling against an independent nucleus reference. Targeted Ruff
check/format and diff checks pass.
All commits in the rebased stack are signed; signing preserved every
commit’s patch and both branch trees.
CPU-only orchestrators crash before collecting rollouts because
`BatchPacker` builds a Qwen3.8 model on the `meta` device for FLOP
counting, while its sparse-attention constructors immediately load
GPU-only `indexed_attention` kernels. No attention forward pass is
needed for this packing-cost estimate.
Guard both constructor-time kernel loads with
`torch.cuda.is_available()`. CPU/meta construction can then count model
shapes and attention FLOPs; GPU trainers still resolve the same kernels
before `torch.compile`. Forward/backward code, weights and numerical
settings are unchanged.
The existing model checks now cover full-attention layers as well as
linear-attention layers. A regression check constructs text/composite
models on `meta` with CUDA reported unavailable and evaluates
`FlopCounter`.
Validation on an H200 with PyTorch 2.13.0+cu130 and Transformers 5.6.2:
| Check | Result |
| --- | --- |
| Upstream model checks, CUDA hidden | 12 passed |
| Upstream model checks, CUDA available | 12 passed |
| Combined-runtime Qwen3.8/Qwen3.5 model and vision checks | 29 passed |
| Real `BatchPacker`, full checkpoint config, 237,568-token cost, CUDA
hidden | Passed on upstream and combined runtime; 12 indexed layers and
identical FLOP counts |
| Real indexed-attention GPU forward/backward | Passed on upstream and
combined runtime; kernels bound before forward, finite outputs and
nonzero finite input gradients |
| Ruff and whitespace checks | Passed |
These are targeted startup and kernel/model checks, not a completed
full-size training step. The fix is also applied unchanged to the Model
Factory runtime alongside #3916 and #4241.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Narrows kernel loading to CUDA hosts; CPU/meta paths are for FLOP
counting only, so training forward behavior on GPU is unchanged.
>
> **Overview**
> Fixes CPU-only orchestrator crashes when **BatchPacker** builds
Qwen3.8 on the **meta** device for FLOP counting: sparse attention no
longer loads GPU-only `prime_kernels` `indexed_attention` at `__init__`
unless `torch.cuda.is_available()`.
>
> **`IndexedGatedAttention`** and **`SparseAttentionIndexer`** still
bind the same kernels on GPU trainers (before compile); only
construction timing changes—forward/backward and weights are unchanged.
>
> Tests now parametrize **`linear_attention`** and **`full_attention`**,
and add **`test_meta_flop_count_without_cuda`** to assert meta
construction and **`FlopCounter`** work with CUDA reported unavailable.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a25a85b7cc26cbe4c25708ff523cccd0982db637. 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: Codex <codex@local>
## Summary
- Policy sampling now applies only to the live policy. verifiers gives
the run's sampling only to seats on the run's client
(PrimeIntellect-ai/verifiers#2973, merged). An agent with its own
client, such as an external judge, uses only its own sampling. Fixes
PrimeIntellect-ai/verifiers#2923.
- Remove `resolve_env_config`, which added `top_k=-1`, `min_p=0.0` and
`return_token_ids=True` to every policy source's `extra_body`.
verifiers' `TrainClient` now sets `top_k=-1`/`min_p=0.0` on its own
`/generate` requests. `return_token_ids` is dropped, because `renderers`
sets it on the request body when needed.
- `validate_policy_sampling` skips agents with their own `client`. A
pinned judge can now set `temperature`, `top_p` and other sampling
values.
- Reword the `validate_no_extra_body_truncation` docstring. It still
accepts the disabled sentinels, so saved configs re-validate.
- Bump `deps/verifiers` to `9f0f03ae`, the merge commit of
PrimeIntellect-ai/verifiers#2973.
## Breaking
- **An env agent with its own `client` no longer inherits the source's
sampling.** Migration: set every value the agent needs on its own
`sampling`. Policy-source validation now allows it.
- **Frozen sources on the renderer client now default to `top_k=-1`,
`min_p=0.0`.** They used to get the model's `generation_config` values.
Migration: set `top_k`/`min_p` on the source sampling to keep other
values.
## Verification
Repro: a policy source on `agentic-judge`, with `sampling = {temperature
= 0.8, top_p = 0.9, top_k = 20}` and a judge pinned to
`openai/gpt-5-mini` on an eval client with `reasoning_effort = "high"`.
Seats resolve as `Env._episode_agents` does, and
`ChatDialect.apply_overrides` builds the wire body.
Before (`main`, verifiers `37ad8fe`):
```
prl accepts judge temperature: no
judge wire={'temperature': 0.8, 'top_p': 0.9, 'reasoning_effort': 'high', 'top_k': 20, 'min_p': 0.0, 'return_token_ids': True, 'logprobs': True, 'model': 'openai/gpt-5-mini'}
```
After (this PR + verifiers#2973):
```
prl accepts judge temperature: yes
solver wire={'temperature': 0.8, 'top_p': 0.9, 'top_k': 20, 'logprobs': True, 'model': 'policy'}
judge wire={'reasoning_effort': 'high', 'model': 'openai/gpt-5-mini'}
```
- `pytest tests/unit/test_configs.py`: 250 passed.
- `pytest tests/unit/orchestrator` (without `test_batch.py`, which needs
`fla`): 92 passed, 1 failed. The failure is
`test_prefill_logprobs_uses_inference_generate`, which needs `vllm`. It
also fails on `main` locally.
- `ruff check` and `ruff format --check`: passed.
- No live training run.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Summary
- Remove the `rl` suite from `.github/workflows/regression.yml`. Every
night it dispatched `tests/regression/configs/rl/*.toml` as hosted
`prime train` runs: alphabet-sort, wiki-search, wordle and
hendrycks-sanity at 8 GPUs each, plus reverse-text.
- Delete `tests/regression/configs/rl/` and the related `rl_config_file`
/ `rl_image_tag` dispatch inputs.
- Update `docs/development.md`.
The `parallel` and `eval` suites and the nightly cron are unchanged.
Context:
https://primeintellect.slack.com/archives/C0C2UUJAP7G/p1792849709248839.
The runs used a full node each and were still on TCP.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> CI and documentation cleanup only; no runtime or training code paths
change. Hosted RL regression coverage is reduced, which is intentional.
>
> **Overview**
> **Removes the nightly hosted RL regression path** from CI while
keeping parallel invariance and eval suites on the same schedule.
>
> The `regression.yml` workflow no longer offers an `rl` suite or the
`rl_config_file` / `rl_image_tag` dispatch inputs. The `rl-plan` and
`rl` jobs (matrix over TOMLs, GHCR image resolution, `prime train`
dispatch with secrets) are deleted entirely.
>
> All five configs under `tests/regression/configs/rl/` are removed
(alphabet-sort, hendrycks-sanity, reverse-text, wiki-search, wordle).
**`docs/development.md`** is updated so regression tier and workflow
tables describe only parallel and eval.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1f9b767e9fc00e16f517fbe22fc6ab5f3e33e378. 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 orchestrator held every in-flight and buffered episode, and every
pending `TrainingSample`, as Python lists with one entry per token. That
made memory about 3.5x larger and put hundreds of millions of references
in every full GC. It also made the per-token Python loops expensive:
advantage assignment, echo weighting and zero-advantage pruning. This PR
keeps per-token streams as typed arrays (int32 ids, bool masks, float32
values) from the vLLM response to the trainer.
- **vLLM to the env server:** `deps/renderers`
(PrimeIntellect-ai/renderers#201) decodes sampled logprobs to a float32
array, without a float64 list round trip. `deps/verifiers`
(PrimeIntellect-ai/verifiers#2961) builds env-server nodes as owned
arrays.
- **Env server to the orchestrator:** env servers always stream node
streams as raw-bytes arrays. In-flight assemblies hold the bytes, and
validated episodes hold arrays that view them.
- **Algorithms** work on arrays, vectorised:
- `assign_advantages` and `assign_reference_logprobs`;
- `scalar_advantage` and `is_trainable`;
- `stamp_loss_routing`;
- grpo `length_weighted_baseline` and `prompt` loss aggregation;
- echo observation weights;
- the advantage-range curriculum gate;
- `_prune_zero_advantages`, which also ran per token on the event loop.
- **Samples and micro batches:** `TrainingSample` and `MicroBatch`
streams are numpy arrays.
- Packing keeps `main`'s shape: each sample's arrays are appended and
concatenated once per bin, and padding uses `np.pad`.
- On the wire, each `MicroBatch` stream is a raw buffer of a fixed dtype
(`MICRO_BATCH_DTYPES`, shipped by the batch encoder's `enc_hook`). The
per-micro-batch alignment assert also checks each stream's dtype.
- **Trainer:** each stream becomes a tensor through one numpy copy that
also widens the dtype (`np.frombuffer` + `astype`), not
`torch.tensor(list)`.
- **`MicroBatch.env_names`** holds one name per sequence, not one per
token. A new `padding` field holds the padding count. The per-env
entropy and mismatch-KL metrics expand the names over `sequence_lengths`
and select tokens with vectorised masks. The annotation export strips
padding by count.
- **Live trace files** decode the raw-bytes streams with verifiers'
public `decode_ndarray` before writing JSON.
- **opd/opsd** send token ids to the scorer as lists.
Depends on PrimeIntellect-ai/verifiers#2961. `deps/verifiers` points at
that PR's commit, so this stays a draft until it merges and the pin
moves to `main`. PrimeIntellect-ai/renderers#201 has merged;
`deps/renderers` points at `main`. Companion to #4225, which stops
automatic full GCs. This PR makes each full GC cheaper.
## Breaking
- **The `MicroBatch` wire format changes.** Per-token streams are raw
buffers, not msgpack lists, and `env_names` is per sequence. The
orchestrator and the trainer must run the same prime-rl commit.
- **Env servers and the orchestrator must both include verifiers#2961.**
Node streams always ride the env-server wire as raw bytes, which an
older client cannot validate.
## Verification
- **Replay at scale.** A recorded batch of 2048 agentic episodes (147
groups, 393k nodes, 194M tokens, branches up to 262k tokens) went
through the production env-server stream, decode, GRPO scoring, sample
building, `prepare_batch` (`seq_len=262144`, 8 ranks), the batch
encoder, the trainer decoder and `_micro_batch_to_tensor`. Both trees
produced the same 1802 samples, 167M sample tokens and 648 micro
batches.
- **Disk and upload formats on the same 2048 episodes,** this branch
against `main`:
- Byte-identical for every episode: the file monitor's trace records
(default `float_decimals`), live trace files, the Prime Traces payload,
the samples projection and the training-viewer parquet rows.
- Full-precision records (`float_decimals=None`) and annotation
advantages print some floats differently, as the float32 value's
shortest form. Every differing number is the same float32 value.
- **Orchestrator equivalence.** On an earlier recorded batch (115
samples, 7.8M tokens), every packed `MicroBatch` field and every scalar
advantage matched `main` (float32 compare). That held for mean and
`prompt` loss aggregation, with and without truncation. Every trainer
tensor also matched `main` on 104 micro batches with padding and dummy
batches.
- **Unit tests:**
- New `tests/unit/orchestrator/test_episode_records.py` sends a
wire-decoded episode through the file monitor's episode, live and
annotation writers and the Prime upload projections. It checks that each
output holds JSON lists.
- `tests/unit/orchestrator`, `transports`, `eval`, `utils` and the
dashboard tests pass locally. One exception:
`test_prefill_logprobs_uses_inference_generate` fails at import, because
the local vLLM lacks `GenerateTokensResponse`.
- **Not yet run:** a GPU training run.
## Measured
The 2048-episode replay. It is single-process and CPU-only; GC is
disabled during timed phases and timed separately; memory is RSS growth.
Trainer figures add up all 8 ranks.
| | `main` | This PR |
|---|---|---|
| Decode (unpack + assemble + validate) | 19.4 s | 6.9 s |
| Memory for the held episodes | 21.2 GB | 6.0 GB |
| Score + build samples | 23.0 s | 7.8 s |
| Memory for the pending samples | 6.8 GB | 3.1 GB |
| Full GC, episodes + samples held | 14.8 s | 7.6 s |
| Pack (`prepare_batch`) | 9.5 s | 3.6 s |
| Batch wire size | 6.79 GB | 3.51 GB |
| Batch encode | 5.3 s | 1.1 s |
| Trainer decode | 20.4 s | 0.003 s |
| Trainer tensor conversion | 25.4 s | 0.20 s |
| Peak orchestrator RSS | 85.3 GB | 17.5 GB |
The remaining full-GC time is pydantic's per-model objects (about 8M for
this batch), not token data. #4225's scheduled-only full collection
keeps it off the hot path.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Breaking batch wire format and env-server ndarray streams require
lockstep orchestrator/trainer/verifiers upgrades; training correctness
depends on dtype alignment and per-sequence `env_names`/`padding`
semantics.
>
> **Overview**
> Moves **per-token training data** from Python lists to **typed numpy
arrays** end-to-end (orchestrator samples → packed `MicroBatch` →
trainer tensors), cutting memory, GC cost, and Python-loop overhead on
advantage assignment, echo/GRPO weighting, pruning, and packing.
>
> **Wire format (breaking):** `MicroBatch` per-token fields are **raw
byte buffers** (`MICRO_BATCH_DTYPES`) via `encode_array`, not msgpack
lists. **`env_names`** is **one entry per sequence** (not per token);
new **`padding`** tracks trailing pad tokens for annotation export and
metrics. Trainer builds tensors with **`np.frombuffer` + `astype`**
instead of `torch.tensor(list)`.
>
> **Algorithms & sink** use vectorized mask/weight ops; OPD/OPSD pass
**`token_ids.tolist()`** to scorers. **Live trace files** decode
`__nd__` payloads with **`decode_ndarray`** before JSON. Disk/upload
paths still emit plain JSON lists (new `test_episode_records.py`).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9652f05d84c10f77e11af1d319a98fda545b1161. 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>
Qwen3.8 CPU-offloaded PLE reload can exhaust GPU memory even with
#4102's chunked broadcast: vLLM retains received CUDA fragments until
the local table is complete. #3919 preserves the CPU destination but
leaves those incoming buffers on GPU.
Copy owned, concrete CUDA fragments into **pinned CPU buffers
synchronously** before vLLM retains them. Existing CPU storage and TP
filtering are preserved. Already-CPU inputs, GPU-resident embeddings and
symbolic tensor subclasses used by NIXL tracing pass through unchanged.
No streams, events or prefetch queue.
GPU checks passed on Nebius H200 / PyTorch 2.13.0+cu130 / vLLM 0.32.0:
- Job 6177: actual layerwise loader, 128 synthetic 16 MiB fragments, TP4
row ranges. Peak extra CUDA allocation fell **512 → 32 MiB**, with
**zero retained CUDA inputs**. Exact rows, shared CPU storage, uneven
final shard, GPU-resident control and already-CPU inputs passed;
received CUDA fragments were retained as pinned CPU tensors.
- Job 6179: reproduced the symbolic-input regression, then verified all
**32 owned PLE copy records per TP range**, original trainer source
names and exact contiguous row coverage, including the uneven rank-3
range. Uses actual NIXL LazyWeight/recorder/replay planning and vLLM PLE
loading; no NIXL network or full-model NIXL fit test.
- Ruff check/format and diff checks passed. Scripts and raw results are
saved privately outside this PR.
Full-model benchmark (India job 2953, completed; three warmed repeats
per mode):
| Transfer + reload | Median | Range |
| --- | ---: | ---: |
| Ordinary synchronous CPU staging | 96.90 s | 96.61–97.12 s |
| **Pinned synchronous CPU staging** | **31.74 s** | **31.60–32.02 s** |
| Async experiment #4242 | 24.19 s | 24.14–24.48 s |
Pinned synchronous reduces measured reload time by **67.2%** and
captures **89.6%** of the async experiment's saving with less code. This
transfers the same frozen 354.8 GB checkpoint in 177 packets into a full
TP4 vLLM 0.31.0 model, using a cached CPU sender and dummy KV
reservation to 0.85. It excludes trainer gathering and generation.
Sampled parameter/buffer hashes and CPU storage identity matched; peak
total CUDA allocation was 131.52 GiB in all modes. Pinned allocation has
a startup cost: the first pinned synchronous warmup took 78.83 s.
Host-memory tradeoff: post-reload RSS rose about **32 GiB per worker**,
retained in the pinned allocator cache. Budget **256 GiB for eight
inference workers/node**. Existing ordinary-staging smoke peaks were
692–748 GiB on nodes with 1,575 GiB RAM, including file cache;
conservatively adding 256 GiB budgets 60–64% of capacity. This is a
budget estimate, not a measured pinned-smoke peak. Warmed RSS
comparisons share the same allocator cache and are not independent
footprint measurements.
Five-step Nebius smokes are queued on the final pinned + NIXL-guard
source at GPU utilization 0.85: **6180 Muon** and **6181 AdamW full CPU
offload**, B32/G8, two trainer + two inference nodes each. The earlier
ordinary-staging runs 6174/6175 were canceled after replacement
submission. File/W&B, per-rank trainer logs and per-node CPU/GPU
resource monitors remain enabled. Final pinned end-to-end validation is
pending; neither PR has been merged.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches hot-path weight reload for Qwen3.8 PLE with device placement
and synchronous copies; wrong gating could break reload or NIXL tracing
subclasses.
>
> **Overview**
> Extends the Qwen3.8 PLE `load_weights` monkeypatch so
**CPU-offloaded** n-gram tables no longer pass **CUDA shard buffers**
into vLLM’s loader (which would retain them on GPU until the table is
complete).
>
> The patch now tracks offload state from the embedding weight and
layerwise kernel tensors, and for plain `torch.Tensor` CUDA inputs only,
**copies synchronously into pinned CPU** tensors before yielding.
**Tensor subclasses** used for NIXL transfer tracing are left untouched;
TP overlap filtering and existing CPU/GPU paths are unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7115867495b31030c91ac7a11e7384b3d802fb67. 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: Codex <codex@local>
Removes the `ppo` and `cispo` RL loss types.
- `PPOLossConfig` / `CISPOLossConfig` and their `LossConfig` entries
- `PPOLoss` / `CISPOLoss` and their dispatch in `setup_rl_loss_fn`
- their unit tests and config assertions
IPO (default), IcePop and custom losses are unchanged. Docs, skills and
examples did not reference PPO/CISPO.
Replaces the closed#3776, redone on current main.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking change for any run still setting `trainer.loss.type` to `ppo`
or `cispo`; remaining RL training paths are unchanged but configs must
be migrated to IPO/IcePop/custom.
>
> **Overview**
> Removes **PPO** and **CISPO** as selectable RL loss types from the
trainer. Config validation no longer accepts `loss.type` of `ppo` or
`cispo`; the discriminated `LossConfig` union and `setup_rl_loss_fn`
only wire **IPO** (default), **IcePop**, and **custom** losses.
>
> Implementation deletes `PPOLossConfig` / `CISPOLossConfig`, the
`PPOLoss` / `CISPOLoss` classes in `loss.py`, and their unit tests
(clipping, importance-ratio caps, gradients). CE, ref_kl, IPO, IcePop,
and custom loss paths are unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a13dfc928edb1d0bebdb8512eaf56e6f8b4fba1f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Without the clone, vLLM ran out of memory on the first weight update of DeepSeek-V4.1 (EP rank 7,
132 GiB allocated): each view kept its whole bucket alive until the layer finished loading.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With `--control`, a running eval serves `GET`/`PUT /v1/concurrency`
(port 8040), so a shared endpoint's capacity can move between evals
without restarting them. `PUT {"target": N}` pins the cap at N, outside
the configured band too, and `{"target": null}` hands it back to the
adaptive controller; lowering it cancels nothing, new episodes wait
until enough running ones finish. It reuses the control server from
#3974, here on the eval's own event loop, and the manual override idea
from #4084 without its file and SIGHUP path.
Tested on rtx-hydra with reverse-text against a local vLLM at `-c 64`:
pinning 16 drained inflight from 64 to 16, releasing it ramped back
toward 64, and `target: 0` was rejected with 422.
### Problem
- NCCL broadcasts gather Qwen 3.8's whole row-sharded ngram table on
**every** trainer rank before converting it into HF fragments.
- For the 320,001,536 × 160 table that is **~95 GiB of BF16 per rank**.
### Fix
- Convert and send one HF fragment at a time (128 fragments, **~763
MiB** max each).
- Build each fragment only on trainer rank 0, the only rank that
broadcasts to inference.
### Design
- `ChunkedConvOp`: a conversion op that yields one final HF packet per
checkpoint shard. Its normal `prime_to_hf` uses the same iterator, so
regular checkpoint conversion is unchanged.
- `NGramEmbeddingWeights` owns Qwen's row ranges and `.shard_N.weight`
names; the transport stays model-agnostic.
- `get_chunked_conversion_ops` finds these ops for weights present in
the state dict, including `torch.compile` names.
- The NCCL sender announces `num_layers + 1 + Σ shard_count` packets.
- `_gather_row_chunk_to_master` assembles a fragment on rank 0:
- Owners in rank 0's replica write their rows into a zero buffer, and
`dist.reduce(dst=0)` sums them (adding zeros is exact).
- Other replicas return immediately and allocate nothing.
- Plain or replicated tables are sliced locally on rank 0.
- Layouts other than a single `Shard(0)` dimension raise an error.
- Requires rank 0 at the origin of the mesh, as `init_device_mesh` lays
it out.
- Chunked ops must produce final HF keys that no other op depends on or
transforms.
- Unchanged: the filesystem transport (it keeps `main`'s full gather),
DCP checkpoints and LoRA.
### Why `reduce` to rank 0
- **All-reduce** (first version): fast, but every rank in every replica
allocates and receives a fragment it doesn't need.
- **Point-to-point** (`batch_isend_irecv`, prototyped in #4199):
- Moves only the needed rows, but GPU-to-GPU traffic between nodes uses
**one NIC path**, while collectives stripe over NVLink and all 8 NICs. A
remote fragment took **~20 ms vs 4–6 ms**.
- With FP32 sources, owners' reserved memory grew by one fragment per
fragment sent, because BF16 temporaries can't be reused until async
sends finish. An owner-side stream sync fixes this at no time cost.
- It only works if the group's communicator already exists. The trainer
passes `device_id` to `init_process_group`, so communicators are created
eagerly; without it, the first cross-node batch hung (Nebius job 5998).
- **`reduce(dst=0)`** combines the good parts:
- Collective multi-NIC routing.
- Only rank 0 receives each fragment, and other replicas skip it.
- One reused BF16 buffer per owner.
- No warm-up needed.
### Benchmark: Nebius, 2 × 8 H200, PyTorch 2.13.0+cu130, NCCL 2.29.7
- Job **5994**: synthetic 320,001,536 × 160 FP32 table, BF16 wire, 128
fragments, functions copied verbatim from the branch.
- Rank 0 does a ~20 ms device-to-host copy per fragment as a stand-in
for the vLLM broadcast. That plus verification is ~2.9 s of each full
pass.
- Medians of 3 passes. Every fragment matched exactly on rank 0, and
other ranks got `None`.
**Owners split across both nodes** (one replica, 16-way row sharding):
| | Full pass | One fragment from a node-1 owner | Owner peak reserved |
Rank 0 peak reserved |
| --- | ---: | ---: | ---: | ---: |
| All-reduce (first form) | 3.25 s | 5.7 ms | 12,974 MiB | 13,474 MiB |
| Batched P2P | 4.34 s | 20.2 ms | 18,322 MiB | 13,474 MiB |
| Batched P2P + owner sync | 4.34 s | 20.2 ms | 12,974 MiB | 13,474 MiB
|
| **`reduce(dst=0)` (this PR)** | **2.96 s** | **4.0 ms** | **12,974
MiB** | 13,474 MiB |
**Owners on rank 0's node** (replica per node, NVLink only):
| | Full pass | One fragment | Owner peak reserved | Other replica peak
reserved |
| --- | ---: | ---: | ---: | ---: |
| All-reduce (first form) | 3.15 s | 4.7 ms | 25,182 MiB | 25,182 MiB |
| Batched P2P | 2.85 s | 2.9 ms | 36,642 MiB | 24,418 MiB |
| Batched P2P + owner sync | 2.85 s | 2.9 ms | 25,182 MiB | 24,418 MiB |
| **`reduce(dst=0)` (this PR)** | **2.91 s** | 3.3 ms | **25,182 MiB** |
**24,418 MiB** |
Findings:
- Across nodes, `reduce` is **~5× faster** per fragment than
point-to-point and **~30% faster** than all-reduce. NCCL logs show
collectives on all 8 InfiniBand NICs with GPUDirect RDMA.
- On one node, all variants are within ~2% per full pass.
- Point-to-point's extra reserved memory is exactly one 763 MiB fragment
per fragment sent. The result is the same with
`expandable_segments:True`.
- With `reduce`, other replicas stay at shard size; with all-reduce they
also allocate a fragment buffer.
- Resident FP32 shards are 12,208 MiB (16-way) and 24,414 MiB (8-way).
Allocated peaks were shard + ~one fragment for every variant.
### Validation
- **Earlier versions** (all-reduce: jobs 5651, 5652, 5653;
point-to-point: job 5903, all on Nebius H200):
- Unit tests.
- Real PyNccl transfers to two receiver GPUs: Qwen text, composite
config, no-ngram control, a non-Qwen chunked op, before and after weight
updates.
- Four-GPU edge cases: FP32/BF16, uneven or empty rows, replicated and
size-one dimensions, rejection of unsupported layouts.
- **`reduce` version:**
- The benchmark above: exact fragments on 16 GPUs in both layouts.
- A CPU (gloo) check on a 2 × 1 × 4 mesh: uneven splits and replicated
tables.
- **Not yet re-run on `reduce`:** real PyNccl transfers to inference
receivers. Full-size training/inference reload and NIXL are not claimed.
- Ruff and formatting pass.
### Related
- Supersedes #4199, which is merged into this branch. Targets current
`main`.
- #3938 bounds lookup/backward memory; this PR bounds broadcast
reconstruction memory.
The automated summary below may describe an earlier revision.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes the distributed NCCL weight broadcast path and DTensor row
assembly for large embeddings; incorrect collectives or shard math could
break inference weight sync despite new unit coverage.
>
> **Overview**
> **Bounds NCCL weight-broadcast memory** for huge row-sharded tables
(e.g. Qwen ngram embeddings) by converting and sending one HF checkpoint
shard at a time instead of materializing the full tensor on every
trainer rank before sharding.
>
> Introduces **`ChunkedConvOp`** with `iter_prime_to_hf` /
`shard_count`, so models declare how a runtime weight maps to
independent HF packets. **`NGramEmbeddingWeights`** uses this for
`.shard_N.weight` intervals. **`get_chunked_conversion_ops`** ties those
ops to keys in the live state dict (including `torch.compile` names).
>
> The **NCCL sender** bumps the announced packet count by `Σ
shard_count`, strips chunked weights from each layer dict, and after the
usual layer broadcast streams each fragment:
**`_gather_row_chunk_to_master`** assembles a row slice only on trainer
rank 0 via `dist.reduce` over row owners (with explicit checks for
replicated / single `Shard(0)` layouts). Non-owning ranks yield `None`
and do not broadcast.
>
> Adds **unit tests** for shard intervals, generic chunked ops, and
compiled parameter name resolution.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6cba629f59dfaf30002429398a267103074ed6d5. 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: Codex <codex@local>
Co-authored-by: Cursor <cursoragent@cursor.com>
Adds text-only training for Muse Glimmer
(`meta-models/Muse-Glimmer-30B`, HF config `muse_glimmer` /
`muse_glimmer_text`).
## Model
`models/muse_glimmer/` is a dense decoder, written against vLLM 0.31's
`muse_glimmer.py`:
- Token embeddings pass through a weightless RMSNorm (no
`sqrt(hidden_size)` scale).
- Gemma2-style sandwich norms. Weights are stored as an offset from one;
pre-norms use `rms_norm_eps` and post-norms use `post_norm_eps`. All
norms compute in fp32.
- Attention:
- Weightless fp32 QK-norm, applied before RoPE.
- The query is then multiplied by `qk_scale_factor`. The raw form is
divided by `sqrt(head_dim)`; the already-folded form is used as-is.
- Softmax scale is `head_dim**-0.5`.
- Output is multiplied by `sigmoid(gate_proj(attn_input))` before
`o_proj`.
- iRoPE: `sliding_attention` layers use NeoX RoPE with the sliding
window. Every fourth `full_attention` layer uses no RoPE.
- SiLU MLP and an untied `lm_head`.
- Logits are scaled by `output_multiplier`, then soft-capped at
`final_logit_softcapping`. The head is linear, so the multiplier is
folded into the final norm.
The model reuses `FlashAttention._compute_attention`, so Ulysses CP
works as for other dense models (32 query heads, 2 KV heads under the
default `cp_blocker`). FLOP and active-parameter accounting come from
the shared `FlashAttention.attention_flops` and `num_active_params`.
Weights keep the checkpoint's `model.language_model.*` names, so
HF↔PrimeRL conversion is the identity. The vision tower is not loaded.
`vision_config` and the token ids stay on the config.
`muse_glimmer` is added to `VLM_REGISTRY` and to the custom VLM mapping
only so that layer-prefix lookup and dispatch find the text backbone, as
for Qwen3.8 Flash Next. `[model.vlm]` training is not supported.
## Shared changes
- **LM head softcap.** `FusedOutputLinear` and `VanillaOutputLinear`
take an optional `softcap`: logits become `softcap * tanh(logits /
softcap)`. It covers the logprob/entropy path, the chunked cross-entropy
path and their backward passes. `inject_prime_lm_head` carries the
softcap over from the model's own head. With `softcap=None` the existing
code paths are unchanged.
- **Parsers.** `meta-models/Muse-Glimmer*` maps to vLLM's `muse_glimmer`
tool-call and reasoning parsers.
- **Docs.** Model rows added to the README and `docs/advanced.md`
tables.
## Renderer
`orchestrator.renderer = "auto"` resolves to the `muse-glimmer` renderer
([renderers
#194](https://github.com/PrimeIntellect-ai/renderers/pull/194)), which
is already in the `deps/renderers` pin on `main`.
## Weight sync
Only the text weights are broadcast. On each reload, vLLM logs `Failed
to load weights` for the 50-layer vision encoder modules: 50 QKV, 50
output projections, 102 LayerNorms, and the adapter/projection linears.
Those modules keep their checkpoint weights (`_place_kernel_tensors`).
Exported weight checkpoints contain only the text weights.
## Tests
- `tests/unit/train/models/test_muse_glimmer.py`:
- Config defaults (NoPE layer indices, query scale for both config
forms).
- Composite config round-trip and registry dispatch.
- State-dict key names.
- `tests/unit/train/rl/test_fused_lm_head.py`: fused softcap logprobs,
entropy, summed CE and gradients against full logits.
- `tests/unit/test_parsers.py`: parser mapping.
An earlier eager-reference forward/backward comparison was dropped in
review: it compared two implementations written from the same
description, not an independent reference. The trainer-vs-vLLM KL runs
below cover this end to end (forward, backward, weight sync to vLLM).
Ruff check and format pass on the changed files.
## Validation
### On-policy run (55 steps)
The mismatch KL compares the trainer's current weights against the
weights vLLM sampled with, so in an async run it also counts policy lag.
To isolate modeling numerics, this run is fully on-policy
(`orchestrator.max_off_policy_steps = 0`), as in the nightly mismatch-KL
check from #3892. Otherwise it uses the same setup as the table below:
`math-env` on Hendrycks-Math, batch 64, group size 8, completion limit
4096, rebased branch, vLLM 0.32.
- 55 steps, all below **0.015**: maximum **0.000791**, mean
**0.000373**. It stays flat (step 1: 0.0002).
### Default-lag run (20 steps)
20 math RL steps with the real `meta-models/Muse-Glimmer-30B` checkpoint
on one 8×H200 node. This run used the branch before its rebase onto
current `main`; the rebase only merged the softcap argument alongside
the new `topk_ids` argument in `lm_head.py`, and the CPU tests above
were rerun after it.
- 4 trainer GPUs (FSDP, FlashAttention, fused LM head at chunk size
8192, default fp32 optimization dtype) and 4 vLLM 0.31 GPUs (DP 4), NCCL
weight broadcast, default router.
- `math-env` on `PrimeIntellect/Hendrycks-Math` (train split),
**batch_size 64**, group size 8, sequence length 8192, completion limit
4096, default reasoning strength (high), default policy lag. Renderer
`auto` → `muse-glimmer`.
- The math-env LLM judge fallback was disabled (`env.taskset.task.judge
= None`), so rewards are math-verify only.
- All 20 mean mismatch KL values are below **0.015**: maximum
**0.010762250** (step 20), mean **0.003626577**. Step 1 is 0.000224.
Later steps rise as the policy moves and off-policy lag reaches 4
(entropy falls from 0.39 to 0.13 over the run).
| Step | Mean mismatch KL |
| --- | ---: |
| 1 | 0.000223969 |
| 2 | 0.001205387 |
| 3 | 0.006474962 |
| 4 | 0.003887596 |
| 5 | 0.000541684 |
| 6 | 0.003174253 |
| 7 | 0.000411350 |
| 8 | 0.000992465 |
| 9 | 0.001279445 |
| 10 | 0.001222895 |
| 11 | 0.004851219 |
| 12 | 0.009074968 |
| 13 | 0.002570692 |
| 14 | 0.005244157 |
| 15 | 0.002843830 |
| 16 | 0.003673188 |
| 17 | 0.003002412 |
| 18 | 0.004181557 |
| 19 | 0.006913262 |
| 20 | 0.010762250 |
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
It prefills DeepSeek-V4.1's layers past the last KV source on each request's last window only,
leaving approximate states the trainer never computes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Round the mHC stream collapse to bf16 before the norm, as vLLM does.
- Indexer: vLLM's 1e-4 fp8 amax floor; fp8-round q/k before cuDNN's bf16 scoring.
- Count only candidate entries in the indexer MFU of candidate-consuming layers.
- Raise on SM100 with fp8 KV until NVFP4 compressed entries are modelled.
- Set kv_precision/dsa_backend on the text config; move is_prime to layers/ngram.py.
- Exclude engram tables from Muon; reject the filesystem broadcast for row-sharded
tables; send frozen tables over NCCL once.
- vLLM: serve V4.1 with the text-only class instead of patching the VL wrapper;
build the engram row writer only for V4.1; drop the received-weight clone.
- Drop the prime-kernels code paths, _random_init_, the example README and docs paragraph.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
## Problem
`Tensors.compute_stats` all-gathers each key's per-token values across
the world, computes the stats, and then appends the gathered tensor back
to itself as a Python list (`self[key].append(tensors.tolist())`).
Nothing reads the lists afterwards; they are left over from the
tensor-distribution logging in #688.
The lists are expensive and they live long:
- A Python float list costs about 40 B per element, against 4 B as
float32.
- Each key holds world_size × the local loss tokens on every rank.
Per-token keys such as entropy, mismatch KL (each overall and per env)
and the score-centering metrics are gathered across CP before logging,
so every CP rank already holds the whole sequence's values, and the
world gather multiplies that again.
- `tensors` is only replaced at the start of the next step's micro-batch
loop, after the next batch has been waited for, received and converted.
So the lists stay in host memory through the entire next batch load.
With long packed sequences and large batches this can reach hundreds of
GB of host memory per rank, on top of the batch being converted, and it
ends in a host OOM.
## Fix
- Drop the `tolist()` append-back in `Tensors.compute_stats`; the popped
keys leave the object empty.
- `del tensors` right after `compute_stats` in the RL train loop, so the
step's stats are freed before the next batch arrives.
The logged metrics (mean, median, std, min, max) are unchanged.
## Testing
- `ruff check` and `ruff format --check` pass.
- A single-process gloo run of `Tensors.compute_stats` returns the same
mean, median, std, min and max as before and leaves the object empty.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Behavior change is limited to memory lifecycle after stats
aggregation; W&B and console metrics are unchanged.
>
> **Overview**
> Fixes a **host memory leak** in RL training where per-step tensor
logging retained huge all-gathered per-token arrays as Python lists long
after metrics were computed.
>
> **`Tensors.compute_stats`** no longer appends each key’s
world-gathered values back onto the accumulator via `tolist()` after
computing mean/median/std/min/max; popped keys are discarded so the
object ends empty. **`train.py`** explicitly **`del tensors`** right
after `compute_stats`, so gathered stats are released before the next
batch is waited on and loaded.
>
> Logged scalar metrics are unchanged; only unused retained
distributions are dropped.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
15560fee6255461cf05a1f5fc7c75e11151db30e. 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
- **Prime monitor on by default** for `rl`, `sft` and `eval`. Turn it
off with `--no-monitors.prime`.
- **Fails loudly when not set up**, like W&B. A missing Prime API key or
a failed run registration (for example, no team) stops the launch with a
fix-it message: authenticate (`prime login`, `prime switch`) or pass
`--no-monitors.prime`. The W&B credential error gets the same kind of
hint.
- **Every episode, as it arrives.** Train and online-eval episodes
upload the moment they land, the same as for the file monitor, errored
and filtered ones included. Before, only the trained cohort uploaded,
and RL online-eval episodes never reached Prime. A multi-agent episode
(for example, solver + judge) uploads as one episode.
- **All run links in the launch banner:**
```
Dashboard · http://localhost:7788
Prime ·
https://app.primeintellect.ai/dashboard/evaluations/g5ikrgtu6rtrn1xw3ax8h5oe
W&B · https://wandb.ai/primeintellect/prime-rl/runs/1hhwn09s
```
Each monitor records its links in `run_dir/monitors/links.json`, and the
launcher waits for every configured monitor. A monitor that is off
doesn't hold up the banner, and neither does a component that fails.
- **CI never runs the Prime monitor:** every integration launch and the
regression eval pass `--no-monitors.prime`. The hosted nightly (`prime
train`) keeps it, because its Prime run is what it checks.
- **Docs:** `docs/training.md` gets a `Monitors` section (File, W&B,
Prime). The dashboard button reads "View on Prime".
## Breaking
- With a Prime API key, every `rl`, `sft` and `eval` run now registers
on Prime and uploads metrics and episodes. To opt out, pass
`--no-monitors.prime` or set `PRIME_RUNS_MODE=disabled`.
- Without Prime credentials, a launch fails unless the monitor is off.
To fix, run `prime login` (and `prime switch` for a team), or pass
`--no-monitors.prime`.
- Prime no longer shows advantages or which episodes were trained.
Episodes now upload at arrival, before batching, and Prime Traces has no
way to update an uploaded episode. The local trace stream and dashboard
still show both, through the file monitor's annotations. See Follow-ups.
## Verification
Each run's local episodes were compared with Prime Traces (episode ids,
member traces, upload latency):
| Run | Links | Episodes (local = Prime) | Upload latency (p50 / max) |
|---|---|---|---|
| reverse-text RL, 5 steps | [Prime
run](https://app.primeintellect.ai/dashboard/training/ux7v798anfv0ubjlqb5rhqy7)
| 755 train + 512 eval | 1.2 s / 3.0 s |
| gsm8k eval (`configs/debug/eval/single-turn.toml`) | [Prime
evaluation](https://app.primeintellect.ai/dashboard/evaluations/inebh2ggk181hsball576mqd)
| 16 | 1.9 s / 2.3 s |
| tb2 `fix-git` under `agentic-judge`, 2 rollouts | [Prime
evaluation](https://app.primeintellect.ai/dashboard/evaluations/u2cx23xqjfzv8cxrvwdftb4g)
| 2, each with `solver` + `judge` traces | 0.9 s / 1.4 s |
- **Hosted training:** `prime train` on reverse-text, 5 steps, at this
branch via `--pr 4096 --image-tag v0.10.1.dev69` ([Prime
run](https://app.primeintellect.ai/dashboard/training/vtsecakzruux0bt81l0oux55)).
- The monitor attached via `$RUN_ID`, and eval reward went from 0.15 to
0.70.
- Prime holds 512 eval episodes (256 per epoch) and 1561 train arrivals,
640 of them trained.
- **Banner:** the gsm8k eval with `--monitors.wandb` printed the three
lines above ([W&B
run](https://wandb.ai/primeintellect/prime-rl/runs/1hhwn09s)).
- **No credentials:** the same eval without a Prime key exited after 4 s
with `The prime monitor found no Prime API key. Authenticate with `prime
login` (or set PRIME_API_KEY), or turn the monitor off with
--no-monitors.prime`.
- **Upload overhead** (CPU-only script): with the real monitor and SDK
queue, `log_episodes` costs 0.5 ms per episode (p99 0.7 ms) and doesn't
block the event loop.
- **Unit tests:** `pytest tests/unit -m "not gpu"`: 921 passed, 1
failed. The failure is `test_cpu_adam`, which needs `ninja`, and `ninja`
isn't installed on this box.
## Follow-ups
- Bring advantages and trained-batch membership back to Prime. Prime
Traces needs an endpoint to update an uploaded episode (backend + SDK
work in `prime`); the monitor would then forward the orchestrator's
batch annotations, as the file monitor does.
- SFT online evals still open one Prime evaluation per epoch. They
should join the trainer's Prime run, like RL online evals do.
- If the platform stalls and the SDK queue fills, each episode upload
can block the orchestrator for up to 5 s. A non-blocking queue put would
fix this.
- The SDK's legacy Parquet fallback (accounts without Prime Traces)
still samples every 10th step. Changing that needs a change in the
`prime` repo.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Default-on Prime changes launch requirements (API key/team) and
uploads all episodes to the platform; CI and local runs without
credentials must pass `--no-monitors.prime`.
>
> **Overview**
> **Prime platform monitoring is now on by default** for `rl`, `sft`,
and `eval`. Disable with `--no-monitors.prime`. Missing `PRIME_API_KEY`
or failed run registration **fails launch** with guidance to
authenticate or opt out (W&B gets the same pattern for bad credentials).
>
> **Launch banners** print Dashboard, Prime, and W&B URLs together.
Monitors write expected/published links to `monitors/links.json`;
launchers wait (via `log_run_links` / `run_links`) until configured
monitors publish. Eval runs the banner on a background thread while the
console stays at ERROR-only.
>
> **Prime train uploads** now stream **every episode on arrival** (`all`
subset), not only the trained cohort on a cadence. Shared **atomic
record I/O** (`utils/record.py`) backs platform records and link files.
>
> **Docs, dashboard UI** ("View on Prime"), skills, regression eval
workflow, and integration tests are updated for default-on Prime and
`--no-monitors.prime` in CI/forks without secrets.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
33a0a209c0c8ce722a6f9ef0dcc2b48d259285a4. 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>
FLA's identity-based metadata cache can skip operations during
activation-checkpoint recomputation. This can misalign
selective-checkpoint replay and fail backward with `RuntimeError:
Autograd not support dtype: Int`
([#3882](https://github.com/PrimeIntellect-ai/prime-rl/issues/3882)).
Disable FLA tensor caching when `apply_ac` is called, for both full and
selective activation checkpointing. This is a process-wide setting after
AC is applied; other FLA users in that process also bypass the cache.
The PR now changes only `trainer/model.py`.
Removed the CPU sequence-length arguments from Qwen3.5, Qwen3.8 and
shared GatedDeltaNet. FLA keeps its existing GPU-to-CPU metadata
preparation. On four H200s, a synthetic 237,568-token CP4 checkpointed
GDN forward/backward measured 119.45 ms without CPU reuse versus 118.55
ms with it. The 0.90 ms difference was noisy (paired-bootstrap 95%
interval: -0.38 to 2.37 ms). Scaling across 36 GDN layers estimates
~0.1% of a 30-second microbatch; this was an eager layer benchmark, not
a full-model speedup measurement (Nebius job 5896).
## Validation
- On one allocated H200 (Nebius job **5901**, PyTorch 2.13.0+cu130 / FLA
0.5.2), all **19** focused model/checkpoint tests passed after removing
the CPU arguments.
- All **6** cache-policy checks passed (full/selective AC, frequencies
1/2/4), including bypassing an already populated FLA cache.
- All **12** eager tiny-model cases and **8** compiled
(`fullgraph=false`) checkpoint-backward cases passed for Qwen3.5 and
Qwen3.8 with 2/4 packed sequences. Losses and embedding gradients
matched no-AC references within the test tolerances. These are
single-GPU checks, not a distributed production-training validation.
- Ruff, formatting and diff whitespace checks passed.
The generated summary below predates removal of the CPU sequence-length
plumbing.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes global FLA behavior for all AC-enabled training runs and
affects backward through FLA-backed layers, but the change is narrow and
aligns replay with the original forward.
>
> **Overview**
> **Disables FLA’s tensor/metadata cache whenever activation
checkpointing is enabled**, so the same FLA op sequence runs on the
initial forward and on checkpoint recomputation.
>
> `apply_ac` now imports `fla.utils` and sets `FLA_DISABLE_TENSOR_CACHE
= True` before wrapping decoder layers. That is a **process-wide
policy** for any model that uses AC (full or selective); models that
never touch FLA are unaffected.
>
> This targets backward failures such as `RuntimeError: Autograd not
support dtype: Int` when selective AC replays layers that use FLA
kernels (e.g. Qwen linear-attention / Gated DeltaNet paths).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c193e086eb9eba2ad02afc4e09ca1f6a7cf0e5d5. 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: Codex <codex@local>
## Summary
- The trainer now treats a `prime/` conversion cache without the
`.prime-v1` marker as an incomplete conversion. The conversion writes
the marker last, so a missing marker means an earlier run died during
the conversion.
- Master logs a warning, deletes the incomplete cache, and converts from
the HF snapshot again. Before this change, every later run raised
`RuntimeError: ... is missing the required .prime-v1 marker` until
someone deleted the directory by hand.
- If `model.name` points directly at a `prime/` directory with no
marker, the trainer still raises. In that case there is no HF source to
convert from.
## Verification
I ran `configs/ci/integration/reverse-text-moe/start.toml`
(`samsja/mini-glm-moe`, HF → prime conversion) with `--max-steps 3` and
`--trainer.model.conversion-dir` set to a temporary directory:
1. Clean run: the conversion wrote `prime/model.safetensors` and
`.prime-v1`, and training finished.
2. Simulated interrupted conversion: I deleted `.prime-v1` and truncated
`model.safetensors` to 500 MB.
- **Before** (on `main`): the trainer failed with `RuntimeError: PrimeRL
conversion cache .../conv/prime is missing the required .prime-v1
marker`.
- **After**: the trainer logged `Removing incomplete PrimeRL conversion
cache .../conv/prime and converting again`, wrote a full 1.09 GB shard
and the marker, and finished 3 steps (mismatch KL 0.0002).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Localized to one-time weight conversion cache handling on master; no
change to training logic or direct prime-path loading behavior.
>
> **Overview**
> **HF → PrimeRL auto-conversion** now treats a `prime/` cache
**without** the `.prime-v1` marker as incomplete (the marker is written
last), not as a finished cache.
>
> On master, if that path exists but the marker is missing, the trainer
logs a warning, **removes the partial directory** with `shutil.rmtree`,
and runs conversion again from the HF snapshot. Previously, an existing
`prime/` folder skipped conversion and later runs failed with a
missing-marker `RuntimeError` until someone deleted the folder manually.
>
> Loading when `model.name` points **directly** at a `prime/` directory
with no marker still **raises**—there is no HF source to rebuild from.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5770f9c4ad387a2d7a8e8551af11c673baad09a7. 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#2960 (merged).
- verifiers now drops a trace that carries no reward signal (a judge's
`task_defect`, a cheating audit) instead of failing it with
`UnscoredError`. A dropped trace is `ok` and carries its reason in
`trace.dropped`.
- `iter_trainable_traces` skips dropped traces, so they stay out of
training batches. The `effective` train and eval subsets skip them too,
so they stay out of reward means.
- The dispatcher logs each dropped trace at INFO: `Trace dropped in
group <id> (<env>) — judge: outcome=task_defect`. This replaces the two
`Trace failed` / `Episode failed` warnings an unscored rollout used to
produce.
- The `all` subset reports a `dropped` rate and a count per reason
(`.../dropped/<reason>`), separate from `has_error` and `error/<type>`.
- `deps/verifiers` is bumped to verifiers `main` at the #2960 merge
(`2f6ed0c`). The bump also brings in the verifiers `main` commits since
`4c2738d`: #2951, #2952, #2953, #2959.
## Verification
- `uv run pytest tests/unit/orchestrator tests/unit/eval
tests/unit/transports` (macOS, CPU torch): 166 passed. The extended
`test_metrics` / `test_algorithms` cases cover the dropped rate, the
per-reason count, the effective subset, and `iter_trainable_traces`
skipping a dropped trace. `test_batch.py` (needs `prime_kernels`) and
`test_prefill_logprobs.py` (needs `vllm`) cannot run on macOS and fail
the same way on the old submodule pin.
- `ruff check` and `ruff format --check` are clean.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Ulysses context parallelism published the full-sequence `cu_seqlens` and
`max_seqlen` through a module global, `ULYSSES_PARAMS`, which attention
read at call time. Compiled blocks guard on that global, so a micro
batch with a different document count recompiles every rank. This PR
drops the global: attention uses the `cu_seqlens` and `max_seqlen` it is
already passed, which the models build from the pre-shard `seq_lens` and
so cover the full sequence each rank holds after the all-to-all.
- `ULYSSES_PARAMS`, `update_ulysses_params` and
`setup_cp_attention_params` are gone, so `setup_cp_params` only shards
inputs.
- Both trainers check once per micro batch, on the CPU `seq_lens`, that
they sum to the full sequence length. This also covers the Qwen3.5 VLM
path that defers sharding to the model, and never syncs with the GPU
(main's check made three host syncs per micro batch).
- GPT-OSS's Ulysses attention gets the same change.
- Rebased onto main after #4134 removed ring CP, so this is now Ulysses
only; the ring half of the original PR is gone with it.
The recompile shows only where blocks compile. On main, EP MoE blocks
run eagerly under the default `fullgraph = false` (fixed by #4086), so
on the MoE workload below this PR alone is speed-neutral. On top of
#4086 it removes the recompile and its slow step:
| 1 x 8 B300, GLM-4.5-Air 8 layers, ep 8, cp 2, real data | median
(min-max) s | recompiles per rank | `ULYSSES_PARAMS` guard failures |
| --- | --- | --- | --- |
| main | 2.246 (2.183-2.344) | 1 | 0 |
| this PR | 2.231 (2.191-2.339) | 1 | 0 |
| #4086 | 1.718 (1.672-8.126) | 3 | 2 |
| #4086 + this PR | 1.702 (1.664-1.819) | 1 | 0 |
Measured at `b57635d84`; the later commit only moves the `seq_lens`
check to the CPU in the trainers. Loss agrees across arms within 0.003
over steps 1-9 and within the repeat spread after that. Baseline:
[`fea1267ef`](https://github.com/PrimeIntellect-ai/prime-rl/commit/fea1267ef65e8b53fe7a09a3768d148112fadac6).
Harness, configs and results: [`REPORT.md` at
f3a57c55f](https://github.com/PrimeIntellect-ai/prime-rl/blob/f3a57c55f5b7922df3a6d0f2d30c8497df6603ea/benchmarks/scripts/cp-ulysses-params-b300/REPORT.md),
removed in the last commit. The ring-era results are in the earlier
report at
[`47070d3d2`](https://github.com/PrimeIntellect-ai/prime-rl/blob/47070d3d281452d748cd64cfa562f05bb9c5eddd/benchmarks/scripts/cp-ring-params/REPORT.md).
GPU unit tests on the same node pass and match main: `test_moe.py`,
`test_checkpointing.py`, the Qwen3.5 CP setup test and the 2-rank
GPT-OSS CP attention test.
Unrelated bugs found along the way, not fixed here:
- GPT-OSS calls FA4 directly because the FA4 custom op has no sink
argument, so it graph-breaks and cannot use fullgraph.
- The color-codeword RL env fails in the orchestrator with `Inline image
count does not match expanded placeholder runs`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This PR passes the EP all-to-all's output length into the op, instead of
creating a dynamic size inside the op's fake, so MoE layers compile
under the default `fullgraph = false`. On main, that fake breaks the
graph inside the activation checkpoint and every MoE layer runs eagerly;
with this PR they match `fullgraph = true` speed, 1.3x to 2.0x faster on
B300.
- The dispatcher passes `int(output_splits.sum())` from CPU splits;
`_mxfp8_all_to_all` gets the same change.
- `fullgraph = true` already compiled these layers because it implicitly
turns on `capture_dynamic_output_shape_ops`.
- The combine reuses the dispatch length, so both all-to-alls share one
symbolic size instead of two.
- At cp 2 each rank recompiles once more, on the `ULYSSES_PARAMS` guard
(one 8.1 s step); #4068 removes it.
| 1 x 8 B300, ep 8, full AC, default compile | seq len per sample | main
(s) | this PR (s) | speedup |
| --- | --- | --- | --- | --- |
| Qwen3-30B-A3B 12 layers, fake data | 16384 | 1.067 | 0.703 | 1.52x |
| mini-glm-moe, fake data | 8192 | 1.066 | 0.542 | 1.97x |
| GLM-4.5-Air 8 layers, real data, cp 1 | 16384, 1-3 docs, median 12.2k
tokens | 1.892 | 1.427 | 1.33x |
| GLM-4.5-Air 8 layers, real data, cp 2 | 16384 (8192 per rank), 1-3
docs, median 12.2k tokens | 2.246 | 1.718 | 1.31x |
| Qwen3-30B-A3B 12 layers, MXFP8 experts and transport | 16384 | 1.093 |
0.716 | 1.53x |
This PR has 0 graph breaks in every arm, against 1 on main, and loss
agrees within same-code repeat noise. Main with `fullgraph = true` runs
the MXFP8 arm in 0.716 s. Baseline
[`fea1267ef`](https://github.com/PrimeIntellect-ai/prime-rl/commit/fea1267ef65e8b53fe7a09a3768d148112fadac6);
harness and full results in [`REPORT.md` at
82984c8a8](https://github.com/PrimeIntellect-ai/prime-rl/blob/82984c8a8d6c8c81939be66eb7f7f1cd01d0f170/benchmarks/scripts/ep-a2a-static-size-b300/REPORT.md),
removed in the last commit.

Qwen3-30B-A3B layer 2 forward, rank 0, on H200 (an earlier version of
this PR with the same fix). Eager elementwise, copy and index kernels
(orange) become a few fused Inductor kernels (green): 16.3 ms to 11.0
ms.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
## Summary
- Bump `deps/verifiers` to verifiers `main` (`4c2738dc6`), which
includes PrimeIntellect-ai/verifiers#2949. Its new agent config fields
reach prime-rl through each source's `env` block:
- `env.agent.scoring.skip_on_truncated`: skip task scoring for a
truncated trace. It keeps no rewards, so its reward is 0.
- `env.agent.scoring.skip_on_timeout`: the same for a trace whose stage
deadline expired before scoring.
- `env.agent.max_turn_tokens`: the framework per-turn limit. It lowers
`sampling.max_tokens` on every request. Like the other `max_*` caps, it
stops the run once a response hits it, with the `max_turn_tokens` stop
condition. This also stops harnesses that continue past a capped turn,
such as RLM.
- Count `max_turn_tokens` as truncation in both copies of
`TRUNCATING_STOPS`, which mirror `Trace.is_truncated`:
`monitors/file/traces/index.py` and the dashboard's `static/app.js`.
- Bump `deps/renderers` to renderers `main`
(PrimeIntellect-ai/renderers#199, 0.1.13.dev16), because verifiers
`main` now requires `renderers>=0.1.13.dev16`
(PrimeIntellect-ai/verifiers#2950).
- The verifiers bump also moves `prime-sandboxes` 0.4.7 → 0.5.0 in
`uv.lock`, because verifiers `main` requires it.
- Mention the flags in the eval skill.
```toml
[[source]]
env.taskset.id = "gsm8k"
env.agent.max_turn_tokens = 4096
env.agent.scoring.skip_on_truncated = true
env.agent.scoring.skip_on_timeout = true
```
## Verification
I ran `uv run eval` on Prime Inference (default model), null harness,
subprocess runtime.
- **Turn cap**, alphabet-sort, `max_turns = 1`, 4 tasks × 2:
- Skip off: the two `max_turns`-stopped traces score `alphabet_sort:
0.5`.
- Skip on: the same traces get `rewards={}` (reward 0) and
`info.scoring_skipped="truncated"`. Traces that end normally still
score.
- **Token cap**, gsm8k, `max_completion_tokens = 24`, 8 tasks × 2:
- Skip off: all 16 traces finish with `length` and score `correct: 0.0`.
- Skip on: all 16 get `rewards={}` and `scoring_skipped="truncated"`.
- **Per-turn limit**, alphabet-sort, skip on:
- `max_turn_tokens = 8`: every request carries `max_tokens=8`, and the
two-turn tasks end after 1 call with `stop=max_turn_tokens`.
- `sampling.max_tokens = 8` instead: the two-turn tasks make 2 capped
calls.
- Every trace is truncated and keeps no rewards.
- Unit tests in `tests/unit/{eval,orchestrator}` and the dashboard and
config tests: 409 pass. One test needs `vllm` and one needs
`prime_kernels`. Neither is installed on macOS.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Low risk: truncation classification parity in monitors/UI, eval docs,
and dependency lock updates; scoring behavior changes come from the
verifiers bump rather than new prime-rl logic in this diff.
>
> **Overview**
> Aligns prime-rl with verifiers’ **per-turn token cap** and **optional
zero-reward scoring** when runs truncate or time out before scoring.
>
> **Truncation handling:** `max_turn_tokens` is added to
`TRUNCATING_STOPS` in the dashboard (`app.js`) and file trace monitor
(`traces/index.py`) so traces stopped by the per-turn limit are treated
like other framework caps when mirroring `Trace.is_truncated` (e.g. for
`is_truncated/mean` and UI).
>
> **Docs:** The eval skill now explains `env.agent.max_turn_tokens` and
`env.agent.scoring.skip_on_truncated` / `skip_on_timeout` as
alternatives to raising `sampling.max_completion_tokens` when truncation
metrics are high.
>
> **Dependencies:** `uv.lock` bumps `prime-sandboxes` to 0.5.0 and
`renderers` to `>=0.1.13.dev16` (with verifiers), plus lock revision.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d06f4439bace64af6e158571956d55f1cd7e21ea. 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>
Retried provider failures with no response node currently appear as
empty green “MODEL CALL” cards in the transcript. Opening a card reveals
no details, so rate limits and other failed attempts are
indistinguishable from successful calls.
Label recorded failures as “FAILED MODEL CALL” in red, show the HTTP
status and error preview, and make the full error, traceback, and call
metadata expandable. Also mark failed calls attached to a message. Calls
without an error retain their normal appearance. Reuse the existing
error renderer and escape provider text.
Validation:
- Full Chromium dashboard smoke test against an isolated local copy of a
recorded evaluation trace, including its 22 recovered HTTP 429 attempts.
- Browser regression coverage for unlinked 429 errors, linked 503
errors, successful unlinked calls, string errors, traceback expansion,
and HTML escaping.
- 12 dashboard timeline/artifact unit tests passed (`pytest
--confcutdir=tests/unit tests/unit/test_dashboard_timeline.py
tests/unit/test_dashboard_artifacts.py -q`).
- Configured pre-commit hooks, JavaScript syntax check, and `git diff
--check` passed.
No evaluation artifacts or private trace data are included.
Before:
<img width="1116" height="720" alt="image"
src="https://github.com/user-attachments/assets/11857bc3-b791-4514-9de8-b09f7a946e42"
/>
After:
<img width="1116" height="720" alt="image"
src="https://github.com/user-attachments/assets/fa765af8-ef5d-45fb-ab9c-d4566cfeb6c3"
/>
Compiled Qwen 3.8 training fails on a single packed sequence with
`ConstraintViolationError`: the ngram/position-learning path specializes
`cu_seqlens` to length 2, but `mark_dynamic` forbids that
specialization.
Use `maybe_mark_dynamic` for this dimension so Dynamo can specialize the
single-sequence case while attempting dynamic shapes for other
packed-sequence counts. Shape guards remain active. This changes only
Qwen 3.8; it does not change embedding sharding, model math, or other
architectures.
Targets `main`, which already contains the affected text-model path.
Multimodal support in #3916 is independent of this fix.
Validation on an H200 compute allocation with PyTorch `2.13.0+cu130`:
- The unmodified strict annotation reproduces the same
`ConstraintViolationError` in the real ngram module.
- The optional annotation passes 10 compiled/eager PLE comparisons: one,
two, four, one and three packed sequences, both with and without
non-reentrant activation checkpointing. Outputs, input/parameter
gradients and AdamW parameter updates match within `rtol=2e-4,
atol=2e-5`.
- Ruff check, formatting check and `git diff --check` pass.
The isolated probe uses small real PLE/ngram modules, not the full
distributed model. These checks do not establish a successful full-model
distributed compiled update.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Single-line Dynamo annotation change in one model; validated for
numerical parity across packed-sequence shapes without altering training
math.
>
> **Overview**
> **Fixes compiled Qwen 3.8 training** when a batch is a single packed
sequence: Torch Dynamo was hitting `ConstraintViolationError` because
the PLE/ngram path specializes `cu_seqlens` length (e.g. to 2) while
`mark_dynamic` blocked that specialization.
>
> In `Qwen3_8FlashNextTextModel.forward`, **`cu_seqlens` dim 0** is
annotated with `torch._dynamo.maybe_mark_dynamic` instead of
`mark_dynamic`, so Dynamo can specialize the one-sequence case while
still treating other packed-sequence counts as dynamic. Scope is **Qwen
3.8 Flash Next only**; model math, sharding, and other architectures are
unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
afcb32da4012c60c917e721bfa8e67797dbc508c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
With `enable_return_routed_experts` (router replay), vLLM materializes
the routing rows of every request's prompt and ships them to the API
server each turn, unless the request sets `routed_experts_prompt_start`.
Chat responses drop `routed_experts`
(`monkey_patch_strip_routed_experts_from_chat`), so for chat requests
those rows are thrown away. In an RL run, chat requests are the online
evals. The rows are 258 B per token for DeepSeek-V4 (43 layers × 6
experts), so tens of MB for a long eval prompt.
`monkey_patch_skip_prompt_routing_for_chat` sets
`routed_experts_prompt_start` to the prompt length on chat requests that
don't set one, so the engine keeps only the completion's rows. A chat
request that sets its own start keeps it. `/inference/v1/generate` and
completions are unchanged.
## Measurements
**Setup:** DeepSeek-V4-Flash, one B300 node, DEP8, vLLM 0.32. RL
inference settings: routed-expert capture on, MXFP8,
`processed_logprobs`, 0.75 memory. FlashInfer autotune was off. Load is
TB2-shaped multi-turn agents, 1 logprob per token. Values are gen tok/s
per GPU and ms per token.
| eval-like requests | 512 per node | 1,024 per node |
|---|---:|---:|
| prompt rows returned (current chat behaviour) | 1,463 · 42.9 | 1,876 ·
66.9 |
| completion rows only (this patch's start) | 1,648 · 38.4 (+13%) |
2,185 · 57.9 (+16%) |
| routed-expert capture off, for reference | 1,812 · 35.0 | 2,682 · 47.1
|
The remaining gap to capture-off is vLLM's per-step routing bookkeeping.
It applies to every request, and this patch doesn't change it.
## Validation
- **Throughput:** measured with the client sending
`routed_experts_prompt_start` = prompt length, the value this patch
sets. No load run went through the patched chat route.
- **Unit check:** on the patched `_log_inputs`, a chat request without a
start gets the prompt length (1,234 of 1,234 tokens), an explicit start
is kept, and completions' `_log_inputs` is untouched. The patch is
idempotent.
- **Loading:** prime-rl's patches load under `vllm serve` on every rank,
and chat responses still return no `routed_experts`.
- **Lint:** ruff check and format pass.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Router replay (`enable_return_routed_experts`) costs a lot of generation
throughput on vLLM 0.32. vLLM's AuxOutput store and worker code are
unchanged since 0.31, where the numbers below were measured. In the v031
defaults experiment (GLM-4.5-Air TP8, about 400 running requests), arm C
vs arm B was −25% generation. Most of the cost is CPU work in vLLM's
AuxOutput path on the output worker (TP0) and in EngineCore, not GPU
work. This PR adds three vLLM patches in `patches.py`. Routing rows are
unchanged.
## Where the time goes
GLM-4.5-Air TP8 on H200, one node, `/inference/v1/generate`, closed loop
with 400 concurrent requests, max 16k tokens, sampling masks on.
Diagnostics: per-function timers, per-thread CPU, GC callbacks, and
stack samples in worker TP0 and EngineCore.
1. **Store eviction on the output worker** (largest cost). vLLM sizes
`BlockObjectStore` to the KV cache, so under load it is full and every
`put` evicts. `_evict_to_fit` scans the LRU from the front and skips
keys referenced by running requests. Those keys pile up at the front, so
each `put` rescans ~300k keys: 9 ms per `put`, 46 puts/s, on the writer
thread. It holds the GIL against the thread that launches the next step,
and `execute_model` goes from 2.7 to 13.8 ms per call.
2. **One array per request per step.** The output worker returns
`dict[request_id, AuxRequestOutput]`. Each step pickles one small array
per running request to EngineCore, each as its own out-of-band buffer.
EngineCore rebuilds them one object at a time. The cost grows with
requests per step, and the churn drives GC.
3. **Engine GC.** vLLM freezes the startup heap of EngineCore and of the
workers but keeps the default thresholds.
## Fix
- `monkey_patch_aux_output_store`
- Before upstream `_evict_to_fit` runs on a full store, it moves the
referenced keys at the front of the LRU to the end. A referenced key
cannot be evicted, and release moves it to the end anyway, so the
victims are identical to upstream.
- The output worker builds the store at 2× vLLM's size. At 100% KV the
referenced rows alone can exceed a store of exactly KV size. `put` then
raises `BlockObjectStoreError` in the writer thread and the engine dies.
The condition does not depend on LRU order, so upstream raises on the
same sequence. Before this PR the engine was too slow to fill the KV
cache in this harness. With only the eviction fix, it reached 100% KV
and died.
- `monkey_patch_packed_aux_outputs` + `PackedAuxOutputs`: the worker
sends one object per step (id→index dict, token starts, offsets, one
rows array). It pickles as three byte strings and answers the
scheduler's `in` / `[]` lookups.
- `monkey_patch_engine_gc`: EngineCore keeps vLLM's freeze and gets
`set_threshold(50_000, 20, 100)`. The workers get `gc.collect()` +
`gc.freeze()` + the same thresholds after `compile_or_warm_up_model`.
## Results (gen tok/s, steady window 240–900 s)
Earlier runs (node A, 400 concurrent, 16k):
| arm | gen tok/s | tok/s per request | KV usage |
|---|---|---|---|
| router replay off, main | 9,356 | 23.5 | 0.72 |
| router replay on, main | 5,724 (−39%) | 14.4 | 0.85 |
| on, GC + packing (no store fix) | 8,250 | 20.9 | 0.76 |
| on, store eviction only (1× size) | crashed at 100% KV | | |
| on, all three (1× size) | 9,412 | 23.8 | 0.72 |
| off, all three | 9,596 | 24.1 | 0.72 |
Ablation of the branch as pushed (node B, same node for every row):
| arm | load | gen tok/s | tok/s per request | running | KV mean / peak
|
|---|---|---|---|---|---|
| all three | 400 conc, 16k | **9,679** | 24.6 | 393 | 0.71 / 0.98 |
| store + GC (no packing) | 400 conc, 16k | 9,493 (−1.9%) | 24.3 | 390 |
0.72 |
| store only | 400 conc, 16k | 8,309 (−14%) | 21.2 | 392 | 0.73 / 1.00,
no error |
| all three | 1000 conc, 2k, `max_num_seqs=1024` | **9,328** | 9.6 | 970
| 0.25 |
| store + GC (no packing) | 1000 conc, 2k, `max_num_seqs=1024` | 9,078
(−2.7%) | 9.4 | 971 | 0.25 |
- **Store only**: EngineCore gen-2 GC takes 10.7% of wall time. With GC
tuning, EngineCore and the workers run 0 collections in the window.
- **Packing**: worker TP0 `MessageQueue.enqueue` takes 0.32 vs 0.94 ms
per call at 400 running, and 0.46 vs 2.85 ms at 970 running (2 calls per
step). EngineCore's unpickle is hidden inside `dequeue`, so the bench
below gives its size.
- **Scaling of packing** (CPU bench of the per-step path; pickle +
unpickle per step, ms):
| requests per step | 400 | 1000 | 2000 |
|---|---|---|---|
| per-request dict | 6.1 | 18.7 | 31.7 |
| packed | 0.13 | 0.37 | 0.8 |
The cost is the same for 46 or 78 MoE layers × top-8: it is per request,
not per byte. Both halves sit on the step's critical path: the worker
main thread, then the EngineCore loop. So packing matters more as
engines run more requests per step, which large sparse MoE engines with
DP/EP do. At 1000 requests it is already ~2.7% end to end on this model.
- Store headroom cost: host RAM per engine ≤ 2 × KV tokens × MoE layers
× top-k × itemsize, on the output worker only. The arena is an anonymous
mmap, so only used slots cost RSS.
- Here: 4.37M tokens × 46 × 8 × 1 B = 1.6 GB, so up to 3.2 GB.
- DeepSeek-V3-class model (58 × 8, uint8), 4M KV tokens per engine: 1.9
GB → 3.7 GB.
- 78 × 8 at 8M tokens: 5 GB → 10 GB per engine.
- With more than 256 experts the rows are uint16, which doubles these
numbers.
## Checks
- **Routing rows.** 24 sequential `top_k=1` requests (12 prompts ×
300/1000 tokens) on node B: token ids and `routed_experts` bytes are
bitwise identical between main and this branch (24/24). Earlier, router
replay off gave identical tokens (24/24).
- **Store eviction.** Compared with upstream on random op sequences (300
seeds × 300 puts): same stored keys, same order of unreferenced keys
(the only order that affects eviction), same errors. Bench with 450k
slots and 320k live keys: 27.7 → 0.40 ms per step.
- **Unit tests.** `tests/unit/orchestrator`,
`tests/unit/test_configs.py`, `tests/unit/inference` with `-m "not
gpu"`: 381 passed (vLLM 0.32 venv). `ruff check` and `ruff format
--check` are clean.
## Notes
- Upstream-worthy: the eviction scan, store capacity at full KV, and
packed per-step aux outputs.
- Upstream: vllm-project/vllm#62044 (store fix; closed without merge, so
the store patch stays), #58328 (open; the store grows past 2x KV instead
of raising), #61086 (open; per-step R3 packing), #62086 (open draft; GC
thresholds).
- **Open question (API server, not this PR).** When ~100 length-capped
16k requests finish together, the API server loop stalls for ~25 s and
clients see `ReadError`s (~110 per 400-concurrent arm). Each response
carries about 8 MB of routed-experts JSON. By-handle payloads (#3902)
avoid this path.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Monkey-patches vLLM engine, worker, and API-server internals and
changes generate response shapes for logprobs and sampling masks;
mitigated by unit tests and documented parity checks for routing rows
and eviction.
>
> **Overview**
> Cuts CPU/GC cost on the **router-replay** path and on
**`/inference/v1/generate`** under heavy RL concurrency by avoiding
per-token Python objects and tuning garbage collection.
>
> **Engine / aux-output path:** Registers four vLLM monkey patches in
`patches.py`. Routed experts per scheduler step are sent as a single
**`PackedAuxOutputs`** blob (replacing per-request dict pickling). The
aux-output **`BlockObjectStore`** gets a 2× capacity headroom and an
eviction tweak so referenced LRU keys are moved to the end before
upstream eviction (avoids multi-ms rescans at full KV). **EngineCore**
and GPU workers **freeze** the post-warmup heap and use higher **`gc`
thresholds**; the API server does the same after startup.
>
> **Generate handler:** **`PrimeRlServingTokens`** strips heavy fields
early via **`_PackedOutputs`**, then returns **base64-packed numpy** for
`routed_experts`, **`completion_logprobs`**, and CSR **`sampling_mask`**
(`{ids, counts}`). Non-streaming requests use **flat logprobs**, and
**detokenize** is disabled when there are no stop strings. A separate
patch keeps **FINAL_ONLY** sampling masks as **`PackedSamplingMask`** in
the output processor.
>
> **Tests / deps:** Adds **`PackedAuxOutputs`** pickle and
store-eviction parity tests; updates serving-token unit tests. Bumps
**`renderers`** and drops **`pytest-cov`** from the lockfile.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e1afb9cf4e6f76d28773ed4d6c46e10330b5bd85. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
`utils/pathing.py` gets `prepare_run(config, ckpt_output_dir=None)`. It:
- sets the run identity (`$PRL_RUN_ID` / `$PRL_RUN_NAME`)
- validates the run directory (deleting it first with `clean`, unless
`$NEVER_CLEAN` is set)
- creates the run directory and the checkpoint output directory
The RL, SFT and eval launchers each had a copy of this block; they now
call `prepare_run`. No behavior change.
The pretrain launcher (#4062) will use the same function.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Mechanical deduplication of existing launcher startup paths; run
identity and directory validation behavior are unchanged.
>
> **Overview**
> Introduces shared **`prepare_run`** in `pathing.py` so eval, RL, and
SFT launchers no longer duplicate startup logic.
>
> Each launcher now calls **`prepare_run(config)`** (or passes an
optional checkpoint output dir for RL/SFT) instead of inline steps for
**`$PRL_RUN_ID` / `$PRL_RUN_NAME`**, **`validate_run_dir`** (including
clean vs **`$NEVER_CLEAN`**), and creating the run and checkpoint
directories. **`uuid`** handling moves into pathing with the helper;
entrypoints drop their local **`validate_run_dir`** imports. Intended as
a no-op behavior change, with pretrain expected to adopt the same helper
later.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
eebb9788610fdcb2666cf2cb1a03ad5d8306221d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
This PR keeps DeepSeek-V4's mHC write-back gates (`comb` and `post`) in
fp32 instead of rounding them to bf16 before the fused kernel, which
matches how vLLM computes the same step at inference.
- vLLM 0.32's
[`mhc_post_torch`](https://github.com/vllm-project/vllm/blob/5df63a7203cdb9328d824a27b682e77c7b9928be/vllm/model_executor/kernels/mhc/torch.py#L135-L147)
takes `comb` and `post` as fp32 and accumulates in fp32. It rounds once,
when it writes the bf16 result.
- The Triton kernel already computed in fp32, so the early bf16 cast of
the two gates was the only extra rounding.
- `update_states` now casts the gates with `.float()`, and the kernel
output and its fake follow the residual's dtype.
- One gap remains: vLLM keeps the mHC `fn`, `base` and `scale` weights
in fp32, but `fully_shard` gathers them in bf16 here.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Adds `eps` (default `1e-8`) to `AdamWConfig` and `MuonConfig`. It is
passed to torch `AdamW` (`eps`) and to dion `Muon` (`epsilon`, used by
its AdamW groups). Both defaults are already `1e-8`, so runs are
unchanged unless `eps` is set.
Smoke test: SFT on `samsja/mini-glm-moe` with fake data, 1 H200, 10
steps, this branch vs main `584a1169a`. Main is not bitwise reproducible
run to run here, so the comparison is against a repeat of main:
| optimizer | max relative loss difference, main vs main | main vs this
branch |
|---|---|---|
| AdamW | 0.25% | 0.19% |
| Muon | 0.09% | 0.08% |
Step-1 loss is identical in all runs (12.3087). Step-1 grad norms, taken
before any optimizer step, vary between runs (88.138–88.144).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Default epsilon is unchanged; only explicit config overrides affect
optimizer numerics.
>
> **Overview**
> Adds a configurable **`eps`** hyperparameter (default **`1e-8`**) on
**`AdamWConfig`** and **`MuonConfig`**, so trainer YAML/JSON can tune
Adam’s denominator stabilization without code changes.
>
> **AdamW** now passes **`config.eps`** into **`torch.optim.AdamW`**.
**Muon** passes the same value as **`epsilon`** on Dion’s **`Muon`**
(for its AdamW parameter groups). Defaults match the previous hard-coded
library defaults, so existing configs should behave the same unless
**`optim.eps`** is set explicitly.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e37202bc3e550a821e277d15d7c33e009aea5d18. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Follows DeepSeek-V4's CP design: each CP rank holds a contiguous run of
queries, while the token KV stream, the compressed entries (and so the
index keys) and the engram hash's token ids are all-gathered, keeping every
key, entry and index value global.
- PackedContext.build takes cp_rank/cp_world_size; per-query fields
(positions, document starts, window, cuDNN indexer segments) cover this
rank's shard, compression layouts the whole row.
- Attention all-gathers the rotated KV on NCCL's stream, overlapped with the
query/compressor/indexer work; the KV-source compressor gathers its
projections (ratio 2) or normalized latents (ratio 1). Picks and candidate
blocks are per query, so the shared state needs no extra communication.
- EngramHasher gathers the row's token ids so the n-gram look-back crosses
shard boundaries, still clipped at document starts.
- cp_blocker returns None; docs and the V4.1 example README updated.
- GPU test (torchrun, cp=2/4): packed multi-document row with documents
crossing the shard cuts and engram on matches the unsharded logits, loss
and gradients.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
post and comb enter the stream write-back in fp32 instead of being rounded to bf16 first
(fused_post_bda now returns the streams' dtype and accumulates fp32 gates unrounded), and
the collapsed streams stay fp32 into the next RMSNorm, so collapse and norm round to bf16
once, as vLLM's fused collapse-norm kernel does. The mHC weights stay bf16 under FSDP.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds a second MFU metric, `perf/mfu_6dn`, next to `perf/mfu` in the RL
and SFT trainers.
`perf/mfu_6dn` uses the plain `6 * N_active * D` estimate:
- `N_active` = `model.num_active_params()` (active experts only for MoE)
- `D` = tokens processed in the step
- no attention / sequence-mixing FLOPs
- no LoRA discount
This makes the number comparable with the common 6ND convention used in
other reports. `perf/mfu` is unchanged.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Observability-only: new metric and log fields; existing MFU
calculation and training logic are untouched.
>
> **Overview**
> Adds **`perf/mfu_6dn`**, a second MFU line that uses the standard **6
× active params × tokens** FLOP estimate (no attention FLOPs, no LoRA
matmul discount), so runs can be compared to external 6ND reports.
**`perf/mfu`** is unchanged and still uses the fuller training FLOP
model (matmul + attention).
>
> `FlopCounter` now exposes `flops_per_token_6dn`; RL and SFT trainers
compute `mfu_6dn` each step, emit it in step logs (**MFU 6DN**), and log
**`perf/mfu_6dn`** to monitors. Training docs clarify that
**`perf/mfu`** includes attention FLOPs and document the new metric.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1b471a81f192ce0ff6bd3f34cea9f3bf88974ee6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Installs FlashInfer's precompiled kernels (`flashinfer-cubin` and
`flashinfer-jit-cache`, matching vLLM's `flashinfer-python` 0.7.0.post1
pin), so inference nodes no longer download cubins and JIT-build
FlashInfer modules on every startup.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Packaging-only change to the gpu extra and lockfile; no runtime code
paths change, though it adds third-party wheel indexes and larger
install artifacts.
>
> **Overview**
> Adds **precompiled FlashInfer** packages (`flashinfer-cubin` and
`flashinfer-jit-cache` at **0.7.0.post1**, aligned with vLLM’s
`flashinfer-python` pin) to the Linux **`gpu`** extra so installs ship
cubins and JIT cache wheels instead of fetching cubins and compiling
FlashInfer on each node at startup.
>
> **uv** wiring includes explicit **FlashInfer indexes**
(`flashinfer.ai/whl` and `/cu130`) with `exclude-newer` disabled, source
overrides for cubin (index) and per-arch **jit-cache** wheels (x86_64 vs
aarch64, with extra sm110a/sm121a deps on aarch64), plus an updated
**`uv.lock`** for the new transitive `flashinfer-jit-cache-sm*`
packages.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
822214d64065ef59fdb6758f7c0b829ca985c88f. 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>
This PR deletes the DeepSeek V4 eager reference and every test that
compares against it, plus a few src fields and checks that only the
reference or old bugs needed. The model has passed e2e tests and trained
successfully, so the dense pure-torch reference has become about 1,600
lines of test code to maintain.
- No test now checks the sparse-attention kernel's output against an
independent implementation. The kept tests compare packed vs unpacked,
compiled vs eager, and a fully masked query, and also check index
invariants and vLLM parity.
- The hash-routing and whole-model backward tests now run the fused
sparse-attention kernel, so they now require an SM90 or SM100 GPU.
- `DeepseekV4Model.forward` no longer validates `position_ids` against
`seq_lens`. Every position comes from `seq_lens`, and #3466 fixed the
1-based fallback that check guarded against.
## Verification
- `test_deepseek_v4.py` and `test_deepseek_v4_kernels.py` on an H200: 44
passed, 0 skipped, `cudnn_flashmla` included.
- E2E SFT with `deepseek-ai/DeepSeek-V4-Flash-0731` truncated to 4
layers (`model.debug.num_layers = 4`, three hash-routed and one
learned-router layer) on one 8xH200 node, ep 8, Reverse-Text-SFT at
seq_len 2048: 20 steps completed, loss 17.7 to 2.5, finite grad norm and
max violation throughout
([W&B](https://forge.coreweave.com/wandb/primeintellect/deepseek-v4-flash/runs/i7shgqml)).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
V4.1 attention reports attention_flops (window plus at most index_topk compressed
entries, and the indexer's scoring on its source layers); the generic active-parameter
walk already skips the engram tables and the routed experts a token does not visit,
so the config's active_mm_params is removed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Round keys and values as vLLM's V4.1 fp8_ds_mla cache stores them (model.dsv4_kv_precision).
- Run sparse attention on the shared V4 cudnn_flashmla backend, which compiles the cuDNN backward
once, and skip FlashMLA's topk_length on SM90 (rejected by the pinned wheel).
- Use prime-kernels' Hopper indexer top-k, mHC projection, sparse attention backward and fused
MoE experts (moe.compute.backend = "prime_kernels") when installed, and cuDNN's fused indexer
on Blackwell.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The per-layer routes were a strided view, so whether reshapes inside the MoE block copied or
viewed depended on the layout, which differed between the forward and the activation-checkpoint
recompute; without compile, the recompute then failed ("aten.view.default invocation index ...
not found in storage"). Every other MoE model already makes the slice contiguous.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- NCCL weight broadcast: send row-sharded tables (the engram tables) in fp8 + ue8m0 row
chunks relayed through the master, instead of gathering ~197 GB per table; the vLLM
worker writes the chunks straight into the engine's (host) table storage.
- Copy received tensors out of multi-tensor buckets so the layerwise reload does not pin
every bucket of a layer (under EP, other ranks' experts included).
- vLLM patches: stream V4.1 weight updates to the language model instead of sorting the
whole update in the VL wrapper, and load V4.1 attention sinks through weight_loader.
- Example RL config (1 inference + 7 trainer nodes) and README section.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The trainer no longer dequantizes the published fp8 / fp4 weights. It
expects PrimeIntellect/DeepSeek-V4.1-Flash-bf16, where only the engram
tables stay fp8 (vLLM serves them only in fp8), dequantizes those on load
and rejects any other quantized weight.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INTELLECT-3-SFT (the example's data) keeps the reasoning inline as <think>...</think> in the
assistant content, which the renderer emitted after an empty think block
(<think></think><think>...). Move it into reasoning_content first. With that, the renderer
matches the checkpoint's reference encoder (encoding.py, thinking mode, effort high) token
for token on 256 math-10k chats.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
- tools/convert_deepseek_v41_to_prime.py streams the published fp8 / fp4 checkpoint into a
bf16 PrimeRL-format checkpoint, one layer per output file and the engram tables in row
chunks, across one worker per GPU; the output also carries the tokenizer the engram hash
is built from.
- examples/advanced/deepseek-v4.1-flash: a V4.1 chat renderer (V4's with the System token
and numeric reasoning effort), EP 8 + FSDP SFT configs with fake- and real-data overlays,
and a README.
- docs: V4.1 in the supported-models table.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
- AllToAllEmbeddingParallel: row-shards an nn.Embedding as a Shard(0) DTensor over a 1-D
mesh and serves lookups with all-to-alls (deduplicated ids to their owners, rows back;
backward retraces the route). setup_fsdp applies it to V4.1's two ~98B-parameter engram
tables over the FSDP mesh and keeps them out of FSDP via ignored_params; dp_replicate > 1
is rejected.
- model.freeze_engram_tables freezes the tables (stored in bf16, the lookup dtype); their
projections and gates still train. V4.1's indexers are frozen like V4's.
- Activation checkpointing must-saves dsv41_index_topk and selectively saves
dsv41_sparse_attn.
- MFU: a config exposing active_mm_params() (V4.1 does) counts its own active matmul
parameters instead of the generic formula.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Adds the deepseek_v41 / deepseek_v41_text model on top of the V4 building blocks (MoE,
rotary, grouped output projection, compression layout, mHC and RoPE kernels):
- Shared long-range attention: only the KV source layers compress (ratio 1 or 2) and only
the index source layers run a Lightning Indexer; later layers reuse their entries and
picks, carried down the stack as explicit tensors. Indexers after the candidate source
score only inside its top entry blocks (two-level selection, dsv41_index_topk on main's
fp8 scoring kernel).
- Delayed mHC gates: each sublayer's pre gate collapses the streams for the next one, and
the last FFN's gate gives the final hidden state (no hc_head).
- Engram: hashed n-gram lookups (bit-identical to DeepSeek's reference hash) gated into the
residual streams, with the q * k gate weight in fp32 as in the reference. The tables are
plain nn.Embeddings; the trainer shards them in a later commit.
- Sparse attention on FlashMLA forward + cuDNN backward on Hopper, TileLang elsewhere.
- Published <-> PrimeRL names, dropping the vision tower, aligner, DSpark head and the
gate's vision bias; fp8 / fp4 dequantization reuses V4's.
Context parallelism is not supported (cp_support declares no style), nor pipeline
parallelism.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
load_dcp_from_hf returned right after to_empty when model.debug.random_init was set, so
debug runs trained on whatever memory the allocator handed back (often all zeros, which
leaves the loss flat). Draw every parameter shard instead: matrices from N(0, 0.02), norm
weights and scales one, everything else zero, each shard seeded from its parameter name
and mesh coordinate.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The file monitor's live traces (`traces/live/<trace_id>.jsonl`) drop
routed experts and sampling masks from each node, but they still write
`top_logprobs`. When top-k logprob capture is on (e.g. for score
centering), that field holds top-k entries per sampled token, so it
dominates the size of every delta. Each in-flight episode's live file
then grows with turns × tokens × top-k, which adds up to a lot of disk
and write load at high concurrency.
Finished records already drop the field. verifiers' `EXCLUDE_FIELDS`
(`verifiers/v1/trace.py`) names the node fields kept on the wire but
excluded from disk: `routed_experts`, `sampling_mask` and
`top_logprobs`. `Trace.to_record` uses it. This PR makes
`FileMonitor.log_live` filter nodes with that same set, so live files
and finished records agree and can't drift. Training is unaffected: the
fields still travel on the wire to the orchestrator.
Nothing reads `top_logprobs` from live files: the dashboard and the
live-trace reader use messages, token ids, masks and scalar logprobs.
## Test plan
- `tests/unit/test_dashboard_timeline.py` and
`tests/unit/test_dashboard_artifacts.py` pass.
- `ruff check` and `ruff format --check` are clean.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Narrows what is written to live trace files only; training wire format
and readers that do not use excluded fields are unchanged.
>
> **Overview**
> Live trace JSONL deltas now strip **all** trainer-only node fields
defined in verifiers' `EXCLUDE_FIELDS`, not just `routed_experts` and
`sampling_mask`. The important new exclusion is **`top_logprobs`**,
which can balloon live files when top-k logprob capture is enabled.
>
> `FileMonitor.log_live` uses a shared `LIVE_NODE_EXCLUDE` frozenset so
live writes stay aligned with `Episode.to_record` / finished traces.
Wire payloads to the orchestrator are unchanged; only what gets
persisted under `traces/live/` is slimmer.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9c0cdd1c2979459f5b54c3f4a342cc2cc141e066. 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>
This PR gives RL the same `pad_to_seq_len` flag that SFT supports
(#4160). The flag pads every packed row to `seq_len`, so torch.compile
and DeepGEMM stop recompiling on new lengths. Full-length padding makes
an existing MoE problem worse (identical pad tokens all route to the
same experts), so this PR also changes RL and SFT to pad with the row's
own tokens instead of a constant id.
- RL used to pad with token 1, and router replay padded with zero bytes,
which sent every pad slot to expert 0. This PR pads text rows with their
own tokens and replay with their real routes.
- Multimodal rows keep a constant pad id, because a repeated image
placeholder would have no image feature to receive.
- This PR supersedes #3932 / #4149 (SFT pad content, credit Mika).
Please keep the `Co-authored-by: Mika Senghaas` trailer when squashing.
Related: #3350.
We ran FP8 e2e checks on one H200 node per run, each with an empty
DeepGEMM cache (harness in a31524ed6):
| Run | Dynamo recompiles per rank, total (after step 1) | DeepGEMM
compiles, total (after step 1) |
| --- | --- | --- |
| SFT GLM-4.5-Air 4L `--data.pad-to-seq-len` | 1 (0) | 22 (0) |
| SFT GLM-4.5-Air 4L | 3 (0) | 34 (7) |
| RL Qwen3-30B-A3B + replay `--orchestrator.pad-to-seq-len` | 0 (0) | 17
(0) |
| RL Qwen3-30B-A3B + replay | 1 (0) | 54 (28) |
The flag only makes the row length static: the number of micro batches
per step, `max_seqlen`, and multimodal shapes still vary. The throughput
and MFU metrics count padding, so they are not comparable with and
without the flag.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Mika Senghaas <mika@primeintellect.ai>
Remove all `fused_lm_head_token_chunk_size = 1024` overrides from
configs and examples so they use the default (8192).
Files:
- configs/advanced/minimax-m2.5/swe.toml
- configs/advanced/nemotron-3-super/swe.toml
- examples/advanced/glm-4.5-air/{search,swe-budget,terminal}.toml
- examples/advanced/glm-5.3/swe.toml
- examples/advanced/intellect-3.1/rl.toml
Note: larger chunk means higher peak LM head memory on these large
long-context configs.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Training memory behavior changes on large long-context configs; higher
LM-head chunk size can increase peak GPU usage and trigger OOMs where
1024 was load-bearing.
>
> **Overview**
> Removes **`fused_lm_head_token_chunk_size = 1024`** from seven
advanced training TOMLs (MiniMax M2.5, Nemotron-3-Super, GLM-4.5-Air
search/swe-budget/terminal, GLM-5.3 SWE, Intellect-3.1) so
**`[trainer.model]`** picks up the framework default (**8192** instead
of 1024).
>
> No other trainer, orchestrator, or deployment settings change—only
dropping this LM-head chunk override. On these **131k** long-context MoE
runs, larger chunks can raise **peak LM-head activation memory** during
training; anyone who relied on 1024 for tight GPU headroom may need to
watch OOMs or re-tune memory knobs.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
981bb601a77e2f30c72071764b0fbf0f334bb448. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Everything needed for MXFP8 RL on the prime-rl side, in six parts:
1. **vLLM: keep the online-MXFP8 MoE kernel across weight reloads**
(previously #4109). Without it mismatch KL is ~0.04.
2. **Trainer: pad samples to a multiple of 32 tokens** when the trainer
uses MXFP8, or its backward crashes.
3. **DeepSeek-V4-Flash: quantize the trainer like vLLM**, so mismatch KL
stays flat (~0.002) instead of growing. Measured on math RL; the SWE
config (6) uses the same setup.
4. **Bump prime-kernels to `v0.1.0-3101960`**, which ships the
`mxfp8_moe` kernel (prime-kernels #16). `moe.compute.type = "mxfp8"`
loads it, and the previous wheel did not include it, so that path failed
with `unknown kernel 'mxfp8_moe'`.
5. **`extra_ignore_patterns`** for FP8/MXFP8 quantization, appended to
the default `ignore_patterns` (lm_head, router, gates, ...). Setting
`ignore_patterns` replaces the defaults, so recipes had to repeat them;
the DeepSeek-V4 SWE config only lists `o_a_proj`, `compressor\.` and
`indexer\.`.
6. **Experiment SWE config** (B300):
`configs/advanced/deepseek-v4-flash/swe_mxfp8.toml`, as used for the
DeepSeek-V4 MXFP8 SWE run.
### 1. Online-MXFP8 MoE reload fix
**Problem.**
With online MXFP8 MoE inference (`quantization = "mxfp8"`), RL mismatch
KL is ~10x higher than expected. On DeepSeek-V4-Flash it was ~0.04 vs
~0.003 for MXFP8 itself.
`Mxfp8OnlineMoEMethod._setup_kernel` rebuilds `moe_quant_config` and
`moe_kernel` on every weight reload. Decode replays CUDA graphs captured
against the boot-time kernel, so after the first update those graphs
read freed memory. Decode then samples sporadic garbage tokens that
eager prefill and the trainer score at -10 to -30, and those tokens
dominate the KL. NCCL broadcast makes it worse because it churns more
GPU memory.
**Fix.**
`monkey_patch_online_mxfp8_moe_keep_kernel_on_reload`: on reload,
convert and install the new weights but keep the boot-time kernel.
Layerwise reload already copies new values into the original parameter
storage, which the boot-time kernel references. Upstream fix:
vllm-project/vllm#62406; the patch goes away once our minimum vLLM
includes it.
**Results** (DeepSeek-V4-Flash, TP8/EP, FLASHINFER_TRTLLM MoE).
vLLM self-check: generate, then re-score the same tokens with
`prompt_logprobs` (decode-vs-prefill KL):
| | fresh | after reload |
|---|---|---|
| CUDA graphs, unpatched | 0.0027 | 0.0065 (glitch tokens) |
| enforce_eager, unpatched | 0.0026 | 0.0027 |
| CUDA graphs, patched | 0.0026 | 0.0028 (0.0025 after 10 reloads) |
60-step RL (lr 1e-6, router replay, NCCL broadcast): mismatch KL mean
0.0437 → 0.0038, steps 1-20 0.0613 → 0.0014.
The reload serves the new weights, not stale boot-time tensors. In this
test, layer 2's routed-expert `w2` is zeroed and loaded by reload into a
server booted on base weights, then compared against a server booted
directly on the zeroed checkpoint:
| | KL |
|---|---|
| base-model tokens: reloaded server vs base logprobs | 0.0065 |
| base-model tokens: fresh-zeroed server vs base logprobs | 0.0066 |
| reloaded server's tokens: fresh-zeroed server vs reloaded server |
0.0026 (two servers on identical weights: ~0.0027) |
No |r|>5 tokens in any test.
vLLM 0.32 still rebuilds the online-MXFP8 MoE kernel on reload, so the
patch is still needed and applies unchanged.
### 2. Pad samples to 32 tokens for the MXFP8 trainer
MXFP8 linears (`[trainer.model.quantization] type = "mxfp8"`) quantize
`grad_output` in 32-token blocks, so the dense backward fails with `rows
must be a multiple of 32` unless each CP rank's token count is divisible
by 32. RL only padded samples to a multiple of `cp`.
`RLConfig.auto_setup_deployment` now sets
`orchestrator.pad_to_multiple_of = lcm(pad_to_multiple_of, cp * 32)`
when the trainer uses MXFP8 quantization, so a larger existing padding
is kept rather than multiplied by 32.
Verified in 60-step RL runs of Qwen3-30B-A3B and GLM-4.5-Air with the
MXFP8 trainer (dense + MoE): no crash, and mismatch KL stays flat.
The SFT packer still pads only to `cp`, so MXFP8 SFT likely hits the
same assert; that path is not changed here.
### 3. DeepSeek-V4-Flash: trainer quantized like vLLM
Measured with math RL (online MXFP8 vLLM inference, 3 trainer nodes + 1
inference node, B300, sequences up to 4k). That math config is not part
of this PR; the SWE config in section 6 uses the same alignment.
**Why the trainer is quantized.** DeepSeek ships V4's dense weights in
FP8, so in the bf16 re-export every MXFP8-quantized linear sits exactly
on the e4m3 grid (MXFP8 round-trip error 0). An lr-1e-6 update is
smaller than half a grid step: after 48 steps, ~94% of the changed
attention and shared-expert elements round back to their base value when
vLLM re-quantizes, and vLLM keeps ~5% of the update (routed experts keep
72-100%). With a bf16 trainer the two policies drift apart. On dumped
v4/v48 broadcast weights, trainer vs a fresh vLLM went 0.0034 -> 0.0058
KL at equal token surprisal, while fresh vLLM vs the RL server stayed
flat (0.0032 / 0.0029); with attention and shared experts kept bf16 in
vLLM the trainer gap stayed at 0.0025 / 0.0024.
The trainer and vLLM run MXFP8 on exactly the same DeepSeek-V4 modules:
| Module | vLLM | Trainer |
|---|---|---|
| wq_a, wkv, wq_b, wo_b, shared experts | MXFP8 | MXFP8
(`model.quantization`, `mxfp8_rceil_wgrad_with_hp`) |
| routed experts | MXFP8 (FLASHINFER_TRTLLM) | MXFP8 (`moe.compute`) |
| wo_a | bf16 (ignored) | bf16 (`o_a_proj` ignored) |
| indexer (wq_b, weights_proj) | bf16 (`*.indexer.*` ignored) | bf16
(`compressor\.`, `indexer\.` ignored) |
| compressors, router, lm_head | bf16 (hard-coded in vLLM) | bf16
(ignored) |
Both sides quantize 1x32 along K with power-of-two scales rounded up and
a round-to-nearest-even e4m3 cast, so the quantized weights are
bit-identical. vLLM still has to leave `*.wo_a` in bf16: its
`deep_gemm_fp8_o_proj` passes the MXFP8 scale to a 128x128 block-FP8
einsum and fails a DeepGEMM assert (`t.dim() == N`). The trainer nests
the indexer inside the compressor, so `compressor\.` keeps it bf16
there; vLLM places it beside the compressor, so it needs its own
`*.indexer.*` entry.
The routed-expert MXFP8 path uses the `mxfp8_moe` kernel from the bumped
prime-kernels wheel.
60-step math run with an eager trainer (lr 1e-6, NCCL broadcast, router
replay), mismatch KL by 10-step block, against the same setup with a
bf16 trainer:
| Steps | 1-10 | 11-20 | 21-30 | 31-40 | 41-50 | 51-60 | mean |
|---|---|---|---|---|---|---|---|
| bf16 trainer | 0.0012 | 0.0016 | 0.0021 | 0.0035 | 0.0061 | 0.0082 |
0.0038 |
| MXFP8 trainer | 0.0018 | 0.0021 | 0.0023 | 0.0020 | 0.0019 | 0.0018 |
0.0020 |
These runs predate the `*.indexer.*` serving entry, so vLLM still ran
the indexer's wq_b in MXFP8 against a bf16 trainer; the math run with
that entry has not been rerun.
Reward (0.64 -> 0.60 over 60 steps) and entropy (~0.37) follow the
bf16-trainer run. Trainer throughput is ~7% lower (5.1k vs 5.5k
tokens/s).
With the trainer compiled (as in the SWE config), a 30-step compiled run
gives the same mismatch KL as eager (mean 0.0020 vs 0.0021; steps 21-30:
0.0022 vs 0.0023), with forward/backward ~4% slower (17.1 s vs 16.4 s
per step).
### 6. Experiment SWE config
DeepSeek-V4-Flash RL on the `scaleswe` taskset at 131k context with
SWE-bench Verified eval, meant for B300: 4 trainer nodes + 4 one-node
inference replicas, same MXFP8 alignment as section 3 with the indexer
bf16 on both sides. Eval sets `tool_call_parser` / `reasoning_parser =
"deepseek_v4"` explicitly, since auto-resolution only matches
`deepseek-ai/DeepSeek-V4` and not this re-export. In-flight episodes are
uncapped, which also slows eval rollouts towards the 1 h timeout late in
the run. In the run, mismatch KL stayed at ~0.003 until step 186, then
rose to ~0.01; the cause is not identified yet.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Phi <phi@primeintellect.ai>
Preserve FP32 router logits directly from the BF16 gate matmul, and
retain weighted expert contributions in FP32 until the routed-expert sum
is complete. Both operations currently round to BF16 too early.
- BF16 is the sole router operand dtype for both RL and SFT. Remove the
`moe_router_dtype` trainer option, automatic dtype selection, and
separate router FSDP units. Routers share their transformer block's FSDP
unit. `optimization_dtype` and `reduce_dtype` are unchanged.
- Add `FP32Linear` in a separate `fp32_linear.py`. Its forward uses
`torch.mm(..., out_dtype=torch.float32)` for CUDA BF16 operands. A
custom autograd function computes gradients in FP32 and returns them in
the operands' dtype. The linear logic lives directly in
`FP32Linear.forward`, preserving the module call and checkpoint keys.
- Keep logits, score functions, normalization, and routing weights in
FP32. Local/Torch dispatch multiplies and sums weighted expert outputs
in FP32, casting once after the sum, including with MXFP8 expert
compute.
- Add one focused BF16 matmul/autograd regression, covering
eager/compiled checkpointing and frozen/trainable gate weights, with
concise precision documentation.
### Matching DeepSeek-V4-Flash vLLM settings
Apply this router-only overlay after the base and precision recipe, with
the vLLM model dtype set to `"bfloat16"`:
```toml
[inference]
enable_fp32_router_logits = false
[inference.vllm.hf_overrides]
moe_router_dtype = "bfloat16"
```
The explicit HF override selects BF16 gate weights/operands with #4098's
serving patch. The `false` flag disables PrimeRL's automatic FP32 HF
override; V4's gate still produces FP32 logits. Quantization and expert
backend settings stay in the existing precision recipe, independently of
router dtype. No inference settings are automatically enforced by this
PR.
For research-prod #286, select `router-bf16.toml`. Configs that still
set `trainer.model.moe_router_dtype` fail config validation and must
drop that line.
### Validation
- Configuration tests: removing `moe_router_dtype` adds no failures (222
passed locally; the 23 failures are config-load tests for environment
packages not installed locally, same as before the change).
- 50 MoE, DeepSeek-V4 and state-offload tests passed on B300, including
the four eager/compiled and frozen/trainable cases of the retained
matmul/autograd regression.
- Two B300s, CP=2, full-block compilation with activation checkpointing
and activation offloading: 24 variable-length steps from 1,024 to 16,002
padded tokens passed. Eight initial graphs were reused without graph
breaks or backward compilation; gradients remained finite and saved
activations were released after backward.
- Two B300s, CP=2 / Torch EP=2 with MXFP8 routed experts and CP×32
padding: 24 variable-length steps passed under full-block compilation
and activation offloading. Ten initial graphs were reused for the final
17 steps, with no graph breaks or backward compilation.
- Ruff check/format and `git diff --check` passed.
### Scope
The FP32 expert-accumulation guarantee applies to Local/Torch dispatch;
DeepEP and MegaMoE use separate combine kernels. Pairing router dtypes
does not assert bitwise equality across training and serving kernels.
Distributed validation uses a reduced three-layer DeepSeek-V4-Flash
fixture with real attention kernels, not a full checkpoint/recipe
training run.
---------
Co-authored-by: Xuan-Phi Nguyen <19323568+nxphi47@users.noreply.github.com>
Co-authored-by: sami jaghouar <sami.jaghouar@gmail.com>
Update `deps/verifiers` from `512b8f77f` to `c5fd0582e` and
`deps/prime-envs` from `91d7d15f6` to `548244b95`, then refresh the
workspace package metadata in `uv.lock`.
The Verifiers pin is the newest main commit and includes the merged
nano-rlm update to `4cd7f39` from
https://github.com/PrimeIntellect-ai/verifiers/pull/2926. The prime-envs
bump brings its environments onto the current Verifiers runtime/scoring
APIs and includes the latest compatibility and grading fixes.
Validation: 339 CPU-compatible orchestrator/config tests passed; `uv
lock --check --offline`, TOML validation, and all pre-commit checks
passed. `test_batch.py` and `test_prefill_logprobs.py` require GPU-only
packages unavailable on this macOS host (`prime_kernels` and `vllm`).
The upstream Verifiers PR records partial live-test results, including
model HTTP 502s and a turn-limit timeout on the new nano-rlm pin.
Further verification is left to CI.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Wide lockfile and submodule pin changes affect scoring/runtime for
many evaluation environments; risk is moderate though scoped to
dependency alignment, with full GPU/live eval coverage deferred to CI.
>
> **Overview**
> Refreshes **`uv.lock`** after bumping **`deps/verifiers`** and
**`deps/prime-envs`**, aligning the workspace with the latest Verifiers
runtime (including the merged **nano-rlm** update noted in the PR).
>
> Across editable **prime-envs** packages, **`verifiers`** constraints
move from **`>=0.4.0`** to pre-release pins (**`>=0.4.1.dev48`**, with
some Harbor/SWE packages on **`>=0.4.1.dev18`**). Several environment
distributions are version-bumped in lock metadata (e.g. **deep-swe**,
**pi-deepswe**, **enterprise-ops-gym**, **mcp-atlas**, **swebench-pro**,
and multiple **swe-atlas**/**harbor** envs), reflecting
API/compatibility fixes in prime-envs rather than application code
changes in this repo’s diff.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
140750a273b4fb7b3ff6f6af2310d08a4b5a5e0c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Add an opt-in `linear-subagent` GRPO length penalty with
`subagent_token_weight = 0` by default. It sums output and newly
introduced input tokens within each branch, then weights semantic
subagent tokens before per-group normalization. Branches are assumed to
have no shared physical prefixes; `min_new_input_tokens` avoids
recounting history across turns within a branch.
The existing `linear` variant keeps its token accounting and remains the
default for a penalty block without a type. Length penalties remain
disabled unless configured.
```toml
[orchestrator.train.algo.length_penalty]
type = "linear-subagent"
subagent_token_weight = 0.0
num_turns_weight = 0.0
```
Membership follows harness-declared subagent calls, continuations, and
compaction, using the same factor for nested subagents. Parent resumes
and unattributed calls count fully. The multiplier leaves turn
penalties, training-token weights, and baseline token weights unchanged;
the example disables turn penalties explicitly.
Validation: 58 focused scoring and config tests passed against main's
pinned Verifiers and Renderers revisions; all pre-commit checks passed.
Coverage includes separate physical branches, nested subagents,
compaction, cross-agent edges, unlabelled traces, weights of 0, 0.7, and
1, preservation of existing linear scoring, and opt-in config parsing.
Adds opt-in score centering to IcePop (`trainer.loss.score_centering =
true`), using captured top-k sampler probabilities and a proportional
tail approximation.
- Bumps verifiers to `512b8f7` for sampler probability transport through
traces and training branches.
- Bumps renderers to `70c8204` for top-logprob capture and compact
response parsing.
Integration of our closed mega-moe based on Sonic Moe's abstractions
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Introduces a new distributed training path with persistent cross-rank
kernels, strict NCCL/SM and buffer sizing constraints, and a proprietary
deep_gemm dependency; misconfiguration can deadlock or fail at runtime.
>
> **Overview**
> Adds **Mega MoE** as a new expert-parallel MoE dispatch path
(`model.moe.dispatch.type = "mega_moe"`) that fuses token dispatch,
SwiGLU expert GEMMs, and combine into prime-mega-moe `deep_gemm`
kernels, overlapping EP communication with compute. Config covers
`precision` (bf16 / mxfp8 / fp8 / fp8_bwd), `max_tokens_per_rank`
(auto-derived from the micro batch in RL/SFT), and `num_reserved_sms`
with a startup check that `NCCL_MAX_CTAS` ≤ reserved SMs to avoid
deadlocks with FSDP NCCL.
>
> Trainer wiring uses **`FusedTokenDispatcher`** plus
**`MegaMoEExpertCompute`** (custom autograd ops, symmetric buffers,
optional MXFP8 casting); **`model.moe.compute` is ignored** when Mega
MoE is selected. **`GroupedExperts`** now accepts fused compute that
takes routing tensors directly. Docs, a multi-GPU benchmark vs the bf16
Torch dispatcher path, activation-checkpointing registration, SFT timing
sync, and a unit test that Mega MoE requires `ep > 1` are included.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e433a59e76d4cdb86df223cf10c470d6ac047f27. 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: S1ro1 <matej.sirovatka@gmail.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
MFU in the trainer is computed the way torchtitan computes it, and the
orchestrator packs micro-batches by the same FLOP count. Both
config-parsing estimators (the trainer's `get_active_mm_params` and the
orchestrator's Megatron-style `_packing_cost_coeffs`) are deleted.
## One FLOP counter
`FlopCounter(model)` in `trainer/perf.py` is the single source of truth:
```python
counter = FlopCounter(model) # walks the model once
counter(seq_lens) # Σ_docs n · 6 · num_active_params + Σ_layers attention_flops(n)
```
- `PreTrainedModelPrimeRL.num_active_params()`: parameters a text token
multiplies through, as torchtitan's `get_nparams_and_active_nparams`.
The default walks the built model (`count_active_params`): routed
experts (`MoE.experts`) count by `top_k / num_experts` (exact integer
arithmetic, expert weights lead with `num_experts`), embedding tables
count only when tied to the lm_head. Qwen3.5 overrides it to drop the
vision encoder.
- `AttentionFlops` (runtime-checkable protocol in `models/base.py`):
`attention_flops(seq_len)` = training FLOPs of a layer's sequence mixing
for one document of `seq_len` tokens. The counter sums it per document,
so a packed micro-batch is charged attention within each document, not
over the packed length. On Python 3.12 the protocol check uses
`inspect.getattr_static`, so attribute-forwarding wrappers
(`MultiLoRAModule`, `CheckpointWrapper`, `OptimizedModule`) do not match
and cannot double count.
- `layers/attn.py` has the two torchtitan rules as document totals:
`quadratic_attention_flops` (`6·heads·(qk+v)·seq_len·attended`, no
causal discount) and `delta_rule_flops` (`18·v_heads·dk·dv·seq_len`).
Implementations:
- `FlashAttention` (Llama, Qwen3, Qwen3-MoE, GLM-4.x, MiniMax, Laguna,
Qwen3.5 full attention, Nemotron-H attention), `AfmoeAttentionBase`,
`GptOssAttention`: quadratic, `attended = min(seq_len, sliding_window)`
on sliding layers.
- Qwen3.5 / Qwen3.8 GatedDeltaNet: delta rule. Nemotron-H Mamba2:
`12·heads·head_dim·state_size·seq_len` (state update x ⊗ B and readout
state·C).
- DeepSeek-V4 (as torchtitan): local window plus compressed entries; CSA
layers add the indexer over the compressed length and read `index_topk`
of them.
- GLM-5.x DSA (MLA, qk = nope + rope, v = `v_head_dim`): attention reads
`min(seq_len, index_topk)`; the indexer term
`2·index_heads·index_head_dim·seq_len²` only on layers that own an
indexer.
- Qwen3.8 IndexedGatedAttention: indexer over `seq_len //
compression_ratio` blocks, attention over `min(seq_len, token_budget)`.
- LoRA: `4·(active − adapters) + 6·adapters` per token (main froze every
non-LoRA parameter in #3855). Adapters go through `count_active_params`,
so MoE expert adapters count by `top_k / num_experts` like the base
experts.
## MFU
The RL and SFT trainers sum `perf_counter.flop_counter(seq_lens)` over
their micro-batches, all-reduce it with the token count over the dp
mesh, and pass it to `get_step_mfu`. Log keys are unchanged.
Example of the per-document attention: GLM-4.5-Air at `seq_len = 131072`
(2x8 H200, cp4 ulysses, EP8, packed SWE samples, ~15 documents per
micro-batch) logged MFU 127.7% / 152.3% on main; the same steps give
24.4% / 29.0%.
FLOPs/token for one document (main vs this PR; torchtitan = its
`get_nparams_and_flops` on the matching flavor, built on meta):
| model | seq_len | main | this PR | Δ | torchtitan |
|---|---|---|---|---|---|
| Qwen3-8B | 8k | 5.9904e+10 | 5.9906e+10 | +0.0% | 5.9906e+10 (exact) |
| Qwen3-8B | 64k | 1.6137e+11 | 1.6137e+11 | +0.0% | 1.6137e+11 (exact)
|
| Qwen3-30B-A3B | 8k | 3.7577e+10 | 3.7579e+10 | +0.0% | 3.7579e+10
(exact) |
| Qwen3-30B-A3B | 64k | 1.7287e+11 | 1.7287e+11 | +0.0% | 1.7287e+11
(exact) |
| GLM-5.3-BF16 | 8k | 3.4925e+11 | 2.7461e+11 | -21.4% | n/a |
| GLM-5.3-BF16 | 64k | 1.2286e+12 | 2.8447e+11 | -76.8% | n/a |
| Qwen3.5-9B | 8k | 5.6032e+10 | 5.1068e+10 | -8.9% | 5.1068e+10 (exact)
|
| Qwen3.5-9B | 64k | 1.4623e+11 | 7.3616e+10 | -49.7% | 7.3616e+10
(exact) |
| Qwen3.5-35B-A3B | 8k | 2.9853e+10 | 2.1988e+10 | -26.3% | 2.1988e+10
(exact) |
| Qwen3.5-35B-A3B | 64k | 1.4260e+11 | 5.0174e+10 | -64.8% | 5.0174e+10
(exact) |
| DeepSeek-V4-Flash | 8k | 2.5126e+11 | 8.7221e+10 | -65.3% | 8.8630e+10
(indexer at 6x) |
| DeepSeek-V4-Flash | 64k | 1.2208e+12 | 9.5676e+10 | -92.2% |
1.0695e+11 (indexer at 6x) |
| gpt-oss-20b | 8k | 3.1307e+10 | 2.6557e+10 | -15.2% | n/a |
| gpt-oss-20b | 64k | 9.8952e+10 | 6.0380e+10 | -39.0% | n/a |
| NVIDIA-Nemotron-3-Nano-30B-A3B-BF16 | 8k | 5.8477e+10 | 2.1927e+10 |
-62.5% | n/a |
| NVIDIA-Nemotron-3-Nano-30B-A3B-BF16 | 64k | 2.0504e+11 | 3.8839e+10 |
-81.1% | n/a |
| Trinity-Mini | 8k | 2.9891e+10 | 2.4026e+10 | -19.6% | n/a |
| Trinity-Mini | 64k | 1.2009e+11 | 4.6574e+10 | -61.2% | n/a |
- Dense and plain-MoE models (Qwen3) are unchanged and match torchtitan
exactly (the tiny difference is norm weights, which torchtitan also
counts).
- Hybrid models go down: linear-attention, Mamba and sliding-window
layers are no longer counted as full attention.
- GLM-5.3: sparse attention reads 2048 tokens and the indexer runs on
the 21 IndexShare `full` layers. Active params 40.3B (main: 37.3B, it
missed the shared expert and the indexer weights).
- DeepSeek-V4: main treated every layer as full attention and counted
18.8B active params (13.3B here).
## Packing
`BatchPacker` builds the model once on the meta device with the
trainer's own `get_model(..., device=meta)`, so it gets the same modules
as the trainer (IndexShare, pad token), and uses its `FlopCounter` as
the bin cost: ranks are balanced against the cost the trainer reports.
Measured: build 0.1–0.4 s and counter construction ≤ 0.02 s for GLM-5.3,
DeepSeek-V4-Flash/Pro, Qwen3.5-35B-A3B, GLM-4.5-Air and Qwen3-30B-A3B
configs; one bin-cost call over 16 documents takes 0.2–2.6 ms. The
orchestrator already imported `prime_rl.trainer.model`, so import time
is unchanged.
The orchestrator runs in the trainer's environment, so if the model
cannot be built (no config, or an architecture without a PrimeRL
implementation, which the trainer rejects too), it fails at startup
instead of falling back to token-count balancing.
## Tests
`tests/unit/train/test_perf.py` builds three architectures on meta from
small configs (dense Qwen3, GLM-MoE-DSA with IndexShare, Qwen3.5 GDN)
and checks the attention term against a hand-computed value, and checks
the dense Qwen3 active-parameter count (attention and MLP projections,
norms, lm_head) against a hand count.
## End to end
1x8 H200, Qwen3-30B-A3B-Instruct-2507 RL on reverse-text (6 trainer
GPUs, ep=2, 2 inference GPUs, seq_len 4096, batch 256x~300 tokens): the
orchestrator built the meta model and packed with the `FlopCounter`; all
15 steps completed (reward 0.28 -> 0.45). Steps 2-15: 12-19 s, 3.8-7.3k
tokens/s, MFU 1.2-2.4%. The MFU matches throughput x 1.83e10 FLOPs/token
over 6 x 989 TFLOPS (e.g. step 15: 6040 tok/s -> 1.9%); it is low
because this batch is tiny for a 30B model on 6 GPUs.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes MFU reporting and micro-batch load balancing for hybrid/sparse
models; orchestrator now requires a buildable PrimeRL model at startup
instead of degrading to token balancing.
>
> **Overview**
> Replaces separate HuggingFace-config FLOP heuristics in the
orchestrator and trainer with a single **`FlopCounter`** built from the
actual PrimeRL model on meta.
>
> **Trainer MFU** now sums per-document FLOPs from packed `seq_lens`
(matmul term from `num_active_params` / MoE-aware `count_active_params`,
plus each layer’s `attention_flops`) and feeds that total into
`get_step_mfu` in RL and SFT instead of a fixed flops-per-token derived
from config.
>
> **Model hooks:** `AttentionFlops` protocol and
`attention_flops(seq_len)` on flash, sliding-window, sparse/MLA (GLM
DSA, DeepSeek V4, Qwen3.8 indexed), delta-rule, and Mamba layers; shared
helpers `quadratic_attention_flops` / `delta_rule_flops` in
`layers/attn.py`.
>
> **Orchestrator packing:** `BatchPacker` drops `AutoConfig` +
`build_bin_cost` and uses the same `FlopCounter(get_model(...))` as bin
cost so DP balancing matches trainer compute (no silent fallback to
token count).
>
> **Cleanup:** Large `PerfCounter` config parsers removed; unit tests
use injectable `bin_cost` stubs and meta-model `FlopCounter` checks.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a30614948245312a6f318acb8774d642a80c377e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
Since #3948, SFT pads each packed row only to a multiple of `model.cp`
instead of to `seq_len`, so rows have variable lengths (2413 to 16384
tokens on the run below). With `torch.compile`, a rank recompiles its
block whenever a row length breaks a guard of the compiled graph, e.g.
the routing sort's `8*args[0].size()[1] >= 32767` (`sort_stable`) or the
FSDP view-stride guards. The recompiling rank stalls for 6-15 s, its
expert-parallel peers wait in the all-to-all, and every rank then waits
in the inter-node FSDP collectives.
This adds `data.pad_to_seq_len` (default `false`, so main's behaviour is
unchanged). With `true`, every packed row is padded to `seq_len *
micro_batch_size` again (the pre-#3948 behaviour), so rows have one
shape and nothing recompiles. It also adds the config that reproduces
the regression, under `benchmarks/scripts/sft_pad_to_seq_len/`.
## Results
Qwen3-235B-A22B SFT, 8x8 H200, vanilla FP8 (DeepGEMM FP8 dense +
`deepgemm_fp8` experts, torch all-to-all), `torch.compile` fullgraph,
full AC, no offload, 64 x 16k tokens/step, 30 steps. Both runs used this
branch with the same config and ran at the same time on separate node
sets; only the flag differs.
| `data.pad_to_seq_len` | Steps 6-30 mean | Slow (>20 s) steps | MFU |
Loss @ 30 | Recompiles (all ranks) |
|---|---|---|---|---|---|
| `false` (main) | 20.2 s | 15 of 25, ~25 s each | 21.5% | 0.2417 | 24 |
| `true` | **12.7 s** | 0 of 25, steady 12.5-13.2 s | **36.7%** | 0.2417
| 0 |
Per-step times with `false` (the same steps are slow on every run):
```
2:29.3 3:26.9 4:26.0 5:25.8 6:25.8 7:27.9 8:25.9 9:25.3 10:12.0 11:25.5 12:25.0 13:12.0 14:12.1 15:12.3 16:11.9
17:12.1 18:25.1 19:25.8 20:26.3 21:25.0 22:24.7 23:12.0 24:24.8 25:25.5 26:25.2 27:26.4 28:12.0 29:12.2 30:12.2
```
Ruled out while bisecting: the NCCL flight recorder from #4019 (same
pattern with `TORCH_FR_BUFFER_SIZE=0`), the `deep_gemm` build (same
pattern with the public 2.5.0 wheel), nodes (same steps slow on three
node sets), and NCCL/torch versions (unchanged). FSDP message sizes and
dtypes are identical between the slow and fast configurations.
A profile of a slow step shows one rank in dynamo/inductor compile for
6.5 s mid-step (`entire_frame_compile`, AOT + inductor backward compile)
while its 7 expert-parallel peers spend ~20 s in the all-to-all
(`ncclDevKernel_SendRecv`), and the inter-node all-gathers stretch from
~8 ms to ~66 ms per call waiting for it.
## How to benchmark it yourself
Needs 8 H200 nodes (64 GPUs) with SLURM. The config is
`benchmarks/scripts/sft_pad_to_seq_len/qwen3_235b_fp8.toml`; set
`[slurm] partition` for your cluster.
```bash
git fetch origin && git switch mario/sft-pad-to-seq-len-recompiles
uv sync --all-extras
# main's padding (rows padded to a multiple of cp)
uv run sft @ benchmarks/scripts/sft_pad_to_seq_len/qwen3_235b_fp8.toml \
--output-dir outputs/pad-cp --run.name pad-cp
# rows padded to seq_len
uv run sft @ benchmarks/scripts/sft_pad_to_seq_len/qwen3_235b_fp8.toml \
--output-dir outputs/pad-seq-len --run.name pad-seq-len --data.pad_to_seq_len true
```
What to look at:
- Step times in `outputs/<run>/.../logs/attempt_1/trainer/node_0.log`
(`Step N | <time>s`): with `pad_to_seq_len=false`, about half the steps
take ~25 s instead of ~12.6 s.
- To see the recompiles, add `TORCH_LOGS = "recompiles"` under
`[env_vars]` in the config and grep every node's trainer log for
`Recompiling function` and the `triggered by` guard failures (`size
mismatch at index 1`, `8*args[0].size()[1] >= 32767`,
`args[0]._base.stride()`). Check all `node_*.log` files: the recompiles
happen on whichever rank first sees a new row length, not only on rank
0.
- To profile, add `trace_path = "<dir>"` at the top level and set
`max_steps` to at most 9 (the trainer refuses longer traces); steps 2-9
are all slow on this data.
Running both configs at the same time on separate node sets keeps
cluster noise out of the comparison. If the Hugging Face Hub is flaky,
point `data.name` at a local snapshot of
`PrimeIntellect/INTELLECT-3-SFT-10K`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Opt-in dataloader padding change with default false; no change to
training math beyond padding length when enabled.
>
> **Overview**
> Adds an opt-in **`data.pad_to_seq_len`** flag (default **`false`**) on
SFT data config so packed training rows can use a **fixed token length**
again.
>
> When enabled, **`setup_dataloader`** pads each packed row to
**`seq_len * micro_batch_size`** instead of only to a multiple of
**`model.cp`**. That restores one static sequence shape per step, which
the PR targets at **`torch.compile`** / DeepGEMM JIT recompiles when row
lengths vary across steps. The tradeoff is **extra padding**; leaving
the flag off keeps current padding behavior unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7c4bfb599d18ea34fc39724b12f4d97cd16e6a18. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Reverts #4110, which made the length-weighted baseline mandatory for
GRPO and ECHO. Restore the plain group-mean reward baseline by default,
with `length_weighted_baseline = true` available as an explicit opt-in.
Length penalties and prompt-mean loss aggregation are unchanged.
The IcePop + SC comparison does not show a clear eval benefit from
length weighting and shows lower entropy and higher mismatch KL.
Staleness and source/runtime revisions differ, so this is a conservative
default rollback rather than a claim that length weighting caused the
divergence.
This is an exact revert of commit `68e5755ed`, based on main
`584a1169a`, including the existing documentation and advantage tests.
Validation: 41 advantage/algorithm tests passed against main's pinned
verifiers/renderers sources using a temporary CPU PyTorch overlay. Ruff
lint and formatting checks passed, including the commit hooks.
`model.dsa_backend` now defaults to `cudnn_flashmla`, for both
`glm_moe_dsa` (DSA sparse MLA, e.g. GLM-5) and `deepseek_v4`. This
backend runs the FlashMLA sparse prefill forward and the cuDNN frontend
sparse backward. `tilelang` is still available as an explicit option.
The plan is to remove it later.
Requirements. If any of these is not met, model setup fails with a
message that names the problem and says to set `model.dsa_backend =
"tilelang"`:
- an SM90, SM100 or SM103 GPU
- `flash-mla` installed
- 64 or 128 attention heads (these are the head counts FlashMLA sparse
prefill supports), one KV head, and head_dim 512
`flash-mla` has moved from its own extra into the `gpu` extra, so `uv
sync --all-extras` (README, CI, Docker) and `--extra gpu` both install
it. Only an x86_64 wheel is published, so on aarch64 you need to set
`tilelang`. The redundant `dsa_backend = "cudnn_flashmla"` lines are
removed from the GLM-5.3 and DeepSeek-V4-Flash configs.
Why: in #3968, on 1x8 H200 with the GLM-5.3 `swe.toml` trainer settings,
`cudnn_flashmla` cut step time by about 22% compared with `tilelang`
(16.6/15.5 s to 12.8/12.1 s, extrapolated to 78 layers). Entropy and
mismatch KL were identical. SM100/SM103 are supported but not measured.
Checks:
- 1x8 H200: 4-layer random-init SFT steps (fake data, seq 8192, ep 8)
for `zai-org/GLM-5.3-BF16` and `deepseek-ai/DeepSeek-V4-Flash-0731`,
with no backend set. Both finished.
- `pytest -m gpu` on `test_deepseek_v4_kernels.py`,
`test_deepseek_v4.py` and `test_fp8_indexer.py`: 125 passed, including
the `cudnn_flashmla` cases.
- `pytest -m "not gpu"` on `tests/unit/test_configs.py` and
`tests/unit/orchestrator`: 351 passed. `tests/unit/train -k "glm or dsa
or deepseek or model or config"`: 78 passed.
- `ruff check` and `ruff format --check` pass.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes the default sparse-attention kernel path and GPU dependency
set; environments without SM90/SM100/SM103, flash-mla, or supported head
shapes will fail at model init unless they override to tilelang.
>
> **Overview**
> **`model.dsa_backend` now defaults to `cudnn_flashmla`** (FlashMLA
sparse forward + cuDNN backward) instead of `tilelang` for GLM MoE DSA
and DeepSeek V4 sparse attention. Example TOMLs drop redundant explicit
settings; unit tests that use unsupported shapes pin **`tilelang`**
explicitly.
>
> **`flash-mla` ships with the `gpu` extra** on x86_64 Linux—the
standalone `flash-mla` optional dependency and Docker/`uv sync --extra
flash-mla` usage are removed so default GPU installs include the forward
kernel.
>
> **Fail-fast validation** is centralized in `cudnn_flashmla_error()`
(GPU arch, 64/128 heads, dim 512, `flash_mla` import). GLM attention and
DeepSeek V4 raise clear errors at init with a hint to set
**`model.dsa_backend = "tilelang"`** when the fused path cannot run.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ef5c5dee3e5433e9004e38737a7b35275ecd3edb. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
In GLM sparse run 4744 (2 nodes, 8 vLLM servers), applying v9 failed on
one engine. `/update_weights` returned 500 on every retry. After about
84 s of retries the orchestrator logged `All inference engines resumed`
and then nothing but the periodic `Train batch 0/128 ... 0 inflight`
line for 32 min. There was no error and no traceback. The dispatcher was
paused waiting for v9, and the trainer was waiting for the receiver.
## Cause
A failed weight update ends the watcher task with the exception. Today
only the step loop surfaces that: `main_loop` calls
`_raise_if_component_stopped()` when it polls `out_q`, and
`wait_for_version` calls it too. If the step loop is waiting anywhere
else, nothing reads the dead task. The error is never logged, and the
run idles until someone cancels it.
I could not reproduce *why* 4744's step loop stopped polling. On one
node (plain and sparse filesystem) and on 2 nodes in 4744's layout
(Qwen3-0.6B, 8 servers, failure injected on DP1 only), the same failure
surfaces within a second. The orchestrator exits 1 and the launcher
stops.
## Fix
A done-callback on the orchestrator's component tasks (dispatcher,
watcher, control). When one fails, the callback:
- logs the error with its traceback right away;
- cancels the step-loop task wherever it waits.
`start()` turns that cancellation into the component's error, so the run
ends through the usual `Fatal error in run_orchestrator` path with exit
code 1. A signal-driven cancel (no failed component) still re-raises
`CancelledError` as before. Teardown cancels component tasks, and that
is ignored.
## Checks
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 350 passed; ruff is clean.
- Qwen3-0.6B reverse-text, 1 node, filesystem. `/update_weights` fails
for v3 (injected), and the step loop is blocked by a synthetic `await
asyncio.Event().wait()` after step 3, which reproduces the 4744 symptom:
- main: engines resumed at 15:48:44, then only `Train batch` lines until
the 720 s test timeout. No error. Same as 4744.
- this PR: engines resumed at 15:42:17, then `Orchestrator component
watcher failed` with the `HTTPStatusError` traceback in the same second.
The orchestrator exited 1 and the launcher stopped 4 s later.
- The injection patches and the 2-node repro are throwaway; they are not
in this PR.
No unit test: the behavior needs a real event loop with the
orchestrator's tasks.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes orchestrator lifecycle and error propagation on the event
loop; mis-handled cancels could affect shutdown, but scope is limited to
failure detection and teardown callback cleanup.
>
> **Overview**
> **Fixes silent hangs when a background orchestrator component dies
while the step loop is blocked outside its usual poll points** (e.g.
watcher failing after a bad `/update_weights`).
>
> `start()` now registers **done callbacks** on dispatcher, watcher, and
control tasks. If one finishes with an exception, `_on_component_done`
**logs the failure with traceback** and **cancels the main step-loop
task** immediately instead of waiting for
`_raise_if_component_stopped()` on the next `out_q` or
`wait_for_version` poll.
>
> On `CancelledError`, the handler calls `_raise_if_component_stopped()`
so component errors still propagate through the normal fatal-exit path;
signal-only cancels re-raise unchanged. **Teardown removes the
callbacks** so stopping components during cleanup does not re-cancel the
main task.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
606f79dbfebf190a7cb4ade822f63af1b5231efd. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
`ep="auto"` resolved to `min(world_size // dp_replicate, 8)` without
looking at the expert count or `cp`. Qwen3-30B-A3B (128 experts) on 6
trainer GPUs resolved to `ep=6` and failed in MoE setup (`MoE expert
count 128 must be divisible by model.ep=6`).
`auto` now picks the largest degree up to 8 that divides the FSDP island
and the expert count and is a multiple of `cp` (1 if none is). For 6
GPUs with 128 experts this gives `ep=2`. Configs that resolved to a
valid degree before resolve to the same value.
- `parallel_dims.py`: `_is_moe_model` -> `_num_experts` (also reads
`num_local_experts`, so GPT-OSS / MiniMax M2 configs count as MoE); new
pure `auto_ep`; one info line when auto falls back to `ep=1`
- one unit test for `auto_ep`; config docstring and `docs/scaling.md`
updated
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes default parallel layout for some MoE + GPU + CP combinations
(lower EP than before), which affects throughput but fixes invalid
configs; behavior unchanged when the old auto value was already valid.
>
> **Overview**
> Fixes **`ep="auto"`** so MoE training no longer picks an
expert-parallel degree that violates MoE layout constraints.
>
> **Before:** auto EP was `min(fsdp_island_size, 8)` and ignored expert
count and context parallelism—e.g. 6 GPUs with 128 experts could resolve
to `ep=6` and fail at setup.
>
> **After:** new **`auto_ep`** chooses the **largest** degree ≤8 that
divides both the FSDP island (`world_size // dp_replicate`) and
**`num_experts`**, and is a multiple of **`cp`** (falls back to `ep=1`
if none). MoE detection now reads expert count via **`_num_experts`**
(including `num_local_experts` for some configs). Docs and `ModelConfig`
docstrings match; unit tests cover `auto_ep`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6046b4af906c90fb286a56380f0ed7fc5c8a07a7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
`tests/unit -m gpu` fails all 24 `cudnn_flashmla` cases in
`test_deepseek_v4_kernels.py` with `The chosen implementation does not
support all required features ... TOPK_LENGTH`. They pass when run
alone.
Cause: `vllm/_flashmla_C.abi3.so` and the flash-mla wheel
(`flash_mla/cuda.*.so`) both export the GNU-unique symbol
`Fwd_Sm90_Impl::features`. The dynamic loader binds every library to the
copy that was loaded first. vLLM's older list has 6 entries and no
`TOPK_LENGTH`; the wheel reads 8 entries from it (hence the trailing
`HEAD_64, HEAD_64` in the error). In the suite,
`test_deepseek_v4.py::test_deepseek_v4_on_disk_keys_map_to_the_names_vllm_expects`
imports vLLM's DeepSeek V4 model, which loads `_flashmla_C`, before the
kernel tests run.
Fix: the kernel test module imports `flash_mla` at collection, so the
wheel's list wins. vLLM only reads the first 6 entries, which are the
same in both lists.
Checked on one H200 node with main's venv:
- `import vllm._flashmla_C` then `flash_mla_sparse_fwd(...,
topk_length=...)` reproduces the CI error; without the vLLM import it
passes.
- `pytest tests/unit -m gpu`: 234 passed, 2 skipped (main CI: 24 failed,
210 passed).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Test-only import ordering fix with no runtime or production behavior
changes.
>
> **Overview**
> Fixes **GPU suite flakes** where all `cudnn_flashmla` cases in
`test_deepseek_v4_kernels.py` fail with missing `TOPK_LENGTH` when run
after other unit tests that import vLLM.
>
> The module now **imports the `flash_mla` wheel at pytest collection**
(when installed), before vLLM can load its older bundled `_flashmla_C`.
Both libraries share the GNU-unique symbol `Fwd_Sm90_Impl::features`, so
whichever loads first wins for the whole process; the wheel’s feature
list includes `TOPK_LENGTH`, while vLLM’s does not.
>
> No production code changes—only test import ordering and an
explanatory comment.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c369ed2b9aa9c0f0ada9f96ab61f2875dad87ce4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Log the inference pause separately from the weight transfer during a
weight update.
`watcher/last_update_weights_time` covers pause + transfer + resume.
`AdminPlane.update_weights` now records each phase, and the watcher logs
them next to it:
- `watcher/pause/{min,mean,max}`: each engine's `/pause` time (`max` is
when every engine has paused)
- `watcher/transfer/{min,mean,max}`: each engine's `/update_weights`
while paused
- `watcher/resume/{min,mean,max}`: each engine's `/resume`
The debug log line now says `All inference engines paused in
<min>-<max>s`.
## Why
The pause can be larger than the transfer, and until now it was
invisible. On Qwen3-30B-A3B with P/D (4 prefill + 4 decode engines, 16
steps per transport, first update dropped), the per-update medians were:
| transport | pause max | pause min | transfer | resume |
|---|---|---|---|---|
| NIXL + overlap | 30.0 s | 0.19 s | 1.47 s | 0.01 s |
| NCCL | 30.0 s | 0.18 s | 5.37 s | 0.01 s |
The 30 s matches vLLM's NIXL `kv_lease_duration` default. A prefill
engine's `/pause` (mode `keep`) only finishes after its pending KV send
leases expire, because the paused decode engines no longer pull or renew
those leases.
## Checks
- `pytest -m "not gpu" tests/unit/orchestrator
tests/unit/test_configs.py tests/unit/inference/test_dynamo.py`: 355
passed
- `ruff check`, `ruff format --check`
- Ran on 2 nodes (job 3913, the table above)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Observability-only refactor around existing pause/transfer/resume
admin calls; no change to weight-update control flow or retry semantics.
>
> **Overview**
> **Weight updates now record per-engine timing for pause, transfer, and
resume** instead of folding everything into
`watcher/last_update_weights_time`.
>
> `AdminPlane.update_weights` stores the latest phase timings in
`update_times` via a shared `_post_all` helper that times each engine’s
admin POST. Pause and resume helpers return those per-engine durations;
the pause debug log reports a min–max range.
>
> **The watcher exposes nine new gauges**:
`watcher/pause|transfer|resume/{min,mean,max}` aggregated across
engines, so slow pauses (e.g. NIXL KV lease waits) are visible
separately from weight transfer.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
89186bd749142cf8b8ab63dde8bcf332037ba06d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
The P/D SLURM templates pin every decode node to one NIC with
`UCX_NET_DEVICES=mlx5_0:1`. This PR removes the pin. Decode then uses
the same list as prefill: every ACTIVE InfiniBand port, falling back to
RoCE.
On a node where `mlx5_0` is not an active InfiniBand port, decode cannot
create its NIXL backend at all. On our H200 nodes, `mlx5_0` is one of
the 8 InfiniBand NICs (see `swe-llmd.toml`). So all 8 decode GPUs pull
KV blocks and NIXL weights through that one NIC.
## Numbers
Qwen3-30B-A3B with P/D on 2 H200 nodes, split into four 4-GPU groups: 2
trainer (EP8), 1 prefill, 1 decode. NIXL weight broadcast with
`overlap_transfer_and_replay`, 16 steps per arm. Medians, first update
dropped:
| decode `UCX_NET_DEVICES` | in-pause weight transfer | p90 | trainer
`time/broadcast_weights` | mismatch-KL (mean) | prefill/decode weight
checksums |
|---|---|---|---|---|---|
| `mlx5_0:1` (main) | 1.47 s | 1.48 s | 33.5 s | 0.005 | 16/16 match |
| all active InfiniBand ports (this PR) | 0.56 s | 0.56 s | 32.6 s |
0.002 | 17/17 match |
Neither arm logged a NIXL error, a failed request or a traceback. Decode
created its NIXL KV connector and NIXL weight agent with the port list.
Prefill and decode shared a physical node in that run, so the KV
transfer did not cross the network.
### Prefill and decode on different nodes
Same setup, but prefill on node 0 and decode on node 1, so every KV
transfer crosses InfiniBand. The trainer spans both nodes. Same tree for
both arms (main + #4059); the only difference is the decode pin. 16
steps per arm. KV numbers are decode-side `vllm:nixl_*` totals from
`/metrics`, summed over the 4 decode engines:
| decode `UCX_NET_DEVICES` | KV transfers | KV bytes | mean KV transfer
time | KV throughput | KV transfers <= 5 ms | failed transfers /
notifications / expired | in-pause weight transfer (median, p90) |
trainer `time/broadcast_weights` | `time/step` | mismatch-KL (mean) |
weight checksums |
|---|---|---|---|---|---|---|---|---|---|---|---|
| `mlx5_0:1` (main) | 9597 | 89.5 GB | 28.2 ms | 0.33 GB/s | 48% | 0 / 0
/ 0 | 2.52 s, 2.52 s | 9.5 s | 117.2 s | 0.0010 | 17/17 match |
| all active InfiniBand ports (this PR) | 9559 | 91.0 GB | 16.2 ms |
0.59 GB/s | 70% | 0 / 0 / 0 | 0.55 s, 0.55 s | 7.2 s | 115.9 s | 0.0010
| 17/17 match |
All prompt tokens on decode came from `external_kv_transfer` in both
arms. Cross-node KV transfer works without the pin. It is 1.7x faster
per transfer, and the weight transfer is 4.6x faster. Step time is about
the same because KV and weight transfer are a small part of the step.
## Checks
- `rl @ examples/advanced/glm-5.3/swe.toml --dry-run` and `inference @
examples/advanced/glm-5.3/infer/pd-llmd.toml --dry-run` render; `bash
-n` passes on both scripts.
- `pytest tests/unit -m "not gpu" -k "slurm or sbatch or template or
disagg"`: 3 passed.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes cluster networking for NIXL/KV and weight transfer on decode;
behavior depends on which RDMA ports are ACTIVE, though benchmarks in
the PR show improved throughput without NIXL failures.
>
> **Overview**
> Removes the decode-only **`export UCX_NET_DEVICES=mlx5_0:1`** from the
P/D branches in **`inference.sbatch.j2`** and
**`multi_node_rl.sbatch.j2`**.
>
> Decode nodes now keep the same UCX device list as prefill: active
InfiniBand ports from sysfs (RoCE fallback, then `all`), which the
templates already set before the role split. **`decode_env_vars`** can
still override UCX per deployment if needed.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
74071cd8f637fdb0f20b9cde48aa0f5cb19c2db8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
In P/D, the orchestrator paused all engines at once before a weight
update. A prefill engine's pause waits until decode has pulled the KV
blocks the prefill still holds. A paused decode engine never pulls them.
So every prefill pause waited for vLLM's NIXL KV lease to expire
(`kv_lease_duration`, 30 s by default). After the update, decode then
read blocks the prefill had already released (`Potentially invalid KV
blocks for unrecognized request` logged on the prefill nodes, the KV
producer).
This PR pauses prefill engines first, then decode engines. The roles
come from `inference_metrics_roles`, which the `rl` launcher already
sets for P/D. Without roles, all engines pause together as before.
## Numbers
Qwen3-30B-A3B with P/D on 2 H200 nodes, split into four 4-GPU groups: 2
trainer (EP8), 1 prefill, 1 decode. 4 prefill + 4 decode DP/EP engines
behind vllm-router, 16 steps per arm. Medians, first update dropped.
| arm | pause (slowest engine) | weight update | trainer
`time/broadcast_weights` | step | "Potentially invalid KV blocks" errors
| final update + shutdown |
|---|---|---|---|---|---|---|
| NIXL, main | 30.0 s | 31.7 s | 33.5 s | 136 s | 354 | killed by the
arm timeout during the final 30 s pause |
| NIXL, this PR | 14.3 s | 15.9 s | 17.6 s | 117 s | 0 | 29 s, exit 0 |
| NCCL, main | 30.0 s | 35.5 s | 37.1 s | 146 s | 362 | 51 s |
| NCCL, this PR | 6.8 s | 12.3 s | 14.1 s | 104 s | 0 | 28 s, exit 0 |
- Prefill and decode weight checksums matched after every update in all
arms. No transfer errors or failed requests.
- With this PR, decode pauses in about 0.15 s. The remaining pause is
prefill waiting for the still-running decode engines to pull its KV
blocks (2.8 to 26.7 s per update here). It depends on decode load, not
on a timer.
Related: #4054 (logs the pause separately; both PRs edit
`_pause_engines`), #4058.
## Checks
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 341 passed.
- `ruff check` and `ruff format --check` pass.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes weight-update pause ordering on the inference admin plane;
misaligned roles vs. engine order could pause the wrong group, but
default behavior is unchanged and P/D runs already supply roles via the
launcher.
>
> **Overview**
> Fixes **P/D weight-update pauses** that stalled ~30s and produced
invalid KV reads when prefill and decode engines were paused in
parallel.
>
> **`_pause_engines`** now runs in two phases: all **prefill** admin
clients `/pause` first, then everyone else (decode and unlabeled
engines). That lets decode keep pulling KV while prefill drains, instead
of decode pausing first and blocking the handoff until NIXL’s KV lease
expires.
>
> **`AdminPlane`** stores optional per-client **roles** (same order as
admin URLs). **`setup_admin_plane`** and the orchestrator pass
**`inference_metrics_roles`** into that path (already set by the `rl`
launcher for P/D). With no roles, behavior is unchanged—single
concurrent pause wave.
>
> Config doc for **`inference_metrics_roles`** now notes it drives pause
ordering as well as metric labels. A unit test asserts prefill `/pause`
completes before decode when roles are set.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c03c5257c160051b7400f22c92daca681a420155. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Experimental vLLM HiSparse for DSA sparse-MLA models (e.g. GLM-5.x) on
P/D decode instances.
- `[inference.hisparse] host_pool_gib = ...` adds `HiSparseConnector` to
the connector chain. Off by default; no example config uses it.
- Under P/D it runs on decode only (`for_pd_role("prefill")` drops it).
- Decode cannot also offload KV: config error unless
`inference.deployment.decode_kv_cache_offload = "None"`. A HiSparse
decode keeps its KV in a host-resident layout. Native offload rejects
it, and Mooncake stores it under the same keys as prefill's regular
layout, so prefill fails to load it (`TRANSFER_FAIL` on GPU).
- Without P/D, HiSparse with native KV offload is a config error (vLLM
rejects it at engine start); Mooncake offload is allowed, because every
writer uses the same layout.
- vLLM checks the rest at startup (V2 runner, no PP/DCP, a DSA model;
vLLM 0.32 also rejects `cudagraph_mode = "FULL"`, while P/D decode
launches with `FULL_DECODE_ONLY`).
- Docs: a short HiSparse section in `docs/inference.md`.
## Checks
- `pytest -m "not gpu" tests/unit/orchestrator
tests/unit/test_configs.py tests/unit/inference`: 317 passed. Ruff
clean.
- GPU (vLLM 0.31.0, 1x 8xH200): tiny random GLM-5 DSA (4 layers),
prefill Mooncake + decode HiSparse, router replay + sampling masks, 6
two-turn conversations: 6/6 OK, expected rows, no errors (statistical
only, no bitwise reference for sparse MLA). Decode HiSparse + decode
Mooncake made prefill's turn-2 load fail, which is why that combination
is rejected.
Not validated: real GLM-5.x quality at long prompts, aggregated HiSparse
against the trainer forward, preemption or failed loads with HiSparse.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes P/D decode KV connector composition and host-memory sizing;
misconfiguration is blocked at validate time, but the feature is
experimental and not fully validated on production GLM workloads.
>
> **Overview**
> Adds **experimental vLLM HiSparse** support for DSA sparse-MLA models
(e.g. GLM-5.x) via `[inference.hisparse] host_pool_gib = ...`, which
injects `HiSparseConnector` into the existing `kv_transfer_config` /
`MultiConnector` chain alongside NIXL and optional Mooncake offload.
>
> Under **disaggregated P/D**, HiSparse applies to **decode only**
(`for_pd_role("prefill")` clears it). Config validation rejects
incompatible setups: decode cannot use KV offload while HiSparse is on
(native offload is also rejected globally when HiSparse is enabled).
**Docs** add a HiSparse section (experimental caveats, RAM budgeting,
offload rules). SLURM templates only note HiSparse in the pinned-memory
`ulimit` comment. **Unit tests** cover decode connector composition and
validation errors.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7d44741eaa125942a4addfa4c08ea7e009ef6c25. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Add an `eval` suite to `regression.yml`, next to `rl` and `parallel`.
It runs nightly at 11:00 UTC, on dispatch (`suite=eval`), and on PRs
that touch `tests/regression/**` or the workflow. The `rl` and
`parallel` suites never run on PRs.
- Add `tests/regression/`, one folder per suite under each of these:
- `configs/eval/gsm8k.toml`: the full gsm8k test split (1319 tasks), 1
rollout each, `internal/glm-5.3-high-throughput`, null harness as a
subprocess. No GPUs needed.
- `baselines/eval/gsm8k.json`: 5 repeats from [an earlier CI run of this
PR](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/38887591005).
- `reports/eval/gsm8k.md`: the error bars of that baseline (mean,
Student-t 95% CI, std, CV, per-repeat values).
- `scripts/eval.py` (stdlib only): `collect` reduces a run dir to a
result JSON, `summarize` renders the job summary and gates on the
baseline, and `baseline` writes a new baseline and its report.
- Eval jobs:
- `Eval / Run`: runs the config on `ubuntu-latest`, once by default.
With `eval_repeats` > 1 there is one job per repeat, named `Eval / Run
(N)`.
- `Eval / Summary`: writes the comparison table to the run's summary
page and fails on a regression. With `eval_set_baseline` it also opens a
PR that replaces the baseline and report with this run's results. This
needs 2 or more runs, and every run must succeed.
- Add `eval` to the `regression.yml` row of `docs/development.md`.
This PR builds on #4121 (align workflows) and #4122 (remove the dead
benchmark and nightly CI), which are both merged.
### Regression rule
A metric regresses when it is worse than the baseline mean by more than
`max(3 · std · sqrt(1 + 1/n), floor)`. The `sqrt(1 + 1/n)` term is the
prediction interval for one fresh run against a mean of `n` baseline
runs. The floors stop a lucky, low-variance baseline from turning every
nightly red.
| Metric | Baseline (n=5) | Floor | Tolerance |
|---|---:|---:|---:|
| Accuracy | 97.65% ± 0.18% | 1 pp | ±1.00 pp |
| Time to finish | 1626 s ± 204 s | 25% | ±671 s |
| Error rate | 0.03% ± 0.04% | 1 pp | ±1.00 pp |
| Truncation rate | 0.27% ± 0.11% | 1 pp | ±1.00 pp |
The table also shows episode latency, eval window and output tokens, but
these metrics don't gate. The check is skipped with a warning when the
env, model, task count or rollout count differs from the baseline.
### Refresh the baseline
Run `gh workflow run regression.yml -f suite=eval -f eval_repeats=5 -f
eval_set_baseline=true`. Then review and merge the PR it opens. For the
bot to open PRs, the repo setting "Allow GitHub Actions to create and
approve pull requests" must be on.
## Follow-ups
- Check the finished `rl` runs against a baseline. Today the `rl` suite
only dispatches the runs.
## Verification
- An earlier CI run of this PR ran 5 repeats of the full config. All 5
finished in about 27 min each. Those results are the committed baseline.
- A later single-run CI run scored 97.27% accuracy and 1581 s. Both are
within tolerance.
- I ran these locally:
- `summarize` on that single-run result passes (exit 0). A doctored
result (accuracy 95%, 2600 s) fails (exit 1). An empty result set fails
(exit 1).
- `baseline` rebuilds the committed baseline exactly from the 5 CI
results, and refuses a single result.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Adds CI that calls Prime Inference with repo secrets and can open PRs
with write permissions; core training paths are unchanged but nightly/PR
gates depend on external eval stability and baseline tuning.
>
> **Overview**
> Adds an **`eval` regression suite** to nightly `regression.yml`,
alongside existing `rl` and `parallel` jobs. The workflow now triggers
on PRs that touch `tests/regression/**` or the workflow file (eval only
on PRs; `rl`/`parallel` are gated off PRs), adds **concurrency**
cancellation, and exposes dispatch inputs for repeat count, optional
model override, and **baseline refresh via bot-opened PR**.
>
> **Eval pipeline:** `Eval / Plan` → matrix of `Eval / Run` jobs that
run `uv run eval` against Prime Inference (starting with `gsm8k.toml`),
then `eval.py collect` for metrics; `Eval / Summary` compares results to
committed baselines with tolerance-based gating and can regenerate
baseline JSON + markdown report.
>
> **New regression assets:** `configs/eval/gsm8k.toml`, five-repeat
`baselines/eval/gsm8k.json`, `reports/eval/gsm8k.md`, and stdlib
**`tests/regression/scripts/eval.py`** (`collect` / `summarize` /
`baseline`). **`docs/development.md`** documents the eval suite and CI
triggers.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9a246eaf6342134bcc8a05f5f933d7197cf78802. 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
- Remove the trainer benchmark CI:
- `.github/workflows/benchmarks.yaml`
- `benchmarks/` (scripts, baselines, `results/BENCHMARKS.md`)
- `tests/integration/test_benchmark_regression.py`
- Remove the `COPY benchmarks/scripts` line from `Dockerfile.cuda`.
- Remove the link to `run_single_benchmark.py` from `docs/scaling.md`.
The manual benchmarking guide in that section stays.
Why:
- The workflow's last runs, in January 2026, were cancelled or failed.
- It never opened one of its results PRs, and the baselines were
refreshed by hand (#2558).
- No CI job runs `test_benchmark_regression.py`.
- Remove the `research-cluster` nightly suite: its example tests in
`tests/nightly/` and
`configs/ci/nightly/multimodal_color_codeword.toml`.
- Keep `test_parallel_invariance.py` (#4003), which checks that DP/CP/EP
layouts train the same first step as a single GPU. It moves to
`tests/regression/` and runs nightly as a new `parallel` suite on the
`prime-rl-2xh200` runners. Layouts that need more GPUs than the runner
has skip, so CP=2+EP=2 runs only on 4-GPU machines.
- Rename the hosted FFT suite in `regression.yml` from `fft` to `rl`.
Its configs move from `configs/ci/nightly-fft/` to
`tests/regression/configs/rl/`. Its dispatch inputs become
`rl_config_file` and `rl_image_tag`.
- Add `tests/regression/configs/` to the paths that
`tests/unit/test_configs.py` loads, so the moved configs keep their
schema check.
- Update the `regression.yml` row and the test layout in
`docs/development.md`: three tiers, with `tests/regression/` as the
third.
Why:
- The last research-cluster run that passed was on 2026-05-13. Since
then, every nightly run waited 24h in the queue and then got cancelled.
No runner picks up `research-cluster` jobs.
- The hosted FFT runs cover the same tasks (alphabet-sort, hendrycks
math, reverse-text, wiki-search, wordle).
This PR is the second in a stack:
1. #4121: align workflows
2. This PR: remove the trainer benchmark CI
3. #4115: add the eval regression suite
## Breaking
- `gh workflow run benchmarks.yaml` no longer exists. To benchmark a
parallelism config by hand, follow the steps in
`docs/scaling.md#benchmarking`.
- Images no longer contain `/app/benchmarks/scripts`.
- `regression.yml` has no `fft` suite. Use `-f suite=rl`, `-f
rl_config_file=...` and `-f rl_image_tag=...` in place of the `fft`
inputs.
- `tests/nightly/` no longer exists. `test_parallel_invariance.py` is
now in `tests/regression/`; dispatch it with `-f suite=parallel`.
`configs/ci/nightly-fft/` is now `tests/regression/configs/rl/`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Removes automated performance baselines and changes nightly regression
coverage; hosted RL dispatch behavior is unchanged but suite names and
config paths are breaking for anyone using old workflow inputs.
>
> **Overview**
> Removes the **trainer benchmark** pipeline end-to-end: the
`benchmarks.yaml` workflow, `benchmarks/` (scripts, baselines,
`BENCHMARKS.md`), Docker image copy of benchmark scripts,
`tests/integration/test_benchmark_regression.py`, and the CI script
reference in `docs/scaling.md`. Manual short-run benchmarking via
`metrics.jsonl` in scaling docs is unchanged.
>
> **Nightly regression** is reshaped: drops the dead `research-cluster`
`tests/nightly/` pytest matrix and `configs/ci/nightly/*`. The former
hosted **FFT** suite becomes **`rl`**, with configs under
`tests/regression/configs/rl/` and dispatch inputs `rl_config_file` /
`rl_image_tag`. **`parallel`** runs
`tests/regression/test_parallel_invariance.py` on `prime-rl-2xh200`,
skipping layouts that need more GPUs than the runner has.
>
> Docs and `test_configs.py` now treat `tests/regression/configs/` as
part of the config schema sweep. Slim-install CI drops `ring_flash_attn`
from the forbidden-import list.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
68e2a433ab039a414a8ff0bf593ee5c9db840e16. 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
- Rename workflows to one word with the `.yml` extension, like verifiers
(`tests.yml`, `style.yml`, `docs.yml`, ...).
- Merge workflows that share triggers:
- `tests.yml` = `cpu_tests.yaml` + `gpu_tests.yaml`. Both run on push to
`main`, PRs and dispatch.
- `regression.yml` = `nightly_tests.yaml` (`rl` suite) +
`nightly-fft.yaml` (`fft` suite). Both run at 11:00 UTC. A `suite`
dispatch input picks one suite.
- Rename only:
- `style.yaml` → `style.yml`
- `sync-docs.yml` → `docs.yml`
- `tag-and-release.yaml` → `release.yml`
- `devx_tag.yaml` → `prerelease.yml` (it cuts the `.dev` tags)
- `build_image.yaml` → `image.yml`
- Rename jobs to match verifiers: short noun ids and short title-case
names. Matrix jobs get a readable name next to the raw test or config
value.
- `tests.yml`: `Unit (CPU)`, `Unit (GPU)`, `Slim install`, `Changes`,
`Integration / <Test>` (e.g. `Integration / Reverse Text LoRA`),
`Integration / GSM8K Eval`.
- `regression.yml`: `RL / Plan`, `RL / <Test>` (e.g. `RL / Wordle`),
`FFT / Plan`, `FFT / <Config>` (e.g. `FFT / Reverse Text`).
- `image.yml`: `Authorize`, `Prepare`, `Build (<arch>)`, `Manifest`.
- Keep `release.yml` and `prerelease.yml` separate. They differ in
concurrency, permissions and dispatch inputs, so merging them would
change release behavior.
- Update every reference to the old names:
- `release.yml` and `prerelease.yml` dispatch `image.yml`
- `scripts/docker-entrypoint.sh` messages
- README badges: one Tests badge instead of CPU + GPU
- `docs/development.md` CI table
- `skills/release/SKILL.md`
- `configs/ci/slim_sft.toml`
- `benchmarks.yaml` stays as it is: the next PR in the stack removes it.
Behavior changes:
- CPU jobs now share the GPU jobs' concurrency group. On pushes to
`main`, a queued run gets replaced by a newer one, as GPU runs already
were.
- The workflow token of the nightly RL jobs is now limited to `contents:
read`.
This PR is the first in a stack:
1. This PR: align workflows
2. Remove the trainer benchmark CI
3. Add the eval regression suite (#4115)
## Breaking
- Manual dispatch commands change:
- `gh workflow run nightly_tests.yaml -f test_file=X` → `gh workflow run
regression.yml -f suite=rl -f rl_test_file=X`
- `gh workflow run nightly-fft.yaml -f config_file=X -f image_tag=Y` →
`gh workflow run regression.yml -f suite=fft -f fft_config_file=X -f
fft_image_tag=Y`
- `gh workflow run build_image.yaml …` → `gh workflow run image.yml …`
(same inputs)
- Workflow URLs, badge URLs and check names change. `main` has no
required status checks, so merging isn't blocked. Run history of the old
workflows stays under their old names in the Actions tab.
## Verification
- `actionlint` reports the same 7 findings on the new files as on main's
original files. They are the custom runner labels (`prime-rl-2xh200`,
`research-cluster`) and the `parallel:` steps, which actionlint doesn't
know. The new files add no errors.
- `tests.yml` runs on this PR. `regression.yml`, `release.yml`,
`prerelease.yml` and `image.yml` only run on cron, tags, main pushes or
dispatch, so this PR doesn't exercise them.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> CI entrypoints and manual dispatch commands change, which can break
automation or runbooks; test logic is mostly moved, but shared
concurrency and tighter regression permissions alter when jobs run and
what tokens they use.
>
> **Overview**
> **Reorganizes GitHub Actions** to match the verifiers repo:
single-word workflow names with `.yml`, merged triggers, and shorter job
titles (including readable matrix names like `Integration / Reverse Text
LoRA`).
>
> **`tests.yml`** replaces separate CPU and GPU test workflows—unit
(CPU/GPU), slim wheel install, path-filtered integration, and GSM8K eval
run from one workflow on PR/push/dispatch. CPU jobs now share the GPU
workflow’s concurrency group (newer `main` runs can cancel queued ones).
>
> **`regression.yml`** replaces nightly RL experiments and nightly
full-finetune dispatch with one scheduled/dispatchable workflow: `suite`
chooses `rl`, `fft`, or `all`; dispatch flags are renamed
(`rl_test_file`, `fft_config_file`, `fft_image_tag`). Workflow-level
permissions drop broad package access; FFT jobs keep `packages: read`
only where needed.
>
> **Renames only** (with dispatch targets updated): `release.yml`,
`prerelease.yml`, `image.yml`, `docs.yml`, `style.yml`. README shows one
Tests badge; docs and release skill point at the new files.
>
> **Breaking for operators:** `gh workflow run` paths and input names
change (documented in the PR). Check/job names in Actions change; no
required checks on `main`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f5d047020a5c7d8b15b72885354d5731a906ae55. 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>
Bumps vLLM 0.31.0 -> 0.32.0.
## Dependencies
- `vllm` 0.32.0 wheel. torch stays 2.13.0, flashinfer stays 0.7.0.post1.
- `transformers` 5.6.2 -> 5.19.0 (vLLM 0.32 requires `>=5.16.1,<5.20`;
5.19.0 is what vLLM's CI tests). The `transformers==5.6.2` override is
removed. `tokenizers` 0.22.2 -> 0.23.3.
- `nvidia-cutlass-dsl` override 4.7.1 -> 4.8.0 (exact pin in vLLM 0.32).
`tokenspeed-mla` 0.2.15, `humming-kernels` 0.1.17, `instanttensor`
0.2.2, `xgrammar` 0.2.8 come from vLLM; `humming-kernels` and
`instanttensor` are exempt from the 7-day cutoff.
- `ifbench` is excluded from the workspace: it pins `setuptools<78`,
vLLM 0.32 needs `>=78.1.1`. No config or test references it.
## Patches deleted (fixed upstream in 0.32)
- `monkey_patch_shm_buffer_ownership`: vllm-project/vllm#61000.
- `monkey_patch_tokenize_params_validation`: vllm-project/vllm#57035
(`max_tokens` is an upper bound, not reserved from the context).
- `monkey_patch_nano_v3_reasoning_parser`: upstream `nemotron_v3`
parser. The Nemotron 3 Nano / 3.5 auto-detection now picks
`nemotron_v3`. Configs that set `reasoning_parser = "nano_v3"` must
rename it.
- DeepSeek V4 `layer_types` shim (`utils/transformers_compat.py` and its
vLLM patch): transformers >= 5.15 knows the V4 layer types.
## Breakages fixed
- `serving_tokens.py`: `GenerateResponseChoice` is gone and
`GenerateResponse` is now a discriminated union
(vllm-project/vllm#58588). Subclass `GenerateTokensChoice` /
`GenerateTokensResponse` and check `isinstance` against
`GenerateTokensResponse`.
- `prefill_logprobs`: validate with `GenerateTokensResponse` (the union
alias has no `model_validate_json`).
- `_patch_lora_key_prefix`: re-copied from 0.32's
`LoRAModel.from_local_checkpoint`; tensorizer support was removed
upstream (vllm-project/vllm#60024).
- NemotronH config: transformers 5.19 renames legacy layer types
(`mamba` → `linear_attention`, `attention` → `full_attention`) by
setting `config.layer_types`, which was a read-only property.
`layer_types` is now an `attribute_map` alias of `layers_block_type` (as
upstream), and the model and conversion code use the new names. Hub
configs with legacy `layers_block_type` or `hybrid_override_pattern`
load as before.
- Qwen3.5 tests: `from_config` through the auto class now swaps a
composite config for its text config; the tests build VLMs with
`Qwen3_5ForCausalLM`, as the trainer does.
- `monkey_patch_kv_xfer_finished_tolerate_freed`: synced the copied
method with 0.32 (`_set_kv_fetch_stage(req,
KV_FETCH_COMPLETED_WAITING)`).
Still needed on 0.32 (fixes land in 0.33 or are not merged): DeepSeek V4
C128 boundary, DeepSeek V4 `attn_sink` loading, GPT-OSS weight loading,
KV-transfer freed assert, MiniMax think-end, routed experts with P/D
connectors. Every remaining patch target still exists in 0.32; targets
whose source changed were checked against the new source.
## Validation
CPU: `pytest tests/unit -m "not gpu"` 854 passed; ruff clean.
Import/attribute check of every `vllm` import and monkey-patch target in
`src/` and `tests/` against 0.32: no missing names; patched methods
whose source changed were reviewed.
GPU (H200, max 2 nodes; 0.31 baselines use main's lock at the same base
commit, same nodes):
| Check | 0.32 | 0.31 |
|---|---|---|
| `tests/unit -m gpu` (NemotronH, Qwen3.5, Mamba CP, DSv4 kernels, …) |
pass after the fixes above¹ | – |
| Integration: reverse_text, reverse_text_moe, reverse_text_lora,
reverse_text_rl_opd, reverse_text_rl_sft, reverse_text_sft,
reverse_text_sft_lora, alphabet_sort | pass² | – |
| Qwen3-30B-A3B RL, bf16, NCCL (15 steps, median step / mismatch KL) |
15.3 s / 0.028 | 14.9 s / 0.025 |
| Qwen3-30B-A3B RL, online fp8 (`fp8_per_block`), NCCL | 15.4 s / 0.061
| 16.4 s / 0.063 |
| Qwen3-30B-A3B RL, bf16, filesystem broadcast (trainer step) | 156 s /
0.030 | 155 s / 0.020 |
| GLM-4.5-Air RL, router replay, 1 train + 1 infer node (10 steps,
median step / mismatch KL / reward) | 23.4 s / 0.0028 / 0.49→0.65 | 24.7
s / 0.0036 / 0.44→0.66 |
| Qwen3-30B-A3B P/D (NIXL 1P1D, vllm-router 0.2.3) vs colocated, router
replay + sampling masks, batch-invariant: identical tokens, rows, masks,
logprobs | c1 10/10, c10 20/20, uint16 c1 10/10 / c10 20/20, decode
preemption 20/20 | same as 0.31 results |
| GLM-4.5-Air (TP4) P/D vs prefill server queried directly (same node),
batch-invariant: identical tokens and rows | 0/10 (decode diverges);
10/10 with `disable_custom_all_reduce = true`³ | 10/10 |
| Long multi-turn prompt (14.4k prompt + `max_tokens` 4096,
`max_model_len` 16384), plain and router-replay server | 200, prompt not
truncated; `/generate` 15.9k + 4096 → 200, capped at `max_model_len`;
16.4k prompt → 400 | same |
| DeepSeek-V4-Flash TP8+EP serving smoke | loads, coherent completion |
– |
¹ The DSv4 `cudnn_flashmla` kernel tests fail the same way on main when
vLLM's DSv4 test loads first (FlashMLA symbol clash); with #4139 applied
they pass on 0.32 (123 passed).
² Each integration module's `test_dashboard` needs `playwright install
--with-deps`, which fails on our nodes; all other tests pass.
³ 0.32 uses the custom all-reduce under `VLLM_BATCH_INVARIANT=1`
(vllm-project/vllm#58623). Two TP>1 servers then no longer decode
bit-identically, so P/D only matches colocated serving bit-for-bit with
`disable_custom_all_reduce = true`. prime-rl does not set batch
invariance; RL is unaffected (GLM row above).
Not covered: Qwen3.5/Qwen3.8 PLE reload (no checkpoint on disk);
GLM-4.5-Air disaggregated RL (needs 3 nodes). Router-replay requests
need `top_k > 0` and `temperature > 0` (sampling-mask replay), on 0.31
and 0.32 alike.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches core inference dependencies and removes several runtime
patches; misalignment with vLLM 0.32 APIs or Nemotron parser changes
could break rollouts or serving until configs are updated.
>
> **Overview**
> **Upgrades the inference stack from vLLM 0.31.0 to 0.32.0**, with
matching pins: `transformers` 5.19.0, `nvidia-cutlass-dsl` 4.8.0, and
direct wheel URLs. `ifbench` is dropped from the uv workspace because
its `setuptools<78` pin conflicts with vLLM 0.32.
>
> Several **vLLM workarounds are removed** now that upstream fixed them:
SHM buffer ownership on dequeue, relaxed `TokenizeParams` prompt-length
checks, the custom `nano_v3` reasoning parser, and the DeepSeek V4
`layer_types` transformers shim (`transformers_compat.py`). **Nemotron 3
Nano / 3.5** auto-detection now uses the built-in **`nemotron_v3`**
parser instead of `nano_v3`.
>
> **API follow-ups for 0.32:** token-in/token-out serving and
`prefill_logprobs` use `GenerateTokensChoice` / `GenerateTokensResponse`
instead of the old `GenerateResponse*` types. The LoRA checkpoint patch
is re-synced from 0.32 (tensorizer path removed). The KV-transfer “freed
request” patch adds `_set_kv_fetch_stage(...,
KV_FETCH_COMPLETED_WAITING)` to match upstream.
>
> **Trainer Nemotron-H** aligns layer-type names with newer transformers
(`linear_attention`, `full_attention`) via `attribute_map`, while still
accepting legacy `mamba` / `attention` in `layers_block_type`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f92627e671e9abd083da8e85a4a0308f4671e6cc. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Disaggregated P/D with per-role KV offload, so P/D + router replay +
sampling replay + KV offload can be configured from the stack alone.
**Stacked on #3831.** Supersedes the parts of #3616 needed here.
**Per-role KV offload**
- `inference.deployment.prefill_kv_cache_offload` /
`decode_kv_cache_offload`: default `"inherit"` (use
`inference.kv_cache_offload`), `None` (`"None"` in TOML) disables
offload for that role, or a full offload config.
- Mooncake `cpu.num_bytes = 0` connects a role to the shared store
without starting a `mooncake_client` on its nodes (no storage
contributed; the vLLM process still uses its staging buffer). Native
offload still needs a positive size.
- Under P/D the Mooncake connector gets `save_decode_cache = true`:
decode also writes the KV it generates, so the next turn's prefill can
load the previous completion. Existing keys are skipped by the store, so
decode re-saving the prompt costs one existence check. Writes are not
clamped; prefill loads are clamped at `routed_experts_prompt_start` by
#3831, which keeps multi-turn completion blocks loadable.
- `_mooncake_store.sh.j2` runs per role: one master on the head node;
storage clients only on roles with capacity. Roles must agree on a
Mooncake disk path (one master, one `-root_fs_dir`).
- Mooncake keys carry model + TP/PCP/DCP/PP rank + content hash only, so
both roles must keep the same KV layout (TP size, `kv_cache_dtype`,
block size) to share the store. Documented.
**Launcher.** One engine config per role
(`inference-{prefill,decode}.json`, `InferenceConfig.for_pd_role` /
`write_pd_configs`); each node picks its file by `$ROLE`. Inference
nodes always run `ulimit -l unlimited` (NIXL/RDMA registers pinned host
pools).
Example (all storage on prefill; decode connects without capacity):
```toml
[inference.deployment.prefill_kv_cache_offload]
type = "mooncake"
[inference.deployment.prefill_kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000
[inference.deployment.decode_kv_cache_offload]
type = "mooncake"
[inference.deployment.decode_kv_cache_offload.cpu]
num_bytes = 0
```
Resulting connectors: prefill `MultiConnector[Nixl,
MooncakeStore(save_decode_cache)]`, decode `MultiConnector[Nixl,
MooncakeStore(save_decode_cache)]`.
Left out (not needed for this use case): GLM-5.3 example configs,
monitoring dashboard and tooling, trainer DRAM contribution to the
store, NUMA/UCX per-rank binding, router timeout/retry fields, lease TTL
and staging-buffer fields, explicit `kv_transfer_config` passthrough.
## Checks run
- `pytest -m "not gpu" tests/unit/test_configs.py tests/unit/inference`:
223 passed. Ruff: clean. Test: `test_pd_role_connectors`.
- Dry run of `examples/advanced/glm-5.3/swe.toml` + router replay +
`top_p = 0.95` (sampling masks) + prefill Mooncake (1 TB + disk) +
decode Mooncake (`cpu.num_bytes = 0`): per-role JSON configs build
`[Nixl, MooncakeStore]` for both roles; `bash -n` on the generated
`rl.sbatch` passes; only prefill nodes start a storage client.
## GPU validation (2026-10-06, vLLM 0.31.0, 1x 8xH200, configs written
by `write_pd_configs`, router v0.2.2)
- Qwen3-30B-A3B TP1, `VLLM_BATCH_INVARIANT=1`, 1P1D NIXL, prefill
Mooncake (RDMA, 40 GB) + decode Mooncake `cpu.num_bytes = 0` with
`save_decode_cache`, router replay + sampling masks, 6 two-turn
conversations (turn 2 start = `len(p1 + c1) - 1`) after evicting
prefill's GPU cache, vs a colocated no-offload reference: **6/6
identical** (tokens, 264 rows, start, masks). Prefill external hits
**16880** = sum of block_floor(start), vs 16512 when only prefill writes
(prompt-only maximum, earlier run with the same conversations): the
turn-1 completion blocks were loaded from decode-saved KV. No errors.
- 1P1D without offload, same configs path: 10/10 and 20/20 (concurrency
10, fresh salt) identical to colocated.
Not validated: multi-node Mooncake role launch on SLURM (template
rendered and `bash -n` only).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes disaggregated inference launch paths, KV connector
composition, and Mooncake SLURM wiring; misconfiguration could break
multi-turn prefix reuse, though config validation and unit tests cover
the main connector shapes.
>
> **Overview**
> Adds **per-role KV cache offload** for disaggregated prefill/decode
via `inference.deployment.prefill_kv_cache_offload` and
`decode_kv_cache_offload` (`inherit`, disabled, or a full offload
block). Resolvers expose `kv_cache_offload_by_role`, `for_pd_role()`,
and emit **`inference-{prefill,decode}.json`** so each node loads the
right connector set.
>
> **Mooncake** now allows `cpu.num_bytes = 0` to join the shared store
without starting a storage client (native offload still requires
positive CPU bytes). Under P/D, the Mooncake connector gets
**`save_decode_cache`** so decode-written KV is available on the next
prefill turn; validation requires a **single disk path** across Mooncake
roles sharing one master.
>
> SLURM templates take a **`mooncake_offloads`** map (replacing global
offload flags), role-aware `_mooncake_store.sh.j2`, and
**`inference-$ROLE.json`** in P/D jobs; inference nodes always run
**`ulimit -l unlimited`** for NIXL/RDMA pinned memory. Docs cover the
typical prefill-storage / decode-connect pattern and KV layout
constraints across roles.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ee5dcc664adb166161568f525b44aace43e3a80d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Adds a nightly GPU test (`tests/nightly/test_parallel_invariance.py`,
auto-discovered by the nightly workflow on the research cluster;
CP=2+EP=2 needs 4 GPUs, more than the 2-GPU PR runners): the first RL
training step must not depend on the parallel layout. It runs
`samsja/mini-glm-moe` on fake data for one step, single GPU vs DP=2,
CP=2, EP=2 and CP=2+EP=2. The DP=2 and CP=2 layouts pass `--model.ep 1`;
with the default `ep=auto` a MoE model would turn on EP=2 there. It then
compares `optim/grad_norm` and `loss/mean` (rel 2 %) and
`entropy/all/mean` / `mismatch_kl/all/mean` (rel 1e-3) against the
single-GPU run.
This catches sharding bugs that leave training running but wrong: a CP
shard that is dropped or double-counted, EP routing to the wrong rank,
or a loss normalizer that is per-rank instead of global.
The fake data loader now seeds each micro batch by its **global** index
(`dp_rank * micro_batches_per_rank + i`). Before, it seeded by the DP
rank, so DP=1 and DP=2 trained different batches. CP ranks of one DP
group still get the same micro batch.
## Checks
- On 1 node (4×H200, through a `uv run` shim onto the main venv): the
test (then under `tests/integration/`): 4 passed in 7.4 min without the
`loss/mean` check. On current main the CP=2 `loss/mean` is within 1.1 %
of the single GPU (measured). This exact test file was not rerun.
- Measured step-1 grad norm, single GPU 2.0571e-3:
| layout | grad norm | rel. diff |
|---|---|---|
| DP=2 | 2.0589e-3 | 0.09 % |
| CP=2 | 2.0508e-3 | 0.3 % |
| EP=2 | 2.0514e-3 | 0.3 % |
| DP=4 | 2.0458e-3 | 0.5 % |
| CP=2+EP=2 | 2.0498e-3 | 0.4 % |
Entropy and mismatch KL agree to about 1e-5 relative.
These runs used the default `ep=auto`, so the DP=2, CP=2 and DP=4 rows
also had EP on. Pure DP=2 and CP=2 (`--model.ep 1`) were not run.
- ruff is clean.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Changes only fake-data RNG for training tests and adds nightly
coverage; no production data path or auth changes.
>
> **Overview**
> Adds a **nightly GPU test** that runs one RL step on fake data across
single-GPU, DP=2, CP=2, EP=2, and CP+EP layouts, then asserts step-1
metrics (`optim/grad_norm`, `loss/mean`, entropy, mismatch KL) match the
single-GPU baseline within tight relative tolerances.
>
> **Fake data seeding** in `get_batch` is updated so each micro batch is
keyed by a **global** index (`batch_counter`, DP rank, and local micro
index) instead of primarily by DP rank. Different DP world sizes now see
the same global batch for a given step, while CP ranks in one DP group
still share the same micro batch.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8f9f38e2d0626fc63c2dfec426b62f4bd8b6144a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
Qwen3.8 Flash Next cloned three Qwen3.5 blocks. They now live once in
`trainer/models/layers/`, and both archs use them:
- `layers/gated_delta_net.py::GatedDeltaNet` (was `Qwen3_5GatedDeltaNet`
and Qwen3.8 `GatedDeltaNet`). It takes keyword args. Qwen3.5 passes
`hidden_act`/`output_gate_type` from its config. Qwen3.8 passes
`"silu"`/`"sigmoid"`, the values it hardcoded before.
- `layers/norms.py::ZeroCenteredRMSNorm` (was `Qwen3_5RMSNorm` and
Qwen3.8 `RMSNorm`).
- `layers/mlp.py::SigmoidGatedFeedForward` (was `Qwen3_5SharedExpert`
and `SigmoidOutputGatedFeedForward`).
The per-arch copies are deleted (`qwen3_5/{gated_delta_net,norm}.py`,
`qwen3_8_flash_next/{gated_delta_net,norm}.py`). State-dict keys, shapes
and dtypes are unchanged for qwen3_5, qwen3_5_moe, the qwen3_5 VLM and
qwen3_8.
**CP conv `cu_seqlens`:** Qwen3.5 passed `cu_seqlens` to the CP conv
call and Qwen3.8 did not. Neither one is a bug. When `cp_context` is
set, FLA's `causal_conv1d` returns early through `causal_conv1d_cp` and
ignores `cu_seqlens` (fla 0.5.2, `fla/modules/conv/causal_conv1d.py`).
The shared module keeps the Qwen3.5 single call. Qwen3.8 also passed
`initial_state=None, output_final_state=False` explicitly. Those are the
defaults, so the calls are the same.
## Behavior change
- Qwen3.5 (dense, MoE, VLM): none (bitwise on CPU, see below).
- Qwen3.8: forward is bitwise identical. Two small differences:
- The shared expert's input gradient can differ in the last fp32 bit.
The old Qwen3.8 code computed `sigmoid(gate) * ffn` and Qwen3.5 computes
`ffn * sigmoid(gate)`. The product is the same, but autograd adds the
two input-gradient terms in a different order. The shared module keeps
the Qwen3.5 order. In a full CPU model, the largest weight-grad
difference was about 3e-8.
- Inside `linear_attn`, Qwen3.8 now registers parameters in the Qwen3.5
order (conv1d first). The keys are the same. Only the order of the
state-dict / `named_parameters()` output changes, and the random init
for a given seed. Models loaded from a checkpoint are not affected.
## What I ran
- CPU unit/model equivalence vs origin/main (`equiv_qwen38blocks.py`).
FLA kernels were replaced by pure-torch reference conv /
gated-delta-rule / gated-norm, and every kernel call's kwargs were
recorded. CP was faked with a stub context. Results:
- qwen3_5 and qwen3_5_moe: all norms, shared experts and GDNs (CP and
non-CP), plus the full-model logits and all grads: bitwise identical.
- qwen3_5 VLM: keys and units identical.
- Standalone norm in fp32/bf16/fp16: bitwise identical.
- qwen3_8: everything is bitwise identical except the shared-expert
input grad described above. With the old multiply order the full model
is bitwise identical, so that order is the only difference.
- `/tmp/prm-equiv/equiv.py check` (CPU archs): all IDENTICAL.
- `pytest tests/unit/train tests/unit/test_configs.py
tests/unit/utils/test_weights.py -m "not gpu"`: 356 passed. The 2
`test_cpu_adam` failures are a missing `ninja` in my env; they also fail
on main.
- ruff check / format: clean.
## GPU checks (1×8 H200, SLURM job 2386)
- qwen3_5 and qwen3_5_moe, branch vs. main on GPU with the real FLA
kernels: bitwise identical (forward, logprobs, entropy, all grads,
buffers). main vs. main is also identical.
- qwen3_8 cannot be built in the equivalence script on this node
(`prime_kernels` has no `indexed_attention`).
- `-m gpu` `tests/unit/train/models/qwen3_5`,
`test_qwen3_8_flash_next.py` and `test_cp_mamba.py`: 11 passed. On main,
the first two give 9 passed; `test_cp_mamba` was not part of the main
run.
## Conflicts
#3833 rewrites the qwen3_5 / qwen3_8 modeling files. This PR touches
only their imports and constructor calls, so expect a small rebase
conflict there.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches core Qwen3.5/Qwen3.8 decoder paths (linear attention, norms,
MoE shared expert) but is largely a refactor with stated bitwise
equivalence for Qwen3.5 and near-identical Qwen3.8 behavior.
>
> **Overview**
> **Consolidates duplicated Qwen3.5 and Qwen3.8 building blocks** into
shared `trainer/models/layers/` modules and rewires both architectures
to import them.
>
> `GatedDeltaNet` replaces per-model linear-attention copies
(`Qwen3_5GatedDeltaNet` and the Qwen3.8 local module), with explicit
constructor kwargs (`activation`, `output_gate_activation`, etc.)
instead of a Qwen3.5 config object. `ZeroCenteredRMSNorm` and
`SigmoidGatedFeedForward` replace arch-specific RMSNorm and
sigmoid-gated shared-expert FFN implementations; Qwen3.5 drops
`Qwen3_5SharedExpert` in favor of the shared MLP class.
>
> Per-arch files `qwen3_5/{gated_delta_net,norm}.py` and
`qwen3_8_flash_next/{gated_delta_net,norm}.py` are removed. Qwen3.8 MoE
now uses `SigmoidGatedFeedForward` from layers (local
`SigmoidOutputGatedFeedForward` deleted). Intended checkpoint
compatibility: state-dict keys unchanged; Qwen3.5/VLM behavior
unchanged; Qwen3.8 forward matches with only minor autograd ordering on
shared-expert input grads and `linear_attn` parameter registration order
for fresh inits.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1d66345d3d53925013166b21be2be386d5afc257. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Model-factory RL runs show an empty Config tab, `OTHER` as the run type,
and missing model and environment details. The trainer and orchestrator
start directly, skipping the launcher that normally saves the
dashboard's configuration files.
Each component now saves its resolved config at startup, regardless of
how it was launched. The local `rl` launcher exports
`PRL_ATTEMPT_CONFIG_DIR` and `PRL_ATTEMPT_LOG_DIR` so its children write
into the same attempt directory. The dashboard reads environment names
from the resolved config as well as environment config files. Live trace
reads also handle a file disappearing between checking and opening it.
The pinned-directory test checks that children save into the launcher's
attempt directory. A new round-trip test loads a real `TrainerConfig`
from JSON and checks that saving it again produces an identical file,
including explicit null settings, while preserving the launch command
and TOML copy.
Earlier validation: 21 focused tests, Ruff, and a two-GPU FFT test on
Telus. Both components finished two training steps, and API/browser
checks verified configs, run details, metrics, and live traces.
Checkpoints were disabled for the successful test; an earlier
checkpoint-enabled attempt failed at the final save.
Validation of the review changes: syntax and `git diff --check` passed.
The updated tests and Ruff could not run locally because Python 3.12 and
the required dependencies are unavailable, and network access is
blocked.
Linear: RES-1382 · RL Stack.
## Summary
`SFTConfig` duplicated most of `TrainerConfig`. This PR adds
`BaseTrainerConfig` in `configs/trainer.py` with the shared fields and
validators. `TrainerConfig` and `SFTConfig` both subclass it.
- Shared fields: `model`, `tokenizer`, `optim`, `scheduler`, `ckpt`,
`log`, `matmul_precision`, `max_steps`, `memory_profiler_path`, `gc`,
`trace_path`, `dist_timeout_seconds`, `heartbeat`, `control`,
`env_vars`.
- Shared validators: `deepep_disables_grad_clipping`,
`full_optimizer_offload_requires_supported_optimizer`,
`full_optimizer_offload_disables_grad_clipping`,
`vlm_freeze_incompatible_with_lora`, `dont_do_massive_traces`,
`validate_scheduler_steps`, `auto_setup_tokenizer`.
- The three `"auto"` settings that resolve differently are class
variables, resolved by one `resolve_auto_defaults` validator (replaces
three validators per class):
| class variable | RL (`TrainerConfig`) | SFT (`SFTConfig`) |
|---|---|---|
| `auto_moe_router_dtype` | `float32` | `bfloat16` |
| `auto_freeze_moe_router` | `True` | `False` |
| `auto_weight_decay` | `0.0` | `0.01` |
- `resume`, `monitors`, `output_dir` and `weight_broadcast` stay per
class: their types or meanings differ.
## Behavior
No runtime change. Defaults, resolved values, warnings and validation
errors are the same.
Visible differences:
- **SFT help text** uses the shared wording for two fields: `max_steps`
("Maximum number of training steps.") and `env_vars` ("...for the
trainer process(es)...").
- **Field order.** Shared fields come first in `model_fields`, `--help`
and resolved-config dumps. The set of fields and their values do not
change.
- **After-validator order.** Shared validators run before class-specific
ones. No class-specific validator reads a value that a moved validator
sets. If a config has several errors, a different one may be reported
first.
## Proof
- Differential dump against `main` at the PR's original base: every TOML
under `configs/` and `examples/` (78 files; there is no `k8s/` TOML),
standalone and composed with each sibling TOML, plus 18 CLI override
cases (auto overrides, trace/max_steps, full offload, Muon + FSDP
offload, cosine scheduler, DeepEP, LoRA, tokenizer). Each case was
parsed with all 7 config classes, with `run.name` uuids pinned. That is
2310 cases, 245 of which parse. `model_dump`, error messages and
warnings are identical.
- `model_json_schema()` is identical for all 7 config classes.
- `--help`: `TrainerConfig` and `RLConfig` have the same lines (order
only). `SFTConfig` differs only in the two descriptions above.
- On current `main` (52455b41f): every `TrainerConfig` / `SFTConfig`
field has the same default and type as on `main` (including
`dist_timeout_seconds = 900` from #4019).
- `pytest tests/unit/test_configs.py tests/unit/orchestrator -m "not
gpu"`: 336 passed.
- `ruff check` and `ruff format --check` are clean.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Refactor-only config hierarchy with parity testing claimed; no
training logic changes, only consolidation and validator ordering.
>
> **Overview**
> Introduces **`BaseTrainerConfig`** in `trainer.py` so RL
**`TrainerConfig`** and **`SFTConfig`** share one definition of
model/tokenizer/optim/scheduler, logging, profiling, distributed
timeout, and the common cross-cutting validators (DeepEP vs grad clip,
full optimizer offload, VLM+LoRA, trace limits, scheduler steps,
tokenizer auto-setup).
>
> **`SFTConfig`** now subclasses the base instead of re-declaring those
fields and copy-pasted validators. RL- vs SFT-specific behavior for
`"auto"` settings is expressed as subclass **`ClassVar`** defaults
(`auto_moe_router_dtype`, `auto_freeze_moe_router`, `auto_weight_decay`)
resolved in a single **`resolve_auto_defaults`** validator on the base.
>
> RL-only and SFT-only pieces stay on the respective subclasses (e.g. RL
`loss` / `rollout_transport`; SFT `renderer`, deployment, online eval
wiring). Intended runtime behavior is unchanged; help text and
field/validator ordering may differ slightly.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1b459c192607b292f79eefcf9d3c662c8013ae43. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
Every LoRA layer is built with one adapter, so the multi-adapter code is
removed:
- `LoRAState` is only the module registry. The global `lora_num_tokens`
/ scaling tensors are gone, and so is the per-micro-step setup (RL CP
cumsum/clip/diff, SFT `set_lora_num_tokens`) and the `lora_num_tokens`
micro-batch field.
- `MultiLoRALinear` → `LoRALinear` (`layers/lora/linear.py`): `base(x) +
alpha/rank * (dropout(x) @ A.T @ B.T)`. No grouped GEMM, cumsum offsets
or `repeat_interleave` scaling.
- `MultiLoRAGroupedExperts` + `MultiLoRANonGatedGroupedExperts` → one
`LoRAGroupedExperts` (adapts `gate_proj` when the experts are gated,
plus `up_proj` and `down_proj`); `MultiLoRAGptOssGroupedExperts` →
`LoRAGptOssGroupedExperts` (`layers/lora/experts.py`). Plain parameters
instead of `ParameterList`s; the per-expert grouped GEMM is unchanged.
- `LoRAModule` holds rank/alpha/scaling/dropout and the shared reset
(kaiming-uniform A, zero B). Each layer only defines its parameters,
`forward` and `adapter_state_dict()`. `get_lora_param_counts`, the
`__repr__` overrides and `__getitem__` forwarding are removed.
- `model.lora.modules_to_save` is removed (config field, validator,
`_should_keep_trainable`, FLOPs branch, `modules_to_save` in
`adapter_config.json`).
- The LoRA experts no longer re-permute tokens under EP. The token
dispatcher already does this, and the old code imported
`TOKEN_GROUP_ALIGN_SIZE_M` from `distributed/expert_parallel`, which no
longer exists. The LoRA experts now just call `to_local()`, like
`GroupedGemmExpertCompute`.
- The dead `_init_lora_parameters` block in `load_dcp_from_hf` is
removed (no module defines it), and so is its now-unused `parallel_dims`
argument.
## Breaking
- `model.lora.modules_to_save` is removed. It was already rejected
unless `data.fake` was set.
- LoRA DCP checkpoint keys change from `lora_A.0` / `lora_B.0` to
`lora_A` / `lora_B`. Old LoRA DCP checkpoints do not resume. Exported
adapters are not affected.
- `adapter_config.json` drops `"modules_to_save": null` (the PEFT/vLLM
default).
## Behavior change
- LoRA scaling is `alpha / rank` as a Python float. Before, it was
rounded through a bf16 tensor, so numerics change only when `alpha /
rank` is not exact in bf16. No repo config has such a value.
- LoRA + MoE + EP (torch dispatch) now runs. On main the forward raises
`ImportError: cannot import name 'TOKEN_GROUP_ALIGN_SIZE_M'`.
- The LoRA startup log line reports adapter params, module count and
total params (no "adapted params" count).
## What I ran
- CPU differential check against main (fixed seeds, random nonzero A/B
and base weights, SDPA in place of flash-attn):
- layers (`LoRALinear` fp32/bf16, gated, non-gated and GPT-OSS experts
in bf16; alpha 32 and 16, dropout 0 and 0.1): init, output, input grad,
A/B grads and adapter state dict are bitwise equal;
- tiny llama (fp32), qwen3_moe and glm4_moe (bf16) with all default
targets: logits and every LoRA grad bitwise equal; gpt_oss: init and
adapter state dict bitwise equal; adapter keys, order and
`adapter_config.json` equal (minus `modules_to_save`).
- CPU EP check, 2-rank gloo, `TorchTokenDispatcher` +
`ExpertWeightParallel` as in `configure_moe_runtime`: qwen3_moe and
gpt_oss LoRA MoE outputs bitwise equal to the single-process run; LoRA
grads match within bf16 accumulation (max rel. 0.6%).
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/train tests/unit/inference -m "not gpu"`: 469 passed, 1
failed (`test_cpu_adam`, needs `ninja`; fails the same on main).
- `ruff check` and `ruff format --check`.
- GPU, 1 node, vLLM 0.31, main vs this PR (SLURM 3408). All 11 arms exit
0:
- `reverse-text-lora` RL start (15 steps) + resume (16-20): reward per
step matches main within noise (step 15: 0.80 main / 0.79 PR; steps
16-20: 0.74-0.84 both). Resume loads the step-15 checkpoint and
continues. Every `/load_lora_adapter` call returns 200.
- `reverse-text-sft-lora` start (5 steps) + resume (6-10) on 2 GPUs:
both run and resume from step 5.
- MoE LoRA (`samsja/mini-glm-moe`, 20 RL steps) at ep=1 on main and the
PR, and ep=2 on the PR: same reward range (about 0.19-0.23), adapter
loads return 200. The PR trains about 2x faster.
- SFT loss: the PR logs about 0.2 lower loss than main from step 2. This
is the compiled LoRA forward being more accurate, not a training
difference (seeded reruns: SLURM 3411/3413/3416 plus 1-GPU probes):
- With `model.compile=None`, the PR matches main: step 1 is bitwise
equal, steps 2-5 are within 0.005. On main, the data-dependent `assert`
in `MultiLoRALinear` breaks the compiled graph, so main's LoRA runs
eagerly. The PR's LoRA layers compile into the decoder layer. Neither AC
nor GPU count changes the gap. Dropout is not involved: it is 0 in this
config, and with dropout 0.1 the compiled layer still applies it
(outputs change with the seed, as in eager).
- In the compiled run, for the same params and batch, the compiled
forward gives exactly the training loss, but `force_eager` reads
0.14-0.21 higher. Read through the eager forward, the compiled-run
adapters match the eager run's (step 5: 6.179 vs 6.186). So training is
the same and only the forward reading differs.
- On the exact trainer batch after 2 updates: fp32 gives 5.827 (6.051
with B=0), compiled bf16 5.834, eager bf16 5.978. The eager bf16
forward, which main uses, loses about two thirds of the adapter's effect
while B is small. Most likely the bf16 rounding of `base_out + scaling *
lora_out` drops it; inductor fuses that add into the next op.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches core training (LoRA forward, MoE+EP, checkpoint keys, compile
behavior) and removes `modules_to_save`; exported adapters and RL smoke
tests were validated but old LoRA DCP checkpoints will not resume.
>
> **Overview**
> **Refactors LoRA from multi-adapter `MultiLoRA*` layers to a
single-adapter stack** (`LoRALinear`, `LoRAGroupedExperts`,
`LoRAGptOssGroupedExperts`), with scaling as `alpha/rank` on each module
and a unified `adapter_state_dict()` for vLLM/PEFT export.
>
> **Removes multi-adapter plumbing:** global `lora_num_tokens` / scaling
tensors, per-step `set_lora_num_tokens` in RL/SFT, the `lora_num_tokens`
micro-batch field, and LoRA re-permutation under expert parallelism
(dispatcher already permutes tokens). **Drops
`model.lora.modules_to_save`**—freezing is adapter-only via
`freeze_all_except_lora`—plus the related config validator and
`modules_to_save` in saved `adapter_config.json`.
>
> **Checkpoint/resume note:** LoRA DCP keys change from `lora_A.0` /
`lora_B.0` to bare `lora_A` / `lora_B`; exported filesystem adapters are
unchanged. MoE LoRA still uses 2D per-expert keys; the Qwen3.5 vLLM
patch comment now points at `LoRAGroupedExperts.adapter_state_dict`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
de7910fae985d3f1e56cd726150de08fa12bd80c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Qwen3.8's ngram table uses vocabulary-row shards, but deployed PyTorch
2.13 DTensor dense embedding backward allocates the full table gradient
on each rank. The 320,001,536 × 160 table would require a **95.37 GiB
BF16 gradient allocation per rank**.
Keep the original row-sharded weights and head mesh, and perform
`F.embedding` on plain local weights so backward allocates only local
rows. Route each flattened ID directly to the rank that owns it instead
of gathering everyone's IDs and computing masked lookups on every rank:
1. Sort local IDs to group them by row owner and exchange per-peer
counts.
2. Stack send/receive counts and copy both to CPU once; the stack
consumes the asynchronous count collective before its values become
split lists.
3. Send IDs to owners with variable-split all-to-all, and look up only
received local rows.
4. Return vectors with autograd-enabled all-to-all and restore local
token/head order with the saved permutation. Its backward sends vector
gradients back to the owners.
No token padding, clamping, non-owner masking or embedding-output
reduce-scatter is needed. Uneven vocabulary shards, empty row shards,
uneven/empty token batches and arbitrary input shapes are supported.
Sparse, frequency-scaled, max-norm and `padding_idx` embeddings fail
explicitly before partitioning; the Qwen ngram table uses none of these
modes.
Current `main` already routes ngram embeddings and expert biases to
AdamW through #4108. This PR retains that upstream optimizer behavior
and changes only the embedding lookup implementation.
Targets `main`, which already contains native text-only Qwen 3.8
support. The diff is limited to `embedding_parallel.py`; multimodal
support remains in #3916. Weight placement, parameter names and
row-shard checkpoint layout remain unchanged.
Companion #4102 bounds reconstruction memory during ngram weight
broadcast. This PR addresses lookup/backward allocations; it does not
avoid full-table gathering in weight transfer by itself.
Merged current `main` on 2026-10-16 to resolve the optimizer conflict
with #4108. The embedding implementation is unchanged (same tested
SHA-256 below).
### Latest validation
Allocated India H200 compute, job **2875**, deployed **PyTorch
2.13.0+cu130**. All compute ran on the allocated node, not the login
node. NCCL NVLS was disabled for the test after a separate attempt
failed during communicator initialization before lookup.
- **NCCL at 1, 2, 4 and 8 GPUs: 375 passing rank-case records.**
FP32/BF16 output and full-gradient parity against unsharded
`nn.Embedding`, equal/uneven token counts, one/all empty ranks,
vocabulary sizes not divisible by world size and empty row shards. Each
rank runs three AdamW updates with two microbatches, including
activation-checkpoint recomputation; updates match within FP32
tolerance.
- Instrumented lookup counts match exactly the number of IDs owned by
that rank. Dense backward receives only its local row count and returns
a plain local gradient. These checks also exercise completion of the
asynchronous count exchange before split lists are used.
- **Four-GPU FSDP:** BF16 computation over FP32 parameters/reduction;
outputs and full gradients match exactly across equal/uneven/empty
batches. AdamW updates and activation checkpointing pass. Distributed
model and optimizer checkpoint restore is exact, a subsequent update
matches the reference, and the saved weights load exactly through the
original rowwise partitioner.
- Additional four-GPU checks pass for a zero-row vocabulary with empty
input, int32 IDs, noncontiguous 3D inputs, 1D inputs and explicit
rejection of unsupported embedding modes.
- The unchanged Muon-to-AdamW exclusion was previously checked against
the baseline optimizer constructor on 12 parameter fixtures: trainable
ngram tables move to AdamW, other Muon/AdamW memberships and frozen
exclusions stay unchanged.
- Ruff, formatting and `git diff --check` pass. The tested module
SHA-256 is
`d26427312f5e3d5c2aba43dc7f03722e03e5c7f0f997918b6662075838ff9d4d`.
A separate four-GPU 65,536 × 1,024 FP32 table check confirms that
DTensor rowwise dense backward allocates **256 MiB**, while this
implementation's local backward allocates **64 MiB** per rank. For
Qwen's actual table at 16 ranks, the local BF16 gradient is
approximately **5.96 GiB per rank**, calculated from dimensions rather
than measured full-model memory.
### Lookup memory and time
Matched synthetic forward/backward benchmark: BF16 65,536 × 160 table,
**16,384 local tokens × 16 heads**, balanced row ownership, one H200
node, NCCL with NVLS disabled. Compared the previous
all-gather/mask/reduce-scatter implementation with the new owner-routed
implementation. Three warmups and ten timed iterations; wall time
includes count exchange and host synchronization. Reported values are
the maximum across ranks. Peak extra allocation includes lookup
temporaries, output and local dense gradient, excluding preallocated
weights and IDs.
| GPUs | Previous peak MiB | Owner-routed peak MiB | Previous
forward/backward ms | Owner-routed forward/backward ms |
|---|---:|---:|---:|---:|
| 2 | 331.0 | 248.0 | 5.76 | 2.44 |
| 4 | 661.0 | 249.0 | 13.71 | 4.45 |
| 8 | 1318.0 | 249.0 | 29.19 | 4.42 |
With balanced ownership, lookup buffers stay approximately constant as
world size increases in this measurement. **This is not a worst-case
guarantee:** sending all IDs to one owner raises its peak. At eight
GPUs, the deliberately skewed case measured **1,318.0 → 842.3 MiB** peak
and **32.36 → 6.84 ms** maximum forward/backward time. At two GPUs, the
skewed owner-routed peak was **332.0 MiB**, slightly above the previous
**331.0 MiB**. Deduplicating repeated IDs is a possible follow-up and is
not included here.
These are isolated embedding measurements, not full-model training
throughput or memory results. Full-model weight broadcast and
compiled-model integration remain unverified. Migration of optimizer
checkpoints whose ngram table previously belonged to Muon is not
covered; these tests also do not establish the cause of the separate
router-replay indexing failure.
Validation scripts and results are private under
`/data/nvme0/hubert/qwen38-embedding-oom-20261008/local-row-backward/owner-routed-20261013/`
and are not included in the diff. No live training run or shared
environment was changed.
The automated summary below describes an earlier commit.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Changes distributed embedding collectives and gradient accounting on
the training critical path; incorrect routing or autograd would silently
break parity or OOM large ngram shards.
>
> **Overview**
> Replaces vocabulary-parallel embedding forward/backward so **row-owned
IDs are all-to-all routed** and lookups run on **plain local weights**,
avoiding PyTorch 2.13 DTensor dense backward that would allocate a
full-table gradient per rank (critical for large ngram tables).
>
> The old **token-batch padding + RowwiseParallel prepare hooks** are
removed in favor of sort/bincount, variable-split `all_to_all` for IDs
and autograd-enabled return of vectors, then permutation restore to the
original token order. Unsupported embedding modes (`padding_idx`,
sparse, etc.) are rejected at apply time.
>
> **Optimizer:** `ngram_embedding` parameters are excluded from Muon and
trained with the existing AdamW group, same as token embeddings and
`lm_head`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7cfdedc8b267728bacae2b94bb435b906b9e86fa. 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: Codex <codex@local>
Removes ring attention context parallelism. Ulysses is now the only CP
implementation, so the `cp_style` option is gone.
- Deletes `layers/ring_attn.py`, `substitute_ring_attn`,
`substitute_gpt_oss_ring_attention`, the ring branches in `utils/cp.py`,
and the `ring-flash-attn` dependency plus its `_compat` shim.
- Removes `model.cp_style` and `resolve_cp_style`.
`setup_context_parallel` always installs the Ulysses attention patch.
`setup_cp_params` / `setup_cp_attention_params` lose their `cp_group`
and `cp_style` arguments.
- DeepSeek-V4 and GLM-5 DSA keep their model-internal CP: queries stay
sequence-sharded and keys are all-gathered inside the attention layer.
This never used the ring patch. For DeepSeek-V4, the KV all-gather is 1
KB/token (MQA, head_dim 512), and the sparse attention work is already
balanced. Ulysses would move 64 heads × 512 of queries and outputs each
way, and its kernels need ≥32 heads per rank, so DeepSeek-V4 stays on
the all-gather.
- `CPSupport` / `cp_support` becomes `cp_blocker(config, cp) -> str |
None`. The default rejects a `cp` that cannot shard the attention heads
at model setup, for example `cp=3 must divide the 32 attention heads and
divide or be a multiple of the 4 KV heads for Ulysses CP`. Before,
`cp_style="auto"` fell back to ring in this case. DeepSeek-V4 and GLM-5
DSA override it to `None`.
- Removes `cp_style = "ulysses"` from the example/advanced configs.
Configs that still set `cp_style` now fail validation.
**Breaking:** `trainer.model.cp_style` is removed. Models whose head
count is not divisible by `cp` can no longer use CP.
Related open PRs:
- #4068 changes how ring attention params are passed. This PR deletes
that code path.
- #3446 defers the ring-flash-attn imports. This PR removes the
dependency.
- #3724 touches CP padding in `utils/cp.py` / the train loops. Expect
conflicts in `setup_cp_params` call sites.
- #4057 (DeepSeek-V4.1) overrides `cp_support` with an empty style set.
After this PR, that override becomes `cp_blocker` returning its reason.
### Validation
SFT, 5 steps, real weights truncated to 4 layers, fake packed
variable-length data (seq_len 16384, batch 4). Each run is `main` vs
this PR on 4 H200s each, with the same seed. On `main`,
`cp_style="auto"` resolved to Ulysses for the FlashAttention models and
to ring (the KV all-gather) for DeepSeek-V4.
| model / CP | loss main | loss PR | max Δloss main vs PR | max Δloss
main vs main | max rel Δ grad norm main vs PR | max rel Δ grad norm main
vs main | peak mem main / PR |
|---|---|---|---|---|---|---|---|
| Qwen3-30B-A3B, cp=2 (Ulysses) | 16.4002 16.2154 16.0340 15.7772
14.8917 | 16.4002 16.2157 16.0356 15.7765 14.8915 | 0.0016 | 0.0018 |
0.84% | 0.99% | 14.6 / 14.6 GiB |
| GLM-4.5-Air, cp=4 (Ulysses) | 15.3254 14.8527 13.9303 13.5545 12.9239
| 15.3254 14.8528 13.9303 13.5546 12.9235 | 0.0004 | 0.0001 | 0.20% |
0.17% | 40.6 / 40.6 GiB |
| GLM-5.3 DSA, cp=4 (own KV all-gather) | 13.3890 13.3431 13.2668
13.2369 13.1076 | 13.3890 13.3431 13.2667 13.2369 13.1076 | 0.0001 |
0.0001 | 0.03% | 0.01% | 81.3 / 81.3 GiB |
| DeepSeek-V4-Flash, cp=2 (own KV all-gather) | 20.2111 19.9461 19.3640
19.2330 18.6930 | 20.2111 19.9463 19.3641 19.2329 18.6930 | 0.0002 |
0.0001 | 0.04% | 0.07% | 124.1 / 124.1 GiB |
"main vs main" is a second pair of `main` runs from the same configs and
seed. In every model, the main-vs-PR deltas are within or near that
run-to-run noise. Step 1 loss is identical in every run. The Qwen3-30B
step-1 grad norm ranges 254.31–255.22 across all four of its runs.
Tests:
- `pytest -m "not gpu"` on tests/unit/orchestrator,
tests/unit/test_configs.py, tests/unit/train, tests/unit/utils: all pass
except
`test_cpu_adam.py::test_native_cpu_adamw_matches_fused_torch_and_preserves_gradients`,
which fails on `main` too.
- GPU: `test_gpt_oss.py -k context_parallel` (torchrun ×2, Ulysses with
sharded sinks), `test_deepseek_v4_kernels.py -k context_parallel` (12
passed), `qwen3_5/test_model.py` (5 passed).
- `ruff check` / `ruff format`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Breaking distributed-training behavior: removes `cp_style` and ring
fallback, so invalid `cp` vs head counts now error instead of using
ring; large deletion in the CP/attention stack affects all long-context
training jobs.
>
> **Overview**
> **Removes ring context parallelism** so Ulysses is the only trainer CP
path: deletes `ring_attn.py`, ring attention patching, the
`ring-flash-attn` GPU dependency, and related `_compat` shims.
>
> **Config and API cleanup:** Drops `trainer.model.cp_style` and
`resolve_cp_style`; `setup_context_parallel` always installs Ulysses.
`CPContext` no longer carries a style; `setup_cp_params` /
`setup_cp_attention_params` no longer take `cp_group` or `cp_style`.
Example/advanced TOMLs lose explicit `cp_style = "ulysses"`.
>
> **Validation model change:** `CPSupport` / `cp_support` becomes
`cp_blocker(config, cp) -> str | None` on model classes—the default
enforces Ulysses head-sharding rules at setup (configs that previously
relied on `cp_style="auto"` falling back to ring will now fail).
DeepSeek-V4 and GLM-5 DSA override with `None` because they keep
**model-internal** CP (sequence-sharded queries, all-gathered keys),
unchanged by this refactor.
>
> Docs in `scaling.md` are updated to describe Ulysses-only CP and
sparse-attention all-gather behavior instead of ring vs Ulysses.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c167f0582d2c9d677b3c4440fcf53d1d6bfbfcc5. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
A trainer rank that raises now exits right away with code 1 instead of
hanging until the NCCL watchdog.
`clean_exit` called `dist.destroy_process_group()` in its `finally`,
also after an exception. When the failing rank still has a collective in
flight that the other ranks never join (e.g. a reduce-scatter in the
final backward), that call waits for it. Interpreter exit also joins
background threads, which can wait on the same collectives. So the rank
stays alive, torchrun and `srun --kill-on-bad-exit` never see a failure,
and the job hangs until the NCCL watchdog fires (1 h with the default
timeout).
Now a process with an initialized process group logs the error, finishes
wandb, flushes the logs and calls `os._exit(1)`. Processes without a
process group (orchestrator, env server) still exit with `sys.exit(1)`
as before. The success path is unchanged.
Seen on a 64-rank GLM-5.3 run: 15 ranks raised `TimeoutError: Timed out
acquiring a D2H slot` (offload pipeline) at 07:30 and logged `Fatal
error in train`, but stayed alive until the watchdog's SIGABRT at 08:30.
Repro (2 H200s, torchrun, 300 s timeout): rank 0 starts an `all_reduce`
that rank 1 never joins (rank 1 sleeps), then raises.
| | rank 0 exits | torchrun |
|---|---|---|
| main | no (hangs) | killed by the timeout after 300 s |
| main, plus a background thread that never finishes | no (hangs) |
killed by the timeout after 300 s |
| this PR | yes | exits with 1 after 20 s |
| this PR, plus that thread | yes | exits with 1 after 22 s |
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes fatal-error shutdown for distributed training ranks; wrong
branching could skip cleanup or exit non-distributed processes
incorrectly, though non-PG paths are preserved.
>
> **Overview**
> When a **sync** trainer rank hits a fatal error and
`torch.distributed` is initialized, `clean_exit` now flushes logging and
calls **`os._exit(1)`** instead of only `sys.exit(1)`. That skips the
normal teardown path where `destroy_process_group()` and interpreter
shutdown can block on NCCL collectives other ranks never join, so
**torchrun / `srun --kill-on-bad-exit` see a fast failure** instead of a
long hang until the NCCL watchdog.
>
> Process-group checks are centralized in
**`_process_group_initialized()`** (lazy lookup via `sys.modules`, no
extra torch import). Ranks without a process group (orchestrator, env
server, eval) still use **`sys.exit(1)`**; success and async paths are
unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6a44ee943b88c7e71ac2a614d951d341e9ba62b5. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Turns on Nesterov momentum for Muon by default.
## What changes
- `MuonConfig` gets `nesterov: bool = True`. It is passed to dion's
`Muon`, whose own default is `False`.
- This changes the default for every SFT and RL run that uses Muon. Set
`optim.nesterov = false` to get the old behavior.
- Resuming works: the momentum buffers are the same with and without
Nesterov; only the update read from them differs.
## Why
- In our pretraining runs (MoE, d=384, Muon), Nesterov lowered the final
loss by 0.0128 ± 0.0017 nats, paired over 4 seeds and several learning
rates. These are internal, unpublished experiments.
- Keller Jordan's Muon and Moonlight use Nesterov momentum.
- dion's own reference implementation (`muon_reference`) defaults to
`nesterov=True`.
The effect on SFT and RL fine-tuning has not been tested.
## Validation
- Ruff passes. The config and SFT unit tests pass (366).
- SFT smoke run with Muon on 1 GPU (`configs/debug/fake/sft.toml`,
Qwen3-0.6B, lr 1e-3, 20 steps, H200): trains without errors, `nesterov =
true` in the resolved config, loss 8.46 at step 1 and 6.61 at step 20
(noisy on the fake data: 4.80 at step 12, 8.37 at step 14).
`debug.force_balanced_routing` did not reach DeepSeek-V4's hash-routed
layers (the first `num_hash_layers`, 3 for V4-Flash). Those layers
always read `tid2eid[input_ids]`. With `debug.random_init` that table is
all zeros, so every token sent all 6 of its picks to expert 0. One EP
rank then did all expert work for those layers, and the other ranks
waited.
Now a hash layer uses the round-robin assignment when `force_balanced`
is set, like every other MoE layer. Real checkpoints and router replay
are unchanged.
Measured on 1x8 H200: DeepSeek-V4-Flash shape, random init, 8 layers,
seq 65536, cp 2, ep 8, AC + compile, 2 micro-batches per dp rank.
- Step: 17.4 s -> 11.1 s.
- Peak memory: 133 -> 112 GiB.
- Before the fix, the trace showed ~350 ms host stalls in FSDP
post-backward. These were allocator map/unmap churn near the memory
limit.
Any earlier fake-data DS-V4 step time measured with random init
over-states the MoE cost.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Single guard on a debug/benchmark routing path; production hash
routing with loaded `tid2eid` is unchanged.
>
> **Overview**
> **Hash-routed** DeepSeek-V4 MoE layers no longer always pull expert
indices from `tid2eid[input_ids]` when `routed_experts` is unset. They
skip that lookup when `self.router.force_balanced` is on, so
`debug.force_balanced_routing` uses the same round-robin expert
assignment as other MoE layers.
>
> Replayed `routed_experts` and real checkpoints (non–`force_balanced`)
behave as before.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
09ad26d84c6ac5da60424737caddd26e5546435b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Use ulysses CP in the recipes that set `cp > 1` and still use the ring
default: INTELLECT-3.1 RL (cp=2), Qwen3-30B-A3B SWE (cp=2), MiniMax-M2.5
SWE (cp=4), all at 131K, and Qwen3-30B-A3B tool (cp=2, 32K). GLM-5.3
also uses the ring default, but its sparse MLA attention gathers K for
CP itself and does not read `cp_style`, so it is left alone.
Ring CP splits each sequence contiguously and all-gathers K/V, so CP
rank r computes about (2r+1)/cp of the causal work, and all ranks wait
for the last rank. Ulysses shards heads, so every rank does the same
causal work. All three models (the tool recipe uses the same
Qwen3-30B-A3B) use the shared `FlashAttention`, support both styles, and
have head counts that divide by cp: 32/4 (Qwen3-30B-A3B), 96/8
(GLM-4.5-Air base), 48/8 (MiniMax-M2.5).
## Measurements (1 node, 8xH200, FA3)
Trainer, Qwen3-30B-A3B, recipe layout: `ep=8 cp=2`, seq_len 131072,
compile + full AC + AC offload (5 in flight), fake data with 2
micro-batches per DP rank. Steady state is the mean of steps 3-6.
| data | ring step (s) | ulysses step (s) | change | peak mem ring /
ulysses (GiB) |
|---|---|---|---|---|
| one 131K sequence per micro-batch | 106.3 | 83.4 | **-21.5%** | 114.6
/ 121.8 |
| packed 1-16K docs (`generate_samples`) | 37.1 | 37.7 | +1.5% | 125.3 /
125.8 |
Step-1 metrics agree within bf16 noise (grad norm 0.00369 vs 0.00375,
entropy 5.0659 vs 5.0671, mismatch KL 6.2119 vs 6.2126).
Attention fwd+bwd per layer, 131072 tokens, through the trainer's
`ring_varlen_attention` and `ulysses_flash_attn_varlen_func`. Times are
in ms; packed means 4 lognormal docs with a median of about 22K:
| shape (q/kv heads) | cp | single ring / ulysses | packed ring /
ulysses |
|---|---|---|---|
| Qwen3-30B-A3B (32/4) | 2 | 571 / 386 | 197 / 170 |
| GLM-4.5-Air (96/8) | 2 | 1710 / 1143 | 587 / 499 |
| MiniMax-M2.5 (48/8) | 4 | 503 / 292 | 220 / 127 |
The per-layer gap predicts the trainer gap. For a single 131K sequence
it is 185 ms x 48 layers x (fwd+bwd + AC re-forward) x 2 micro-batches,
about 24 s per step; we measured 23 s. Short packed documents gain
nothing, because their imbalance is small and the all-to-all costs about
the same as the saved work.
The tool recipe runs at 32K and was not measured. Each sequence is
shorter, so the gain should be smaller than at 131K.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Config-only change to an existing CP mode; training numerics were
checked to match within bf16 noise for the benchmarked setup.
>
> **Overview**
> Sets **`cp_style = "ulysses"`** on four advanced training recipes that
already use context parallelism (`cp > 1`) but were still on the default
**ring** CP path: MiniMax-M2.5 SWE (`cp = 4`), INTELLECT-3.1 RL (`cp =
2`), Qwen3-30B-A3B SWE (`cp = 2`), and Qwen3-30B-A3B tool (`cp = 2`).
>
> This is a recipe-only switch to Ulysses head sharding (balanced causal
work per CP rank) instead of ring contiguous splits (skewed work and
straggler ranks). No trainer or model code changes in this diff; GLM
recipes that ignore `cp_style` are unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
892b9e1649269f281224c60a6626c539ef3427b6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Make the token-length-weighted reward baseline the only baseline for
GRPO and its ECHO subclass. Always compute `sum(L_i * R_i) / sum(L_i)`
over trainable tokens after optional length shaping, and remove the
`length_weighted_baseline` configuration flag and plain-mean branch.
Update the algorithm descriptions and existing advantage tests to check
token-weighted centering, including unequal rollout lengths, multiple
turns, observation exclusion, and length penalties.
Validation: all 41 advantage and algorithm tests pass using the PR's
pinned verifiers/renderers sources and a temporary PyTorch overlay. Full
pre-commit checks pass. Direct config checks confirm GRPO/ECHO expose no
baseline flag and reject the removed opt-out. The broader config suite
has failures due to taskset packages missing from the local environment.
Bump the `dion` pin from `6f9242d` to `0c801b0`, the fork's current
`main`, which adds samsja/dion#6 and routes MoE expert biases to AdamW
so gpt-oss keeps working with Muon under EP. The fork rewrote its `main`
history, so the old pin is no longer on `main` and could stop resolving.
- Muon now orthogonalizes EP- and FSDP-sharded expert weights locally
instead of padding them through an all-to-all.
- Muon now raises on the 2D expert biases of gpt-oss and Nemotron-H
(`mlp_bias`) under EP; at the old pin they got silently wrong updates.
`muon_enabled` now sends `mlp.experts.*_bias` to AdamW.
- The Qwen3.8 ngram embedding table also moves from Muon to AdamW,
matching token embeddings.
- Resuming a Muon checkpoint for these models from before this PR fails
on missing optimizer keys; use `ckpt.skip_optimizer=true`.
## Verification
SFT with Muon on 1 node of 8 H200s, fake data, 20 steps. "Pin only" is
`9377b31d2`, the dion bump without the routing change. The harness
(configs and a CPU routing probe) is in `bc85b74ec` on
`exp/bump-dion-verification`, removed in the next commit.
| Run | Commit | Result |
| --- | ------ | ------ |
| gpt-oss-20b, EP 8 | pin only | `ValueError: Parameter is sharded over
ranks [0..7], but Muon communicates over ranks [r]` |
| gpt-oss-20b, EP 8 | tip | trains, 2.5 s/step, 33.1 GiB peak |
| Qwen3-8B, `dp_replicate=2`, `cp=2` | tip | trains, passes dion's
shard-rank check |
- The probe shows only expert biases (gpt-oss, Nemotron-H) and
`ngram_embedding` (Qwen3.8) change groups.
- gpt-oss without EP also changes: its expert biases used to get Muon
updates and now get AdamW.
- 2-node layouts were not rerun here. samsja/dion#6 benchmarks them.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Qwen3.8's CPU-offloaded PLE embedding loads successfully, but its first
checkpoint-format weight reload can OOM: vLLM records the default CUDA
device as the restore device and materializes the CPU table's
replacement on GPU. Our TP4 H200 startup failed trying to allocate
another 23.84 GiB per rank despite the original table residing in pinned
CPU memory.
Before loading PLE chunks, use the saved original weight's CPU device as
the layer's restore device. This leaves initial loading, GPU-resident
embeddings and existing TP overlap filtering unchanged. vLLM copies the
result into the original pinned storage, preserving UVA references. No
dependency or quantization changes.
Measured with vLLM 0.31.0 on four H200s, native Qwen PLE
storage/loaders, TP4, 128 checkpoint fragments and three reloads per
variant per rank (36 rank-reloads total). The reduced-size table is
80.08 MiB per rank:
| Measurement, per rank | Existing CPU-offloaded reload | Fixed
CPU-offloaded reload |
| --- | ---: | ---: |
| CUDA allocation for replacement table | 80.08 MiB | 0 MiB |
| Peak extra CUDA allocation during reload | 160.16 MiB | 80.08 MiB |
| Median reload time | 10.54 ms | 78.62 ms |
The change trades GPU allocation for CPU materialization/copy work; it
is an OOM fix, not a demonstrated speedup. GPU-resident controls retain
the original 160.16 MiB peak and CUDA placement. Every reload preserved
exact values, original storage identity and placement; CPU weights
remained pinned and UVA lookup results matched. Malformed shard
validation and patch idempotence also passed. Ruff check/format and diff
checks passed. Validation scripts and raw measurements are kept
privately, outside this PR.
Full-model India restart completed its startup weight reload on all
twelve inference ranks and entered the base evaluation (198 episodes).
All three engines subsequently generated the correct answer `4` to a
direct `2 + 2` probe. First-call latencies were 72–74 seconds during
cold sampling-kernel compilation and concurrent evaluation; these are
functional checks, not a steady-state latency benchmark. No inference
OOM occurred. Settings remained unchanged, including GPU utilization
0.75. All ranks received all 177 streamed state dictionaries; the
orchestrator waited for startup synchronization from 17:11:53 to
17:16:02 UTC (249 seconds, including the full model transfer/reload, not
isolated PLE timing).
Read-only `nvidia-smi` sampling every 10 seconds across all twelve
inference GPUs measured:
| Inference engine | Maximum sampled GPU memory used | Minimum sampled
GPU memory free |
| --- | ---: | ---: |
| Engine 1 | 131.80 GiB | 8.00 GiB |
| Engine 2 | 131.81 GiB | 7.99 GiB |
| Engine 3 | 131.91 GiB | 7.90 GiB |
Post-cache, pre-reload usage was approximately 106.2–106.3 GiB per GPU.
These production values are NVML device usage, including
allocator-reserved memory; they are sampled peaks, not exact PyTorch
allocation peaks. The small regression above measures exact PyTorch
allocation. Received-weight buffers remain on GPU, so the CPU fix does
not eliminate reload staging or justify increasing utilization from
steady-state headroom alone.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches hot-path weight reload for Qwen PLE embeddings; wrong
`restore_device` handling could break reload correctness or memory
placement, but scope is narrow and gated on CPU original weights.
>
> **Overview**
> Extends the Qwen3.8 PLE `load_weights` monkey-patch so
**CPU-offloaded** n-gram embedding tables keep their placement on
checkpoint reload. Before delegating to vLLM, it reads layerwise reload
metadata and, when the saved original `weight` is on CPU, sets
**`restore_device`** to that CPU device instead of letting vLLM default
to CUDA.
>
> That stops the first reload from allocating a full GPU replacement
table (OOM on large TP setups) while leaving GPU-resident embeddings and
existing TP shard overlap filtering unchanged. The docstring now
documents both behaviors and the upstream vLLM fixes this patch is
waiting on.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
93094ba98549f5d155cdae5e95c3dc8cce79f1c2. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Completed rollout groups with no training signal could keep large
episode graphs alive until another batch shipped. This PR records their
scalar statistics when the group finishes and releases the discarded
graph immediately. Queued, stale, pruned, and cancelled traces release
their references at the appropriate boundary.
Training metrics remain batch-aligned: each shipped batch emits one
record with both all-rollout (`train/*/all`, including
rejected/error/cancelled groups) and shipped-trace (`train/*/effective`)
statistics. Exact percentile observations and rate denominators are
retained. Training charts use custom `step`; `rollout/window` existed in
an intermediate PR revision but was published by neither pre-PR main nor
this revision.
Shutdown synchronizes with pending admissions before cancelling groups,
including attempts that were reserved but never dispatched. Archive turn
counts now exclude copied assistant history; existing saved indexes need
rebuilding to correct older counts. The current trainer-requested
filesystem/ZMQ batch handshakes are preserved.
### Validation
- [CPU CI after merging
main](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/38550476797):
**803 passed, 1 skipped**; affected-area checks: **130 passed, 1
skipped**. A paired replay of 50 scenarios matched 412,085 metric
values, shipped samples, and step counters against the previous
implementation.
- Nebius Qwen 3.5 smokes resumed the same step-110 checkpoint. The table
covers completed steps **111–119**. A monitor sampled the orchestrator
process's proportional set size (PSS) on its compute node and probed
event-loop lag every 50 ms. Max stall is the longest observed lag.
| Smoke | Orchestrator PSS mean / peak | Mean event-loop lag | Max stall
|
| --- | ---: | ---: | ---: |
| [4190: with #3806
stack](https://wandb.ai/primeintellect/perplexity-qwen-travel/runs/3cba96dda403413eae860e28bc8d432d)
| 65.2 / 210.7 GiB | 6.44 ms | 13.97 s |
| [4192: without #3806
stack](https://wandb.ai/primeintellect/perplexity-qwen-travel/runs/c1716a73a0924f86b77e4c96d6f2f29c)
| 68.9 / 181.5 GiB | 5.83 ms | 60.00 s |
An earlier three-update smoke checked the integrated runtime separately:
| Smoke | Stack | Completed steps | Max full-run event-loop lag |
| --- | --- | ---: | ---: |
|
[3761](https://wandb.ai/primeintellect/perplexity-qwen-travel/runs/e4ceddff45d84e45a9342075dddd3918)
| #3806; no #3811/#3821/#3822 | 96–98 | 78.48 s |
|
[3762](https://wandb.ai/primeintellect/perplexity-qwen-travel/runs/2a464e25d2a0417ca1e9b19f61f2f1fc)
| #3806 + #3811/#3821/#3822 | 96–98 | 4.84 s |
In the newer pair, 4190 used #3811/#3821 through this PR while 4192 did
not; neither used #3822. Both kept the same other model/runtime PRs,
fractional rewards, and 2 trainer + 2 inference nodes. The with-stack
run had lower mean PSS and shorter worst stalls, but higher peak PSS and
slightly higher mean lag. The older full-run lag includes startup; the
newer table is step-scoped. These are independent rollouts with bundled
changes, so neither pair isolates #3806 or proves a memory or speed
improvement.
---------
Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
CUDA scatter-add can combine a token's MoE expert contributions in
different orders, making identical frozen trainer forwards produce
different logprobs. This change restores each contribution to its
original token/route slot, then sums each token's expert outputs in FP32
in a fixed route order.
The existing expert-sort permutation is retained in dispatcher state.
Input lookup still uses `route_index // top_k`; combine uses the full
unique route index to undo expert sorting, reshapes to `[num_tokens,
top_k, hidden_dim]`, and reduces the expert axis. Each destination row
is written once. FP16/BF16 outputs accumulate in FP32 and are cast back;
FP32/FP64 retain their accumulation dtype. Existing score multiplication
and contribution rounding are preserved.
No additional sort or global deterministic-algorithm setting is
introduced. Local/Torch dispatchers and the MXFP8 Torch subclass use
this combine; DeepEP's separate combine is unaffected. The diff changes
only `token_dispatcher.py`.
### Validation
Restored the implementation and comments from `0fbfb1f`. Its executable
AST matches the GPU-tested implementation `f518827` exactly. Validation
tests are retained locally and excluded from the PR diff.
Allocated India H200 compute, job 2868, PyTorch 2.13.0+cu130:
- **72 passed, 7 skipped**: CPU/CUDA combine and existing MoE tests,
forward/backward, FP16/BF16/FP32/FP64, top-k 1/2/8, cancellation, empty
inputs and gradcheck. Skips were optional SonicMoE cases.
- Two-GPU NCCL EP2 forward/backward passed with unequal token counts and
a zero-token rank, with scores applied before or after experts; input,
score and expert gradients matched references.
- Real archived combine input repeated exactly in eager and
full-graph/dynamic compiled execution, and eager/compiled outputs
matched. Input gradients matched exactly; compiled score-gradient
maximum absolute error was **1.2e-7**.
- On restoration, verified exact file equality with `0fbfb1f`,
executable AST equality with `f518827`, Ruff lint/format and `git diff
--check`. GPU experiments were not rerun for this byte-identical
restoration.
### Frozen-model replay
Same archived one-image response, 423 generated tokens; frozen
pretrained **Qwen/Qwen3.5-122B-A10B**, model revision
`dc4d348443bc740c68e2d77492492c11606384d5`, CP4/EP8 on 16 H200s. The
code baseline is parent `main` commit `4487ef3`. Initial
parameters/buffers on every rank, token IDs, pixels/image grids,
recorded routes, scoring alignment and inference-logprob reference were
independently checked against the baseline. No optimizer updates; model
compilation and activation checkpointing disabled.
| Implementation | Mean sampled-token mismatch KL | Repeatability |
|---|---:|---|
| Parent main: atomic BF16 scatter | 0.000757466 | All 48 within-rank
repeat comparisons differed |
| This PR: restore route slots + FP32 sum | **0.000676875** | All 423
response scores bitwise identical across 16 ranks and 3 forwards |
| Scoped deterministic FP32 scatter candidate | 0.000721250 | All 423
response scores bitwise identical across 16 ranks and 3 forwards |
Means pool four independent replica groups over three forwards, with the
same 423 tokens per response. Every saved per-token value was recomputed
as `expm1(trainer_logprob - inference_logprob) - (trainer_logprob -
inference_logprob)`. This is the sampled-token mismatch estimator, not
full-vocabulary KL. The **10.6% reduction versus atomic scatter** is
specific to this frozen response and does not establish the cause of KL
growth during training.
### Combine timing and memory
Matched H200 benchmark, 2,231 tokens × top-k 8 × hidden 3,072, BF16; 40
warmed calls timed with CUDA events. Compilation, sorting, inputs and
model weights are excluded. Memory is peak additional allocated memory
for outputs and temporaries.
| Scores applied | Execution | Atomic scatter ms / MiB | This PR ms /
MiB | Scoped FP32 scatter ms / MiB |
|---|---|---:|---:|---:|
| After experts | Eager | 0.487 / 420.0 | 0.718 / 420.0 | 0.803 / 420.1
|
| After experts | Compiled | 0.328 / 13.1 | **0.467 / 117.7** | 0.515 /
394.1 |
| Before experts | Eager | 0.085 / 26.1 | 0.313 / 143.8 | 0.403 / 288.6
|
| Before experts | Compiled | 0.319 / 13.1 | 0.452 / 117.7 | 0.407 /
288.6 |
The restored-slot buffer scales with `num_tokens × top_k × hidden_dim`.
This implementation avoids a full FP32 copy of the contributions: the
reduction converts values as it consumes them. It uses less temporary
memory than the scoped FP32 scatter candidate, but remains more
expensive than the original atomic scatter. Timing depends on score
placement; these are combine-only measurements. A full compiled trainer
update and end-to-end training throughput/memory have not been
validated.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes MoE output aggregation on the training hot path (numerics and
repeatability vs prior atomic scatter), with a modest
combine-time/memory cost; DeepEP combine is untouched.
>
> **Overview**
> Replaces MoE **combine**’s CUDA `scatter_add` with a deterministic
path: keep full per-token route slot indices through dispatch, undo
expert sorting by writing each expert row once into a buffer, then sum
`[num_tokens, top_k, hidden]` in **FP32** (for FP16/BF16) before casting
back.
>
> Dispatch still gathers token inputs with `route_index // top_k`; state
and APIs rename `token_indices_experts_sorted` →
`route_indices_experts_sorted`. `_scatter_routed_output` becomes
`_combine_routed_output`, with an early return when `num_tokens == 0`.
**Local**, **Torch**, and **MXFP8** token dispatchers share this
combine; score-before/after-expert behavior is unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d45d8194d17b6aea0eb9ed2dd288e249af9a55e1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
The prefix-cache salt for live-policy requests is
`str(policy_version_at_start)`. After a trainer crash and resume from an
earlier checkpoint, policy versions repeat with different weights. If
the inference engines (kept alive by the fault-tolerance work, or run as
their own job) or a persistent KV offload pool (Mooncake / native
offload) outlive the restart, a new group at version `v` gets the same
salt as the crashed attempt's version `v`. It can then hit or reload KV
computed with the old weights. Nothing reports this.
The salt is now `<attempt>-<version>`. `attempt` is a random id made
once per dispatcher, i.e. once per orchestrator process. It is the same
for all groups and turns of one attempt and differs after any restart.
In-flight rollouts do not survive an orchestrator restart, so no
reusable cache is lost. `PRL_RUN_ID` is not used because it is the run
identity: it can be the same across resumes.
Same approach as the salt part of #3997 (closed).
## Checks
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 341 passed.
- `ruff check` / `ruff format --check`: clean.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how live-policy inference keys prefix cache, which affects
training correctness after fault-tolerant restarts, but the scope is
limited to salt formatting in the dispatcher.
>
> **Overview**
> **Fixes incorrect prefix-cache reuse after an orchestrator restart**
when policy version numbers repeat but weights differ (e.g. resume from
an earlier checkpoint). Live-policy rollouts that use a changing weight
set previously keyed prefix cache only on `policy_version_at_start`, so
engines or a surviving KV offload pool could serve KV from the crashed
attempt.
>
> Each dispatcher now generates a one-time `cache_salt_prefix` (8 hex
chars) at init and sets `cache_salt` to
`{prefix}-{policy_version_at_start}` instead of the version alone. The
prefix is shared for all groups in that process and changes on any
orchestrator restart; frozen-policy train paths still pass
`cache_salt=None`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
afc171d0a08cafadd29526cb33b7b95c52c19183. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Bumps the **renderers** and **prime-envs** submodules to latest main and
moves the first-party pins to their released floors (**verifiers
0.4.0**, **renderers 0.1.12**). Re-landed on current main: the previous
version of this PR conflicted with the v0.10.0 release.
| dep | from | to |
|---|---|---|
| verifiers | `e888a71` (main's pin) | unchanged; pyproject floor ->
released `>=0.4.0` |
| renderers | `ca029b5` | `5d870d8` (main) |
| prime-envs | `89dcc7f` | `91d7d15` (main) |
**Why verifiers stays at main's pin instead of the `v0.4.0` tag:**
main's pin is v0.4.0+12: it carries
[#2778](https://github.com/PrimeIntellect-ai/verifiers/pull/2778)
(packed CSR sampling-mask decoding), which the packed per-token
`/generate` payloads from #3900 require. Pinning the tag exactly would
break router-replay runs: the tag's `SamplingMask.from_sampling_mask`
only accepts the one-list-per-token form, while `/generate` emits packed
`{ids, counts}`. So this PR holds verifiers where main has it (the 0.4.0
line) and only raises the floor to the released `0.4.0` — no new
verifiers commits; the unreleased refactors past main (task workspace
deployments #2833, agentic judging in the selected workspace #2832,
verification into the rollout lifecycle #2830, Runtime view split from
provider backends #2827) stay out.
What comes in:
- **renderers** (1 commit): GLM-5.3 Flash renderer with image support
(#191)
- **prime-envs** (9 commits): HLE variants and ALE CLI evaluation
adapter (#979), require verifiers 0.4.0 across all environments (#983),
fix lean memory for isolated proof grading (#986), fix nl2repobench
offline VM image selection (#985), fix lab Prime image namespace (#984),
fix terminal-bench-2 repaired QEMU task images (#974), fix swe staged
task inputs for Harbor 0.24 (#975), remove pi-terminal-bench-2 (#973),
speed up pull request smoke tests (#976)
**Workspace change:** `deps/prime-envs/environments/office/ale_cli` is
excluded from the workspace. It requires `numpy>=2.4.4` (via the
agents-last-exam `tasks` package), and vLLM 0.31.0 requires `numpy<2.4`
via `mistral-common`, so it can't share the lock (same treatment as
tau2/apex).
The lock changes only first-party packages: env versions move (deep-swe
0.1.2, hle 0.3.1, swe-sweep 0.1.1, terminal-bench-2 0.1.1;
pi-terminal-bench-2 removed) and envs align on `verifiers>=0.4.0` with
explicit `datasets>=3.0.0`. No third-party version moved.
Validated locally: `uv lock` resolves and `uv lock --check` is clean;
CPU unit tests pass against the bumped sources (`uv run pytest
tests/unit -m "not gpu"`: **827 passed, 1 skipped, 236 deselected**).
Not yet run: GPU/integration CI and a sandboxed RL smoke run.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Wide verifiers 0.4 rollout and workspace exclusion affect every env in
the shared lock; upstream changes to verification and task workspaces
may change RL/eval behavior even though prime-rl source is mostly
unchanged.
>
> **Overview**
> Bumps first-party training stack deps to released floors:
**`verifiers[harbor]>=0.4.0`** and **`renderers[multimodal]>=0.1.12`**
(dropping dev pre-release pins), with **`uv.lock`** refreshed so
workspace env packages match.
>
> **Workspace:** **`deps/prime-envs/environments/office/ale_cli`** is
added to **`tool.uv.workspace` `exclude`** because its numpy floor
conflicts with vLLM’s numpy cap—same pattern as tau/apex envs.
>
> **Lock alignment:** Editable prime-envs now require
**`verifiers>=0.4.0`**; many dataset-driven envs also declare explicit
**`datasets>=3.0.0`**. **`pi-terminal-bench-2`** drops out of the
workspace/lock; a few env package versions tick up (e.g. **deep-swe**,
**hle**, **swe-sweep**, **terminal-bench-2**). No third-party PyPI
version churn beyond first-party metadata in the lock.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b9750ab87eda9b56cfc37e6e12f6d50733d31b96. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
vLLM serves DeepSeek V4 with an FP8 KV cache, and its attention reads
keys and values only from that cache, so the trainer scored tokens
against slightly different K/V than the rollout policy did. The trainer
now reads the same K/V as vLLM 0.31.0, bit for bit, by default:
`model.dsv4_kv_precision = "bf16"` opts out, and other models ignore the
field.
- The sliding-window and CSA/HCA compressed KV go through `fp8_ds_mla`
fake quantization, with a straight-through gradient.
- vLLM floors the amax on its window writes and the scale on its
compressor writes, and we mirror both.
- Not gated: the DSv4 indexer's FP8 amax floor moves from `1e-10` to
vLLM's `1e-4`. GLM keeps `1e-10`.
Verification: GPU tests at `cfee2aeeb` checked that the outputs exactly
equal vLLM's sliding-window insert and CuTeDSL compressor store on
edge-case tiles (zero tiles, amax below either floor, amax exactly `448
* 2^k`), and that the gradient passes straight through, eager and
compiled. They passed on H200 after the rebase onto `main`, and
`8ede47596` drops them to keep the suite lean.
Op time on H200 (do_bench median, lower is better), against a bf16 clone
of the same tensor:
| input | fake quant | bf16 clone |
|---------------------------------|------------|------------|
| SWA kv, 4096 tokens per GPU | 0.008 ms | 0.007 ms |
| SWA kv, 14336 tokens per GPU | 0.014 ms | 0.013 ms |
| CSA compressed kv, 3584 entries | 0.008 ms | 0.007 ms |
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Router replay now works with disaggregated P/D on vLLM 0.31, together
with sampling replay. It replaces main's config rejection of router
replay + P/D.
**Problem on 0.31.** vLLM 0.31 captures routed experts through the
AuxOutput connector (V2 runner only, vllm#45635) and rejects P/D
connectors (`_verify_aux_output_compatibility`). The rejection is real:
a decode (D) instance never computes a remotely prefilled prompt, so its
worker would try to materialize the prompt rows from its block store
(`BlockObjectStoreError`), and D's first forward (token `prompt_len-1`)
starts mid-block, which the routed-experts buffer rejects.
**Fix (plugin patch `monkey_patch_routed_experts_with_pd_connectors`,
our upstream AuxOutput patch 02):**
- Config: skip only the P/D connector check when the KV transfer config
has `NixlConnector` (alone or inside `MultiConnector`). Every other
AuxOutput check still runs.
- Scheduler: a request on D (`kv_transfer_params` with a
`remote_engine_id` and no `do_remote_decode`; NIXL clears
`do_remote_prefill` but keeps that) emits rows only from its first
forward on D (`num_computed_tokens` at that point: normally
`prompt_len-1`, lower after a failed KV load, where D recomputes those
rows itself). The floor survives preemption and is dropped when the
request finishes.
- Worker: the partially known first block is not buffered or published;
later blocks D computes in full are published as usual.
**Router v0.2.3 required (router#61); the decode `start` comes from
#3900 (merged).** On a decode instance the rows start at its first
forward, so the response carries only the rows D computed. #3900's
packed `/generate` anchors the rows at the end: `start = len(prompt) +
len(completion) - 1 - len(rows)` (equal to `routed_experts_prompt_start`
without P/D). This PR does not touch
`routed_experts.py`/`serving_tokens.py`, so it and #3900 (and
#3920/#3794 on it) land in either order; P/D router replay needs both.
Router v0.2.3 cuts decode rows by position (`(prefill.start +
prefill.seq_len) - decode.start`) and also handles uint16 routing
(models with more than 256 experts). This PR pins `vllm-router` to
v0.2.3 in `pyproject.toml`/`uv.lock`. Without #3900, the merge would
drop real completion rows.
Also: removes `validate_disaggregated_no_routed_experts` (both
validators on main), docs.
Stack: **this PR** → #3831 (router replay with KV offload) → #3832 (P/D
per-role KV offload) → #4023 (draft, HiSparse on decode).
## Checks run
- `pytest -m "not gpu" tests/unit/test_configs.py tests/unit/inference`
on this head: 214 passed. `ruff check` / `ruff format --check`: clean.
- New tests (`test_routed_experts_pd.py`): the scheduler floor (first
forward, preemption, cleanup) on vLLM's real
`AuxOutputSchedulerConnector`, and the worker skip on the real
`RoutedExpertsBuffer`. `test_combined_replay_uses_v2_runner` is
parametrized over single-node and P/D.
- vLLM's own `tests/distributed/aux_output_connector/test_store.py`
(v0.31.0) with this patch applied plus patch 02's two new tests: 66
passed. Without the patch the two new tests fail.
## GPU validation (2026-10-06, vLLM 0.31.0, 1x 8xH200, Qwen3-30B-A3B
TP1, `VLLM_BATCH_INVARIANT=1`, router v0.2.2 with zero-padded decode
rows)
- 1P1D (NIXL) vs colocated, router replay + sampling masks: 10/10
identical at concurrency 1 (prompts 64-6000 tokens, 128 completion
tokens) and 20/20 at concurrency 10 with a fresh `cache_salt`. Identical
means tokens, prompt and completion routing rows (100%) and sampling
masks; rows = prompt + completion - 1.
- Forced decode preemption (D with 1300 blocks, 20 requests, 1000-4000
prompts, up to 1024 tokens, concurrency 10): 6 preemptions on D, 20/20
identical to colocated.
- All engines log `Using V2 Model Runner`; no `BlockObjectStoreError`.
Re-run (job 2900, 2026-10-06, same setup, launched from per-role configs
written by #3832's `write_pd_configs`): 1P1D (NIXL, no offload) vs
colocated, router replay + masks: 10/10 identical at concurrency 1 and
20/20 at concurrency 10 with a fresh `cache_salt`; 0 errors.
Not run: injected NIXL load failure
(`kv_load_failure_policy=recompute`), MTP on decode, an `rl` run with a
P/D config.
## GPU validation with router v0.2.3 (2026-10-14)
1x 8xH200, vLLM 0.31.0, Qwen3-30B-A3B TP1, `VLLM_BATCH_INVARIANT=1`,
router replay + sampling masks. prime-rl = #3830 (978146cf5) merged with
#3900 (20a322525); router = `release/v0.2.3` (ff818da, this PR + version
bump), wheel built locally. 1P1D (NIXL) through the router vs a
colocated server. Identical means: same tokens, same routing rows for
prompt and completion (100%, rows = prompt + completion - 1, merged
`start` = 0), same sampling masks, same logprobs.
- Concurrency 1 (prompts 64-6000 tokens, 128 completion tokens): 10/10
identical.
- Concurrency 10, fresh `cache_salt` on the colocated side: 20/20
identical.
- uint16: no knob exists (vLLM picks uint8 for <=256 experts), so a
test-only `sitecustomize` forced vLLM's capturer to `uint16` on P, D and
the colocated server. The responses carry `dtype: uint16`. Concurrency
1: 10/10 identical; concurrency 10: 20/20 identical.
- Forced decode preemption (D with `num_gpu_blocks_override=1300`,
1000-4000 token prompts, up to 1024 tokens, concurrency 10): 6
preemptions on D, 20/20 identical.
- Router logs: no errors or warnings during the runs (only the shutdown
warning). Engines: all `Using V2 Model Runner`, no
`BlockObjectStoreError`.
- Negative control, router v0.2.2 with the same P/D pair: 8/10 requests
fail (HTTP 500 `decode routed_experts has 128 rows, expected at least
<prompt_len>`). The 2 prompts of 64 tokens return 128 rows instead of
191, and the completion rows are wrong.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> Changes expert-routing capture on NIXL P/D via vLLM monkey patches and
removes prior safety guards; training correctness depends on router
0.2.3 merge behavior and patch edge cases (preemption, failed KV load).
>
> **Overview**
> **Router replay** and **sampling replay** are now allowed on
**disaggregated prefill/decode (P/D)** deployments, where they were
previously blocked by config validation and vLLM’s AuxOutput + NIXL
incompatibility.
>
> Config validators that rejected `enable_return_routed_experts` with
`deployment.type = "disaggregated"` are removed from inference and RL
configs. Docs now describe P/D behavior: prompt routing from prefill,
completion routing from decode, and that sampling capture can run
alongside router replay under P/D.
>
> A startup **vLLM monkey patch**
(`monkey_patch_routed_experts_with_pd_connectors`) bypasses only the P/D
connector check in `_verify_aux_output_compatibility`, raises an emit
floor on decode so routed-expert rows start at the instance’s first
forward, and skips buffering a partial first block after remote prefill.
**`vllm-router` is pinned to v0.2.3** so the router can merge
prefill/decode expert rows correctly.
>
> Unit tests cover scheduler floors, worker buffering, and V2 runner
setup for both single-node and disaggregated configs.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e586ef860e6d679481ca89d275430c3edb8fc93a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
Pause a running RL or SFT job through an HTTP control API on each
component: the trainer's master rank (`[trainer.control]`, port 8040;
SFT: `[control]`) and the orchestrator (`[orchestrator.control]`, port
8041). `POST /v1/actions {"type": "pause"}` to the trainer is accepted
at its next step N, which it trains, saves and stops after; `POST
/v1/actions {"type": "pause", "step": N}` to the orchestrator saves its
state as of shipping N, held in memory from each ship. A paused trainer
never requests N + 1, so the orchestrator cannot get past N however late
its request arrives.
Each component saves only its own state and neither reads the other's:
the operator composes the two calls, and `GET /v1/actions/{id}` on each
reports `committed` once it saved N. Both keep serving the API after a
pause until the run's owner stops the run.
Tested on rtx-hydra with reverse-text: the trainer accepted a pause at
step 15, the orchestrator paused at 15, both committed with both halves
on disk, further actions were rejected, and the resume loaded both step
15 halves and completed at step 30.
Require every saved attempt's resolved eval config to match the current
config before reusing its episodes. Config mismatches report the
differing top-level fields and point to `--resume.skip-checks` for
intentional changes.
The comparison excludes only `resume`, since enabling resume necessarily
changes that field. All other settings must match, including logging,
concurrency, source order, and shared defaults. Saved JSON is compared
directly so missing fields cannot silently acquire current defaults.
A bare `--resume` or empty `[resume]` TOML section enables the checks.
Missing snapshots or config differences stop the resume before trace
rotation. `--resume.skip-checks` bypasses checks for every attempt while
preserving trace restoration and archival, and warns that saved episodes
may use different experiment settings.
Saved episodes retain schema validation, and successful episodes are
passed to the shared rollout planner for content-hash matching and
grouping by selected occurrence. Incompatible trace records stop the
resume before archival.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Resume behavior changes for anyone who previously resumed with altered
settings; mismatches now fail unless `--resume.skip-checks` is set,
which can mix episodes from different experiment configs.
>
> **Overview**
> **Eval resume now enforces config compatibility** before reusing
episodes from prior attempts. `resume` is no longer a bare boolean: it
is an optional `EvalResumeConfig` (e.g. bare `--resume` / `[resume]`
enables resume with checks; `skip_checks` opts out).
>
> On resume, `take_landed` compares each attempt’s stamped `eval.json`
to the current resolved config (JSON equality, only `resume` excluded).
Missing snapshots or any top-level field drift—including model,
sampling, `select`/`group_size`, client, concurrency, logging, source
order, and shared defaults—raises before the file monitor is rotated.
**`--resume.skip-checks`** skips those checks for every attempt and logs
a warning that restored episodes may not be comparable.
>
> Docs in `eval.md` document the stricter behavior and the escape hatch;
unit tests cover mismatch paths, archived attempts, and `skip_checks`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
65d7e4cc15866e383b4ebf8f2ccaba8612e13b55. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
With trainer FP8 on, DeepSeek V4's grouped attention output projection
(`o_a_proj`) stayed bf16 while vLLM serves `wo_a` in FP8, so the two
sides disagreed on that projection. It now runs through a new grouped
FP8 op that feeds DeepGEMM's `fp8_einsum` the same quantized inputs vLLM
does.
Forward plus backward is 17-19% faster, but the forward alone is 7%
slower. In the forward, the FP8 GEMM saves 0.14 ms per call at 4096
tokens over bf16, while the bandwidth-bound input and weight casts in
front of it cost 0.15 ms. The net win is in the backward, where the bf16
bmm's backward makes two 0.27 ms copies of its transposed operands per
call that the FP8 backward avoids, and its GEMMs are 0.26 ms faster.
- The block-diagonal linear moves to `layers/grouped_linear.py` as
`GroupedLinear`, so the FP8 layer no longer imports the DeepSeek V4
model.
- `Float8BlockwiseGroupedLinear` keeps the 8 groups and calls the new
`prime_rl::fp8_blockwise_bmm` op. The dense FP8 rewrite would have
dropped the grouping.
- The input cast uses power-of-two scales on every device, as vLLM's
`wo_a` cast does. The backward uses the device default.
- The backward is FP8 like every other quantized projection. Add
`o_a_proj` to `ignore_patterns` to keep it bf16 in both directions.
- The weight gradient's per-group GEMMs compile with a dynamic token
dimension (`compiled_dims="mn"`). DeepGEMM builds at most two kernels
per weight shape instead of one per 128-padded micro-batch length on
every rank. This costs about 3% on the weight gradient (0.70 to 0.73 ms
at 4096 tokens), which the tables below predate.
- Each group's weight-gradient scales are copied into the layout
DeepGEMM expects for that group. A slice of the whole-tensor scales
keeps the full tensor's stride, which SM90 silently copies and SM100
rejects with a host assert for every micro-batch longer than 128 tokens.
The copy is speed-neutral on H200.
Tests check that the einsum inputs and output are bitwise vLLM's,
gradients are within 3.8% relative error of bf16, compiled forward and
backward are bitwise eager, and FSDP2 is bitwise the unsharded module.
Only SM90 (H200) was run. Calling DeepGEMM's SM100 scale packing
directly on H200 reproduces the assert without the copy and passes with
it, but the full op has not run on Blackwell yet. That is planned once a
node is available.
H200, 8 groups of 4096 to 1024, `do_bench` median in ms, lower is better
(harness in deef0c65c and addf56d10):
| tokens per GPU | pass | bf16 bmm | fp8 einsum |
|----------------|---------|----------|------------|
| 4096 | fwd | 0.352 | 0.379 |
| 4096 | fwd+bwd | 1.689 | 1.394 |
| 14336 | fwd | 1.411 | 1.515 |
| 14336 | fwd+bwd | 5.529 | 4.504 |
Kernel time per forward plus backward call at 4096 tokens, from
`torch.profiler`, ms:
| kernels | bf16 bmm | fp8 einsum |
|-------------------------|----------|------------|
| GEMM | 1.06 | 0.80 |
| FP8 casts | 0.00 | 0.45 |
| bf16 copies and fills | 0.55 | 0.09 |
| total | 1.61 | 1.33 |
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This PR makes the trainer's FP8 block weight cast match vLLM's online
quantizer bit for bit, removes the wrapper overhead around DeepGEMM's
FP8 grouped GEMM that kept FP8 MoE training slower than bf16 on H200,
and stops DeepGEMM from JIT-compiling the dense weight-gradient kernels
once per micro-batch length. Apart from the weight cast, op outputs are
bit-identical.
- The old cast floored the scale `amax/448` instead, which inflated the
scale of every weight block with amax below 0.0448. Dense FP8 linears
share the kernel and are fixed too.
- Expert weight grads are written in the parameter's layout, removing a
strided copy (3.9 ms per gate_up backward on H200).
- Expert groups are padded to DeepGEMM's 128-row block, so the forward
never syncs with the host and the row-unpack copies are gone.
- The MoE permute's backward gathers instead of scatter-adding every
padding slot into one zero row. bf16 gets faster too.
- The dense weight-gradient GEMM keeps the token count dynamic and gets
its scales in DeepGEMM's layout, so a new micro-batch length no longer
compiles kernels mid-step. Verified on H200, SM100 is pending.
- On SM100, DeepGEMM does not skip the dispatcher buffer's unused tail
rows, about 1% extra grouped-GEMM work at 32k tokens/GPU.
# Measurements
Median `time/forward_backward` per step, lower is better. Speedup is the
column's time divided by fp8 after's time, above 1 means fp8 after is
faster. DeepSeek V4 Flash SFT on H200, `ep=8`, real weights, fake
fixed-length data.
| setup | bf16 | fp8 before | fp8 after | speedup vs bf16 | speedup vs
fp8 before |
|---|---|---|---|---|---|
| 1 node, 6 layers, `cp=1`, full AC, 32k tok/GPU | 2.888 s | 2.903 s |
2.781 s | 1.038x | 1.044x |
| 1 node, 6 layers, `cp=8`, selective AC, 32k tok/GPU | 8.082 s | 8.078
s | 7.921 s | 1.020x | 1.020x |
| 8 nodes, 43 layers, `cp=8`, full AC, 16k tok/GPU | 9.712 s | 9.853 s |
9.504 s | 1.022x | 1.037x |
"Before" is `main` at `88faa6dc2`, the merge base at measurement time,
and "after" is this branch's current code. Each run had its own SLURM
job. The single-node rows are means over three runs per FP8 arm and one
bf16 run. Same-code runs differ by up to 60 ms at `cp=1` and 290 ms at
`cp=8`, so the `cp=8` gain is within noise. The 8-node row is one run
per arm with about 20 ms of step-to-step spread. It uses full AC because
selective AC ran out of memory at 16k tokens per GPU. Fixed-length data
means no row shows the compile cost below.

**Figure:** where the first row's saving comes from, per traced step,
with both arms traced serially on one node. The removed copies (strided
copy, row unpack, permute index) save about 67 ms of compute, and a
second traced pair agrees. The exposed-communication bar is not stable
across traced pairs (+46 ms on a pair traced on two nodes), so the
dashed untraced line, 121 ms per step, is the real saving.
The configs, commands, logs and summaries behind the table and the
figure are in
[`07a7dfafc`](https://github.com/PrimeIntellect-ai/prime-rl/tree/07a7dfafc475e6d8e8b25ee2ad2c12fe6c13effb/benchmarks/scripts/fp8_cleanup_h200_table).
# Compile cost vs steady state
DeepGEMM compiled one weight-gradient GEMM and one scale transpose per
padded micro-batch length, and each rank stalled on its own new lengths
while the others waited at the next collective. A DeepSeek V4 Flash FP8
RL run lost about 29 min of forward-backward time to this over 80 steps.
The dynamic-K GEMM trades that for a slightly slower warm kernel. The
weight-gradient GEMM computes `grad_weight[m,n] = grad_output[k,m]
x[k,n]`, summed over tokens `k`: M and N are the weight's output and
input features, and K is the 128-padded token count. H200, (M, N) =
(1024, 4096) and (32768, 1024), lower is better.
Varying shapes, empty JIT cache: one call per K = 128..4096 step 128 at
both (M, N), 64 calls in all. CUDA events around each call count the
time the GPU sits idle while the host compiles.
| arm | kernels compiled (GEMM + transpose) | total time, 64 calls |
|---|---|---|
| main | 65 + 31 | 8914.7 ms |
| this PR | 3 + 0 | 63.2 ms |
Fixed shapes, every kernel already compiled (do_bench median). Above 1
in the last column means this PR is faster:
| M | N | K | main | this PR | `main/PR` ratio |
|---|---|---|---|---|---|
| 1024 | 4096 | 1024 | 0.032 ms | 0.028 ms | 1.14x |
| 1024 | 4096 | 14336 | 0.144 ms | 0.146 ms | 0.99x |
| 32768 | 1024 | 4096 | 0.330 ms | 0.343 ms | 0.96x |
| 32768 | 1024 | 14336 | 1.152 ms | 1.182 ms | 0.97x |
Each GEMM variant takes about 140 ms to compile on an idle node, which
equals about 4,700 calls' worth of the worst warm slowdown (0.03 ms).
The harness, per-arm tables and logs are in
[`15506a9e4`](https://github.com/PrimeIntellect-ai/prime-rl/tree/15506a9e48fb2b805ea9f1a776530c06c0e0e963/benchmarks/scripts/fp8_dynamic_k_wgrad).
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Adds a `cudnn_flashmla` option to `model.dsa_backend` for DeepSeek V4
that runs the same FlashMLA sparse prefill forward vLLM uses for
DeepSeek V4 prefill, so the trainer and inference compute attention with
the same kernel. The backward is the cuDNN frontend's DSA kernel; it
runs on SM90, SM100 and SM103, and `tilelang` stays the default.
- `cudnn_dsa_patch` stops cuDNN recompiling its backward each time
sequence length or packing changes.
- On B300 (SM103), both DSv4 test files pass and the kernels match a
float32 reference; no end-to-end run there yet.
- On H200 at the B300 changes (`6a1cae560`), both DSv4 test files pass
again, and a 3-step end-to-end run (cp 8,
ep 8) compiles 3 cuDNN kernels per rank in step 1 and matches the
earlier losses, step time and peak memory.
- Fixes GLM-5's SM100 `cudnn_flashmla` backward, which omitted cuDNN's
required workspace and always raised.
- `tilelang` stays the shared `dsa_backend` default and
`configs/advanced/deepseek-v4-flash/sft.toml` opts in to
`cudnn_flashmla`, following #3829, which did the same for the GLM-5.3
configs. FlashMLA only ships an x86_64 wheel
in an optional extra, so a `cudnn_flashmla` default would break aarch64
and installs without the extra. We can flip
the default instead if reviewers prefer.
DeepSeek-V4-Flash first 6 layers, real weights, cp 8, ep 8, one 8xH200
node. Sparse attention GPU time per step, rank 0 profiler trace at 8k
tokens/GPU:
| kernels | tilelang | cudnn_flashmla | speedup |
|---|---|---|---|
| forward, incl. recompute (48 calls) | 56.3 ms | 26.5 ms | 2.12x |
| backward (24 calls) | 71.3 ms | 36.7 ms | 1.94x |
| all sparse attention | 136.0 ms | 76.7 ms | 1.77x |
Sparse attention is under 5% of the step here, so the end-to-end gain is
smaller. Median steady-state step time:
| tokens/GPU | tilelang | cudnn_flashmla | speedup | max loss diff vs
tilelang | max loss diff, two tilelang runs |
|---|---|---|---|---|---|
| 8k | 2.86 s | 2.80 s | 1.02x | 1.0e-3 | 1.7e-3 |
| 16k | 4.59 s | 4.36 s | 1.05x | 7.3e-4 | 1.4e-3 |
Peak memory is equal, and each rank compiles 3 cuDNN kernels, all in
step 1. Baseline
[`main`](https://github.com/PrimeIntellect-ai/prime-rl/commit/7c9d4744cd1d892eb6524191d869d6994c802252);
[results](https://github.com/PrimeIntellect-ai/prime-rl/blob/524ec668e5684134210cef64b3575476fdf59693/benchmarks/scripts/dsv4_cudnn_flashmla_pr/results/README.md)
and
[config](https://github.com/PrimeIntellect-ai/prime-rl/blob/524ec668e5684134210cef64b3575476fdf59693/benchmarks/scripts/dsv4_cudnn_flashmla_pr/sft.toml)
at `524ec668e`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
## Problem
Under RL load (GLM-4.5-Air, 1 trainer + 1 inference node, ~130-300
concurrent 16k-token requests), the vLLM API server spends 25% (top_p
1.0) to 42-43% (top_p 0.97 + sampling replay) of its wall time in gen-2
GC, with single pauses up to 64 s. During a pause the server answers
nothing (/health, /metrics, completions, weight-update calls). With
sampling replay this cost -30% effective generation throughput and +50%
step time, and with default router health checks 25-83% of rollouts
failed.
Cause: tens of millions of GC-tracked per-token objects alive at once in
the API-server process: `Logprob` objects and dicts per token plus
decoded strings (output processor), one pydantic object per token in
`_create_tokens_logprobs`, one Python list per token for the sampling
mask, and the JSON encoding of all of it. Every gen-2 pass walks them
all.
## Change
`/inference/v1/generate` (prime-rl's `PrimeRlServingTokens`) now builds
no per-token objects:
- **Packed payloads**, encoded like `routed_experts` (one `encode_array`
helper for all three; `routed_experts.py` is removed). `routed_experts`
adds `start`, anchored at the last forwarded token: `len(prompt) +
len(completion) - 1 - len(rows)`. Without P/D this equals
`routed_experts_prompt_start`; on a P/D decode instance (#3830) the rows
begin at its first forward.
- `choice.completion_logprobs = {data, shape, dtype}`: base64 float32,
the sampled token's logprob per completion token (clamped at -9999 like
upstream). `choice.logprobs` is no longer set, so `/generate` no longer
returns `top_logprobs` (whatever `sampling_params.logprobs` asks for).
renderers asks for `logprobs = 1` and only reads the sampled logprob, so
nothing in our stack uses them.
- `choice.sampling_mask = {"ids": {...}, "counts": {...}}`: CSR base64
int32 arrays instead of `list[list[int]]`.
- **Flat logprobs, no detokenization**: non-streaming `/generate`
requests get `flat_logprobs = True` (vLLM's `FlatLogprobs`: a few lists
per request instead of a dict + `Logprob` objects per token) unless they
ask for prompt logprobs, and `detokenize = False` unless they set stop
strings (`/generate` returns token ids only, so the text and the
per-token decoded logprob strings were never used).
- **Masks stay numpy in the output processor**
(`monkey_patch_packed_sampling_masks`, non-streaming requests only):
keep only the per-step id arrays (untracked by GC) instead of a tuple
per token, and hand the serving layer a `PackedSamplingMask(ids,
counts)` instead of `list[list[int]]`.
- **API-server GC**: after app init, `gc.collect(); gc.freeze()`
(startup objects leave GC) and `gc.set_threshold(50_000, 20, 100)`
(default `(700, 10, 10)`).
- Streaming `/generate` and the OpenAI endpoints are unchanged.
Clients: https://github.com/PrimeIntellect-ai/renderers/pull/174 reads
`completion_logprobs` (same checks as the per-token path);
https://github.com/PrimeIntellect-ai/verifiers/pull/2778 decodes the
packed mask. Both keep the old forms for stock vLLM.
## Pins
- `deps/renderers` 41f9290 -> ca029b5 (renderers main, the merge commit
of renderers#174).
- `deps/verifiers` 2cb0a6d -> e888a71 (verifiers main, the merge commit
of verifiers#2778).
Landing order: renderers#174 -> verifiers#2778 -> this PR, with the
prime-rl re-pins to renderers/verifiers main in the same commit as the
server change. An old client against a new server gets no
`logprobs.content`.
## Measurement
One node, GLM-4.5-Air TP8, 130 concurrent closed-loop requests (Polaris
prompts, top_p 0.97 / top_k 512, max 16k tokens, ~12.5k
tokens/response), 15 min per arm, before (main) vs after (this branch):
| arm | gen tok/s | done reqs | errors | gen2 GC % wall | all GC % wall
| gen2 count | max GC pause s | health p50/p99/max s | resp MB mean |
client parse ms mean | tokens/resp |
|:------------------|------------:|------------:|---------:|-----------------:|----------------:|-------------:|-----------------:|:-----------------------|---------------:|-----------------------:|--------------:|
| base-nomask | 5497 | 512 | 0 | 11.8 | 13 | 164 | 1.87 |
0.003/1.34/21.7 | 1.71 | 28.5 | 12490 |
| fix-nomask | 5601 | 516 | 0 | 0 | 0 | 0 | 0 | 0.003/0.01/0.3 | 0.12 |
1 | 12619 |
| base-mask | 5453 | 508 | 0 | 23.8 | 25.8 | 111 | 4.27 |
0.003/4.37/30.1 | 1.83 | 31.4 | 12479 |
| fix-mask | 5446 | 504 | 0 | 0 | 0.9 | 0 | 0.99 | 0.003/0.07/1.8 | 0.31
| 1.4 | 12582 |
| fix-mask-nogctune | 5480 | 512 | 0 | 5.1 | 5.7 | 31 | 2.63 |
0.003/1.94/2.8 | 0.31 | 1.3 | 12500 |
The closed-loop tok/s does not move, because the engine core keeps
generating during API-server pauses. The RL cost came from what the
pauses block (health checks, dispatch, responses, weight updates),
measured here by /health latency. Ablation: packing alone takes gen-2 GC
from 23.8% to 5.1% of wall time; gc.freeze + thresholds take it to zero
gen-2 passes.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes the `/generate` response contract and patches vLLM internals;
clients must understand packed fields, though streaming and OpenAI
routes are unchanged.
>
> **Overview**
> Under heavy RL concurrency, `/inference/v1/generate` no longer builds
millions of per-token Python objects in the API server.
**Non-streaming** responses now return **packed, base64 numpy payloads**
for `routed_experts`, new `completion_logprobs` (sampled-token logprob
per position), and CSR `sampling_mask` (`ids` + `counts`), with
serialization consolidated in `serving_tokens` and `routed_experts.py`
removed.
>
> The handler enables **flat logprobs** and disables **detokenization**
when safe (no prompt logprobs / no stop strings), so upstream stops
materializing `Logprob` dicts and decoded strings. A vLLM
**output-processor monkey patch** keeps sampling-mask chunks as numpy
until finish for `FINAL_ONLY` requests.
>
> After app startup, the API server runs **`gc.collect()` /
`gc.freeze()`** and raises GC thresholds to cut gen-2 pauses. Unit tests
cover packing and `post_process`; **`renderers`** is pinned to a release
that reads the new fields (paired client PRs).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a6f0da59559e6c330d16cb107c148438ea49f62f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
- model.lora.init_path on trainer and orchestrator initializes a fresh
optimizer run from an attention-only PEFT adapter (strict shape, key,
and finiteness checks).
- Adapter reload read timeout 30s -> 300s and retry budget 120s -> 600s;
loaded TP2/DP3 servers can take minutes to apply an update.
Trainer ranks pull batches: every rank requests step N when it is ready
to train it, and the orchestrator sends N only once every trainer rank
asked. So the trainer only ever holds the batch it is training on, and
the last step the orchestrator sent is always the one the trainer is on.
- zmq: one ROUTER in the orchestrator, one DEALER per trainer rank (from
#4066). The orchestrator replies to each rank on the connection it asked
on, so there's no slow-joiner race, no READY barrier and no `hwm`.
`ROUTER_MANDATORY` raises on a vanished rank instead of dropping.
- Every trainer rank counts, not one per data rank: requests carry rank,
world size, data rank and step. A request for any other step raises,
since it means the two sides resumed from different steps.
- filesystem: each rank drops `step_N/rank_R.request` holding the world
size, and the orchestrator renames the step's files into place once all
are there.
- `send` blocks until the step went out and returns the hand-off
seconds, logged as `time/send_batch`. The wait before it is now
`time/wait_for_policy` (same key, measured at the send instead of while
the dispatcher is paused). Encoding happens before the wait.
- The ship-time policy-version hold is removed: it was a proxy for
"trainer is ready", which the request now says directly. The dispatch
gate and off-policy filter still bound rollout staleness.
Tested on telus (3x H200: 2 trainer ranks + 1 inference, reverse-text,
20 steps, `commit-4b3319f3a` + this patch):
- zmq: finished, mean step 4.14s (steps 2-20), `time/send_batch` mean
0.6ms / max 6ms
- filesystem: finished, both ranks wrote their request marker each step
- resume from step 15 (zmq): continued to step 20
Linear: RES-1384
The k8s launcher (and potentially prime CLI for client side config
validation) needs to serialize validated RL configs using the selected
schema without importing runtime launchers. Expose
`dump_rl_components()` from the CPU config package and reuse it in the
local RL launcher when writing component JSON files.
The shared helper preserves schema fields and null values, retains the
existing inference launcher-field exclusions, and disables the inference
router for multi-node deployments. The launcher's JSON output behavior
stays the same.
Validation: Ruff and `git diff --check` passed on the rebased branch.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Behavior-preserving refactor that centralizes existing JSON
serialization rules; no auth, data, or runtime wiring changes.
>
> **Overview**
> Adds **`dump_rl_components()`** to the CPU-only `prime-rl-configs`
package so validated RL configs can be split into
trainer/orchestrator/inference dicts **without importing launchers or
writing files**—for k8s and client-side validation.
>
> The helper reuses `dump_resolved_config` (JSON with explicit nulls),
applies the same inference exclusions (`deployment`, `slurm`,
`output_dir`, `dry_run`), and sets `inference["router"]` to `None` for
**multi-node** deployments. `RLConfig` is referenced only under
**`TYPE_CHECKING`** to keep the slim package lightweight.
>
> The local RL launcher’s **`write_subconfigs`** now loops over
`dump_rl_components()` instead of inlining that logic; output paths and
JSON shape are unchanged (docstring updated from TOML to JSON).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
499aa13b77eda37fc2435d9e22c5f1f3cb44f88c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## What
`[inference.vllm] quantization` is typed as `Literal["fp8_per_block"]`,
so it is currently impossible to serve with MXFP8. This PR adds
`"mxfp8"`.
## Why
vLLM supports `--quantization mxfp8` as an online shorthand: a BF16/FP16
checkpoint's weights are quantized to MXFP8 at load (E4M3 values with
block-32 E8M0 scales) and activations are quantized dynamically per
forward, for both dense linears and MoE experts. On Blackwell
(SM100/SM103) vLLM auto-selects native W8A8 block-scaled GEMMs
(FlashInfer CuTe-DSL); older GPUs fall back to W8A16 (Marlin). This is
useful for serving BF16 SFT exports on B200/B300 without building an FP8
checkpoint.
## How
The value already passes through verbatim to vLLM's `--quantization`;
the pydantic `Literal` was the only gate. vLLM validates the shorthand
and picks the kernel at startup (`Using <kernel> for MXFP8 GEMM`), so no
further wiring is needed. Unknown shorthands (e.g. `mxfp4`) stay
rejected.
Verified locally: `InferenceConfig(vllm={"quantization": "mxfp8"})`
validates, `ruff check`/`format` pass, and `tests/unit/test_configs.py`
shows no new failures (20 pre-existing failures reproduce on pristine
`origin/main` with this checkout's venv).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Single-type widening in config validation with no runtime wiring
changes; vLLM still validates quantization at server startup.
>
> **Overview**
> Extends **`inference.vllm.quantization`** so configs can set
**`mxfp8`** alongside the existing **`fp8_per_block`** option. That
value already forwards to vLLM’s `--quantization`; the only change is
lifting the Pydantic **`Literal`** gate that previously rejected MXFP8
at parse time.
>
> This enables online MXFP8 serving (quantize BF16/FP16 weights at load,
dynamic activation quant) on supported hardware without a separate FP8
checkpoint—useful for BF16 SFT exports on Blackwell-class GPUs.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
777ad501a85ced1985b1b735b4d633ff2ec2d71d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Large out-of-band NumPy arrays returned by vLLM can still alias a
shared-memory ring slot after `MessageQueue.dequeue()` releases it.
Subsequent messages overwrite retained routed-expert IDs, so router
replay can consume different IDs from those originally produced.
Backport merged [vLLM
#61000](https://github.com/vllm-project/vllm/pull/61000) through Prime
RL's general plugin. Copy SHM out-of-band buffers inside the read
context, and reuse the owned `bytearray` when rebuilding Torch tensors.
Inline metadata, overflow/remote ZMQ paths and the wire format retain
their existing behavior. The patch is idempotent; its code comment links
upstream and identifies when the backport can be removed.
Validation ran in isolated CPU processes without editing installed
dependencies:
- The upstream unpatched queue fails both SHM NumPy retention cases;
this backport passes the applicable upstream queue suite: **52 passed, 2
GPU skips, 6 deselected** due to the login node's 64 MiB SHM limit.
- The pinned **vLLM 0.31.0** source passes the lifetime and tensor
compatibility cases: **21 passed, 1 skipped**. The private harness
explicitly closes test ZMQ contexts with zero linger: that version's
`shutdown()` only wakes readers, and the initial combined run hung
during context destruction. The production patch does not change
shutdown.
- Patch installation is idempotent. Ruff check, Ruff format and `git
diff --check` pass.
No fresh GPU serving or training benchmark was run for this backport;
upstream's merged PR includes GPU validation.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Patches core vLLM inter-process messaging (`MessageQueue.dequeue`);
incorrect behavior could affect distributed inference correctness,
though the change mirrors an upstream fix and is scoped to buffer
lifetime.
>
> **Overview**
> Backports vLLM’s shared-memory buffer ownership fix into Prime RL’s
vLLM plugin so large out-of-band payloads no longer alias reusable ring
slots after `MessageQueue.dequeue()` returns.
>
> The new `monkey_patch_shm_buffer_ownership()` copies non-primary SHM
slices into owned `bytearray`s while still inside the read lock, and
registers a matching `_rebuild_tensor` helper so pickled torch tensors
rebuild from those copies. Overflow/remote ZMQ paths and the on-wire
layout are unchanged; the patch is idempotent and is meant to be dropped
once the pinned vLLM version includes upstream #61000.
>
> This addresses incorrect **routed-expert** IDs during router replay
when retained NumPy arrays were overwritten by later SHM messages.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c629d022462755dc268b82423fe6c6aea3827eda. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Release the CUDA allocator cache once after every checkpoint load:
`gc.collect()` + `torch.cuda.empty_cache()` right after `dcp_load`
returns in `CheckpointManager.load_from_path`.
- Remove the cleanup from `AppState.load_state_dict`. It ran only with
CPU offload, and the new cleanup now covers that path too.
Net diff: one `ckpt.py` change. The cleanup moves from the offload-only
path to every load path (SFT and RL, with and without CPU offload).
## Problem
Without CPU offload (`model.offload = "none"`), a resume peaks at much
more reserved memory than an uninterrupted run at the same step. A
24-node SFT run (192 ranks, 512K sequence length, 267.7 GiB GPUs)
showed:
| Step 901, same batch | Peak reserved |
|---|---|
| Fresh run, 900 steps in | 216.8 GiB |
| Resumed from step 900 | 257.0 GiB (96%) |
The resumed run logged `expandable_segments: memory mapping failed with
OOM` during its first step.
Cause: DCP's `_init_optim_state` builds the optimizer state with a
zero-grad `optimizer.step()`. This allocates a `zeros_like` gradient for
every parameter, so allocated memory peaks about one fp32 parameter
shard above the steady state during the load. When the load ends, those
blocks stay in the allocator cache. The first step does not reuse them
and reserves on top of them. Peak *allocated* memory does not change, so
the extra memory is cache fragmentation, not live tensors. With CPU
offload, the old cleanup in `AppState.load_state_dict` already released
the cache, so only the non-offload path was affected.
## Verification
Single-node runs: Qwen3-30B-A3B SFT on 1 node of H200s (6 trainer GPUs,
2 inference GPUs), online evals on, seq len 8192. A base run trains 1
step and saves a checkpoint. Each variant resumes from that checkpoint
and trains step 2. Each change was toggled with an env var, so all
variants share the same code and checkpoint. Numbers are rank 0, in GiB.
**`offload = "none"`.** Ablation of each candidate change (the first two
were in an earlier version of this PR):
| Step 2 | Reserved after load | Peak allocated | Peak reserved |
|---|---|---|---|
| Fresh run (no resume) | — | 83.7 | 93.6 |
| Resume, `main` | 80.0 | 83.5 | **114.9** (+21.3) |
| Resume, unconditional cleanup in `AppState.load_state_dict` | 60.5 |
83.5 | 95.4 (+1.9) |
| Resume, `empty_cache()` before the SFT startup broadcast | 80.0 | 83.5
| 93.5 |
| Resume, both of the above | 60.5 | 83.5 | 93.5 |
| **Resume, this PR** | **58.6** | 83.5 | **93.5** |
- Peak allocated is the same in every row. Only the cached, unused
memory changes.
- On `main`, the load leaves 21.4 GiB cached (reserved 80.0 vs allocated
58.6). Step 2 reserves about 31 GiB on top of it.
- With this PR, reserved memory after the load equals allocated memory,
and step 2 matches the fresh run.
- The cleanup inside `AppState.load_state_dict` leaves 1.9 GiB cached:
some load buffers are freed only after `dcp_load` returns.
- The `empty_cache()` before the startup broadcast also removes the gap,
but only because it runs right after the load, and only when online
evals are on. This PR does not need it.
- Memory outside the PyTorch cache stays at about 2.4 GiB in every run.
The cached blocks do not take memory away from NCCL or cuBLAS.
- The `offload = "none"` variants ran twice, with identical numbers.
**CPU offload.** Removing the cleanup from `AppState.load_state_dict`
changes nothing:
| Resume | Reserved after load | Step-2 peak reserved |
|---|---|---|
| `offload = "optimizer"`, `main` | 19.5 | 82.0 |
| `offload = "optimizer"`, this PR | 19.5 | 82.0 |
| `offload = "full"`, `main` | 9.8 | — (killed by an unrelated HF Hub
429 in inference) |
| `offload = "full"`, both cleanups | 9.8 | 35.1 |
| `offload = "full"`, this PR | 9.8 | 34.9 |
Not tested: RL resumes (they use the same
`CheckpointManager.load_from_path`), and the 24-node run above with this
exact diff.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Behavior change is limited to memory reclamation after resume; no
changes to model, optimizer, or checkpoint I/O logic beyond when
`empty_cache` runs.
>
> **Overview**
> **Moves GPU cache cleanup to run on every checkpoint resume**, not
only when optimizer CPU offload is enabled.
>
> Post-load `gc.collect()` and `torch.cuda.empty_cache()` are removed
from `AppState.load_state_dict` (previously gated on `has_cpu_offload`,
with optional `state_dict.clear()`). The same cleanup now runs in
`CheckpointManager.load_from_path` immediately after `dcp_load`, with a
note that DCP’s optimizer materialization can leave gradient allocations
in the CUDA cache and inflate reserved memory on the first training step
after resume.
>
> This targets inflated peak reserved memory (and near-OOM on large SFT
resumes with `model.offload = "none"`) without changing checkpoint
contents or load semantics.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9193c739e325a8764a33c9cb1617fa63eed47281. 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 the prime-rl project version from 0.9.0 to 0.10.0
- update the matching prime-rl entry in uv.lock
- prepare the [draft v0.10.0 GitHub
release](https://github.com/PrimeIntellect-ai/prime-rl/releases/tag/untagged-4435562ccd29fd8d2e32)
with notes for 264 commits since v0.9.0 (up to #4048)
## Verification
- uv lock --check
- git diff --check
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Version-only release metadata with no runtime or dependency graph
changes in the diff.
>
> **Overview**
> Bumps **prime-rl** from **0.9.0** to **0.10.0** in `pyproject.toml`
and updates the editable `prime-rl` package version in `uv.lock` so the
lockfile stays consistent. No application or dependency changes beyond
the release version tag.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7e719dbc7e5cd2f4d503bdd15209ec2f99511bb3. 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>
With `length="variable"` and `input_ids="random"`, `FakeDataset` drew a
per-sample `seq_len` but always generated `self.seq_len + 1` random ids.
Samples ended up with `input_ids`/`target_ids` of length `self.seq_len`,
while `position_ids`, `loss_mask` and `seq_lens` used the drawn length.
After packing with `CatDataset` + `cat_collate` this gave e.g.
`input_ids` of shape (1, 128) next to `position_ids`/`loss_mask` of
shape (1, 101).
- `_draw_sample` now generates `seq_len + 1` random ids. Normal
iteration and fast-forward both go through `_draw_sample`, so resume
still replays the same generator stream. The stream itself changes for
variable+random, which is fine for fake data.
- `num_tokens["fake"]` now counts `seq_len` (the emitted `input_ids`
length), matching `SFTDataset`'s post-shift count, instead of `seq_len +
1` (or `self.seq_len + 1` in the random case).
- Added `test_fake_dataset_sample_lengths`, parametrized over `length` ×
`input_ids`. It asserts that `input_ids`, `target_ids`, `position_ids`
and `loss_mask` all have the same length and that `sum(seq_lens)` equals
it. On the old code it fails only for `[random-variable]`.
## Test plan
- `pytest tests/unit/train/sft/test_fake_dataset.py`: 12 passed (the new
test fails on `main` for `random-variable`)
- Packed 20 variable+random samples with `CatDataset(..., 128)` +
`cat_collate`: `input_ids`, `target_ids`, `position_ids` and `loss_mask`
shapes match
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
#3638 set a reduce-scatter buffer cap of 2 on the fp32 MoE router's FSDP
unit. Back then the experts were their own FSDP unit, so with one buffer
the router's reduce-scatter had to wait for the experts' large
reduce-scatter to finish, stalling backward. #3753 later moved the
experts into the block's FSDP unit (for `fullgraph` compile). With that
layout and full activation checkpointing, the expert reduce-scatter
finishes inside the next layer's recompute, so the second buffer no
longer buys anything. This PR makes the cap configurable
(`model.reduce_scatter_max_input_buffers`), sets it once on the root
FSDP module, and changes the default to 1 (torch's default).
- Before: fp32-router runs had an effective cap of 2 (torch takes the
max over all units), bf16-router runs had 1. Now every run uses the
configured value, 1 by default.
- A single root-level call is enough: torch keeps one reduce-scatter
queue and resolves the cap once as the max over all FSDP units.
- Cap 2 helps only when reduce-scatters are exposed, which in our runs
needed short sequences without activation checkpointing (last rows and
the second figure). It is free with the fp32 router but costs ~9 GiB/GPU
on the bf16 path with `ep=1`. Cap 3 never beat 2.
**Why one buffer is enough now.** The block and the fp32 router are
still separate FSDP units with separate reduce-scatters. The cap is a
single global count of reduce-scatters allowed in flight, and at cap 1
each unit's hook must wait for the previous reduce-scatter to finish
before launching its own. What #3753 changed is which reduce-scatter
that is when the router's hook runs in layer `L`'s backward:
```
Before #3753 (experts are their own unit), cap 1, backward of layer L:
compute [ recompute L ][ MoE bwd L ][ router bwd ][ STALL ][ attn bwd L ]
RS stream [====== experts L RS ======][ router L ]
^ launched just before the router hook,
with no compute in between to hide it
After #3753 (experts in the block's unit), cap 1, backward of layer L:
compute [ recompute L ][ MoE bwd L ][ router bwd ][ attn bwd L ]
RS stream [== block L+1 RS ==] [ router L ]
^ launched at the end of layer L+1, so it has
all of layer L's recompute and MoE backward to finish
```
Before #3753 that big reduce-scatter launched just before the router's
hook, with no compute in between to hide it, and cap 2 was the fix. Now
it is the previous layer's, launched a whole layer earlier, so the
current layer's recompute and MoE backward run while it finishes. It
only stalls when that compute is shorter than the reduce-scatter (the
second figure).
Median s/step and rank-0 peak GiB, GLM-4.5-Air truncated to 24 layers
(16 for 8k without AC), 2x8 H200, fp32 router, untraced, lower is
better. Spread is the gap between two same-code runs on different node
pairs.
| layout | tokens/GPU, AC | cap 1 (PR) | cap 2 (main) | cap 3 | spread |
peak GiB, cap 1 / 2 / 3 |
| ------ | -------------- | ---------- | ------------ | ----- | ------ |
----------------------- |
| `ep=8` | 16k, full | 4.697 | 4.650 | 4.693 | 0.068 | 75.3 / 75.1 /
76.1 |
| `ep=1` | 16k, full | 4.535 | 4.521 | 4.543 | 0.041 | 88.9 / 88.4 /
98.0 |
| `ep=8` | 4k, full | 1.238 | 1.234 | 1.237 | 0.002 | 63.6 / 63.6 / 63.6
|
| `ep=1` | 4k, full | 2.056 | 2.064 | 2.050 | 0.006 | 80.1 / 80.1 / 88.8
|
| `ep=8` | 1k, none | 0.848 | 0.841 | 0.826 | 0.011 | 68.2 / 68.2 / 68.1
|
| `ep=1` | 8k, none | 1.318 | 1.279 | 1.280 | 0.001 | 102.7 / 102.7 /
111.4 |
| `ep=1` | 4k, none | 1.761 | 1.629 | 1.627 | 0.002 | 109.6 / 109.6 /
118.3 |
| `ep=1` | 1k, none | 1.651 | 1.515 | 1.506 | 0.005 | 85.6 / 85.6 / 94.4
|
In a whole-step trace (`ep=8`, 16k tokens/GPU, full AC, rank 0), neither
`main` nor this PR has a compute-stream gap of 2 ms or more anywhere
inside the model's backward. The only such gaps are at the start of
forward, the start of backward, and the end of backward, where the last
hooks and FSDP's final callback wait on the last reduce-scatters.
Notation in the figures (`RS` = reduce-scatter, `AG` = all-gather):
- `E`: the experts' gradient reduce-scatter, over the ranks that hold
copies of the same experts.
- `D`: the reduce-scatter of the block's dense parameters (attention,
norms, shared experts).
- `R`: the fp32 router's reduce-scatter (the router is its own FSDP
unit).
- `D+E`: the whole block's reduce-scatter, used when there is no EP and
the block has one parameter group.

**Figure:** one layer of backward at a production shape (`ep=8`, 16k
tokens/GPU, full activation checkpointing), before and after this PR.
The expert reduce-scatter (orange, top row) finishes while the next
layer is still recomputing, well before anything waits on it, so
dropping to cap 1 adds no stall.

**Figure:** what failure looks like: the compute stream waiting on a
reduce-scatter (red). It shows up at this odd shape we don't run in
production (one node, 8 layers, `ep=2`, 2k tokens/GPU, no activation
checkpointing), where each layer's expert reduce-scatter outlasts the
compute that would hide it. Raising the cap to 2 (bottom) removes most
of the wait and makes the step 6.5% faster (0.277 to 0.259 s) at no
extra memory. We include it to show what to look for in traces and when
to bump the cap.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The docs expanded IPO as "Importance Policy Optimization". It stands for
**INTELLECT Policy Optimization**. Fixes the expansion at its first
mention in `docs/algorithms.md` (IPO Loss) and `docs/ipo.md`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Documentation-only wording fix with no runtime or configuration
impact.
>
> **Overview**
> Corrects how **IPO** is spelled out in the docs: the expansion is now
**INTELLECT Policy Optimization** instead of Importance Policy
Optimization.
>
> Updates the first-definition lines in `docs/algorithms.md` (IPO Loss
section) and `docs/ipo.md` (page intro). No training behavior, config,
or loss math changes.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9c732151621e848c5e300e684293adeff5b1f1a7. 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 a docs page explaining IPO, the default RL loss, with the ablation
behind `eps = 0.3` and configs to reproduce it.
- **`docs/ipo.md`** (nav after Algorithms):
- Why IPO masks by absolute probability (`|p_train - p_infer| > eps`)
instead of ratio like IcePop, with the two worked examples and the link
to KPop
- Ablation setup table and result: on GLM-4.5-Air agentic SWE RL (no
router replay, 64 steps off-policy), IcePop collapses around step 1.2k
while IPO `eps` 0.2 and 0.3 train through
- How `eps = 0.3` was chosen: mask rates replayed on 1.8M tokens (0.1 →
1.98%, 0.3 → 0.25%, IcePop → 0.06%)
- **`docs/assets/ipo/`**: the two figures (solve rate + mismatch KL; eps
choice).
- **`examples/advanced/glm-4.5-air/ipo-ablation/`**: `base.toml` +
`ipo.toml` / `icepop.toml` overlays (eps 0.2 via `--trainer.loss.eps
0.2`). Ported from the research-prod `exp/air-scaleswe-ablation-sweep`
configs to the current schema; dropped cluster-specific paths and
sandbox-label cleanup so arms can run side by side.
- Links from `docs/algorithms.md` (IPO Loss) and the GLM-4.5-Air README.
Validated: `tests/unit/test_configs.py` passes for the new configs, and
the three arms resolve through `cli(RLConfig, ...)` to the intended
loss, no router replay, 64 off-policy steps, and batch 256 × 16.
Content is condensed from the internal IPO blog draft.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
The trainer defaults are tuned for memory (optimizer CPU offload, AC
offloading, compile without `fullgraph`) so large models fit on few
GPUs. This documents how to trade that memory back for throughput, with
an example to reproduce it.
- **`docs/scaling.md`**: new "Max-Throughput Recipe" section after the
memory-tight one: `offload = "none"`, `ac_offloading = "None"`,
`fullgraph = true`, bf16 router, add nodes instead of CP, one
full-length sequence per GPU. Points to the two examples below.
- **`examples/advanced/qwen3-235b-a22b/sft-max-perf.toml`** (+ README):
Qwen3-235B-A22B SFT on 4 x 8 B300 at 16k with that recipe (EP 8, full
AC, fp32 AdamW, balanced routing, 20 steps), around 46% MFU.
- The existing GLM-5.3 `16k-12-node.toml` overlay is referenced as the
second example.
Config ported from @MarioSieg's #3765 to the current schema (no
`model.impl`, `offload = "none"`, no cluster-specific paths); supersedes
it. Validated with `tests/unit/test_configs.py`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Documentation and example TOML only; no trainer or runtime code
changes.
>
> **Overview**
> Adds a **Max Trainer Throughput Recipe** to `docs/scaling.md` as the
counterpart to the memory-tight section: when GPU memory allows, disable
optimizer and activation offloading, enable `torch.compile` with
`fullgraph`, use bf16 MoE routing, prefer scaling nodes over context
parallelism, and keep `micro_batch_size = 1` per full-length sequence.
The doc calls out RL’s fp32 router default as a caveat for `fullgraph`.
>
> Ships a new **`examples/advanced/qwen3-235b-a22b/`** reference run
(`sft-max-perf.toml` + README): 20-step SFT on `Qwen3-235B-A22B` across
4×8 B300 at 16k with that recipe (~46% MFU), balanced routing for stable
benchmarking, and no checkpoint block. **`examples/README.md`** lists
the example; the scaling doc also points at the existing GLM-5.3
`16k-12-node.toml` overlay.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
de9878cd0251e5b40a2f47d11a9210a16f0cea07. 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: Mario Sieg <mario.sieg.64@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
DeepSeek V4 serving on vLLM 0.31.0 corrupts long-context KV under
piecewise CUDA graphs and drops the attention sinks on every layerwise
weight reload. Two vLLM patches fix both.
- C128: vLLM 0.30+ skips the compressed-KV write on mixed batches under
piecewise graphs, so it now always runs. Step-1 mismatch KL on the 131k
SWE run drops from 0.0070 to 0.0005.
- attn_sink: upstream's bare slice copy landed in a meta tensor on
reload, so updates kept boot-time sinks. Sinks now load through
`param.weight_loader`.
- Both register last in `apply_shared_vllm_patches`, so a failing
DeepSeek V4 import cannot skip the other patches.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Reverts #3925. With an fp32 router and activation checkpointing, #3925
changed checkpointed MoE blocks from `compile(AC(block))` to
`AC(compile(block))`, which makes the checkpoint recompute re-enter
Dynamo on the autograd thread. Since then, MoE RL runs with context
parallelism, activation checkpointing and compile crash in an early
backward with `aten.empty_like.default` or `aten.empty.memory_format
encountered during backward but not found in storage`. That happens with
both ring and ulysses CP, which shows that reverting #3925 removes the
crash on the same batches).
The runs in #3925 (no CP) never hit this, and the root cause is not yet
understood. This PR restores the previous layout and the `AC -> Compile
-> FSDP` order until it is. The cost is #3925's speedup: MoE blocks with
an fp32 router and AC run eager again (GLM-4.5-Air about 5.2 to 6.2
s/step, Qwen3-30B-A3B 4.5 to 6.0 s/step in #3925's benchmarks). A
follow-up will root-cause the crash and decide whether to re-land #3925
together with #3951.
This conflicts with #4029, which edits the unwrap block removed here.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
A hung collective (dead rank, NCCL hang) now fails the trainer after 15
minutes instead of an hour, and leaves a trace of which rank hung where.
- `dist_timeout_seconds` default: 3600 → 900, for the RL trainer and
SFT. It is the c10d timeout of every trainer process group
(`setup_torch_distributed` patches it onto the dp/cp/ep sub-groups).
`weight_broadcast.timeout` (#3980) is a different knob and stays 3600.
- Two waits ran inside an NCCL barrier while only the master worked, so
they were bounded by `dist_timeout_seconds`:
- the weight broadcast handshake: non-master ranks sat in
`dist.barrier()` while the master waited for `.receiver_ready`, which
can take up to `weight_broadcast.timeout` (at startup it covers
inference start-up);
- the one-time HF ↔ PrimeRL conversion on the master.
Both now hold the other ranks on the c10d store (`wait_for_master` in
`trainer/world.py`; the conversion key is per model) instead, bounded by
`weight_broadcast.timeout` and 4 h. The handshake hold moved into
`WeightSender.broadcast`, so it covers every transport (before, the
filesystem LoRA path had no hold). The barriers it replaces in the NCCL
and filesystem senders are gone.
- DCP checkpoint save and load, and the HF weight load
(`load_dcp_from_hf`), run their collectives on a gloo group with a 4 h
timeout (`get_dcp_group`), not on NCCL. DCP's collectives wait for the
slowest rank: its writes on save, its reads on load, and on the first HF
load its `snapshot_download`. On large checkpoints or a slow shared FS
this can take longer than 900 s. The two mkdir barriers in
`CheckpointManager.save` use the same group. A dead rank during a
checkpoint now hangs up to 4 h instead of 900 s. The 4 h is a constant
(`DCP_TIMEOUT`), not a config field. Gloo across nodes uses
`GLOO_SOCKET_IFNAME` (set by the multi-node template when `GLOO_IFNAME`
is given) or gloo's own interface detection; this was not tested across
nodes.
- Not covered: general step skew, e.g. the master writing a filesystem
weight broadcast while the other ranks enter the next step's FSDP
collectives. Large recipes may still need a higher
`dist_timeout_seconds` when a long wait is not one of the store or DCP
waits above.
- The DeepSeek-V4-Flash SFT recipe drops `dist_timeout_seconds = 14400`;
it was only there for the conversion.
`examples/advanced/glm-5.3/swe.toml` keeps its explicit 1800.
- The NCCL flight recorder is on for trainer processes
(`DEFAULT_TRAINER_ENV_VARS`): `TORCH_FR_BUFFER_SIZE=2000`,
`TORCH_NCCL_DUMP_ON_TIMEOUT=1`, and dumps to
`/tmp/nccl_trace_<uid>_rank_<rank>` on each node. `torchfrtrace` reads
them. All three can be overridden through `env_vars`.
## Checks
- 2 ranks on 1 node (H200), NCCL timeout 20 s, `CheckpointManager.save`
then `.load` of a small model, with rank 1 sleeping 60 s before each:
both finish (rank 0 waited 61 s and 60 s), and an NCCL all-reduce
afterwards works. The same script with DCP on the default NCCL group
dies on the 20 s watchdog.
- GPU tests `test_load_dcp_from_hf_keeps_checkpoint_selection_bias` and
`test_deepseek_v4_hash_table_survives_the_load_path` pass; they now stub
`wait_for_master` and `get_dcp_group`.
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/train -m "not gpu"`: 534 passed. ruff is clean.
- `wait_for_master`, 2 processes, gloo with a 2 s PG timeout: the
non-master waited 5 s on the store and the next barrier passed.
- GPU, 1 node (H200), reverse-text Qwen3-0.6B, 2-rank trainer (DP=2):
NCCL broadcast for 6 steps plus a resume to step 8 (startup and per-step
broadcasts go through the store hold), and filesystem broadcast to step
2. Merged test branch with #3906/#3998/#4018/#4020. A collective timeout
and its dump were not provoked. This run predates the gloo DCP group.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes distributed synchronization and checkpoint/weight-load process
groups; mis-tuned timeouts could fail long DCP I/O or mask hangs
differently, but behavior is intentional and recipe overrides remain
possible.
>
> **Overview**
> **Shortens the default distributed collective timeout** from 3600s to
**900s** for RL trainer and SFT configs, with clearer docs that this
bounds hung NCCL/c10d collectives. Trainer processes also get **NCCL
flight recorder** env defaults so timeouts dump recent collective traces
to `/tmp`.
>
> **Moves long master-only waits off NCCL barriers** via
`wait_for_master` (c10d store): HF↔PrimeRL one-time conversion (up to
4h), weight-broadcast handshake in `WeightSender.broadcast` (all
transports, including filesystem LoRA), and NIXL ModelExpress
discovery/completion. Per-transport `dist.barrier()` holds in
NCCL/filesystem senders are removed.
>
> **DCP checkpoint save/load and HF weight `dcp_load`** now use a cached
**gloo `get_dcp_group()`** with a **4h** `DCP_TIMEOUT` instead of the
default NCCL PG, including mkdir barriers in `CheckpointManager`. The
DeepSeek-V4-Flash SFT recipe drops its explicit `dist_timeout_seconds =
14400` that only existed for conversion.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
873a952a777f246957051d61a86ec11b972cb59e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
- NIXL: the master-only ModelExpress discovery (startup) and completion
waits now also hold the other ranks on the c10d store before the NCCL
`broadcast_object_list` / `barrier`, so the 900 s timeout can't kill
them while the master waits up to `weight_broadcast.timeout`.
When the orchestrator's step loop raises, its `finally`:
- saves `step_{progress.step - 1}/orchestrator`. That step usually has
no trainer checkpoint, so a bare `--resume` picks a step the trainer
cannot load (`FileNotFoundError: Checkpoint not found at
.../step_K/trainer`). If the step does have a trainer checkpoint, the
crash-time save overwrites the interval checkpoint with mid-step state.
- if teardown exceeds `SHUTDOWN_TIMEOUT_S`, calls `os._exit(0)`. On
SLURM that exit 0 counts as a finished orchestrator:
`.orchestrator.done` is touched, `--kill-on-bad-exit` does not fire, and
the trainer waits until a timeout fails it.
Now the final orchestrator checkpoint is saved only once the step loop
has finished (the last step is fully shipped), matching the trainer,
which saves its final checkpoint only after its loop. A failure later,
while waiting for the final broadcast, still saves it, so the last step
stays resumable. The forced exit uses code 1 when the exit was not
clean. A clean exit that hits the teardown timeout still exits 0.
`os._exit(0)` in `Orchestrator.stop` is the only `os._exit` in
prime-rl's `src/` (none in verifiers).
## Checks
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 335 passed. ruff is clean.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes shutdown and checkpoint persistence on failure paths, which
affects resume correctness and cluster job exit semantics, but logic is
narrowly scoped to the orchestrator `finally`/`stop` teardown.
>
> **Overview**
> Fixes orchestrator teardown so **crashes no longer write a misleading
final checkpoint** and **non-clean shutdowns can fail the job** instead
of looking successful.
>
> On a clean run, a new `loop_done` flag gates the existing “save
`step_{progress.step - 1}`” logic so it only runs after `main_loop()`
finishes (and the usual final-broadcast path), matching the trainer’s
“checkpoint only after the loop” behavior. If the step loop raises
mid-step, teardown skips that save so `--resume` won’t point at a step
the trainer never checkpointed or overwrite an interval ckpt with
partial state.
>
> `stop()` now takes `clean_exit`; when graceful shutdown hits
`SHUTDOWN_TIMEOUT_S` and forces `os._exit`, the process exits **0 only
on a clean exit** and **1 otherwise**, so SLURM/launcher hooks treat
interrupted orchestrator runs as failures while a clean run that wedges
during teardown can still exit 0.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
255c716aeb04a52f869aa3aa5707fff55aa11a1c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Changes the default of `trainer.data.num_workers` from 0 to 1. The RL
trainer now prepares micro batches on one background thread.
Why: the evidence comes from #3917, which added the option. Its
benchmark: Qwen3.5-9B, trainer only, 4×H200, 1024 px JPEG micro batches,
median s/step.
| arm | main thread | 1 thread | saved |
|---|---|---|---|
| default | 24.98 | 18.86 | 24.5% |
| optimizer CPU offload | 26.56 | 20.24 | 23.8% |
The same PR reports that one thread gives the full speedup, that loss
and grad norm match bit for bit, and that host memory rises by only 0.3
GiB.
Scope and safety:
- `DataLoaderConfig` is RL-only. SFT has its own `data.num_workers`,
which already defaults to 1, so SFT is unchanged.
- `WorkerPool` yields results in input order and keeps at most 2 items
in flight (`src/prime_rl/utils/worker_pool.py`).
- `prepare_micro_batch` (`src/prime_rl/trainer/rl/data.py:180`) is
CPU-only and uses no RNG, so results do not depend on threading. For
text-only batches it only sets the multimodal fields to `None`.
- `0` still prepares micro batches on the main thread.
Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/utils/test_worker_pool.py -m "not gpu"`: 340 passed.
- `ruff check` and `ruff format --check` on `trainer.py`: clean.
- I did not re-run the GPU benchmark; the numbers above come from #3917.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Single default-value change for RL-only data loading; explicit `0`
preserves prior behavior and threading is documented as numerically
safe.
>
> **Overview**
> **Default RL micro-batch prep now uses one background thread** instead
of the main training thread.
>
> `DataLoaderConfig.num_workers` in the RL `TrainerConfig` changes from
`0` to `1`, so new runs overlap CPU micro-batch preparation with the
training step without editing config. Setting `num_workers` to `0` still
prepares batches on the main thread. SFT already defaults
`data.num_workers` to `1` via its own config type, so behavior there is
unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7274894702d1d048f3c80e3a994f9441cb2b5c33. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## What
- `VLLM_CACHE_ROOT=/tmp/.vllm-cache-<uid>` and
`FLASHINFER_WORKSPACE_BASE=/tmp/.flashinfer-cache-<uid>` are added to
`DEFAULT_INFERENCE_ENV_VARS`. `TRITON_CACHE_DIR` got the same treatment
in #3877.
- The by-hand copies (`/tmp/.vllm-cache`, `/tmp/.flashinfer-cache`) are
removed from the four GLM-4.5-Air recipes. Those paths were shared by
every user on a node.
- docs/scaling.md gets one paragraph that lists the node-local cache
defaults.
The paths are dot-prefixed so the SLURM start-up cleanup (`rm -rf
/dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-*
/tmp/torchelastic_*` in the multi_node_rl, multi_node_sft and inference
sbatch templates) does not wipe them. These are the same names the
recipes used before.
Precedence is the same as for the other launcher defaults: `[env_vars]`
or `[inference.env_vars]` override them; a value exported in the shell
does not.
## Why
- Without these, vLLM's AOT/Inductor compile cache lives in
`~/.cache/vllm` and FlashInfer's JIT cache under `$HOME`, which is
usually the shared filesystem.
- Measured while testing #3877 (GLM-4.5-Air TP8, vLLM 0.31): a crashed
start left a partial shared vLLM cache. On the next start, 4 TP ranks
loaded those artifacts and the other 4 recompiled. The ranks diverged
and hung in a collective. So one crash breaks every later start that
uses that cache.
- The original scaleswe recipe (#2862) moved this cache to `/tmp`
because the NFS cache hung inference startup.
- Cost: the first start on each new node has a cold vLLM cache.
GLM-4.5-Air: 465 s cold vs 375 s with a warm vLLM cache, so about 1.5
min once per node.
## Overlap
- #3627 (garrett361, draft) adds
`VLLM_CACHE_ROOT`/`FLASHINFER_WORKSPACE_BASE` under `/tmp/garrett/` to
new DeepSeek-V4 recipes. With this PR those lines can go.
## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/utils -m "not gpu"`: 365 passed (rebased on origin/main
41a8ed019).
- Ran the cleanup globs in a scratch dir that held `.vllm-cache-<uid>`,
`.flashinfer-cache-<uid>` and, as a control, `vllm-cache-<uid>`. Only
the control matched.
- `ruff check` and `ruff format --check` on `process.py`: clean.
- `rl @ examples/advanced/glm-4.5-air/swe.toml --dry-run`:
- The rendered `rl.sbatch` exports both vars only in the inference block
(`/tmp/.vllm-cache-<uid>`, `/tmp/.flashinfer-cache-<uid>`).
- With `--inference.env-vars '{"VLLM_CACHE_ROOT": "/scratch/vc"}'`, the
sbatch exports `/scratch/vc`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Launcher default env vars for inference only; configs can still
override, with no auth or training logic changes.
>
> **Overview**
> Inference launches now default **vLLM** and **FlashInfer** compile/JIT
caches to per-user paths under `/tmp` (`VLLM_CACHE_ROOT`,
`FLASHINFER_WORKSPACE_BASE`), matching the existing Triton cache
behavior and avoiding shared `$HOME` or NFS caches that can leave
tensor-parallel ranks on mismatched artifacts and hang.
>
> The four GLM-4.5-Air example recipes drop redundant
`[inference.env_vars]` blocks that duplicated those settings.
**docs/scaling.md** documents the launcher defaults and notes overrides
via `[env_vars]` or component `env_vars`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fe8a34dcb68c8fc314f2ea4f363fcd865fbde951. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Problem
`eval.retrigger_on_resume` is rejected at config-validation time unless
`weight_broadcast.type == "filesystem"`:
```python
if self.eval.retrigger_on_resume:
raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
```
With the default `nccl` transport the flag is therefore unusable, and
resuming an SFT run at an interval-aligned step silently skips that
step's evals: the trainer broadcasts the resume checkpoint at startup
and the evals process loads it, but nothing re-fires, so the next eval
is a full interval away and the step resumed from is never evaluated.
## Why the gate isn't needed
The in-memory path already meets the precondition the gate was
protecting. `OnlineEval.watch()` rendezvouses with the trainer's startup
broadcast before the re-fire, for every transport:
```python
startup_step = config.resume_step or 0
await self.receiver.sync_startup(startup_step, timeout=STARTUP_BROADCAST_TIMEOUT_S)
```
and `sync_startup` is transport-agnostic in
`transports/weights/base.py`:
```python
async def sync_startup(self, step: int, timeout: float) -> None:
await asyncio.wait_for(self.wait_published(step), timeout=timeout)
await self.receive(step)
```
So by the time `maybe_run_eval(step=config.resume_step)` runs, the
served weights are already the resume checkpoint's — and that call
passes `reload_weights=False`, so it never needs to re-read them from
disk, which is the only thing a filesystem broadcast would have added.
Cancellation is unchanged: the re-fired epoch gets the usual
`superseding_step` callback, so a newer broadcast supersedes it exactly
as for any other eval epoch.
NIXL remains rejected by the check immediately above. The RL
orchestrator already honours `retrigger_on_resume` with no transport
restriction, so this also removes an SFT/RL inconsistency.
## Change
Two-line deletion. No tests assert the removed error.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Config-validation-only change; removes an overly strict guard with no
runtime logic changes.
>
> **Overview**
> **Allows `eval.retrigger_on_resume` with NCCL (in-memory) weight
broadcast for SFT online evals.**
>
> SFT config validation no longer raises when `retrigger_on_resume` is
set alongside non-filesystem `weight_broadcast` (e.g. default `nccl`).
Resuming at an interval-aligned step can re-fire that step’s evals
without forcing `weight_broadcast.type = 'filesystem'`. **LoRA +
in-memory broadcast** and **NIXL** restrictions in the same block are
unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
acf86f21d9345e3677852baaefe690f73b938026. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Qwen3.5 training with context parallelism can fail on the first forward
after #3925 places compilation inside activation checkpointing. FLA's CP
setup reads tensor-valued sequence boundaries and calls
`torch.searchsorted`; Inductor fails to specialize the resulting scalar:
```
GuardOnDataDependentSymNode:
Could not extract specialized integer from data-dependent expression (u0//4)
```
Wrap `build_cp_context` with `torch.compiler.disable`, alongside the
existing eager CP convolution wrapper. CP setup runs eagerly while the
surrounding block remains eligible for compilation. CP calculations,
model parameters and checkpointing settings are unchanged.
Validation ran on an allocated India H200 compute node with PyTorch
2.13.0+cu130 and FLA 0.5.2. A bounded CUDA/FSDP/checkpoint reproducer
used two sequence-boundary fixtures and logical CP size 4:
| Layout | Result | Maximum absolute
output/input-gradient/parameter-gradient difference vs eager |
| --- | --- | --- |
| Earlier outer compilation | Pass | 0 |
| Inner compilation introduced by #3925 | Same `(u0//4)` compiler
failure | — |
| Inner compilation with eager FLA CP metadata | Pass |
1.9073486328125e-6 |
This reproducer uses one CUDA/FSDP rank; it does not exercise real
four-rank CP collectives or a full Qwen training step. Full distributed
training validation remains outstanding. Ruff and `git diff --check`
passed for the patch. No test or experiment files are included in this
diff.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Narrow trainer workaround for a known torch.compile + FLA CP setup
issue; behavior matches eager CP setup with negligible numeric drift in
repro.
>
> **Overview**
> Fixes Qwen3.5 **context-parallel (CP)** training failures when the
block is compiled inside activation checkpointing (#3925). Inductor
cannot specialize scalars from FLA’s `build_cp_context`
(`torch.searchsorted` on tensor sequence boundaries), which triggers
`GuardOnDataDependentSymNode`.
>
> The change wraps **`build_cp_context`** with
**`torch.compiler.disable`** (same pattern as the existing eager CP
**`causal_conv1d`** wrapper) and calls **`build_cp_context_eager`** in
the forward path when CP is enabled. CP math, parameters, and
checkpointing are unchanged; only CP metadata setup runs outside the
compiled graph.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c192fc98cedc342e16af9307577f38fa77213b4e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Replaces the three switches `model.fsdp_cpu_offload`,
`model.optim_cpu_offload` and `model.full_offload` with one field:
```toml
[model]
offload = "optimizer" # default; also "full", "none"
```
This applies to both the RL trainer and SFT. The `fsdp` switch is not
migrated: the mode is removed outright (rationale below). The
`[model.full_offload] numa_bind` knob is dropped: no recipe, deployment,
template or doc sets it. Full offload now always pins each rank's CPUs
to its GPU's NUMA node. That was already the default. Ranks whose GPU
reports no NUMA node still skip binding with a warning. On hosts without
GPU sysfs topology (`/sys/bus/pci/devices/<bus>/numa_node`), binding is
no longer optional: full offload fails there instead of being switched
off.
Why: the three switches could only be used one at a time, enforced by
`cpu_offload_mutual_exclusion`. Because `optim_cpu_offload` defaulted to
`true`, enabling full offload also meant writing `optim_cpu_offload =
false`, otherwise validation failed (see the old
`configs/advanced/deepseek-v4-flash/sft.toml` comment). With one value
the conflicting combinations cannot be expressed, so that validator is
deleted. The default behaviour does not change: optimizer-state offload
stays on.
Why drop `fsdp`: the mode was the stock torch FSDP2 `CPUOffloadPolicy`
with no in-tree config, example, or test user; Muon rejected it and it
broke NCCL weight broadcast. It was kept only for long-context runs
whose fp32 masters/moments no longer fit on GPU (the reason it was
restored in #3052); the `full` mode added in #3234 keeps FP32 masters,
moments, and gradients in host RAM, covering that memory pressure
instead. Gone with it: the `CPUOffloadPolicy` selection in `setup_fsdp`,
CPU-side model init in `setup_model`/`load_dcp_from_hf`,
`_move_buffers_to_cuda`, and the fsdp leg of the Gloo special case.
Changes:
- `ModelConfig.offload: Literal["none", "optimizer", "full"] =
"optimizer"` replaces the three fields.
`OptimizerInBackwardOffloadConfig` (and with it `numa_bind`) and its
bool-normalizing `BeforeValidator` are gone.
- Validators in `TrainerConfig` and `SFTConfig`:
- full offload accepts only AdamW or SignSGD and disables clipping, now
reading `offload == "full"`;
- the `Muon optimizer does not support FSDP CPU offload` validators are
deleted with the mode.
- Runtime:
- `setup_optimizer(..., offload=...)` replaces `cpu_offload` +
`full_offload_config`, and its "both enabled" check is gone.
- `FullCPUOffloadOptimizer` drops its unused `offload_config` argument.
- `setup_full_cpu_optimizer_offload()` takes no arguments and always
binds.
- `model.py`: FSDP always uses the default `OffloadPolicy()`; CPU-side
model init in `setup_model`/`load_dcp_from_hf` and
`_move_buffers_to_cuda` are gone.
- Tomls: `glm-4.5-air/swe-budget.toml` and
`ci/integration/reverse-text-sft/full-offload-resume.toml` → `offload =
"full"`; `glm-5.3/sft/h200/16k-12-node.toml` → `offload = "none"`;
`glm-5.3/sft/h200/base.toml` → `offload = "optimizer"`. Also updated
`docs/scaling.md`, the `deepseek-v4-flash/sft.toml` comment, and
`skills/training/start-run/SKILL.md`, which documented the removed
fields.
Breaking: the old keys now fail with `extra_forbidden`, and `offload =
"fsdp"` fails the `Literal`. There is no shim.
Interaction with #3849 (one trainer-common config base): #3849 moves the
full-offload and Muon/FSDP validators from `TrainerConfig`/`SFTConfig`
onto `BaseTrainerConfig`. This PR edits the full-offload validator's
condition and deletes the Muon/FSDP one, so the conflict is textual
only: keep #3849's single copy of the full-offload validators with
`self.model.offload == "full"` and drop its Muon/FSDP copy. Whichever
lands second takes a small rebase.
Other open PRs that set or read the old keys need a rebase:
- tomls: #3883, #3879, #3766, #3765, #3729, #3629, #3627, #3616, #3544
- code: #3885 (`optim_cpu_offload`), #3739 (`full_offload` validators),
#3724, #3719, #3699, #3610, #3487 (`fsdp_cpu_offload` / `enable_gloo`)
Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/train/test_cpu_adam.py tests/unit/train/test_state_offload.py
-m "not gpu"`: 336 passed, 1 skipped (Qwen3-VL snapshot not cached on
this host), 4 deselected (GPU; this host has no GPU). The existing
offload config tests are updated to the new field. `test_load_configs`
covers the 4 edited tomls.
- `cli(TrainerConfig|SFTConfig, ...)`: `--model.offload full|none` and
the default (`optimizer`) resolve as expected; `optim_cpu_offload` and
`offload = "fsdp"` are rejected.
- `import prime_rl.trainer.rl.train, prime_rl.trainer.sft.train` works.
- `ruff check` and `ruff format --check` on the changed Python files:
clean.
- Not run: GPU or multi-node training with `offload = "full"`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking TOML/API surface touches distributed training memory paths
(FSDP offload, optimizer-in-backward, Gloo); behavior should match prior
modes when mapped correctly, but mis-migrated configs will fail at parse
time.
>
> **Overview**
> **Breaking config change:** `model.fsdp_cpu_offload`,
`model.optim_cpu_offload`, and `model.full_offload` are replaced by a
single **`model.offload`** setting (`"optimizer"` default, or `"full"`,
`"fsdp"`, `"none"`). RL and SFT share the same field; example TOMLs and
scaling docs are updated accordingly.
>
> The mutual-exclusion validator between the old flags is removed
because only one mode can be expressed. **`[model.full_offload]` /
`numa_bind` is dropped** — `"full"` always runs NUMA binding and CPU
optimizer thread setup via parameterless
`setup_full_cpu_optimizer_offload()`. Runtime paths (`setup_optimizer`,
FSDP CPU offload in `model.py`, Gloo when offload is `"full"` or
`"fsdp"`) key off the new enum; `FullCPUOffloadOptimizer` no longer
takes an offload config object.
>
> Default training behavior is unchanged: optimizer-state CPU offload
remains the default (`"optimizer"`). Old TOML keys are not aliased and
should fail validation.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
35da73ad2f1a73533595a979a971b0cdd8d6e63f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Co-authored-by: sami jaghouar <sami.jaghouar@gmail.com>
## What
- `weight_broadcast.timeout` default goes from 1200 s to 3600 s
(`configs/shared.py`).
- It now also bounds the orchestrator's wait for the trainer's startup
broadcast. `orchestrator.ckpt.wait_for_weights_timeout` and the
hardcoded `STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200` fallback are removed.
Configs that set the old field fail validation (`extra="forbid"`); no
in-repo config sets it.
- The `[weight_broadcast]` blocks in five recipes only repeated `type =
"nccl"` (already the `rl` default when inference is managed and LoRA is
off) and `timeout = 3600`. They are removed: glm-4.5-air
swe/swe-budget/search/terminal and nemotron-3-super swe. glm-5.3 keeps
its `timeout = 12000`.
- Orchestrator `ckpt` and `resume` docstrings: `resume` had two
docstrings and `ckpt` had none. The stray one now documents `ckpt`.
## Why
- Every large multi-node recipe raises the timeout: 3600 s in five
recipes, 12000 s in glm-5.3.
- Measured startups come close to 1200 s or pass it. GLM-4.5-Air TP8
cold start takes 465-623 s. GLM-5.3 and DeepSeek-V4 inference startup
with cudagraph capture took about 16 min.
- vLLM's own engine-ready timeout is already 4200 s
(`VLLM_ENGINE_READY_TIMEOUT_S`).
- The startup wait and the per-step waits had two knobs with the same
1200 s default. The startup one was under `ckpt`, but it applies without
`ckpt` too.
- Trade-off: a consumer that dies is detected after 60 min instead of
20.
## Overlap
- #3652 (mikasenghaas, draft) reformats the `wait_timeout = ...` line
that this PR removes. Whichever lands second has a one-line conflict.
- Rebased over #3983, which removed the neighbouring orchestrator
`ckpt.keep_last`/`keep_interval` fields. The orchestrator
`CheckpointConfig` now has only `interval`.
## Test plan
- Rebased onto origin/main 32c48f5d9. `pytest tests/unit/orchestrator
tests/unit/test_configs.py -m "not gpu"`: 335 passed. `test_configs`
validates every TOML under `configs/` and `examples/`.
- `ruff check` and `ruff format --check` on the changed files: clean.
- Resolved `RLConfig` of the 5 edited recipes, main vs this branch:
identical (apart from the checkout path in `template_path`).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes orchestrator startup behavior and timeout defaults for
trainer–inference weight sync; mis-tuned timeouts could delay failure
detection (up to 60 min) or still timeout on very slow large-model
startups.
>
> **Overview**
> **Unifies weight-broadcast timing** so one knob
(`weight_broadcast.timeout`) covers both the trainer handshake and the
orchestrator’s wait for the trainer’s **startup** broadcast. The default
rises from **1200 s to 3600 s**, and docs note raising it for large
models on slow filesystems.
>
> **Removes** `orchestrator.ckpt.wait_for_weights_timeout` and the
orchestrator’s `STARTUP_WEIGHT_WAIT_TIMEOUT_S` fallback; startup sync
now uses `config.weight_broadcast.timeout` in `sync_startup`.
**Orchestrator config** docstrings are fixed so `ckpt` is documented on
the right field.
>
> **Five example/advanced recipes** drop redundant `[weight_broadcast]`
blocks that only repeated NCCL type and `timeout = 3600` (now defaults).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e318f1cb0b10a8a5507520f2c6b1176f9fbd0813. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Multi-node RL jobs that crash currently sit idle for an hour.
On any non-zero exit (crash, OOM, SIGTERM, wall-time),
`multi_node_rl.sbatch.j2` ran an unconditional `sleep {{
cleanup_grace_period }}` (default 3600 s, #2670) before tearing down.
The sleep keeps the task alive so `--kill-on-bad-exit` does not reap
trainers that are mid-checkpoint. But it waits the full hour even when
no checkpoint is being written, so a crashed N-node job idles for 1 h.
Now the node waits only while the newest `checkpoints/step_*/trainer`
has no DCP `.metadata` yet, i.e. a trainer save is still in flight. It
polls every 10 s, with `cleanup_grace_period` as the cap, and tears down
as soon as that save finishes or there is none. Runs without `[ckpt]`
tear down immediately. The checkpoint dir follows `ckpt.output_dir` when
it is set. The default stays 3600 s; it is now only an upper bound.
Limitation: if the crash happens right before a save starts (step dir
not created yet), we no longer wait for that save. Only that save is
lost; the previous checkpoint is intact.
**Interaction with #3875 (requeue + step watchdog):** before this
change, every requeue of a crashed multi-node RL job first waited the
full grace period. Now it waits only for an in-flight checkpoint.
`.metadata` is the same completeness marker that #3906 uses for "latest
complete checkpoint". The SFT and inference templates do not use
`cleanup_grace_period` and are unchanged.
Test plan (all run):
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed.
- `rl @ examples/advanced/glm-4.5-air/swe.toml --dry-run`: the rendered
sbatch has the wait loop with the run's `checkpoints/` path and passes
`bash -n`. With `--no-ckpt` the loop is not rendered.
- Ran the rendered teardown snippet in bash against a temp checkpoint
dir:
- empty dir: no wait;
- newest step complete: no wait;
- newest step in flight: waits until the cap;
- older incomplete step but newest complete: no wait;
- in-flight save that completes after 1 s: waits ~1 s.
- `ruff check` and `ruff format --check` on the changed Python files.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes multi-node job teardown timing and checkpoint detection logic;
incorrect polling could tear down early or delay allocation release, but
scope is limited to SLURM RL launcher scripts.
>
> **Overview**
> Multi-node SLURM RL jobs no longer **sleep the full
`cleanup_grace_period` (default 1h) on every failure**. Teardown after a
non-zero exit now waits only while an **in-flight trainer checkpoint**
is detected.
>
> The `multi_node_rl.sbatch.j2` teardown block is gated on both
`cleanup_grace_period` and a rendered **`ckpt_dir`** (from
`get_ckpt_dir` when `[ckpt]` is enabled). Instead of a fixed `sleep`, it
polls every 10s: if the newest `step_*/trainer` directory lacks DCP
**`.metadata`**, it keeps the task alive (preserving
`--kill-on-bad-exit` behavior for peer trainers); otherwise it tears
down immediately. **`cleanup_grace_period` is documented as an upper
bound**; runs without checkpoints skip the wait entirely.
>
> `write_slurm_script` in `rl.py` passes `ckpt_dir` into the multi-node
template renders.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8168264718f38f6e2e9636ea7bc7098e91743ba3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## What
Renames `tasks_per_minute` to `dispatch_per_minute` on `orchestrator`,
the `eval` entrypoint and the SFT online `[eval]` block. This uses the
same name and wording as #3652.
The old name was wrong. The dispatcher takes one rate-limiter token per
**episode** it starts (`Dispatcher.acquire`, called once per scheduled
episode), not one per task. With `group_size = 8`, `tasks_per_minute =
80` started only 10 tasks per minute. The docstrings now say what is
counted: at most N episodes start per minute, and a group counts
`group_size` times.
Breaking: configs that set `tasks_per_minute` now fail validation
(`extra="forbid"`). No shipped config, doc, test or skill sets it or
mentions it.
## Overlap
#3652 (draft, orchestrator as hook-wired components) makes the same
rename. This PR lands it on its own and does not depend on that
refactor.
## Test plan
- `pytest tests/unit/orchestrator tests/unit/eval
tests/unit/test_configs.py -m "not gpu"`: 357 passed.
- `ruff check` and `ruff format --check` on the changed files.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Breaking config field rename only; runtime rate limiting behavior is
unchanged aside from clearer documentation.
>
> **Overview**
> **Breaking rename:** `tasks_per_minute` → `dispatch_per_minute` on
orchestrator config, eval/SFT online eval config (`ServedEvalConfig`),
and everywhere it is passed into `Dispatcher` (orchestrator + eval
runner).
>
> The limit semantics are unchanged in code (still `AsyncLimiter` with
one token per scheduled episode in `Dispatcher.acquire`), but the name
and docstrings now match behavior: the cap is **episodes started per
minute**, and a rollout group with `group_size` N consumes N tokens.
Configs that still use `tasks_per_minute` will fail validation under
`extra="forbid"`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0436304d5e40baed76abfadaa5b989048e818b6a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Removes `model.index_cache` (`IndexCacheConfig.topk_freq` and
`.topk_pattern`). The trainer still turns on IndexShare from the model's
own `indexer_types` schedule (`src/prime_rl/trainer/model.py`), as
before.
Why: the override changes the trainer only. No inference-side config
matches it, so setting it makes the trainer pick different top-k indices
than vLLM unless the user also passes the same vLLM `hf_overrides` by
hand. The setting appears in no config, example or test. The HF-level
`use_index_cache` / `index_topk_freq` / `index_topk_pattern` attributes
on `GlmMoeDsaConfig` stay, so a checkpoint's own `config.json` still
drives them.
Breaking: `[trainer.model.index_cache]` / `[model.index_cache]` now
fails validation.
Overlap with open PRs:
- #3833 rewrites the same `index_cache` lines in `model.py`
(`set_model_options(model_config, "index_cache", ...)`). Whichever lands
second drops or rebases that block; the conflict is small.
- #3879 is based on that code too.
- #3616 already leaves `trainer.model.index_cache` unset for the reason
above: a trainer frequency override replaces the checkpoint schedule and
requests weights the checkpoint does not have.
Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed.
- `pytest tests/unit/utils/test_weights.py` (includes
`GlmMoeDsaForCausalLM`): 7 passed.
- `ruff check` and `ruff format --check` on the changed Python files:
clean.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking config validation for anyone using `index_cache`, and it
changes sparse-attention index scheduling to follow the checkpoint
only—important for trainer/inference logprob alignment on DSA models.
>
> **Overview**
> **Removes the trainer-only `[trainer.model.index_cache]` override**
(`topk_freq` / `topk_pattern`). Configs that still set it will fail
validation.
>
> IndexShare for GLM-5.2-style DSA models is unchanged in behavior: when
the checkpoint’s `indexer_types` includes `"shared"` layers, the trainer
still sets `use_index_cache` on the HF config and logs the full/shared
layer counts. It no longer applies manual `index_topk_freq` /
`index_topk_pattern` or clears `indexer_types`, which could diverge from
vLLM rollouts.
>
> Docs no longer mention manually overriding the schedule via
`[trainer.model.index_cache]`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bf75c92edd9982a776bff29601c1e8c4519aebeb. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
vLLM 0.31's routed-experts capturer already returns uint8 or uint16,
chosen from the model's expert count (`uint8 if num_experts <= 256 else
uint16`). `serialize_routed_experts` cast every request back to uint8
whenever its ids happened to be below 256. On a >256-expert model
(NemotronH Super/Ultra: 512 experts), a request whose ids all fall below
256 therefore came out uint8 while the others were uint16. Packing two
such samples into one micro batch trips `assert routed_experts.dtype ==
sample.routed_experts.dtype` in `orchestrator/batch.py`. Multi-turn
traces hit the same mix: verifiers concatenates the per-turn arrays, and
NumPy widens the result.
`serialize_routed_experts` now keeps the capturer's dtype and asserts
that it is uint8 or uint16. Every request of a model then has the same
dtype. Models with 256 or fewer experts are unchanged (uint8).
Tests: the existing serialize test now passes a uint16 array with ids
below 256 and checks that it stays uint16. `tests/unit/orchestrator`,
`tests/unit/inference`, `tests/unit/utils`, `tests/unit/test_configs.py`
pass with `-m "not gpu"`; `ruff check` and `ruff format --check` are
clean.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Narrow inference serialization fix; ≤256-expert models stay uint8, and
behavior only changes where mixed dtypes previously caused orchestrator
batch asserts.
>
> **Overview**
> **Fixes inconsistent routed-experts dtypes** that broke micro-batch
packing on models with more than 256 experts (e.g. NemotronH 512).
>
> `serialize_routed_experts` no longer re-encodes expert indices to the
smallest integer width based on per-request max values. It keeps the
array dtype from vLLM’s capturer (`uint8` or `uint16` from model expert
count), with assertions that the input is 3-D and one of those two
types. The serialized payload’s `"dtype"` field reflects that array
unchanged.
>
> Unit tests now decode using `encoded["dtype"]` and assert a `uint16`
capture with all ids < 256 stays `uint16` through serialize/decode.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e4a8e9ea05cb4e960192cdb7929e2c2566ca9734. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Under `rl`, `inference.deployment.gpus_per_node` was never set from
`deployment.gpus_per_node`. `InferenceConfig.auto_setup_disaggregated`
sizes `data_parallel_size_local`, `data_parallel_size` and
`api_server_count` from the nested copy, which defaults to 8. The
launcher, sbatch `dp_per_node` and weight-broadcast world size use the
top-level copy. So a P/D run on nodes that do not have 8 GPUs got
mismatched engine counts.
Example: `examples/advanced/glm-5.3/swe.toml` with
`deployment.gpus_per_node = 4` resolved to `data_parallel_size_local =
8` and `api_server_count = 8`, while the template launched 4 engines per
node.
Changes:
- `propagate_shared_fields` now fills
`inference.deployment.gpus_per_node` from `deployment.gpus_per_node`. As
with the other shared fields, setting both to different values raises.
- `RLConfig.validate_shared_configs` requires the two to be equal. This
catches a nested-only override that leaves the top-level value at its
default.
## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 335 passed (includes the new
`test_disaggregated_inference_inherits_deployment_gpus_per_node`)
- Parsed all 78 tomls under `configs/` and `examples/` with every config
class on main and on this branch: same results, none fail
- glm-5.3 `swe.toml` with `deployment.gpus_per_node = 4` now resolves
`inference.deployment.gpus_per_node = 4`, `dp_local = 4`,
`api_server_count = 4`
- `ruff check` / `ruff format --check` on the changed files
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Mis-sized inference parallelism and launcher/engine counts on
multi-node disaggregated runs; the change is narrow config propagation
plus validation with low blast radius beyond P/D sizing.
>
> **Overview**
> Fixes a config bug where **`deployment.gpus_per_node`** at the RL top
level did not flow into **`inference.deployment.gpus_per_node`**, so
disaggregated P/D runs could size **`data_parallel_size_local`**,
**`api_server_count`**, and related fields from the nested default (8)
while SLURM/launchers used the top-level value (e.g. 4).
>
> **`propagate_shared_fields`** now copies top-level
**`deployment.gpus_per_node`** into
**`inference.deployment.gpus_per_node`** (with the same
shared-vs-sub-config conflict rules as other shared fields).
**`RLConfig.validate_shared_configs`** additionally requires the two
values to match when inference is enabled, catching nested-only
overrides that disagree with the top-level deployment.
>
> A unit test asserts inheritance and that mismatched nested/top-level
**`gpus_per_node`** fails validation.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
863bbf67298b456c48418c7326c820cc930ca203. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Drops seven typed `[inference.vllm]` fields: `seed`, `enforce_eager`,
`dtype`, `trust_remote_code`, `enable_dbo`, `max_loras`,
`all2all_backend`, and the `All2AllBackend` alias. Each one only
repeated vLLM 0.31's own default, and nothing in prime-rl reads it.
`VllmConfig` is `extra="allow"`, so all seven keys still pass through to
vLLM unchanged. The `VllmConfig` docstring says to type only fields that
prime-rl types, defaults or reads back; these were none of those.
`all2all_backend` also suggested control it doesn't have for P/D: the
sbatch templates set the per-role backend in `ROLE_EXTRA`
(`inference.sbatch.j2:261,276`, `multi_node_rl.sbatch.j2:405,419`). That
stays as is.
Behavior: I resolved the vLLM serve args (`to_namespace` →
`make_arg_parser().parse_args`) on main and on this branch for the
default config and for `--vllm.enforce-eager`, `--vllm.enforce-eager
true`, `--vllm.max-loras 2`, `--vllm.dtype bfloat16`, `--vllm.seed 7`,
`--vllm.all2all-backend deepep_low_latency`, `--vllm.enable-dbo true`,
`--vllm.trust-remote-code true`, `@
examples/advanced/glm-5.3/infer/pd.toml`. All seven values are
identical. The nested rl form `--inference.vllm.enforce-eager
--inference.vllm.max-loras 2` also resolves to `True, 2`. `"enable_dbo"
= true` in `examples/advanced/glm-5.3/swe.toml` sits under
`prefill_vllm_overrides` and is unaffected.
Differences:
- `--no-vllm.enforce-eager` (the negated bool flag) only exists for
typed fields. Use `--vllm.enforce-eager false`. All four removed bools
default to False, so this only matters when undoing a toml that set one
to true.
- `dtype` now accepts every value vLLM accepts (for example `half`)
instead of prime-rl's narrower Literal.
`skills/configs/SKILL.md` used `enforce_eager = true` as its TOML
boolean example. It now uses `enable_prefix_caching = true`, which is
still typed, so `--no-flag` applies to it.
## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/test_parsers.py -m "not gpu"`: 489 passed
- Parsed all 78 tomls under `configs/` and `examples/` with every config
class on main and on this branch: same results
- The resolved-args comparison above
- `ruff check` / `ruff format --check` on the changed file
## What
Drop recipe lines that only repeat what the config already resolves to.
The resolved configs do not change, except for `skip_optimizer` (see
below).
- `[weight_broadcast] type = "nccl"`: `rl` already picks NCCL when
inference is managed and LoRA is off. Removed from minimax-m2.5 swe,
intellect-3.1 rl, and qwen3-30b-a3b swe/math. The block stays in
examples/extra/dynamo/rl.toml (no managed inference, so the default
there is filesystem) and in glm-5.3 (it also sets port and timeout).
- `ac.freq = 1` (the default) is removed from 8 recipes. The
`[*.model.ac]` table header stays, matching the GLM-4.5-Air recipes.
- `trainer.dist_timeout_seconds = 3600` / `dist_timeout_seconds = 3600`
(the default) is removed from 5 RL recipes and vlm/sft-moe.
- `inference.vllm.enable_return_routed_experts = true` is removed where
`trainer.enable_router_replay = true` already sets it (glm-4.5-air ×4,
nemotron-3-super).
- `[trainer.ckpt] skip_optimizer = true` is removed from glm-4.5-air
swe-budget/search/terminal and nemotron-3-super swe.
- It only affects loading: on resume, it drops the AdamW/Muon state.
- It came from the #2862/#2915 ablation configs. None of these recipes
warm-starts from another run's checkpoint. They train from the HF model
and resume their own checkpoints, which include optimizer state.
- configs/ci/integration/reverse-text-sft/full-offload-resume.toml keeps
it on purpose: it tests that path.
- docs/scaling.md: the `fused_lm_head_token_chunk_size` default is 8192
(since #3302), not 1024.
## Not touched
- `fused_lm_head_token_chunk_size = 1024` pins (7 recipes) and `attn =
"flash_attention_3"` pins (10). Should they stay as memory/hardware
choices?
- `[ac_offloading] max_inflight_activations` lines (a separate PR
removes the field).
- The `[weight_broadcast]` blocks of the GLM-4.5-Air and nemotron
recipes (handled in the weight_broadcast.timeout PR, to avoid a
conflict).
## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed (validates every TOML under configs/ and examples/).
- Resolved configs of all 14 edited recipes, main vs this branch
(RLConfig/SFTConfig `model_dump`):
- identical, except `trainer.ckpt.skip_optimizer` True → False in the 4
recipes above;
- the checkout path in `template_path` also differs (main checkout vs
this worktree), which is not a recipe change.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Mostly documentation and deduplication; the only resolved-config
change is `skip_optimizer` false on four recipes that resume with full
optimizer state, which matches their intended training flow.
>
> **Overview**
> Trims RL/SFT example and advanced recipe TOMLs by deleting settings
that already match framework defaults, so recipes only spell out
non-default choices.
>
> Removed redundant **`[weight_broadcast] type = "nccl"`**,
**`trainer.model.ac` `freq = 1`**, **`dist_timeout_seconds = 3600`**,
and **`inference.vllm.enable_return_routed_experts`** where NCCL
broadcast, AC frequency, dist timeout, and routed-expert return are
implied (e.g. managed inference + **`enable_router_replay`**). Dropped
**`[trainer.ckpt] skip_optimizer = true`** from four GLM-4.5-Air and
Nemotron SWE/search/terminal recipes so resume loads optimizer state
from their own checkpoints instead of discarding it.
>
> **`docs/scaling.md`** now documents
**`fused_lm_head_token_chunk_size`** default **8192** (was incorrectly
**1024**). Explicit pins like **`fused_lm_head_token_chunk_size =
1024`** in memory-tight recipes are unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c87c43defc655e83c39559736ca874740327d266. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Sets `dsa_backend = "cudnn_flashmla"` for the trainer in the GLM-5.3 RL
example (`examples/advanced/glm-5.3/swe.toml`). The SFT example already
uses it (#3829); the RL example still ran the TileLang forward and
backward.
Measured on 1x8 H200 with the trainer settings of `swe.toml` (131k seq,
cp 4, ep 8, fp8 + `deepgemm_fp8`, full AC + offload, compile). Random
init, 8 layers (3 dense + 5 MoE), fake data, 2 micro-batches per dp
rank, balanced routing:
| `dsa_backend` | step 2 / 3 | sparse attn fwd per call | sparse attn
bwd per call |
|---|---|---|---|
| `tilelang` | 16.6 s / 15.5 s | 35 ms | 190 ms |
| `cudnn_flashmla` | 12.8 s / 12.1 s | 12 ms | 53 ms |
- Entropy and mismatch KL are identical to 4 decimals.
- With a 4-layer run (5.7 s), one MoE layer costs 1.6 s instead of 2.07
s. Extrapolated to 78 layers at this shape: ~124 s vs ~160 s per step
(-22%).
- Kernel check at the CP shape (8k local queries vs 32k keys, cp rank 0
and 3, top-k 2048, sentinel slots): out / dq / dkv relative error vs
TileLang 5e-4 to 9e-4, LSE 7e-8.
- Needs the `flash-mla` extra, which the README's `uv sync --all-extras`
installs.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Single example TOML knob with no production code changes; requires the
optional flash-mla dependency for the new backend.
>
> **Overview**
> Aligns the GLM-5.3 RL example trainer config with the SFT example by
setting **`dsa_backend = "cudnn_flashmla"`** in
`examples/advanced/glm-5.3/swe.toml`, so sparse DSA attention uses the
cuDNN/FlashMLA path instead of the default TileLang forward/backward.
>
> This is a **performance-only** example change for long-context RL
training (131k seq, CP/EP, fp8 MoE); behavior should match TileLang
within measured numerical tolerance when the `flash-mla` extra is
installed.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e2135c38262af40b51d866026cdfa3a83fb7c7b4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Use Verifiers' shared sampling config and resolution path for evaluation
and rollout dispatch. Parameter names, provider options, source
defaults, and agent overrides follow the same rules in native Verifiers
and Prime-RL. Training retains its strict config for the distribution
the trainer replays.
## Sampling flow
```mermaid
flowchart TD
T["Train source and agent config<br/>TrainSamplingConfig and replay bounds"] --> V["Validate live-policy sampling<br/>Source owns the distribution"]
V --> S["Shared Verifiers SamplingConfig<br/>Normalize aliases and extra_body"]
V --> A["AgentConfig.sampling<br/>Sparse overrides across config transport"]
E["Eval source and agent config"] --> S
E --> A
S --> R["RunRequest to env server"]
A --> M["Verifiers resolve_agent<br/>Shared merge_defaults"]
R --> M
M --> P["Provider request<br/>Non-null resolved parameters"]
M --> C["Trace<br/>Complete resolved sampling"]
```
## Shared parameters
Verifiers normalizes `max_tokens` / `max_completion_tokens` and flattens
`extra_body` before merging each override layer. Source values replace
group defaults; agent values replace inherited sampling. An explicit
null clears an inherited parameter.
Within one sampling block, top-level values take precedence over
`extra_body`. A typed training `top_k=20`, or the automatic replay bound
of `512`, therefore takes precedence over `extra_body.top_k=-1`. With no
typed `top_k`, the disabled sentinel remains effective.
Prime-RL carries `vf.SamplingConfig` through dispatch and converts
`TrainSamplingConfig` once. Source defaults and agent overrides use
Verifiers' `merge_defaults`; duplicate eval schemas and
sampling-dictionary converters are removed. Request-specific cache salts
are copied onto the shared config.
Unresolved agent overrides remain sparse across env-server config
boundaries. `resolve_agent` materializes the sampling used for
generation, and traces record the complete resolved config. Provider
dialects and the renderer client omit nulls when constructing requests.
## Training ownership
Live-policy sources validate their sampling when the config loads.
Unsupported source parameters, including `frequency_penalty`, are
rejected before generation.
The source owns the distribution replayed by the trainer. Every agent in
a live-policy source, including non-trainable roles, may override only
`max_tokens`, `reasoning_effort`, and `chat_template_kwargs`.
Distribution parameters belong on the source, even when an agent would
repeat the same value. Policy logprobs remain enabled. Evaluation and
frozen-model sources retain general agent overrides.
This removes the post-rollout sampling comparison from `TrainSink`.
## Dependency
Pins Verifiers `2cb0a6d`, the merged commit for [Verifiers
#2762](https://github.com/PrimeIntellect-ai/verifiers/pull/2762), for
shared sampling normalization and resolution. This includes merging
per-call judge sampling overrides before constructing SDK requests,
preserving unrelated configured provider parameters. The lockfile
updates `prime-tunnel` to `0.1.14` to meet the merged dependency's
minimum.
Before publishing packages outside this source checkout, release that
Verifiers change and raise the `verifiers` minimum in both `prime-rl`
and `prime-rl-configs`. The current `>=0.3.2.dev158` package constraints
do not guarantee these semantics.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how sampling is resolved and validated for all rollouts;
mis-merged configs or rejected agent overrides could break existing
TOMLs, though unit tests cover the main inheritance and policy rules.
>
> **Overview**
> **Unifies rollout sampling** on Verifiers' shared `SamplingConfig` and
merge rules instead of Prime-RL–specific eval schemas and
`to_sampling_args()` dict builders.
>
> Eval sources and group defaults now use `vf.SamplingConfig`;
train/eval env wrappers carry a typed `SamplingConfig` through to the
env server (including per-request `cache_salt` via `model_copy`). Policy
train sources get **load-time validation**: the source owns distribution
parameters (`temperature`, `top_p`, etc.), while agents may only
override `max_tokens`, `reasoning_effort`, and
`chat_template_kwargs`—frozen-model and eval paths stay permissive.
`TrainSink` reads temperature from `env.config.sampling` instead of a
resolved args dict.
>
> **Docs** describe alias normalization (`max_tokens` /
`max_completion_tokens`), `extra_body` merging, and live-policy override
limits. **Tests** cover inherited sampling merges and policy sampling
rejection cases. Lockfile bumps `prime-tunnel` to `0.1.14`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
671a5aa9857a39a4d44fa7902f1c89021b8fd380. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- `WeightWatcher.poll_interval` default: 1.0s → 0.1s
- `WeightReceiver.wait_published` sleep: 0.2s → 0.1s
## Why
The trainer blocks in `WeightSender._wait_for_receiver_ready` until the
orchestrator notices `.sender_ready`. With a 1s poll, that adds 0–1s
(~0.5s avg) of idle trainer time on every step. NVIDIA flagged this
while benchmarking the ModelExpress broadcast (#3890).
A poll is one `glob("step_*")` on the broadcast dir (≤2 entries thanks
to `_clean`) plus a few `exists()` calls, so 10Hz is negligible.
Correctness relies on the marker handshake + `update_lock`, not on the
poll timing.
Caveat: these are sync FS calls on the orchestrator event loop. On a
very slow shared FS, that might show up in `EventLoopLagMonitor`. If it
does, we can move them to `asyncio.to_thread`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Timing-only tuning on poll loops; no change to weight handshake logic,
though more frequent sync FS calls could add event-loop lag on very slow
filesystems.
>
> **Overview**
> **Faster weight-version discovery** so the trainer spends less time
blocked waiting for the orchestrator to see `.sender_ready`.
>
> The orchestrator `WeightWatcher` default `poll_interval` drops from
**1.0s to 0.1s**, cutting typical idle wait on each broadcast handshake
from ~0.5s toward ~0.05s. `WeightReceiver.wait_published` uses the same
**0.1s** sleep (was 0.2s) while waiting for the sender marker.
>
> Handshake correctness is unchanged (markers + `update_lock`); cost is
slightly more frequent lightweight FS checks on the orchestrator event
loop.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5c825d0f126e16885eae77f4f6ebc2ddf306de59. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## security(ci): pin BuildKit builder to v0.33.1 and rotate the GHCR
registry buildcache (CVE-2026-93318)
### What changed (rebased onto current main)
`.github/workflows/build_image.yaml`:
1. **Builder pin** — `docker/setup-buildx-action@v4` now sets
`driver-opts: image=moby/buildkit:v0.33.1`. Without it the job starts
the rolling `moby/buildkit:buildx-stable-1` tag, and because these are
persistent self-hosted runners (`image-builder`,
`image-builder-arm-2204`), the builder version is not even guaranteed to
follow the tag — a stale local image can keep a pre-patch builder alive
indefinitely. The pin makes the builder version deterministic.
2. **Registry cache rotation** — both shared cache refs rotated:
- `:dependency-buildcache-<suffix>` ->
`:dependency-buildcache-v2-<suffix>`
- `:application-buildcache-<suffix>` ->
`:application-buildcache-v2-<suffix>`
### Why rotation (evidence)
- The registry-backed cache was introduced in d8f3d0101 (2026-08-16,
#3279) and has been written on nearly every run since — including all
runs before the patch was published.
- BuildKit v0.33.1 (the CVE fix) was released **2026-09-30T17:08Z**; the
rolling `moby/buildkit:buildx-stable-1` tag only moved to that digest at
**2026-09-30T17:32Z**. Every cache write before that timestamp came from
a builder older than v0.33.1, on runners that may also hold stale local
images.
- Per the CVE-2026-93318 playbook: stop importing a shared cache that
pre-fix builders wrote, rebuild from trusted inputs, and pin the patched
builder so every future write is attributable to a fixed version.
### Expected cost
The first run per platform suffix after merge does a cold build of the
dependency layer + application layer (no cache import). The old
`*-buildcache-*` tags can be deleted from the `prime-rl` GHCR package as
cleanup — they are cache-only refs, never deployed.
### Out of scope / notes
- `docker-push.yaml` (old Docker Hub publisher) no longer exists on main
— nothing to pin there.
- No GHA-scope (`type=gha`) caches exist in this repo's workflows
(verified by grep), so no Actions-cache cleanup applies.
- Build image runs are frequent and mostly manual dispatch; this PR
should merge before the next `main` image build.
### Security review requested
- Cache invalidation: confirm the `*-v2-*` refs fully replace the old
buildcache lineage.
- Published-image provenance: GHCR `prime-rl` images built before
2026-09-30T17:32Z were produced by a pre-patch builder; assess whether a
clean rebuild of the current release tags is warranted.
- No applicable CODEOWNERS entry exists in this repo; CI/build owner
please review.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> CI-only security remediation with intentional cache busting (slower
first builds); no application runtime code changes, but GHCR images
built before the fix may need a separate provenance/rebuild decision.
>
> **Overview**
> Remediates **CVE-2026-93318** in the GHCR image build workflow by
making the BuildKit builder version fixed and breaking reuse of
artifacts produced before the patch.
>
> **BuildKit pin:** `docker/setup-buildx-action` now sets `driver-opts`
to `moby/buildkit:v0.33.1` (digest-pinned) so self-hosted
`image-builder` runners do not keep serving a stale local
`buildx-stable-1` builder.
>
> **Cache and deps lineage:** Shared registry cache refs move to
`dependency-buildcache-v2-*` and `application-buildcache-v2-*` so layers
written by pre-v0.33.1 builders are not imported. Dependency base tags
gain a `-v2-` epoch (`deps-${key}-v2-${suffix}`) so existing
`deps-${key}` images are not reused as the runtime base when only
Dockerfile/lock inputs are unchanged.
>
> The first build per platform after merge is expected to be cold (no
old cache import); published runtime tags are unchanged—only CI
remediation naming and builder configuration.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0310e6d89608d9d34fd0c1a4c0e9a5c6ba5261bf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Warn when SFT constructs a renderer that does not guarantee prefix
stability. The warning explains that each conversation is rendered once
into one training sample, that N assistant turns are not expanded into N
samples, and that earlier reasoning may be omitted by the template.
Cached renderers warn only on construction; stable renderers stay quiet.
Custom renderers without the capability are conservatively treated as
unknown.
Pin `deps/renderers` to merged main revision `41f9290`, which includes
https://github.com/PrimeIntellect-ai/renderers/pull/184. It provides the
resolved capability and the manual, opt-in witness audit. Sample
construction is unchanged.
Validation: all **73 SFT dataset tests passed**, including
stable/unstable renderer selection and cache-warning behavior. Prime-rl
unit-test CI passed on the preceding revision; this update changes only
the renderer gitlink to the merged revision. Dependency requirements are
unchanged apart from renderer Python >=3.11, compatible with prime-rl
Python 3.12. The manually invoked renderer audit passes **59 tests** and
is excluded from normal CI discovery.
Reduce CI time and GPU usage by selecting the relevant test suites for
each PR, moving hosted eval to CPU, and running independent setup steps
in parallel.
- Select GPU unit tests, SFT, RL, and hosted eval from changed paths
before allocating runners. Shared runtime and dependency changes retain
broad coverage; pushes to `main` and manual runs execute the full suite.
- Keep RL/SFT coverage for checkpoint converters, dashboard code, and
the shared dashboard smoke helper.
- Run `gsm8k_eval` on `ubuntu-latest` because it uses hosted inference.
- Run public submodule initialization and `uv` setup concurrently, then
wait for both before installing dependencies. Keep dependency caching
keyed on `uv.lock` and the five-job limit on GPU integration tests.
- Cancel superseded CPU and style runs on the same PR.
- Give the GPU workflow read-only contents access and the test selector
PR read access.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Path-based GPU job gating can skip integration coverage on PRs if
filters miss a dependency; full suite still runs on main and manual
dispatch.
>
> **Overview**
> **GPU CI now picks which jobs to run from the PR diff**, instead of
always running the full GPU unit + integration matrix on every non-draft
PR. A new **Select tests** job uses path filters for unit, SFT, RL, and
eval; pushes to `main` and `workflow_dispatch` still run everything.
RL/SFT integration scenarios are built dynamically (still capped at
`max-parallel: 5` on `prime-rl-2xh200`).
>
> **`gsm8k_eval` is split out** into a dedicated job on `ubuntu-latest`
(hosted inference), so it no longer consumes GPU runners. Integration
pytest invocations use `tests/integration/test_${{ matrix.test }}.py`
from the dynamic matrix rather than per-row `pytest_args`.
>
> **Setup and queueing tweaks:** submodule init and `setup-uv` run in
parallel in CPU/GPU jobs; CPU and style workflows cancel in-progress
runs per PR; GPU workflow gets `workflow_dispatch`, read-only
`contents`, and PR-scoped concurrency cancel. `docs/development.md`
documents the new triggers and runner split.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
20da35f30de85b2b18cf82e29598846a1228ca12. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
SFT now pads packed rows only to a multiple of cp, as RL does, instead
of to `seq_len`. The fp8 indexer drops its autotuning, which
re-benchmarked configs on every new row length and made unpadded rows
slower than padded ones on DeepSeek-V4 (#3726).
- The indexer pads keys to a multiple of 16 and runs one fixed config,
within 1.05x of the best.
- Every rank, including RL on DeepSeek-V4 and GLM-5, runs that config
with bitwise-identical top-k.
- SFT and RL throughput count trained tokens, not `seq_len` × rows or
the first row × count.
- The SFT `seq_len % (2 * cp)` check is gone: CP only needs `seq_len %
cp`, which configs enforce.
Same samples per arm, time summed over steps 5 to 20, one H200 node:
| Workload | Padding on main | main | This PR | Speedup |
|---|---|---|---|---|
| DeepSeek-V4-Flash 6L, scaleswe, 256K rows, cp 8 | 19.8% | 61.2 s |
38.2 s | 1.60x |
| GLM-4.5-Air 8L, math, 131K rows, dp 4 cp 2 | 7.3% | 223.8 s | 200.1 s
| 1.12x |
| GLM-4.5-Air 8L, scaleswe, 131K rows, dp 4 cp 2 | 19.7% | 701.0 s |
623.0 s | 1.13x |
On DeepSeek-V4, the 1.60x exceeds the 1.25x that removing 19.8% of
tokens predicts because two effects multiply: main's token-0 pads crowd
onto the same experts, and the padding itself costs compute. The
DeepSeek-V4 ablation section below separates the two.
On GLM with scaleswe, removing 19.7% of the tokens would predict about
1.25x, but it measured 1.13x. Its 4 data-parallel ranks now get rows of
different lengths, and each step likely waits for the rank with the
longest rows.
Loss matches main to within 1e-3 per step. This overlaps
https://github.com/PrimeIntellect-ai/prime-rl/pull/3932 in
`CatDataset._finalize_pack`. Harness:
[`benchmarks/scripts/sft_pad_to_cp/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/0ed0e78b33e8533d7fd1e0d603759dc2ab50e5dd/benchmarks/scripts/sft_pad_to_cp)
(removed before merge).
## DeepSeek-V4 ablation
Each row changes one thing on the DeepSeek-V4 workload above, to
separate the cost of the padding length, of token-0 pads crowding onto
the same experts, and of indexer re-tuning:
| Arm | Time | Speedup vs main |
|---|---|---|
| main: pads every row to `seq_len` with token 0 | 61.2 s | 1.00x |
| main, but pads with the row's own tokens (#3932) | 49.6 s | 1.23x |
| pads only to a multiple of cp, indexer still autotuned | 73.6 s |
0.83x |
| pads only to a multiple of cp, fixed-config indexer (this PR) | 38.2 s
| **1.60x** |
## Alternatives considered
- Bucketing the autotune key on `next_power_of_2(S_q)` reached 1.47x on
DeepSeek-V4. Each bucket kept its first row's config (up to 1.44x slower
later), short rows paid extra tunes, and each rank still tuned on its
own rows, so ranks could run different kernels.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
SFT samples can contain prefilled assistant turns that must remain in
context without becoming training targets. Read an optional
`message_loss_mask` dataset column and pass it directly to
`renderers.build_training_sample`; for a user/assistant/user/assistant
conversation, `[0, 0, 0, 1]` trains only the final assistant turn.
The renderer owns token attribution and mask validation, including GLM's
assistant-generated closing markers. prime-rl performs no owner walking
or template-specific mask reconstruction. Selection only removes
existing loss targets and preserves input/target token IDs. Missing or
null masks preserve normal supervision; fully masked samples follow the
existing skip behavior.
`data.columns.message_loss_mask` supports renamed columns. For
prompt/completion rows, the mask covers their concatenated message list.
This API reads a separate column; datasets with inline
`messages[].trainable_mask` need conversion before use.
Pins `deps/renderers` to upstream main commit
`e3ace557545274385abb30435975c134c7c2429d`, which merges
https://github.com/PrimeIntellect-ai/renderers/pull/181. The renderer
dependency is now merged.
Validation:
- Signed pin update `838828713` points to the merged renderer commit.
Its Git tree is identical to the previously tested renderer head; no
source changes accompany the pin update.
- The following tests and checks passed on signed implementation commit
`7e0800051`:
- 73 SFT dataset tests passed, including real GLM-5 and Qwen3
tokenizers, both dataset layouts, custom column names,
missing/null/all-enabled masks, excluded initial/final turns, fully
masked samples, and invalid values/lengths.
- Ruff 0.13.0 lint and formatting checks passed for the changed Python
files; `git diff --check` passed.
- CPU tests ran in an isolated Python 3.12 environment with Transformers
5.6.2 and PyTorch 2.14.1. No GPU training run performed.
- Commit signature verified locally.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes which tokens receive loss during SFT when datasets supply
masks; incorrect masks could silently train the wrong turns, though
behavior is opt-in and heavily tested against real renderers.
>
> **Overview**
> Adds **optional per-message SFT loss selection** via a dataset
`message_loss_mask` column (0/1 or booleans, one entry per resolved
message—including prompt+completion rows). The trainer forwards the
column to `build_training_sample` so renderers drop supervision on
excluded turns **without changing token IDs** (e.g. `[0, 0, 0, 1]` keeps
context but trains only the last assistant reply). Missing/null masks
behave as today; all-zero masks still skip the sample.
>
> **Config and docs:** `SFTColumnsConfig.message_loss_mask` defaults to
`"message_loss_mask"` and can be remapped (e.g. `"selection"`); dataset
init errors if a remap points at a missing column. `docs/training.md`
documents the format and semantics.
>
> **Tests:** Coverage for GLM-5 and Qwen3, both dataset layouts, custom
column names, partial masks, fully masked rows, and invalid mask
values/lengths.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
838828713529afa49a57cf441071f946ec195cdf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Why
Since **Sep 2** the `4xa6000` runner has been offline. Since then,
`benchmark_regression` has queued on a dead label on **every single GPU
Tests run**, hit GitHub's 24h self-hosted queue timeout, and failed the
workflow. There has not been one green GPU Tests run in over a month, so
the per-PR GPU check is permanently red and real regressions hide in the
noise. Measured over Sep 29-Oct 6: all 28 completed runs failed at
exactly 1440 +/- 1 min, and 20+ phantom `benchmark_regression` jobs were
sitting in the queue at any time.
## What changes
1. **uv cache on the GPU jobs** (`enable-cache: true`, keyed on
`uv.lock`, mirroring `cpu_tests.yaml`) — each h200 pod currently
re-resolves and re-downloads the full dependency set from PyPI on every
job.
2. **`benchmark_regression` removed from the PR matrix.** It cannot
simply move to `prime-rl-2xh200`: the test unconditionally runs a 1-GPU
**and** a 4-GPU benchmark (a 2-GPU pod cannot host the latter), and it
asserts against A6000-captured baselines with a 15% tolerance (H200
results would blow through it). It belongs on benchmark hardware
(`benchmarks.yaml`) or behind a 4-GPU scale set when one exists — happy
to re-add once either exists.
3. **`max-parallel: 5` on the integration matrix** — a concrete per-PR
ceiling:
- 9 integration jobs + unit-tests = **6 h200 pods peak per PR**, 2 waves
- at current job durations (~10-15 min each) a PR finishes in ~25-35 min
- with 2-3 PRs in flight: <= ~18 pods steady-state; the ARC scale set
`maxRunners` (suggest 16-20) is the complementary global cap
4. `docs/development.md` CI table updated to match (also adds
`gsm8k_eval`, which was missing, and the current runner).
## Result
GPU Tests runs **only** on the `prime-rl-2xh200` scale set, and every PR
gets a real green or red within ~30-60 min instead of a guaranteed 24h
failure.
## Not in this PR (follow-ups)
- Bake git/uv into the CI image to kill the per-job `apt-get install
git`
- PVC-backed `~/.cache/uv` mount to avoid per-pod cache archive
downloads
- Nightly Tests still target a `research-cluster` runner that does not
exist — needs the same treatment or a cron disable
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> CI workflow and documentation only; no runtime or auth changes.
Benchmark regression no longer runs on every PR until re-homed to
suitable hardware.
>
> **Overview**
> **GPU Tests** is adjusted so PR runs can finish on live hardware
instead of timing out on a dead runner label.
>
> Both GPU jobs now enable **uv dependency caching** keyed on `uv.lock`
(same pattern as `cpu_tests.yaml`), cutting repeated PyPI
resolves/downloads on each H200 pod. The integration matrix **drops
`benchmark_regression`** (it targeted offline `4xa6000` hardware and
cannot run meaningfully on 2×H200), and adds **`max-parallel: 5`** so at
most five integration jobs run at once per PR. **`docs/development.md`**
updates the CI table to list the current integration scenarios
(`gsm8k_eval` included), `max-parallel`, and **`prime-rl-2xh200`** as
the runner.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8207cc05d9a731a4c5d7c561354284f1a79792d4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Bump `deps/verifiers` from `1fa2bbc42` to main `da75527ca`. This pulls
in the Harbor adapter changes from PrimeIntellect-ai/verifiers#2808:
- Honor reward-file precedence and select named rewards explicitly.
- Resolve separate verifier definitions by Harbor image precedence.
- Align the adapter with Harbor 0.24.0 and reject multi-step tasks.
- Move the `harbor` upload cutoff in `[tool.uv.exclude-newer-package]`
from 2026-08-11 to 2026-10-08, which matches `deps/verifiers`. verifiers
now pins `harbor==0.24.0`, which the old cutoff excluded.
- Relock: `harbor` 0.21.0 → 0.24.0, and `semver` 3.1.0 is new.
`deps/prime-envs` is already at its main head (`89dcc7ffc`). The current
verifiers pin already has the network notice
(PrimeIntellect-ai/verifiers#2769), so this bump supersedes #3734.
## Verification
- `uv sync --all-extras --all-packages --locked` succeeds.
- `uv run pytest -m "not gpu" tests/unit`: 663 passed.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Lockfile and uv policy changes only; risk is mainly behavioral shifts
from Harbor 0.24.0 and updated verifiers Harbor adapter usage in
eval/training paths.
>
> **Overview**
> Updates dependency resolution so **`harbor` 0.24.0** (via the
`verifiers[harbor]` pin) can install under uv’s rolling
**exclude-newer** policy by moving the bounded **`harbor` cutoff** from
`2026-08-11` to **`2026-10-08`** in `pyproject.toml`, mirrored in
`uv.lock`.
>
> The lockfile refresh bumps **`harbor` 0.21.0 → 0.24.0**, records new
transitive deps **`jsonschema`** and **`semver`**, and aligns the
verifiers harbor extra specifier to **`==0.24.0`**. This pairs with the
verifiers main bump described in the PR (Harbor adapter alignment and
reward/verifier precedence behavior), even though those code changes
live outside this diff.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
69e62c1fc116896ce99c79dbfc454959c748cb47. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
On torch 2.13.0 with compile and router replay, some MoE layers silently
replay layer 0's routing instead of their own from the second training
step on. This PR calls `.contiguous()` on each layer's routed-experts
slice, which removes the bug.
Each decoder layer `l` receives `routed_experts[:, :, l]`, a view into
one shared int32 tensor with axes (batch, sequence, layer, expert slot).
When `top_k` is not a multiple of 4, that view starts at a byte offset
that is not 16-byte aligned for some layers (odd layers on DeepSeek V4,
`top_k = 6`).
Inductor copies a misaligned input into a fresh aligned buffer, which
starts at offset 0. Once automatic dynamic shapes recompile the layer,
AOTAutograd mistakenly applies that offset 0 to the original shared
tensor when it rebuilds the layer's routed-experts output. Offset 0 of
the shared tensor holds layer 0's experts. A contiguous slice is its own
aligned tensor, so Inductor never makes the copy.
- Applied to the eight models that passed the raw view. `glm4_moe`
already called `.contiguous()`.
- Fixed upstream in pytorch/pytorch#191002 (torch 2.14.0 and 2.14.1, no
2.13.x release). The copy is cheap, so it can stay after an upgrade.
- Models with `top_k = 8` (Qwen3-30B-A3B, Trinity-Mini, GLM-4.5-Air)
were unaffected.
DeepSeek V4 Flash RL probe (compile on, router replay on, lr 0),
mismatch KL mean, lower is better:
| trainer | step 1 | steps 2-10 |
|---|---|---|
| compiled, strided slice (main) | 0.0008 | 0.022-0.11 |
| compiled, contiguous slice (this PR) | 0.0009 | 0.0007-0.0025 |
With compile off, the same probe spans 0.0008-0.0032 over steps 1-10.
## Verification
A standalone torch reproducer was added in
66641b0b0b31da76082edaadd70b4f601b13a53a and removed again at the end of
this branch, so main never carries it. Run it on one CUDA device from
that commit with `TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 uv run python
tools/repro_misaligned_replay_alias.py`. In earlier runs it printed `BUG
REPRODUCED` on torch 2.13.0 and was clean on the 2.14.0.dev20260809 and
2.16.0.dev20261008 nightlies.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Hosted runs with online evals score real rewards but the run dashboard
shows no `eval` metric group (ENG-6573).
The dashboard's `eval` group is built from the run's own metric keys
(`eval/{env}/...`). The orchestrator's in-process evals reach it through
the train monitor, but when evals run in a process of their own (SFT
online evals) the metrics are dropped: `PrimeEvalMonitor.log_metrics`
was a deliberate no-op.
- `PrimeEvalMonitor` now attaches to the parent training run via
`$RUN_ID` and forwards each epoch's `eval/...` metrics there.
- The eval process never reports the parent run's status: the SDK's
atexit crash hook is unregistered and `finalize()` only drains the
queue. Without that, an eval process exiting while the trainer is still
going would mark the whole run failed.
- No parent attached without `$RUN_ID`, so a standalone `prime eval` is
unchanged.
Note the ticket proposes exposing `environmentshub/resolve` on the
platform's internal API instead. That's a separate gap: it silences the
`EnvironmentResolutionError` warning and would create per-epoch
Evaluation records, but it does not produce the `eval` metric group, and
it needs four more `/evaluations` routes that the internal surface also
lacks.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how eval processes interact with the parent platform run
(metrics + SDK lifecycle hooks); mistakes could misreport run status or
drop metrics, but behavior is gated on $RUN_ID and explicitly avoids
finishing the parent.
>
> **Overview**
> Fixes hosted runs where **SFT online evals** compute rewards but the
run dashboard never shows the **`eval`** metric group (keys like
`eval/{env}/...`).
>
> **`PrimeEvalMonitor`** now attaches a metrics-only handle to the
parent training run when **`$RUN_ID`** is set, and **`log_metrics`**
forwards sanitized epoch aggregates there instead of being a no-op.
Standalone **`prime eval`** (no **`$RUN_ID`**) is unchanged.
>
> Lifecycle is guarded so the eval subprocess cannot poison the parent
run: the SDK **atexit** hook on the attached parent is **unregistered**,
and **`finalize()`** only **`flush`**es the upload queue—never finishes
or reports status on the trainer’s run.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
892035628173119b14a591b2975a5b6176f4c357. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
This is an alternative to #3907. The RL trainer decoded and preprocessed
each micro batch's images on the main thread right before its forward
pass, leaving the GPU idle. `WorkerPool`, a small ordered thread pool
configured by `data.num_workers` like torch's DataLoader, now prepares
micro batches ahead of the loop through a single `prepare_micro_batch`
hook.
- `num_workers` defaults to 0, which prepares on the main thread as
before, and one thread gives the full speedup. Here it counts threads,
unlike SFT's DataLoader processes.
- An earlier version used forked worker processes. They pickle data
through `/dev/shm`, risk copy-on-write memory, and were 0.6 s/step
slower than a thread.
- Pinned memory and `non_blocking` copies are left to a follow-up that
first removes the per-micro-step CUDA syncs.
Qwen3.5-9B trainer-only on 4 H200s, mock micro batches of 1024 px JPEGs
(about 1 s of CPU decoding each), median s/step, lower is better
(benchmark code added in
[`331fc83fe`](https://github.com/PrimeIntellect-ai/prime-rl/commit/331fc83fed9ff8b6fb435df5207a07e37b08c0e5)
and removed in the next commit):
| Arm | main thread | prepared ahead | time saved |
|---|---|---|---|
| this PR, 1 thread | 24.98 | 18.86 | 24.5% |
| this PR, 1 thread, optimizer CPU offload | 26.56 | 20.24 | 23.8% |
| earlier process version, 2 workers | 24.79 | 19.02 | 23.3% |
| #3907 (thread with pinned memory) | 24.98 | 18.63 | 25.4% |
Every arm matches the main-thread baseline bit for bit in loss and grad
norm. Host memory stays flat over 30 steps, 0.3 GiB above the baseline
for the prefetched images.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
## Summary
Two bugs in how `rl` sets `weight_broadcast.inference_world_size` on
main:
1. **World size computed before the DP fill.**
`auto_setup_weight_broadcast` set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
before `auto_setup_deployment` fills the single-node inference GPUs with
DP ranks. With `num_infer_gpus = 4` and `data_parallel_size` unset, the
NCCL group was sized for 1 inference worker while vLLM started 4, so the
first weight update cannot form the group.
2. **A single-node SLURM job cannot re-parse its `rl.json`** (since
#3788). The resolved `rl.json` always contains
`weight_broadcast.inference_world_size` (default 1), and #3788's guard
rejects any config that sets it. So `rl @ rl.json` in the single-node
sbatch fails validation for every NCCL config.
## Fix
- Single-node: set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
right after the DP fill in `auto_setup_deployment` (non-filesystem
only). Multi-node already sets it there.
- `auto_setup_weight_broadcast` copies `weight_broadcast` to the trainer
and orchestrator without touching the world size, and the guard is
removed. The top-level value is now only passed through: `rl` overwrites
it whenever it knows the inference size.
This also fixes what #3924 fixes.
## Behavior change
Yes (bug fixes).
- Resolved configs for every TOML in `configs/`, `examples/`, `k8s/`
that parses as `RLConfig` (41 of 78) are identical before and after,
except `trainer`/`orchestrator.weight_broadcast.inference_world_size`
goes from 1 to 4 in `examples/basic/hendrycks-sanity/rl.toml` and
`configs/ci/nightly/multimodal_color_codeword.toml` (4 infer GPUs, DP
unset).
- Re-parsing the dumped config (as the single-node sbatch does) fails on
main for all 18 single-node NCCL configs and passes for all of them
here.
- With `inference = None` and NCCL against external servers, a user-set
`weight_broadcast.inference_world_size` is now passed through instead of
rejected.
## Checks
- `pytest tests/unit/test_configs.py tests/unit/orchestrator -m "not
gpu"`: 298 passed
- `ruff check`, `ruff format --check`: clean
- New test `test_single_node_nccl_resolved_json_roundtrips`: dumps a
single-node NCCL config like `rl`'s `write_config`, re-parses it, and
checks it is equal. It fails on main with the guard error.
- `rl @ examples/basic/reverse-text/rl.toml --deployment.num-infer-gpus
2 --slurm.partition all --dry-run`, then re-parse the written `rl.json`:
fails on main, passes here (world size 2).
- GPU (one node): running: `rl @ examples/basic/hendrycks-sanity/rl.toml
--max-steps 3` on main and on this branch, plus the rendered single-node
sbatch for reverse-text (2 infer GPUs) run end to end.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes when NCCL weight broadcast groups are sized for single-node
runs; mis-sizing previously caused deadlocks or init failures during
weight updates.
>
> **Overview**
> Fixes incorrect **NCCL/NIXL** `inference_world_size` on single-node RL
runs when vLLM **data parallel size** is inferred from `num_infer_gpus`
rather than set explicitly.
>
> **`auto_setup_weight_broadcast`** no longer derives
`trainer`/`orchestrator.weight_broadcast.inference_world_size` from
`data_parallel_size × tensor_parallel_size` (which ran before DP was
filled) and no longer rejects a user-set `inference_world_size`.
**`auto_setup_deployment`** (single-node) now sets
`inference_world_size` to `dp × tensor_parallel_size` immediately after
the DP/`api_server_count` fill, so the in-memory transfer group matches
every inference GPU that joins NCCL.
>
> Unit tests assert the resolved world size (2 infer GPUs → size 2) and
that a dumped `rl.json` round-trips unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f5553f5c5dd2f91aa11003338ef13e285a6c9ee6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
- Delete `trainer/models/layers/rms_norm.py`. It only re-exported
`RMSNorm`/`RMSNormConfig` from `layers/norms.py`, and nothing imported
it.
- Move `quantize_to_fp8_blockwise` from `trainer/models/fp8.py` into
`tools/convert_bf16_to_fp8.py`, its only user.
`tools/convert_dcp_to_fp8.py` still imports it through
`convert_bf16_to_fp8`. While moving it, the 9-line zero-pad block
becomes `F.pad(weight, (0, pad_cols, 0, pad_rows)).contiguous()`; the
output is bitwise identical to the old function (bf16/fp16/fp32, padded
and unpadded shapes, contiguous and transposed inputs).
## Behavior change
None.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Dead-code removal and relocating a tool-only quantizer; no trainer
inference or training path changes.
>
> **Overview**
> Removes dead trainer surface area and keeps FP8 checkpoint conversion
self-contained in the tooling layer.
>
> **`trainer/models/layers/rms_norm.py`** is deleted (it only
re-exported `RMSNorm` / `RMSNormConfig` with no importers).
**`trainer/models/fp8.py`** is removed and
**`quantize_to_fp8_blockwise`** now lives in
**`tools/convert_bf16_to_fp8.py`**, which was its only consumer;
**`convert_dcp_to_fp8.py`** continues to pull quantization helpers from
that script. Padding inside the moved helper uses **`F.pad`** instead of
manual zero-fill, with the same blockwise e4m3 logic otherwise
unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c35ca75057037c6d98f0080bdffae8efd24e2f85. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Processes that share `~/.triton` on a shared filesystem can hang or
crash (seen with Nemotron-H, where many ranks compile the Mamba Triton
kernels at once; reproduced below with Qwen3.5 and GLM-4.5-Air).
This PR adds `TRITON_CACHE_DIR = /tmp/triton-<uid>` to
`DEFAULT_COMMON_ENV_VARS`. It is per-user because `/tmp` is shared by
all users on a node. Like the other launcher defaults, it reaches every
launched component: the local `rl`/`sft`/`inference` launchers (also
used by the single-node sbatch scripts) and the trainer, orchestrator,
inference (incl. prefill/decode), and online-eval env blocks of the
multi-node and inference sbatch scripts. `[env_vars]` (or a component's
`env_vars`) overrides it; a value exported in the shell or `.env` does
not. It also removes the `TRITON_CACHE_DIR` overrides from six example
configs (glm-4.5-air swe/swe-budget/search/terminal, glm-5.3 and
qwen3-30b-a3b sft h200 base): they pointed every user at the same `/tmp`
dir and are now covered by the default. `docs/scaling.md` says so in one
paragraph.
vLLM 0.31's own default: when `TRITON_CACHE_DIR` is unset, its Inductor
adaptor points it at
`$VLLM_CACHE_ROOT/torch_compile_cache/<hash>/rank_<i>_<j>/triton_cache`
(`~/.cache/vllm` by default, so usually on the shared home). That only
covers Triton kernels compiled after torch.compile initializes, and it
is still on the shared filesystem. vLLM keeps a `TRITON_CACHE_DIR` that
is already set, so with this PR vLLM uses `/tmp/triton-<uid>` too.
### Measured cost (one H200 node, vLLM 0.31 venv, Triton 3.7.1)
Each run starts from a fresh process with the same config. "Ready" is
launch → first trainer step logged (Qwen) or launch → `/health` OK
(GLM). For GLM, the first generated token came 1.3–2 s after ready in
every run that came up. Inductor's cache dir was emptied before each run
except the warm node-local one.
| Triton cache | Qwen3.5-4B SFT, 8 GPUs, compiled blocks (step 1 time) |
GLM-4.5-Air vLLM TP8 |
|---|---|---|
| shared, cold (today on a new cluster / after a Triton or torch update)
| **failed 2/2**: `FileNotFoundError` on a cache file that another rank
was writing (`causal_conv1d_fwd_kernel.llir`, `l2norm_fwd_kernel.ptx`) |
**failed 2/2**: 4 of 8 ranks hit `FileNotFoundError` in the cache during
Inductor autotune, the other 4 hung in a collective until killed (1st
run). The 2nd run crashed instead of hanging. |
| shared, warm | not measured cleanly (see below) | 344 s |
| node-local, cold (this PR, first job on a node) | 233 s (step 1: 91
s), 164 kernels compiled | 375 s with vLLM's compile cache warm (106
kernels); 465 s if vLLM's cache is also cold (87 kernels) |
| node-local, warm (this PR, later jobs on the same node) | 138 s (step
1: 8.3 s) | 344 s |
- A cold node-local cache costs about **95 s per node for Qwen3.5** (FLA
+ Inductor kernels) and about **31 s for GLM-4.5-Air inference** when
vLLM's own compile cache is warm. Warm node-local and warm shared take
the same time.
- The rest of the GLM startup does not depend on the Triton cache: about
3.5 min of Python imports and process spawn from the shared venv, 13 s
to load weights.
- vLLM: `VLLM_CACHE_ROOT` (`~/.cache/vllm`, shared home) holds vLLM's
AOT/Inductor artifacts. With this PR it stays shared. On a new node,
vLLM loads those artifacts (`torch.compile` 0.6 s instead of 30 s), and
the Triton binaries are compiled into `/tmp/triton-<uid>` (106 kernels,
+31 s). `TORCHINDUCTOR_CACHE_DIR` (default `/tmp/torchinductor_<user>`,
already node-local) stayed empty in these runs. Inductor's Triton
kernels go to `TRITON_CACHE_DIR`.
- A crash on the shared cache can also break later starts. After the
first failed GLM run, the shared vLLM cache only had AOT artifacts from
the 4 ranks that got through. On the next start, those 4 ranks loaded
the artifacts and the other 4 recompiled, so the ranks diverged and hung
(Triton cache warm-ish, 60 kernels). For the same reason the Qwen
"shared, warm" run started from a partial cache and failed again. The
warm-shared GLM number comes from a shared dir seeded with a complete
cache.
### Possible middle ground (not implemented)
Because the cold cost is above 1 min per node for FLA-heavy models, a
run could seed the node-local cache from a shared read-only copy at job
start. For example, on each node before the components start:
`[ -n "$TRITON_CACHE_SEED" ] && cp -rn "$TRITON_CACHE_SEED"/.
"$TRITON_CACHE_DIR"/`
The seed would be a warm `/tmp/triton-<uid>` copied once to the shared
FS. Triton keys entries by source, compiler, and GPU, so stale entries
are never reused, only skipped. Only reads hit the shared FS, so the
concurrent-write race does not occur. I left it out to keep this PR
minimal.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Launch-time env default only; behavior is overridable via config and
fixes known multi-rank Triton cache races, with a one-time cold-compile
cost on each node.
>
> **Overview**
> **Sets a global launcher default** so every trainer, orchestrator, and
inference process gets `TRITON_CACHE_DIR=/tmp/triton-<uid>` via
`DEFAULT_COMMON_ENV_VARS`, avoiding concurrent Triton kernel writes
under `~/.triton` on a shared filesystem (hangs / `FileNotFoundError`
under multi-rank compile).
>
> **Removes redundant `[env_vars]` overrides** from six GLM-4.5-Air RL
and GLM-5.3 / Qwen3-30B SFT example configs that previously pinned
Triton cache paths under `/tmp`; those runs now inherit the per-user
node-local default (still overridable through config `env_vars`).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f21642046ea59cab0b9460863560b4df825f29c0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
---------
Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
## Summary
Fold `GenerationSource` into `TrainEnv`, its only owner. Move
`connect_frozen_client` from `algo/base.py` to `clients.py`, so `algo`
no longer imports `clients` lazily. Give `TrainEnv` `setup()`/`aclose()`
so orchestrator setup and teardown no longer reach into its parts.
## What changed
- `orchestrator/generation_source.py` is deleted. `TrainEnv` (`envs.py`)
now holds `clients`, `renderer_config`, `connected` (the frozen source
clients it connected) and `uses_live_policy`. Dropping `logprobs` for
frozen sources happens in `TrainEnv.__init__`.
- `TrainEnv.setup()` connects the frozen generation source and runs
`algorithm.setup()` concurrently. `TrainEnv.aclose()` closes `connected`
and `algorithm.connected`, never the shared policy clients.
- `connect_frozen_client` is a plain function in `clients.py`, next to
`check_inference_ready`. `algo/base.py` imports it at module level. It
is no longer re-exported from `prime_rl.orchestrator.algo`.
- `dispatcher.py` reads the `TrainEnv` directly at the four former
`generation_source` call sites. `orchestrator.py` calls `env.setup()`
and `env.aclose()`.
- `docs/algorithms.md` and the `algo/__init__.py` docstrings refer to
`TrainEnv`.
## Behavior change
None.
## Checks run
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 297 passed.
- `ruff check`, `ruff format --check`: clean.
- Equivalence script, old `GenerationSource` (`origin/main`) vs new
`TrainEnv`, on 4 configs: policy, policy with `top_p=0.9`, sft with a
frozen `sampling.source`, opd with a frozen teacher. Identical
`sampling_args`, `requires_sampling_masks` and `uses_live_policy`. After
`setup()`, the same generation clients (policy object, or the frozen
endpoint with the same train client config) and the same algorithm
clients. Teardown closes the same clients.
- GPU smoke on one node (vLLM 0.31): reverse-text RL (15 steps), sft
with a frozen `sampling.source` (5 steps), opd with a frozen teacher (5
steps). All three ran to "Training finished" and exited 0.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Internal orchestrator refactor with stated behavioral equivalence and
no changes to training algorithms or dispatch semantics beyond
indirection.
>
> **Overview**
> **Refactors train rollout sourcing** by deleting `GenerationSource`
and moving its responsibilities onto `TrainEnv`: inference `clients`,
live-vs-frozen policy detection (`uses_live_policy`), sampling-arg
tweaks (e.g. dropping `logprobs` for frozen endpoints), and frozen-pool
connection in `setup()`.
>
> `TrainEnv.setup()` now connects frozen `sampling.source` endpoints and
runs `algorithm.setup()` together; `TrainEnv.aclose()` closes only
env-owned clients (`connected` + algorithm pools), not the shared policy
pool. The orchestrator and dispatcher call these surfaces instead of
reaching into a nested `generation_source`.
>
> `connect_frozen_client` moves from `algo/base.py` to `clients.py`
(next to `check_inference_ready`); it is no longer re-exported from
`prime_rl.orchestrator.algo`. Docs and package docstrings now describe
`TrainEnv` as owning the sampling half of the algorithm config.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e89ca1a663ae6ae808b05ff3326ce9ed63c9b467. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Apply a policy-version cache salt only when inference weights can change
during a run. Standalone evaluations and frozen-model requests omit the
training salt; live RL rollouts and online evaluation retain it so
caches distinguish policy versions.
## Before
The dispatcher added the policy version as `cache_salt` to every request
using the live policy source. Standalone evaluation used that same
source path, so fixed-weight evaluations received a training cache salt
even though no weight updates occurred. Frozen-model requests already
omitted it.
```mermaid
flowchart TD
Standalone["Standalone evaluation with fixed weights"] --> Live["Live policy source"]
Training["RL or online evaluation with changing weights"] --> Live
Live --> Salt["Always add policy-version cache_salt"]
Salt --> Request["Verifiers provider request"]
Frozen["Frozen model source"] --> Plain["Omit training cache_salt"]
Plain --> Request
```
## After
```mermaid
flowchart TD
Request["Prime-RL dispatcher builds request sampling"] --> Mode{"Live policy source with changing weights?"}
Mode -->|"Yes: RL or online evaluation"| Salt["Set cache_salt to policy version"]
Mode -->|"No: standalone evaluation or frozen model"| Plain["Omit training cache_salt"]
Salt --> Client["Verifiers client builds provider request"]
Plain --> Client
Client --> Provider["Inference provider"]
```
The dispatcher records whether policy weights can change. The standalone
evaluator disables version salting, SFT online evaluation enables it,
and RL orchestration keeps it enabled. The request decision also checks
whether the source uses the live policy.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Narrow behavior change to cache salting on eval paths; RL and online
eval keep prior salting via the default flag.
>
> **Overview**
> Adds a **`policy_weights_change`** flag on `Dispatcher` so inference
**`cache_salt`** (policy version) is only attached when weights can
actually change during the run.
>
> **Standalone eval** (`EvalConfig`) sets the flag to **false**, so
fixed-weight evaluation no longer invalidates prefix caches on every
training policy version. **SFT online eval** and **RL orchestration**
(default **true**) still salt live-sourced requests so caches stay
correct across weight updates.
>
> The cache decision is now **`live_sourced and policy_weights_change`**
instead of salting all live policy paths.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5a2d7d9652740106e63fee31a6e79da13816dae7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Keep successful empty environment outcomes in evaluation results. A
trace-less episode or clean zero-turn trace retains the verdict returned
by Verifiers, while training and curriculum logic exclude zero-turn
traces.
## Before
The dispatcher changed successful trace-less episodes into
`EmptyEpisode` failures. Clean, non-timeout zero-turn traces became
`EmptyTrajectory` failures, marking both the trace and episode
unsuccessful. Evaluation therefore recorded a failure even when the
environment had returned success, while training and curriculum filters
relied on those injected errors to exclude empty traces.
```mermaid
flowchart TD
Env["Verifiers returns an empty successful outcome"] --> Dispatch["Prime-RL dispatcher"]
Dispatch --> Episode["No traces: inject EmptyEpisode"]
Dispatch --> Trace["Clean zero-turn trace: inject EmptyTrajectory"]
Episode --> Failed["Rewrite outcome as failed"]
Trace --> Failed
Failed --> Eval["Evaluation records a failure"]
Failed --> Training["Training and curriculum filter injected errors"]
```
## After
```mermaid
flowchart TD
Env["Verifiers environment returns an episode"] --> Dispatch["Prime-RL dispatcher preserves empty outcome verdicts"]
Dispatch --> Eval["Evaluation records and metrics"]
Dispatch --> Filter["Training trace eligibility"]
Filter --> Empty["Zero turns: no training sample"]
Filter --> Sample["Eligible trace with sampled tokens: training sample"]
Dispatch --> Curriculum["Curriculum ignores zero-turn traces and admits only trainable groups"]
```
Remove the synthetic `EmptyEpisode` and `EmptyTrajectory` errors.
`iter_trainable_traces()` filters empty traces alongside failed and
untrainable traces before advantages are assigned, so the advantage gate
needs no separate zero-turn check. Difficulty sampling also excludes
zero-turn traces. Empty groups finish without producing a trainer
payload, and mixed groups retain their eligible traces. Curriculum
admission also requires a trainable trace, so groups without training
samples cannot inflate admission metrics. Sampler observations of
completed turns are retained even when token metadata is unavailable.
Verifiers' no-agent validation and training timeout handling remain in
place.
[#3824](https://github.com/PrimeIntellect-ai/prime-rl/pull/3824) applies
the same ownership rule to partially failed episodes: preserve
environment results, then decide training eligibility explicitly.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes evaluation outcome recording and which rollouts feed
training/curriculum admission, which can shift eval metrics and training
batch composition without touching auth or data stores.
>
> **Overview**
> Stops the dispatcher from **injecting** `EmptyEpisode` /
`EmptyTrajectory` errors on successful trace-less or zero-turn outcomes,
so **evaluation keeps Verifiers’ success verdict** instead of recording
synthetic failures.
>
> Training and curriculum now **exclude zero-turn traces explicitly**:
`iter_trainable_traces()` skips `num_turns == 0`, difficulty-pool reward
updates require `num_turns > 0`, and curriculum admission requires
**both** passing gates **and** at least one trainable trace via
`iter_trainable_traces()`. Scored rollouts without token/advantage
metadata can still update sampler difficulty; groups with no trainable
samples no longer count as admitted.
>
> Tests cover mixed groups with non-trainable traces, empty-only groups,
and reward-only observations for the sampler.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8582fb8c18e7cb4aa0dc7af58c6e0a4474bd7b40. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
Raises the `prime-runs[train]` floor from `>=0.1.3` to `>=0.1.4` and
updates `uv.lock` to match.
## Why
`prime-runs` 0.1.4 lets a run opt out of Prime Traces and upload its
samples to the legacy sample tables instead
(PrimeIntellect-ai/prime#998):
- `PRIME_TRACES_OPT_OUT=true`
- `prime config set-traces-opt-out true`, which sets `traces_opt_out` in
`~/.prime/config.json`
- `prime_runs.init(traces_opt_out=True)`
`prime-runs` 0.1.3 doesn't know about any of these. With 0.1.3
installed, which is what `uv sync` gives today, a user who sets the
environment variable or the config key gets no error and no warning, and
their runs keep uploading to Prime Traces. Requiring 0.1.4 makes the
setting take effect.
Nothing changes for runs that don't opt out. The Prime monitor calls
`prime_runs.init()` without the new argument, so the default (upload to
Prime Traces) is unchanged.
A training run that opts out needs pyarrow for the legacy sample
encoder. prime-rl already depends on `prime-runs[train]`, which includes
it.
## Changes
- `pyproject.toml`: `prime-runs[train]>=0.1.3` →
`prime-runs[train]>=0.1.4`.
- `uv.lock`: `prime-runs` 0.1.3 → 0.1.4. No other package moves;
`prime-traces` stays at 0.0.7.
The `deps/verifiers` submodule is not changed. Its own floor is raised
separately in PrimeIntellect-ai/verifiers#2805, and this PR doesn't
depend on it.
`uv lock --check` passes. I did not run the test suite.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Dependency floor bump only; no application code changes and default
trace upload behavior stays the same.
>
> **Overview**
> Raises the **`prime-runs[train]`** minimum from **`>=0.1.3`** to
**`>=0.1.4`** in `pyproject.toml` and pins **`prime-runs` 0.1.4** in
`uv.lock`.
>
> This ensures installs pick up **Prime Traces opt-out** behavior
(`PRIME_TRACES_OPT_OUT`, `prime config set-traces-opt-out`, or
`prime_runs.init(traces_opt_out=True)`), which 0.1.3 silently ignored so
opted-out runs could still upload to Prime Traces. Default runs that do
not opt out are unchanged; `prime-rl` still depends on the **`[train]`**
extra for legacy sample encoding when opting out.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
06caa96109250b6b800d8e757de7133b4f152031. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
With `moe_router_dtype="float32"` (the RL default) and activation
checkpointing on, every MoE block ran eager under `torch.compile`. Two
things combine to cause it:
- The fp32 router is its own FSDP2 unit, and FSDP2 hooks are
dynamo-disabled, so the router always breaks the graph.
- Under `compile(AC(block))` the checkpoint compiles as a higher-order
op, which forbids breaks, so Dynamo ran the whole block eagerly.
This PR compiles inside the checkpoint instead: for any checkpointed
block that holds a nested FSDP unit (today, the fp32 router), an eager
checkpoint now wraps the compiled block (`AC(compile(block))`), so the
nested unit's break only splits the block into compiled graphs. To see
those units, compile now runs after FSDP. Compiling in place keeps the
same module object, so the order changes nothing at runtime.
The reorder is safe. The old `AC -> Compile -> FSDP` comment was ported
from TorchTitan in #923, when `apply_compile` still wrapped each block
with `torch.compile(block)`. #957 switched to in-place `.compile()` two
days later without revisiting it. With in-place compile, both orders
trace the same frames: graph breaks, loss and step time match on both
workloads, and `fullgraph=True` (with a bf16 router) still compiles with
zero graph breaks.
| Workload (8x H200, EP 8, full AC) | before (s/step) | after (s/step) |
MFU |
|---|---|---|---|
| GLM-4.5-Air, 16 layers, real data | 6.21, 6.17 | 5.22, 5.21 | 35% to
42% |
| Qwen3-30B-A3B, fake data | 5.96, 5.96 | 4.51, 4.51 | 32% to 42% |
Two runs per arm, each the median `time/step` over steps 5 to 20, no
offloading. Peak memory is unchanged, and loss and grad norm track the
baseline within run-to-run noise.

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

</details>
## Alternative considered
Keeping recompute inside the compiler: drop the block-level checkpoint
and instead checkpoint two compiled regions that exclude the router, the
attention module and the post-router MoE work. It beat the baseline but
was slower than this PR (Qwen3-30B 5.50 vs 4.51 s/step, GLM-4.5-Air 5.85
vs 5.22 s/step) and used more memory, because the norms and the router's
fp32 activations stay outside any checkpoint.
## North star: fullgraph fp32 router support
Fullgraph compile with an fp32 router stays unsupported, and
`model.compile.fullgraph=true` still raises for it. The blocker is the
router's FSDP unit itself: FSDP2 applies one mixed-precision policy per
unit, so the fp32 router cannot share the block's bf16 unit, and its
dynamo-disabled hooks are the graph break above. PyTorch
[#196626](https://github.com/pytorch/pytorch/pull/196626) adds
per-parameter mixed precision, which lets the router stay in the block's
unit. That removes the break, enables fullgraph, and makes this PR's
compile-inside-AC path unnecessary, so it should be reverted then.
#196626 is on PyTorch `main` but not yet in a release.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
## Summary
Add `iter_moe_blocks(model)` in `trainer/model.py`. It yields the `MoE`
MLP of each decoder layer. It replaces the five copies of the
decoder-layer MoE lookup in `freeze_moe_router`,
`apply_fp32_moe_router`, `get_full_offload_dtype_policy`,
`apply_force_balanced_routing` and `get_load_balance_stats`.
## What changed
- New `iter_moe_blocks` next to the helpers that use it. The helpers
stay in `model.py`, so no imports change.
- The four `layer.mlp if hasattr(...) else layer.feed_forward ...`
lookups and the `getattr(mlp)` + `hasattr(tokens_per_expert)` scan in
`get_load_balance_stats` now call `iter_moe_blocks`.
- Removed the stale "HF impl" comment in `get_expert_load_stats`. The HF
fallback was removed in #3773.
## Behavior change
None. The `feed_forward` fallback is gone. Every prime-rl decoder layer
uses `mlp`. `get_load_balance_stats` already looked only at `mlp`. Only
`MoE` registers `tokens_per_expert`, so it selects the same layers as
before.
## Checks
- CPU equivalence vs `main` (throwaway script, not in the repo). Tiny
Qwen3-MoE (`mlp_only_layers=[1]`) and GLM4-MoE
(`first_k_dense_replace=1`) models with fixed router-count buffers.
Compared `is_tt_moe_model`, `get_load_balance_stats`,
`get_global_moe_stats`, `compute_expert_load_stats`,
`get_expert_load_stats` and `get_full_offload_dtype_policy`, plus
parameter dtype and `requires_grad`, and router
`fp32_gate`/`force_balanced` after the three router helpers. All 16
outputs were bit-identical.
- `pytest tests/unit/train tests/unit/orchestrator
tests/unit/test_configs* -m "not gpu"`: 450 passed, 1 failed. The
failure is
`test_cpu_adam.py::test_native_cpu_adamw_matches_fused_torch_and_preserves_gradients`
(ninja build), which fails the same way on `main`.
- `ruff check` and `ruff format --check`.
- GPU: reverse-text MoE RL smoke vs `main` on one node, running.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Mechanical refactor of MoE traversal with no intended behavior change;
only risk is if a model relied on the removed feed_forward path (none in
this codebase).
>
> **Overview**
> Introduces **`iter_moe_blocks`**, a single iterator over decoder
layers whose `mlp` is a **`MoE`**, and rewires MoE
router/offload/metrics helpers to use it instead of repeated per-layer
`mlp` / `feed_forward` lookups.
>
> **`freeze_moe_router`**, **`apply_fp32_moe_router`**,
**`get_full_offload_dtype_policy`**, **`apply_force_balanced_routing`**,
and **`get_load_balance_stats`** now loop over that iterator; the unused
**`feed_forward`** fallback is removed. **`get_expert_load_stats`** only
drops an outdated comment on the empty tensor guard.
>
> Intended as a no-op for supported models: same router freezing, fp32
gates, FSDP dtype policy, debug balanced routing, and load-balance /
expert-load metrics.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2cf0399ca4e467c9ae028082c2a03f02604abbf8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Make `trainer.model.freeze_moe_router` default to on for RL.
## What changes
- `model.freeze_moe_router` is now `bool | "auto"`, default `"auto"`. It
resolves to `True` on the RL `TrainerConfig` and to `False` on
`SFTConfig`, following the per-trainer pattern of `moe_router_dtype`. An
explicit `true`/`false` still wins.
- `freeze_moe_router()` no longer raises on non-MoE models; it does
nothing, so dense RL runs keep working with the new default.
- `docs/training.md` knobs table lists the field.
## Why
In RL, router updates amplify the train/inference routing mismatch: the
trainer's expert choices drift away from the ones inference sampled. So
RL keeps the pretrained router by default. SFT is unchanged.
What gets frozen: the router gate parameters (`mlp.router.gate.weight`,
plus `gate.bias` on gpt-oss). The aux-loss-free `selection_bias` buffer
is not a parameter, and nothing on main updates it. Shared-expert gates
(Qwen3.5) and Nemotron-H latent projections are not touched. Frozen
routers get no optimizer state.
## Breaking changes
- RL runs on MoE models no longer train the router. All MoE RL examples
are affected (glm-5.3, glm-4.5-air, intellect-3.1, qwen3-30b-a3b,
minimax-m2.5, nemotron-3-super). Set `trainer.model.freeze_moe_router =
false` for the old behavior.
- An explicit `freeze_moe_router = true` on a non-MoE model is now a
no-op instead of an error.
- Resuming: a checkpoint saved before this change (trainable router)
loads into a frozen-router run; the extra router optimizer state is
ignored. The reverse, resuming a frozen-router checkpoint with
`freeze_moe_router = false`, fails on missing DCP keys (noted in the
field docstring).
- With LoRA, a router listed in `lora.modules_to_save` is frozen again
by the new default unless `freeze_moe_router = false` is set.
## GPU check
One node (8×H200), FSDP over 8 ranks, `samsja/mini-glm-moe` (23 MoE
layers), SFT with fake data, `freeze_moe_router = true`,
`moe_router_dtype = "float32"` (so each router is its own fp32 FSDP unit
whose params are all frozen), 5 steps with a checkpoint every step:
- Log: "Froze 23 MoE router parameters", "Running 23 MoE router gates in
fp32"; all 5 steps ran with finite loss and grad norm.
- DCP checkpoints step 1 vs step 5: all 23 fp32 router gate weights are
bitwise unchanged; expert weights changed; no optimizer state exists for
any router parameter.
#3753 let MoE blocks compile with `model.compile.fullgraph = true`, but
it was validated on B300 with FA4. On H200, where FA3 is the default,
fullgraph still failed at the first forward, because FA2's and FA3's
`flash_attn_varlen_func` are autograd.Functions and Dynamo rejects the
same `cu_seqlens` tensor passed as both `cu_seqlens_q` and
`cu_seqlens_k`. FA2 and FA3 now run through `prime_rl_attn` custom ops
like FA4 (#3754), so the checkpointed MoE blocks compile with fullgraph
and no graph breaks on H200 too.
- AFMoE, Ulysses CP and the Qwen3.5 vision encoder now call the op
wrappers; FA4's op takes optional `max_seqlen_q/k` for Ulysses.
- The ops match the library functions bitwise, except FA3's GQA
`dk`/`dv`, which the library itself doesn't reproduce run to run.
- `apply_compile` traces `max_seqlen` symbolically: as a constant, each
rank recompiled on its first new value and stalled every rank for ~6 s.
A
[benchmark](https://github.com/PrimeIntellect-ai/prime-rl/blob/9db5336241304a0263664c8408e03159cbb8767e/tools/benchmark_flash_attn_max_seqlen.py)
shows the symbolic int costs nothing measurable.
| GLM-4.5-Air, 24 layers, 2 x 8 H200, ep 8, bf16 router | s/step (lower
is better) | tok/s/GPU (higher is better) |
|---|---|---|
| main, FA3, fullgraph off (fullgraph fails) | 4.64 | 3533 |
| this PR, FA3, fullgraph on | 3.83 | 4282 |
That is 17.5% less time per step, or 21.2% more tokens per second per
GPU. Medians over steps 5 to 20; loss tracks main within 0.03 over 20
steps. The GPU is about 99% busy in both arms, so the gain is fusion:
per step, about 1030 ms of unfused aten kernels (MoE routing glue, RoPE)
become 262 ms of Inductor-fused Triton kernels.

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

**Figure:** the same layer's recompute and backward, 106.7 ms after
versus 131.6 ms before. The bottom panel totals the whole step: about 1
s of unfused aten kernels became 262 ms of fused Triton kernels, while
FlashAttention and GEMM time barely changed.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
## Problem
`Integration tests (reverse_text_lora)` has failed since the vLLM 0.31
bump (#3888's own CI run, and main's GPU Tests at b9c0bfe87). The first
`POST /load_lora_adapter` returns `400 Bad Request` and the orchestrator
exits.
Root cause: vLLM 0.31 added a check to
`OpenAIServingModels._check_load_lora_adapter_request`. It rejects a
`lora_name` equal to a served base model name ("conflicts with a served
base model", 400). vLLM 0.30 had no such check. prime-rl registers its
adapter under the model name (`model.name`) on purpose, because every
client (rollouts, evals, the renderer client) sends that name. vLLM
serves the base model under the same name by default, so the two
collide.
## Change
No vLLM patch. With LoRA on, the inference server serves the base model
under a different name, and the adapter keeps the name clients already
send.
- `InferenceConfig.to_namespace` sets `served_model_name =
[f"{vllm.model}-base"]` when `vllm.enable_lora` is on, unless the user
sets `served_model_name` explicitly. Every launch path builds the vLLM
args here: local `rl`/`sft`, standalone `uv run inference`, SLURM
single/multi-node, and P/D prefill/decode ranks.
- `maybe_check_has_model` (startup readiness) also accepts the name as a
model's `root`. Before the first weight sync, a LoRA server lists only
`<model>-base`, whose `root` is the model path.
- The `load_lora_adapter` docstring, an orchestrator comment, and the
LoRA section of `docs/advanced.md` now describe the served name.
## Checks
- **Nothing on the policy server asks for the base model by name.**
Rollouts, evals, and the renderer/prefill scorer all send `model.name`,
which is now the adapter. OPD teachers and frozen reference models are
separate endpoints. A LoRA server also cannot serve a frozen reference
under `model.name`. Before this change that name would already have
resolved to the adapter, and the base model can now be reached as
`<model>-base`. Admin routes (`/pause`, `/update_weights`,
`/load_lora_adapter`, health, liveness) do not take a model name.
vllm-router and llm-d configs do not reference model names. Dynamo
workers are external, so this change does not affect them.
- **The v0 adapter is loaded before the first request.** The
orchestrator and online evals wait for the trainer's startup broadcast
(v0, or the resume step). They load it through `/load_lora_adapter`
before they dispatch any rollout or eval. Readiness is the only earlier
check that uses the model name, and the `root` match covers it.
- **`/metrics`:** vLLM's `model_name` label becomes `<model>-base`. The
inference-metrics collector and the concurrency controller group samples
by the `engine` label only, and the dashboard does not read vLLM's
`/metrics`.
## Tests
- `configs/ci/integration/reverse-text-lora/start.toml` on one H200 node
(vLLM 0.31.0, this commit, patch module absent): all 15 steps run and
16/16 `/load_lora_adapter` calls return 200. There are no 400s or 404s.
Reward goes from 0.145 to 0.798, matching the patched version (0.14 to
0.79). Before the first sync, `/v1/models` lists only
`...-Reverse-Text-SFT-base` (root `...-Reverse-Text-SFT`). After it, the
list also has the adapter `...-Reverse-Text-SFT` (parent
`...-SFT-base`).
- `reverse-text-sft-lora/start.toml` (5 steps) passes.
- `pytest tests/unit/orchestrator tests/unit/inference
tests/unit/test_configs.py tests/unit/test_parsers.py -m "not gpu"` (469
passed), `ruff check`, and `ruff format --check` all pass.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how LoRA vLLM instances advertise models at startup and during
readiness checks; client-facing model IDs stay the same, but anything
expecting the base under the policy name would need `<model>-base`.
>
> **Overview**
> Fixes LoRA inference startup on **vLLM 0.31**, which returns 400 when
an adapter is registered under the same name as a served base model.
>
> When `enable_lora` is on and `served_model_name` is not set
explicitly, **`InferenceConfig.to_namespace`** now serves the base
weights as ``<vllm.model>-base`` so the reloaded policy adapter can keep
**`model.name`** for all rollout/eval clients.
**`maybe_check_has_model`** treats a match on either the model **`id`**
or **`root`**, so readiness passes before the first `/load_lora_adapter`
when only the `-base` entry is listed. Docs and comments describe the
naming split.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
18064f3367009c265c11ffd58fb9d5b989ca7ec1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Turn off loguru's `diagnose` on every handler.
With loguru's default `diagnose=True`, every logged exception (including
the `Fatal error in …` that `clean_exit` logs) `repr()`s the variables
in each traceback frame. A `torch` storage repr walks the storage in
Python, element by element. When a frame holds a multi-GB tensor or
storage (a checkpoint state dict, a staging buffer, model shards),
formatting the traceback takes hours. The crashing trainer then looks
hung instead of exiting, and the real error never reaches the log.
Seen while debugging async DCP checkpoint saves: the trainer stopped at
`Saving checkpoint at step 2` with no error. A faulthandler dump showed
the main thread inside `loguru/_better_exceptions.py` →
`torch/storage.py __repr__`. The actual exception (a staging error) only
showed up through `traceback.print_exc`.
Repro on CPU (a frame whose failing line references an 8 MB
`UntypedStorage`):
- main: formatting took 19.1 s. It scales with size, so about 40 min per
GB.
- this PR: 0.0 s.
Tracebacks are still logged in full; only the per-variable value
annotations are dropped.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Logging-only change that reduces exception detail slightly; improves
reliability when failures involve large tensor locals.
>
> **Overview**
> Disables loguru’s **`diagnose`** mode on every handler installed in
`setup_logger` (JSON console, colorized stdout, and optional file sink).
>
> With the default **`diagnose=True`**, exception formatting
**`repr()`s** locals in each traceback frame. When those locals are
large PyTorch tensors or storages, that step can take minutes or hours,
so a fatal error during logging looks like a hang and the real exception
may never appear in logs. **Full tracebacks are still logged**; only the
per-variable value annotations are omitted.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
93a682f6fedf415561d4e5f31cbf0ee8b92a2a04. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Use Verifiers' client configuration and resolvers for Prime-RL
endpoints, credentials, headers, and timeouts. Standalone evaluation
honors an explicit URL, then `PRIME_INFERENCE_URL`, the Prime CLI
config, and the default Prime endpoint. Partial overrides retain the
correct defaults for each run type.
## Before
Prime-RL owned a separate client schema and credential/header resolvers.
Standalone eval supplied a hardcoded Prime endpoint, so changing
`PRIME_INFERENCE_URL` did not change that default. Client setup resolved
environment headers into static values, prefill scoring constructed its
own SDK client, and admin authentication reused the inference
configuration instead of resolving against the admin URL.
```mermaid
flowchart TD
Eval["Standalone eval hardcodes Prime URL and key defaults"] --> Config["Prime-RL ClientConfig"]
Config --> Local["Prime-RL credential and header resolvers"]
Local --> Inference["Construct Verifiers client with resolved static headers"]
Inference --> Prefill["Prefill builds its own OpenAI SDK client"]
Local --> Admin["Admin client resolves using inference config"]
AdminURL["Separate admin URL"] --> Admin
```
## After
```mermaid
flowchart TD
Eval["Standalone eval: Prime endpoint defaults"] --> Config["Verifiers BaseClientConfig"]
Train["Training and online eval: localhost vLLM defaults"] --> Config
Config --> Inference["Inference client configuration"]
Config --> Prefill["Shared SDK builder for prefill scoring"]
Config --> Admin["Admin configuration with its own URL"]
Inference --> Resolve["Resolve credentials and headers for actual destination"]
Prefill --> Resolve
Admin --> Resolve
Runtime["Environment values and Prime CLI config"] --> Resolve
Resolve --> Endpoint["Target endpoint"]
```
Training and online evaluation retain their vLLM defaults, including
when only part of the client config is overridden. Frozen models require
an explicit endpoint. Environment-backed headers remain references in
saved configs, and header overrides compare names case-insensitively.
Admin authentication uses the admin destination. Prefill scoring uses
the shared SDK builder's timeout and retry policy.
Depends on [Verifiers
#2766](https://github.com/PrimeIntellect-ai/verifiers/pull/2766). When
combining this with
[#3782](https://github.com/PrimeIntellect-ai/prime-rl/pull/3782) and
[#3808](https://github.com/PrimeIntellect-ai/prime-rl/pull/3808), pin a
Verifiers revision containing all three companion fixes.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how eval and inference clients pick URLs, API keys, and
headers at runtime; mis-resolution could break eval or admin traffic,
though behavior is covered by new default-preservation tests.
>
> **Overview**
> **Client configuration now delegates to Verifiers** instead of a
duplicate Prime-RL schema and local credential/header resolvers.
`ClientConfig` extends Verifiers' `BaseClientConfig`; training and
online eval use `VLLMClientConfig` (`localhost:8000` / `VLLM_API_KEY`).
Standalone `uv run eval` drops the hardcoded Prime URL and inherits
Prime Inference defaults from Verifiers (honoring `PRIME_INFERENCE_URL`,
Prime CLI, then the standard endpoint). Frozen external models require
an explicit `base_url`.
>
> **Runtime client setup** forwards unresolved config into Verifiers
train/eval clients (`setup_client` dumps `BaseClientConfig` fields),
resolves auth per destination in admin clients (including separate admin
URLs), and builds prefill scoring via `build_async_openai`. Docs
describe the eval endpoint precedence; tests assert partial `[client]`
overrides keep the right defaults per run type.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c643ef25637bfafb13af555d56167fdbd3525e57. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
`TokenChoiceTopKRouter` gets a `"sqrtsoftplus"` score function
(`sqrt(softplus(logits.float()))`, DeepSeek V4's). The copied
`DeepseekV4Router` (its whole `forward` was restated for that one
scoring line) is deleted. Standard V4 layers use `TokenChoiceTopKRouter`
directly, and `DeepseekV4HashRouter` subclasses it, forwarding the
router kwargs and only adding `tid2eid` and `selection_bias=False`. The
router signature uses `ScoreFuncType` instead of repeating the
`Literal`. The `DeepseekV4MoE` guard that rejected any `scoring_func`
other than `sqrtsoftplus` is removed, because the shared router
implements every score function.
Clamped activation: `GroupedExperts` and `FeedForward` now take either
an activation name or an `Activation` object. A new shared
`ClampedSilu(limit)` in `layers/activations.py` holds V4's clamp
(`silu(gate.clamp(max=limit)) * up.clamp(-limit, limit)`, limit from
`config.swiglu_limit`). V4's routed experts are a plain
`GroupedExperts(activation=ClampedSilu(...))` and its shared expert a
plain `FeedForward(activation=ClampedSilu(...))`. Deleted from
`deepseek_v4/moe.py`: `ClampedSwiglu`, `DeepseekV4Experts` and
`DeepseekV4MLP`. The one init difference (HF draws expert `up_proj` at
std 0.02, not `initializer_range`) is a 3-line
`DeepseekV4MoE.init_weights` override. The hash-routing table and
forward stay in the V4 file. gpt-oss's `clamped_swiglu` is different
math (`(up+1) * gate * sigmoid(1.702 * gate)`, limit fixed at 7), so it
is not merged with this. Sonic MoE rejects `ClampedSilu`, as it rejected
the old V4 experts.
## Behavior change
None for V4 checkpoints, which all ship `sqrtsoftplus`. A V4 config with
another `scoring_func` now builds with that score function instead of
raising. `sqrtsoftplus` takes the non-softmax confidence branch
(`top/sum(scores)`), the same as the deleted copy. State dict keys are
unchanged.
## Equivalence
- CPU: router and full `DeepseekV4MoE` (hash and standard layers, with
and without replay, fp32/bf16, active clamp) are bitwise identical to
main: forward, all grads, buffers and state-dict keys. Other MoE archs
(qwen3_moe, glm4_moe, minimax_m2, afmoe, laguna, gpt_oss) are unchanged.
- GPU (8×H200): qwen3_moe, glm4_moe, laguna and nemotron_h are bitwise
identical to main. deepseek_v4 is not deterministic on GPU even main vs
main; the branch is within that run-to-run spread.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches shared MoE routing and expert activation paths used beyond V4;
behavior change only for non-default V4 `scoring_func`, but incorrect
`sqrtsoftplus` parity would affect training/inference for V4
checkpoints.
>
> **Overview**
> **DeepSeek V4 MoE is refactored onto shared layer primitives** instead
of V4-only router, expert, and MLP subclasses.
>
> `TokenChoiceTopKRouter` now supports **`sqrtsoftplus`**
(`sqrt(softplus(logits))`), so the duplicated `DeepseekV4Router` is
removed and standard V4 layers use the shared router directly.
`DeepseekV4HashRouter` subclasses `TokenChoiceTopKRouter` and only adds
the `tid2eid` buffer. The config no longer documents `scoring_func` as
V4-only, and `DeepseekV4MoE` drops the guard that rejected
non-`sqrtsoftplus` values (other score functions now build through the
shared router).
>
> **Clamped SwiGLU** moves into shared `ClampedSilu(limit)`;
`FeedForward` and `GroupedExperts` accept either an activation name or
an `Activation` instance. V4 wires `GroupedExperts` and optional
`FeedForward` shared experts with `ClampedSilu(config.swiglu_limit)`;
`DeepseekV4Experts`, `DeepseekV4MLP`, and local `ClampedSwiglu` are
deleted. HF-style expert `up_proj` init (std 0.02) lives in a small
`DeepseekV4MoE.init_weights` override. Unit tests target
`GroupedExperts` + `ClampedSilu` instead of `DeepseekV4Experts`.
>
> Shipped V4 checkpoints (`sqrtsoftplus`) should behave the same;
configs with other `scoring_func` values now construct instead of
raising.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
019f42b643266b8be15ce15985b8a82034925d4b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
The dashboard smoke check at the end of the `alphabet_sort` integration
test flakes at `tests/integration/dashboard_smoke.py:164`. It asserts
that `#replay-top` is active after Home. It failed on #3767 and #3774,
which don't touch the dashboard.
**Root cause.** The smoke test presses `t` and then Home. When thinking
is hidden, a trace that overflowed the replay pane gets shorter and
fits. The browser then clamps `scrollTop` and queues a scroll event.
That event fires after Home. At that point the pane fits, so the scroll
handler sees the view as "at bottom", switches back to follow mode, and
clears `#replay-top`. The same thing happens when the pane overflows by
less than the 24px threshold, because top and bottom then count as the
same position.
**Fix.** When the replay output fits (overflow < 24px), the scroll
handler leaves the follow mode alone. Home and End decide it, and that
choice still applies if the output grows later. Scrolling a long trace
by hand still switches between the modes as before.
**Check.** I ran headless Chromium against a dashboard serving synthetic
runs, with the same steps as the smoke test (skip inference, `t`, Home,
End):
- trace that fits after hiding thinking: 4/4 failed before the fix, 4/4
passed after
- 14px overflow: 4/4 failed before the fix, 4/4 passed after
- short trace that always fits: passed before and after
- long scrollable trace: passed before and after
- long trace, scrolling up and back down by hand: still toggles follow
mode and the top/live buttons
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Small dashboard UI scroll-handler guard with no auth, data, or API
impact.
>
> **Overview**
> Fixes flaky replay **Home/End** behavior when the trace output
**fits** (or barely overflows) in the replay pane.
>
> The `#replay-output` scroll listener now **bails out** when
`scrollHeight - clientHeight < 24`, so clamped or near-no-op scroll
events (e.g. after hiding thinking shrinks the content) no longer force
**follow/live** mode and clear **`#replay-top`**. **Home/End** and
manual scrolling on long traces are unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
83d2f3f9b71e5b4309b98146eb1ffa944db08c23. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
- Bump vLLM 0.30.0 → 0.31.0 (exempt `flashinfer-python` 0.7.0.post1 from
the `exclude-newer` cooldown).
- Read `enable_return_routed_experts` from
`VllmConfig.aux_output_config` (moved in 0.31).
- Router replay now always uses the V2 runner; router replay with
disaggregated P/D is rejected at config time (0.31 has no NIXL
routed-expert capture).
- Resync the copied LoRA loader in `_patch_lora_key_prefix` with 0.31
(`modules_to_save`).
Removed patches:
- `monkey_patch_deepseek_v4_request_tools_placement`: fixed upstream
(vllm#51856).
- `monkey_patch_return_routed_experts_with_nixl_connector`: crashes the
engine on 0.31.
Tested end to end: multi-node RL on SLURM (1 trainer + 1 inference
node), Qwen3-0.6B reverse-text, 10 steps. Eval reward 0.08 → 0.81.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Deletes tests that are skipped unconditionally, plus the 777-line
vendored HF AFMoE model that only the skipped AFMoE test used (rev-infra
P4).
Deleted:
- `tests/unit/train/models/test_afmoe.py` (whole module skipped: "HF
afmoe model does not support flash attention 2") and
`tests/unit/train/models/afmoe_hf_modeling/` (vendored HF model;
transformers 5.6.2 ships `transformers.models.afmoe` anyway).
- `tests/unit/train/test_model.py::test_model_with_sequence_packing`
(skipped since 2025-05, "Sequence packing for Qwen not working") and
`::test_model_forward_custom_impl` (skipped, "need special token for
meta stuff in ci").
-
`tests/unit/train/rl/test_fused_lm_head.py::test_full_model_fused_vs_vanilla`
(skipped, "Produces NaNs in bf16 with FA3").
- `tests/unit/transports/test_nccl_broadcast.py` (skipped since 2025-12,
"fail only in ci").
- The `free_port` fixture in `tests/conftest.py`: only the NCCL test
used it (and it called the int as a function, so it was broken too).
No source changes. Behavior change: none. These tests never ran.
## Checks
- CI test selection: `pytest --collect-only -q tests/unit -m "not gpu"`
gives the same 673 ids before and after. `-m gpu` goes from 190 to 182
ids, and the diff is exactly the 8 skipped ids listed above. Nothing
that ran before is gone.
- `pytest -m "not gpu" tests/unit/orchestrator
tests/unit/test_configs.py tests/unit/train/rl/test_fused_lm_head.py`:
297 passed.
- `ruff check .`, `ruff format --check .`: clean.
- GPU: none needed (only skipped tests are removed).
## Conflicts
- #3833 (remove transformers modeling) edits `test_afmoe.py`,
`test_model.py::test_model_with_sequence_packing` and
`test_fused_lm_head.py::test_full_model_fused_vs_vanilla` to port them
to the new model API, but keeps them skipped. Text conflict only.
Whichever PR lands second resolves it by keeping the deletion.
- #3794 and #3698 edit the import block of `test_fused_lm_head.py`. This
PR drops `selective_log_softmax` from the same import line. Expect a
trivial text conflict.
- If an AFMoE parity check is still wanted, port it to upstream
`transformers.models.afmoe` with `sdpa` in a follow-up. That would need
a GPU run to validate.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Test-only deletions with no application code changes; CI coverage for
tests that actually ran is unchanged per PR checks.
>
> **Overview**
> **Removes dead test code** that never executed in CI: unconditionally
skipped GPU/unit tests and the vendored HuggingFace AFMoE copy they
depended on.
>
> Deleted the whole `tests/unit/train/models/afmoe_hf_modeling/` tree
(~777 lines) plus `test_afmoe.py`, since upstream `transformers` already
ships AFMoE and the module was skipped for flash-attention
incompatibility. Also drops skipped cases in `test_model.py` (sequence
packing, Meta Llama custom forward),
`test_fused_lm_head.py::test_full_model_fused_vs_vanilla`, and the
entire `test_nccl_broadcast.py` module.
>
> `tests/conftest.py` loses the unused `free_port` fixture and its
`socket` import (only the NCCL test used it, and incorrectly).
`test_fused_lm_head.py` no longer imports `selective_log_softmax` after
removing the skipped full-model test.
>
> **No production/runtime behavior change** — only fewer collected tests
(8 GPU-marked ids removed).
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
61235f155a74f04ee3119deb9a4b557839313bec. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Moves every GPU Tests job that fits in 2 GPUs onto the `prime-rl-2xh200`
ARC scale set, so runs stop queueing behind the two `vm` runners.
Stacked on #3834.
**Assignment**
- `prime-rl-2xh200` (9): unit-tests, reverse_text, reverse_text_sft,
reverse_text_sft_lora, reverse_text_lora, reverse_text_moe,
reverse_text_rl_opd, reverse_text_rl_sft, alphabet_sort, gsm8k_eval
- `4xa6000` (1): benchmark_regression, unchanged
The `vm` runners are left registered and untouched - just no longer on
the GPU Tests path.
**Sizing checks**
- Integration configs put inference on GPU 0 and trainer on GPU 1, so 2
GPUs each.
- Unit tests peak at `world_size=2` (NCCL broadcast test); `gsm8k_eval`
needs no GPU.
- benchmark_regression stays put: baselines are A6000-pinned
(`benchmark-4xa6000-*.json`) and the 4-GPU case exceeds a job pod. Note
`4xa6000` has zero registered runners today, so it queues regardless of
this PR.
**Worth knowing:** 12 tests in `test_deepseek_v4_kernels.py` are gated
on `requires_datacenter_gpu` (compute capability 9/10). They skip on
A6000 and will begin running on H200 - new coverage, but they have not
run in CI before.
Runners use `containerMode: kubernetes`, so `container:` blocks work
unchanged - each job gets a fresh pod, no Docker daemon, no privileged
containers.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> CI-only runner reassignment can surface new failures when
datacenter-GPU-gated unit tests run on H200 for the first time;
production code paths are untouched.
>
> **Overview**
> **GPU Tests** CI now targets the `prime-rl-2xh200` Kubernetes runner
scale set instead of `vm` for every job that needs at most two GPUs.
>
> The **unit-tests** job and nine **integration-tests** matrix entries
(`reverse_text*`, `alphabet_sort`, `gsm8k_eval`, etc.) all use
`prime-rl-2xh200`. **`benchmark_regression`** is unchanged on `4xa6000`
because it needs four GPUs and A6000-pinned baselines.
>
> No test commands, containers, or matrix structure change—only
`runs-on` / `runner` labels. Unit tests on H200 may start executing
tests gated by `requires_datacenter_gpu` in
`test_deepseek_v4_kernels.py` that previously skipped on
`vm`/A6000-class hardware.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
579a43fe10fbd114a1bf935bd43917fc63873a18. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Hosted image `v0.9.1.dev200` fails when GLM-5 selects `model.dsa_backend
= "cudnn_flashmla"`: the forward path imports `flash_mla`, but Docker's
explicit sync extras omit `flash-mla`. The [dev200 build
log](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/37265534904)
confirms the missing extra; `nvidia-cudnn-frontend` is already
installed.
Add `--extra flash-mla` to the dependency-image sync and the
source-override entrypoint sync. Add an amd64 package-presence check
before publishing the dependency image. The existing Linux/x86_64 marker
excludes the wheel on arm64, and the Dockerfile change invalidates the
dependency-image fingerprint.
## Verification
- Compared locked requirement exports with the exact Docker extras
before and after the fix: amd64 adds only the pinned FlashMLA wheel;
arm64 requirements are unchanged. Neither platform loses dependencies,
and both include `nvidia-cudnn-frontend==1.30.0`.
- Confirmed Docker and source-override entrypoint extras match.
- Downloaded the pinned CPython 3.12/CUDA 13/PyTorch 2.13 wheel and
verified its lockfile SHA256. Confirmed it exports
`flash_mla_sparse_fwd` and includes the native extension.
- Docker Buildx Dockerfile checks: no warnings. Bash syntax and `git
diff --check`: passed.
GPU import and execution checks on a rebuilt image are still pending.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Build-time dependency and publish-time presence checks only; arm64 is
unchanged because the extra is x86_64-gated in the lockfile.
>
> **Overview**
> Adds the **`flash-mla`** optional dependency to CUDA image builds and
runtime source overlays so GLM-5 paths using `model.dsa_backend =
"cudnn_flashmla"` can import `flash_mla` in hosted images.
>
> **`Dockerfile.cuda`** includes `--extra flash-mla` in the builder `uv
sync` (alongside the other GPU extras) and, on **x86_64 only**, asserts
`flash-mla` is present in the published dependency image via
`importlib.metadata`. **`scripts/docker-entrypoint.sh`** adds the same
extra to `uv sync` when `PRIME_RL_REF` overlays a checkout, keeping the
entrypoint extras list aligned with the Dockerfile comment.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
12329d455836ab80ac581e18de7339718312e7a9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Removes legacy config options and their code paths. They have had no
changes of their own in 4+ months.
## Removed
- **SGD optimizer** (`optim.type = "sgd"`): `SGDConfig`, its union
member, and the `torch.optim.SGD` branch in `trainer/optim`. AdamW,
Muon, and SignSGD stay.
- **`ckpt.skip_progress`** (orchestrator and trainer ckpt configs):
resume now always restores progress. This affects the orchestrator ckpt
loading and SFT resume.
- **`Jackmin108/` model-name special case** in
`validate_shared_model_name`. Trainer and orchestrator model names now
must always match when no inference config is given.
## Kept
- **`orchestrator.collect_inference_metrics`** stays, unchanged from
main. Hosted training uses Grafana for inference metrics and sets it to
`false` to turn off W&B mirroring. The `/metrics` poll for the
concurrency controller always runs either way.
## Also included (#3774, merged into this branch)
- `RLConfig`: top-level shared fields (including `resume`) go through
`propagate_shared_fields` only. The old `validate_shared_*` helpers in
`validation.py` are replaced by inline cross-component checks in
`RLConfig.validate_shared_configs`.
## Breaking changes
TOMLs/CLI args that set any of these now fail validation:
- `trainer.optim.type = "sgd"` (and `optim.momentum`, `optim.nesterov`)
- `orchestrator.ckpt.skip_progress`, `trainer.ckpt.skip_progress` (SFT
`ckpt.skip_progress`)
No configs, examples, docs, or skills in the repo reference these
options.
## Validation
- `pytest tests/unit -m "not gpu"` (excluding
`tests/unit/train/test_cpu_adam.py`, which needs `ninja` to build a C++
extension on this machine): 651 passed
- `ruff check .` and `ruff format --check .` (only `docs/algorithms.md`
is flagged, same as on main)
- GPU/integration tests were not run (no GPU on this machine).
Rebased on main f42630873; resolved conflicts in `configs/rl.py` and
`utils/validation.py` (main's #3788 already removed
`validate_shared_weight_broadcast`; kept that and this PR's removal of
the other `validate_shared_*` helpers).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking config validation for old TOMLs/CLI flags and stricter
cross-component model/resume rules; resume behavior changes if anything
relied on skipping progress restore.
>
> **Overview**
> Removes **legacy config knobs** that are no longer supported:
**`optim.type = "sgd"`** (config type + `torch.optim.SGD` factory), and
**`ckpt.skip_progress`** on trainer/orchestrator checkpoints. Resume now
**always** restores orchestrator progress/curriculum state and SFT
training progress (step counter always advances after load).
>
> **RL config validation** is consolidated: shared-field helpers in
`validation.py` are deleted in favor of
**`RLConfig.validate_shared_configs`** using a generic `require_equal`
check (model name, chat template, `max_steps`, `resume`, ckpt/W&B
parity, seq_len bound). Top-level **`resume`** is propagated via
**`propagate_shared_fields`** instead of a separate `auto_setup_resume`
validator; the **`Jackmin108/`** trainer/orchestrator model-name
exemption is gone.
>
> CI slim-install smoke test imports **`propagate_shared_fields`** only.
Unit tests drop SGD from full-offload optimizer coverage.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1df3854c75fc652e2b0a5dbd7d019555e73736ba. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Two small cleanups in `orchestrator/algo/`. Item 4 of the orchestrator
review.
- `action_loss_type` is now declared once, on the algorithm config
classes. Before, it was declared on the config classes and again on the
runtime classes (`algo/base.py`, `sft.py`, `opd.py`, `opsd.py`), and
`build_algorithm` asserted that the two agreed. Now `Algorithm.__init__`
copies it from the config, so `train_sink`'s
`env.algorithm.action_loss_type` is unchanged.
- `Algorithm.finalize_group` is removed. It only called `score_group`,
and `train_sink` now calls `score_group` directly. `finalize_episode` is
kept: its "has sampled tokens" guard matters for `echo`, whose
`score_episode` does not filter on the mask.
- `docs/algorithms.md` is updated to match.
Behavior change: none. Every algorithm type gets the same loss routing
as before, because the old assert guaranteed that the config and runtime
values were equal.
## Checks
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 291 passed (`test_algorithms` covers the per-type
`action_loss_type`).
- `ruff check`, `ruff format --check`: clean.
GPU checks: none needed.
## Conflicts
`algo/base.py` and `algo/__init__.py`: #3802, #3803 (small). #3838 (fold
`GenerationSource`) also edits `algo/base.py` and `algo/__init__.py`
(`connect_frozen_client`), which needs a trivial rebase.
`train_sink.py:245`: #3652 rewrites `train_sink.py` (a one-line change
there).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Refactor-only: loss routing and group scoring call paths are unchanged
in effect; no auth, data, or trainer hot-path logic changes.
>
> **Overview**
> **Single source of truth for loss routing:** runtime `Algorithm`
instances now take `action_loss_type` from the algorithm config in
`__init__` instead of duplicating it on each subclass and asserting
agreement in `build_algorithm`. Per-algorithm class variables on `OPD`,
`OPSD`, and `SFT` are removed; `train_sink` still reads
`env.algorithm.action_loss_type` when stamping samples.
>
> **Thinner scoring API:** `Algorithm.finalize_group` is dropped and the
train sink calls `score_group` directly when a group has trainable
survivors. `finalize_episode` remains as the guarded entry point for
rollout-local `score_episode` (skips episodes with no trainable sampled
tokens).
>
> **Docs:** `algorithms.md` is updated to describe this pipeline wiring
and config-owned `action_loss_type`.
>
> No intended training behavior change—loss routing values are the same
as before when config and runtime matched.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1ebee7fec9fab8740b04de41e3aee9e89d4ca6d7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Moves `BatchPacker` (35 lines) from `orchestrator/packing.py` into
`orchestrator/batch.py` and deletes `packing.py`. The class only wraps
`build_bin_cost` and `prepare_batch`, which already live in `batch.py`.
Item 6 of the orchestrator review.
Behavior change: none (pure move; the import in `orchestrator.py` is
updated).
## Checks
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 291 passed
- `ruff check`, `ruff format --check`: clean
- `python -c "import prime_rl.orchestrator.orchestrator"` OK
- Equivalence: the class body is copied byte for byte (`git diff` shows
only the move and the import lines).
GPU checks: none needed.
## Conflicts
- #3840 (FLOP estimator): textual, in the `batch.py` imports only.
- #3652: its `Shipper` imports `BatchPacker` from `packing`, which
becomes a one-line change to `from prime_rl.orchestrator.batch import
BatchPacker`.
- #3819, #3836, #3794 touch other parts of `batch.py`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Pure file move and import path update with no logic changes to
training batch packing.
>
> **Overview**
> **Colocates batch packing with the bin-packing helpers it already
delegates to.**
>
> `BatchPacker` moves from `orchestrator/packing.py` into
`orchestrator/batch.py` next to `build_bin_cost` and `prepare_batch`;
`packing.py` is removed. The orchestrator now imports `BatchPacker` from
`batch` instead of `packing`. Class behavior and `pack()` semantics are
unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
986f5bf0f692cca69a2bf1d49bbec53b09ececef. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Removes duplicate and unused entries from `pyproject.toml` (rev-infra
P9). The set of installed packages does not change for any extra
combination (checked below).
| Removed | Reason |
|---|---|
| second `orjson>=3.10` in `dependencies` | Duplicate of
`orjson>=3.11.0` a few lines above. |
| `pandas>=2.0` | Nothing imports it: no `import pandas` / `pd.` in
`src/`, `tools/`, `scripts/`, `tests/`, `examples/`, `skills/`,
`packages/`. It was added for the nano bridge (7089ba1e4). It stays
installed because `datasets` depends on it. |
| `pyarrow>=21.0.0` | No direct use anywhere in those directories. The
one parquet writer, `tools/convert_traces_to_hf_dataset.py`, calls
`datasets.Dataset.to_parquet`, and `datasets` depends on `pyarrow`
itself. It stays installed. |
| `nixl-cu13==0.10.1` in the `disagg` extra | `disagg` already lists
`nixl`, and the `[[tool.uv.dependency-metadata]]` override for `nixl`
0.10.1 requires exactly `nixl-cu13==0.10.1`. The `gpu` extra keeps its
explicit pin, because `transports/weights/nixl/agent.py` imports
`nixl_cu13` directly. |
| `mamba-ssm` dependency group | Duplicate of the `gpu` extra entry,
which was added with the native Nemotron-H model (#3426). Every user of
the group also syncs `--extra gpu` or `--all-extras`, so I dropped
`--group mamba-ssm` from `Dockerfile.cuda` (2 places),
`scripts/docker-entrypoint.sh` and the `pre_run_command` in
`configs/advanced/nemotron-3-super/swe.toml`. The `[tool.uv.sources]`
git pin and the build dependencies for mamba-ssm stay. |
Behavior change:
- None for installs: same locked packages and versions.
- `uv sync --group mamba-ssm` no longer works; use `--extra gpu`, which
every repo caller already passes.
- `pandas` and `pyarrow` lose their direct lower bounds. They are still
pulled in by `datasets`.
## Checks
- `uv lock`: resolves 564 packages, the same set as before (568
`[[package]]` entries before and after). `uv lock --check` passes. The
`uv.lock` diff only touches prime-rl's own metadata. I reverted the
reordering of `[options.exclude-newer-package]` that my uv version
(0.12.10) introduced.
- I ran `uv export --frozen --all-packages` and compared the package
lists before and after, ignoring the `# via` comment lines. They are
identical for: no extras, `--extra disagg`, `--extra gpu`, `--extra
dashboard`, `--all-extras`, and `--all-extras --all-groups`. `--extra
disagg` still yields `nixl==0.10.1` and `nixl-cu13==0.10.1`, and
`--extra gpu` still yields `mamba-ssm` at the pinned rev.
- No Python changes, so no unit tests are affected. GPU: not needed. The
Docker image build in CI covers the Dockerfile and entrypoint edits.
## Conflicts
Text conflicts only in `pyproject.toml` / `uv.lock`, as with any
dependency PR. None of the open PRs that touch these files (e.g. #3829,
#3803, #3767, #3660) edit the lines removed here. A re-lock after rebase
is enough.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Metadata and sync-flag cleanup only; lockfile exports are unchanged
and runtime installs should match prior behavior.
>
> **Overview**
> Cleans up **duplicate and redundant dependency declarations** in
`pyproject.toml` and aligns `uv.lock`, Docker, and Slurm sync commands
with the slimmer manifest. **No intended change to installed packages**
for existing extra combinations (`gpu`, `disagg`, `--all-extras`, etc.).
>
> **Removed from core `dependencies`:** duplicate `orjson>=3.10`, unused
direct pins on `pandas` and `pyarrow` (they still come in via
`datasets`). **Removed from `disagg` extra:** explicit
`nixl-cu13==0.10.1` because `nixl` metadata already pulls that version;
the **`gpu` extra keeps** its explicit `nixl-cu13` pin for direct
imports. **Dropped the `mamba-ssm` dependency group** as a duplicate of
the `gpu` extra entry—`Dockerfile.cuda`, `scripts/docker-entrypoint.sh`,
and the Nemotron SWE `pre_run_command` no longer pass `--group
mamba-ssm`.
>
> **Workflow note:** `uv sync --group mamba-ssm` alone is no longer
supported; use `--extra gpu` (or `--all-extras`), which callers already
use.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f0f2ff6b6365165a92be511c8029a47080f748e0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Fixes two wrong statements in `docs/scaling.md` (from the whole-codebase
review, rev-infra P8 / rev-trainer §6). Docs only. No code or behavior
change.
- **`ep = "auto"`**: the doc said auto picks the largest divisor of
`num_experts` that divides the FSDP island, is a multiple of `cp`, and
is ≤ 8. The code (`trainer/parallel_dims.py:resolve_ep`) returns
`min(world_size // dp_replicate, 8)` for MoE models and 1 otherwise.
That matches the `ModelConfig.ep` docstring. The doc now describes what
the code does and says to set `ep` explicitly when the result does not
fit `cp` / `num_experts`.
- **NIXL wheel**: `scripts/install_nixl_from_source.sh` names the wheel
`nixl-cu13` (lines 85-88, 105). `docs/advanced.md:216` already says
`nixl_cu13-*.whl`, but `scaling.md` said `nixl_cu12-*.whl`, so that
install command did not match any file.
Checks: docs only. Compared against `resolve_ep` and the install script.
Conflicts with open PRs: none. No open PR touches `docs/scaling.md`.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Documentation-only corrections to scaling and install instructions; no
runtime or training behavior changes.
>
> **Overview**
> Updates **`docs/scaling.md`** so it matches current behavior—no code
changes.
>
> **Expert parallelism (`ep = "auto"`)**: Replaces the old description
(largest valid divisor of `num_experts` subject to FSDP island, `cp`,
and cap 8) with what **`resolve_ep`** actually does: for MoE,
`min(world_size // dp_replicate, 8)`; for non-MoE, `1`. The doc now
notes that auto does not consider `num_experts` or `cp`, and that you
should set **`ep`** explicitly when the resolved value fails those
constraints.
>
> **NIXL install**: Changes the documented wheel from
`deps/nixl_cu12-*.whl` to **`deps/nixl_cu13-*.whl`**, consistent with
`scripts/install_nixl_from_source.sh` and other docs.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
778befd26ff787ee71cb7308071a26542c9cc470. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Removes the Kubernetes deployment path. The Helm chart has had no
functional change since its initial additions (last own change
2026-08-12 was a docs fix), and supported multi-node deployment is SLURM
(see docs/scaling.md). The trainer `metrics_server` (Prometheus
`/metrics` + `/health`) only existed to serve the chart's
liveness/readiness probes.
## Removed
- `k8s/` Helm chart (and `COPY k8s` from `Dockerfile.cuda`)
- `src/prime_rl/utils/metrics_server.py` (`MetricsServer`,
`HealthServer`) and its unit test
- `MetricsServerConfig` (configs/shared.py), trainer `metrics_server`
field, and its setup/update/teardown in `trainer/rl/train.py`
- Kubernetes sections/mentions in README,
`examples/basic/reverse-text/README.md`, `docs/training.md`; `k8s/`
TOMLs dropped from `test_configs.py`
- Inference `liveness_timeout_seconds` docstring reworded neutrally; the
`/liveness` endpoint stays (used by SLURM/router health checks)
`prometheus-client` stays in `pyproject.toml`:
`orchestrator/inference_metrics.py` still uses its parser.
## Breaking changes
- Trainer configs that set `metrics_server` now fail validation.
- The Helm chart and `/app/k8s` in the image are gone.
## Validation
- `pytest tests/unit/test_configs.py -m "not gpu"` (205 passed)
- `ruff check .` and `ruff format --check .`
- No GPU on the machine used; GPU/integration tests not run.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Breaking for anyone using the Helm chart or trainer `metrics_server`
config; training/runtime core paths are unchanged but deployment and
observability options shrink.
>
> **Overview**
> **Removes the Kubernetes/Helm deployment path** and related trainer
observability that existed mainly for chart probes.
>
> The entire `k8s/` Helm chart (StatefulSets, services, PVC,
reverse-text example values/TOMLs, and `k8s/README.md`) is deleted.
**`Dockerfile.cuda`** no longer copies `k8s/` into the image, and
docs/README/example copy now describe **Slurm-only** multi-node
deployment (K8s sections dropped from `reverse-text` README).
>
> **Trainer Prometheus/health HTTP server is removed:**
`MetricsServerConfig`, the `metrics_server` trainer config field,
`src/prime_rl/utils/metrics_server.py`, RL trainer
startup/update/shutdown hooks, and unit tests. Configs that still set
`metrics_server` will fail validation.
>
> **Minor doc tweaks:** inference `liveness_timeout_seconds` help text
is generic (not K8s-specific); `env-server` docs refer to externally
managed hosts instead of pods. Config validation tests only scan
`configs/` and `examples/` TOMLs, not `k8s/`.
>
> Inference `/liveness` and `prometheus-client` elsewhere (e.g.
orchestrator) are unchanged.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
42e89b437dc19ae11abd0172672b89b9f03e6c30. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Removes legacy leftovers that were last touched 2025-11 to 2026-02 or
were orphaned by features that are already gone. Behavior does not
change.
- **`orchestrator/patches.py`**: deletes the OpenAI chat-type
monkeypatches, which were written for verifiers 0.1.8. The orchestrator
and eval processes no longer parse `ChatCompletion` or message objects
in-process. Rollouts run in separate env-server processes, which never
applied the patch, and `prefill_logprobs` reads the raw
`httpx.Response`.
- **`FileSystemWeightUpdateWorker.init_broadcaster`**: deletes this
no-op stub. `/init_broadcaster` is only called by the NCCL and NIXL
transports, whose workers define their own method. The stub took no
arguments, so the route could never have dispatched to it anyway.
- **`prime_rl.utils.utils` pathing re-export**: deletes the shim (its
TODO asked for this) and points the remaining imports at
`prime_rl.utils.pathing`. The shim's file-wide `noqa: F401` was hiding
three unused imports in `utils.py`; they are removed too.
- **`tests/unit/inference/test_serving_chat_with_tokens.py`**: deletes
this empty file.
- **`ConcurrencyController.record_episode`**: now takes only `tokens`.
`env_name`, `kind` and `duration` are left over from the removed per-env
cost model and were ignored. The dispatcher's `on_episode_complete`
callback type now matches, and the `ConcurrencyConfig` docstring no
longer mentions "learned per-env episode costs".
- **`@deprecate_kwarg("past_key_value", ...)`**: removed from the llama,
glm4_moe and glm_moe_dsa decoder layers. These layers never accepted
`past_key_value(s)`, and transformers is pinned to 5.6.2. The signatures
still accept everything their callers pass.
## Breaking changes
- `from prime_rl.utils.utils import get_ckpt_dir` (and the other pathing
helpers) no longer works. Import them from `prime_rl.utils.pathing`.
- `ConcurrencyController.record_episode(tokens)` and the
`Dispatcher(on_episode_complete=...)` callback now take one argument.
- `prime_rl.orchestrator.patches` no longer exists.
## Validation
- `ruff check .` and `ruff format --check .`
- `pytest tests/unit/orchestrator tests/unit/eval tests/unit/inference
tests/unit/train/models tests/unit/utils tests/unit/test_configs.py -m
"not gpu"`: 417 passed, 154 deselected
- Import check of every modified module.
- GPU and integration tests were not run: this machine has no GPU.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Mostly deletions and import-path changes with documented API breaks;
adaptive concurrency still uses token counts for growth gating.
>
> **Overview**
> This PR deletes unused orchestration and compatibility shims and
tightens a few callback signatures. Runtime behavior for supported
entrypoints is intended to stay the same.
>
> **Removed OpenAI monkey-patches** — `orchestrator/patches.py` and
startup calls in the orchestrator and eval runner are gone. Rollouts no
longer parse `ChatCompletion` in those processes.
>
> **Concurrency hooks** — `ConcurrencyController.record_episode` and the
dispatcher `on_episode_complete` callback now only receive **token
count**; leftover per-env cost-model args were unused.
`ConcurrencyConfig` docs now describe KV-pressure sizing only.
>
> **Misc cleanup** — Drops
`FileSystemWeightUpdateWorker.init_broadcaster`, the
`prime_rl.utils.utils` re-export of pathing helpers (call sites import
`prime_rl.utils.pathing` directly), `@deprecate_kwarg` on custom decoder
layers, and an empty inference unit test file.
>
> **Breaking for downstream imports** — `prime_rl.orchestrator.patches`
is removed; pathing helpers must be imported from
`prime_rl.utils.pathing`; `record_episode` / `on_episode_complete` take
a single `int` argument.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
079daae952aeae8c1e6dd1a009ec3d950d0f4767. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Platform is adding a reverse proxy for the dashboard (platform#5719)
that forwards the bare path upstream with no prefix, so every
browser-side reference needs to be relative, not absolute.
- `index.html`: dropped the leading `/` from the icon, stylesheet, brand
image, and script `src`/`href` paths.
- `app.js`: the `api()` fetch helper now strips a leading `/` before
calling `fetch`, and the `EventSource("/api/view/events")` call is
relative too.
- `style.css` already only used `data:` URIs, no change needed.
Verification: served the static files through a throwaway reverse proxy
mounted under a sub-path prefix (mirroring the proxy's bare-path
forwarding), confirmed the HTML/JS no longer contain absolute `/static`
or `/api` references, and confirmed requests like
`.../prefix/static/app.js` and `.../prefix/api/runs` correctly resolve
relative to the page and reach the upstream dashboard.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> URL resolution-only changes for static assets and API/SSE calls; no
server or auth logic touched.
>
> **Overview**
> Makes the dashboard work when it is served behind a reverse proxy that
mounts it under a sub-path and forwards **bare** paths upstream (no
`/prefix` on upstream requests).
>
> **`index.html`** switches icon, CSS, images, and script tags from
root-absolute (`/static/...`) to **relative** (`static/...`) so assets
resolve against the current page URL.
>
> **`app.js`** strips a leading `/` in the shared `api()` `fetch` helper
so existing `api("/api/...")` callers emit relative `api/...` URLs, and
changes the live view **`EventSource`** from `/api/view/events` to
`api/view/events`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9efe2aa17fc084cf71491dabd88e9b039ff40555. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Removes the orchestrator `token_batch_size` option (token-budget batch
cutting). Batches are now always cut by sample count (`batch_size`).
**Why:** the train sink had two parallel batch-cut paths. Sample-count
batching is the one every shipped config uses, including GLM-5.3.
Removing the token path drops the `pending_tokens` / `payload_tokens`
accounting and the token branches in `process_batch`, `_drop_stale`,
`_maybe_batch` and `_record_zero_output`.
**Changes**
- `OrchestratorConfig.batch_size` is now a plain `int = 128` field.
Before, it was `int | None` and the validator set the 128 default.
- Removed `token_batch_size` and the "set exactly one of batch_size or
token_batch_size" check. The `batch_size` divisibility check by group
size stays.
- `TrainSink` takes `batch_size: int` only. `batch_progress()` now
returns `(count, target)` without the unit string. Its only caller is
the orchestrator status log.
- `constant_trainer_batch_size` is unchanged. No metric keys changed.
**Breaking:** configs that set `orchestrator.token_batch_size` now fail
validation. Use `batch_size` instead. No config, example, doc or skill
in the repo set it.
## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 300 passed
- `ruff check .` and `ruff format --check .`: clean
- GPU and integration tests were not run (no GPU on this machine).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how train batches are formed at the orchestrator; configs
using token batching break, but sample-count batching behavior for
existing runs should be unchanged.
>
> **Overview**
> Removes **token-budget batching** from the orchestrator so training
batches are always cut by **sample count** (`batch_size`).
>
> `OrchestratorConfig` drops `token_batch_size` and the mutual-exclusion
validator; `batch_size` is now a required `int` defaulting to **128**
(no longer optional with a validator fallback). `TrainSink` only tracks
trace count for readiness, staleness drops, zero-output warnings, and
`process_batch`—`pending_tokens`, `payload_tokens`, and token-based
partial cuts are gone. `batch_progress()` returns `(count, target)`
only; pipeline status logs no longer show a traces/tokens unit.
>
> **Breaking:** configs that set `orchestrator.token_batch_size` fail
validation; use `batch_size` instead.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
be797adb554eb5ba99aeb0cd3c3c210eac6e2e0d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Adds `GRPOAlgoConfig.loss_aggregation: Literal["token", "prompt"] =
"token"`. `echo` gets it too because it subclasses GRPO.
**Why:** the trainer averages the `rl` loss over every loss token in the
batch. Prompts whose groups produce long trajectories therefore dominate
the gradient. SWE groups can differ by about 10x in total tokens.
`"prompt"` implements MiMo-V2.6's prompt-mean aggregation exactly (Eq.
1, p8): `L = mean_q (1/T_q) Σ_{i,t ∈ q} ℓ_{i,t}`. MiMo uses it to keep
response length from growing too fast.
**How:**
- **Trainer:** the `rl` component now divides by the global sum of its
per-token weights, not by the count of nonzero-weight tokens. Every `rl`
weight set in prime-rl today is 0/1, so the sum equals the old count,
and the default path is bit-identical to main. `ce` and `ref_kl` still
divide by their token counts. This is on purpose: echo's fractional `ce`
weight (`alpha`) must keep scaling the loss instead of cancelling out.
- **Orchestrator:** with `"prompt"`, `GRPOAlgorithm.score_group` gives
each trainable token of group q the `rl` weight `1/T_q`. `T_q` is the
group's trainable tokens, the same tokens the advantage is assigned to.
Each group's weights sum to 1, so the `rl` denominator becomes the
number of groups in the step, all-reduced across ranks like before.
There is no extra state.
- **Config:** a validator rejects runs that mix `"token"` and `"prompt"`
across envs with an `rl` loss. In a mixed batch, a whole prompt-mean
group would weigh as much as one token of a token-mean env.
- **Known difference from MiMo:** zero-advantage pruning still drops
zero-advantage tokens from `rl`. A group with a zero-advantage rollout
therefore keeps less than its full weight of 1. MiMo divides by all of
the group's tokens.
- **#3789 (length-weighted baseline):** compatible. Within a group the
weights are uniform, so a length-weighted baseline still keeps the
per-token advantage zero-mean.
**Breaking changes:** none for the default. One behavior change: an `rl`
weight stream with fractional weights would now be normalized by its
sum. Nothing in the repo produces such a stream today.
## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 301 passed. This includes an updated test in `test_advantage.py`:
each group's `rl` weights are exactly `1/T_q` and sum to 1, for two
groups of different length.
- Manual check that the config validator rejects mixed
`loss_aggregation` across envs.
- `ruff check .` and `ruff format --check .`: clean.
- Not run, because this machine has no GPU:
- `tests/unit/train/rl/test_loss.py`, which needs CUDA and also fails
here on main.
- The trainer denominator change in `train.py`.
- GPU and integration tests.
- A training run.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes how the RL loss denominator is computed globally; default
token aggregation should be numerically equivalent, but prompt-mean
alters gradient weighting for long trajectories and mixed configs are
blocked at validation time.
>
> **Overview**
> Adds **opt-in prompt-mean RL loss aggregation** for GRPO and echo via
`loss_aggregation = "prompt"` (default `"token"` stays unchanged).
>
> When enabled, **`GRPOAlgorithm.score_group`** stamps each trainable
token with `rl` weight `1/T_q` so each prompt group’s weights sum to 1
(MiMo-style prompt mean). The **trainer** now normalizes the `rl`
component by the **global sum of `rl_weights`** (not nonzero-token
count); with the default 0/1 weights this matches prior behavior. **`ce`
/ `ref_kl`** still divide by token counts so fractional echo `ce`
weights behave correctly.
>
> **Orchestrator config** rejects mixing `"token"` and `"prompt"` across
envs that use an `rl` loss. **Docs** describe the knob; a **unit test**
checks per-group `rl` weights sum to 1.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
91cf0629f13c3fa39d7c78f476e549b097efa025. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## What
Removes the Hugging Face model-implementation fallback (`model.impl =
"hf"`). The trainer now only builds PrimeRL model implementations
(`src/prime_rl/trainer/models/`). An unsupported architecture fails at
setup with `'<model_type>' has no PrimeRL model implementation`.
- `model.impl` is removed. With `"hf"` gone, `"auto"` and `"custom"`
resolved to the same thing.
- `trainer/model.py`: removed impl resolution, `AutoModelForCausalLM` /
`AutoModelForImageTextToText` loading, the CPU-load fallback
(`can_reinit_empty_buffers`, `fix_model_post_empty`), HF weight
re-tying, the HF router-freeze branch, and the HF output handling in
`forward`.
- Removed `lm_head_gemma.py` and its hook in `inject_prime_lm_head`. It
only served HF-impl models with final-logit softcapping.
- Removed the HF CP patches (`substitute_hf_flash_attn`,
`substitute_hf_ulysses_attn`). The config already rejected CP for the HF
impl.
- Removed the `qwen3_vl`, `qwen3_vl_moe` and `gemma4` entries from the
trainer VLM registry. They could only be loaded through the HF path.
Orchestrator and inference multimodal adapters are unchanged.
- Removed the config validators that only checked `impl` (EP, CP, FA4,
quantization, router replay, VLM, trust_remote_code).
- `hendrycks-sanity` (`examples/basic`, `configs/basic`,
`configs/ci/nightly-fft`) used
`deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` (Qwen2 architecture, which
has no PrimeRL implementation). It now uses `Qwen/Qwen3-1.7B`. No other
settings changed.
- Dropped `impl = ...` from all configs/examples/docs, and updated
README, docs, and tests.
- `test_fused_lm_head.py`: the HF-model tests now use a tiny PrimeRL
Qwen3 (same config as #3768, which removes PrimeRL Llama), built in bf16
because the PrimeRL attention is FlashAttention-only (the fp32 build
failed CI with `FlashAttention only supports fp16, bf16, and fp8_e4m3`).
## Why
The HF fallback is an aging path: added 2025-09, last changed on its own
on 2026-07-17. It keeps a second loading, buffer-reinit, LM-head and CP
code path alive next to the custom implementations. After the
hendrycks-sanity switch, custom implementations cover every shipped
example and config.
## Breaking changes
- `model.impl` / `--trainer.model.impl` is no longer accepted. Configs
that set it fail validation (`extra_forbidden`), so delete the line.
- Architectures without a PrimeRL implementation (for example Qwen2,
Gemma, Qwen3-VL, Mistral) can no longer be trained.
- hendrycks-sanity now trains `Qwen3-1.7B`. Its dataset
(`mikasenghaas/Sanity-Test-R1D-1.5B`) was filtered to problems that
R1-Distill-Qwen-1.5B solves 20-80% of the time, and that band was not
measured for Qwen3-1.7B. **The expected reward, curves, and the nightly
thresholds (`MIN_TRAIN_REWARD = 0.75`, the mismatch-KL band in
`tests/nightly/test_hendrycks_sanity.py`) need GPU re-validation.**
## Validation
- `pytest tests/unit/test_configs.py tests/unit/train -m "not gpu"`: 356
passed, 2 failed. The 2 failures are in `test_cpu_adam.py` (ninja is
missing on this machine). They fail the same way on `origin/main`.
- `ruff check .` and `ruff format --check .`: clean.
- `test_fused_lm_head.py` inject tests: checked on CPU that the tiny
Qwen3 resolves to `flash_attention_3` / `FlashAttention`; the GPU run is
left to CI.
- Manual CPU check: `get_model` builds `Qwen/Qwen3-1.7B` on the meta
device, and a Qwen2 config raises the new setup error.
- Not run: GPU unit tests (including the edited `test_fused_lm_head.py`,
`test_model.py`, `qwen3_5/test_vlm.py`), integration tests, and nightly
runs. There is no GPU on this machine.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **High Risk**
> This is a breaking API and behavior change: unsupported architectures
hard-fail, and the hendrycks-sanity model swap can invalidate nightly
reward/KL gates until re-validated on GPU.
>
> **Overview**
> **Removes the Hugging Face training path** by deleting `model.impl`
(`hf` / `custom` / `auto`). The trainer always loads PrimeRL classes
from `src/prime_rl/trainer/models/`; unknown `model_type` values fail at
setup with a clear error.
>
> **Trainer/runtime cleanup:** `get_model` no longer branches to
`AutoModelForCausalLM` or HF VLMs, drops the CPU/meta fallback
(`can_reinit_empty_buffers`, `fix_model_post_empty`), and always uses
PrimeRL weight conversion and `init_buffers_post_meta`. **Removed**
Gemma softcapped LM head (`lm_head_gemma.py`), HF context-parallel
patches, and HF-specific MoE router freeze / forward handling.
>
> **Config & docs:** `impl = "custom"` (and related validators tying EP,
CP, VLM, etc. to `impl`) are stripped from Pydantic configs, examples,
and docs. VLM registry narrows to Qwen3.5 families (drops `qwen3_vl`,
`gemma4` trainer paths). Sampling-replay docs no longer mention Gemma
rejection.
>
> **Hendrycks sanity** now trains **`Qwen/Qwen3-1.7B`** instead of
`DeepSeek-R1-Distill-Qwen-1.5B` (no PrimeRL Qwen2 impl); dataset
filtering is still keyed to the distill model’s 20–80% band.
>
> **Breaking:** configs with `model.impl` fail validation;
Qwen2/Gemma/Qwen3-VL and other unregistered archs cannot be trained.
Nightly sanity thresholds may need re-baselining on GPU.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3524e2eeabd2642b1e607a0b59ff0af6489ad3a8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
rebased on main 243cfba0f; resolved conflicts in
src/prime_rl/trainer/model.py (kept main's parallelize_module import),
src/prime_rl/utils/vlm.py (kept native qwen4_exp from #3434), and
dropped configs/basic/hendrycks-sanity + configs/debug/concurrency.toml
(deleted on main by #3777).
## Summary
`optim.weight_decay` defaults to `"auto"` and resolves per trainer at
config-construction time: **`0.0` for RL**, **`0.01` for SFT** (the
historical default). Explicit values are untouched.
Follow-up to #2422, which flipped the shared default to `0.0` for both
trainers. Resolving per trainer keeps the RL motivation (no silent L2
decay of the policy during reward optimization) without changing SFT
behavior.
## How it works
Same pattern as `model.moe_router_dtype = "auto"`:
- `BaseOptimizerConfig.weight_decay` is now `Annotated[float,
Field(ge=0)] | Literal["auto"] = "auto"`.
- A `resolve_weight_decay_auto` model validator on `TrainerConfig` (RL)
resolves to `0.0`, and one on `SFTConfig` resolves to `0.01`.
- Because resolution happens at model construction, dumped configs
(`trainer.json` / `sft.json`) and `--help` always show the concrete
float — a resumed or reparsed run never sees `"auto"`.
- TOML / JSON / CLI overrides all keep working, including `weight_decay
= "auto"` explicitly.
| Trainer | `weight_decay` default |
| ------- | ---------------------- |
| RL (`rl`, `trainer`) | `0.0` |
| SFT (`sft`) | `0.01` (unchanged) |
## Notes
- Example configs that already set `weight_decay` explicitly are left
as-is; `examples/basic/wiki-search/rl.toml` and
`examples/advanced/glm-5.3/swe.toml` (`0.0`) now match the default and
could be simplified in a follow-up.
- LoRA runs resolve the same way (the optimizer is built from the same
`config.optim`).
## Testing
-
`tests/unit/test_configs.py::test_weight_decay_auto_resolves_per_trainer`
covers defaults, explicit floats, and the explicit `"auto"` string.
- Verified end-to-end locally: defaults, `RLConfig` sub-config,
`dump_resolved_config` output, TOML round-trip through `cli()`, and the
param group the optimizer receives.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Config-default change only at construction time; RL gets no weight
decay by default while SFT behavior stays at 0.01 unless users override.
>
> **Overview**
> **`optim.weight_decay` now defaults to `"auto"`** on shared optimizer
config instead of a fixed `0.01`. At config construction, each trainer
resolves it to a concrete float—the same pattern as
`model.moe_router_dtype`.
>
> RL **`TrainerConfig`** maps `"auto"` → **`0.0`** so policy training
does not apply L2 decay toward zero by default. SFT **`SFTConfig`** maps
`"auto"` → **`0.01`**, preserving the historical supervised default.
Explicit numeric values (and leaving `"auto"` in user input until
validation) behave as before; resolved dumps should show floats, not
`"auto"`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5219af74484473a3b4d884ec0569530e3521fa93. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## What
Adds step-level MoE expert-load metrics to the RL and SFT trainers,
logged as mean and max over MoE layers:
- `expert_load/cv/{mean,max}`: std/mean of the per-expert token counts
in a layer.
- `expert_load/max_mean/{mean,max}`: the busiest expert's count divided
by the mean count.
- `expert_load/cold_frac/{mean,max}`: the fraction of experts that
receive under 0.1x the mean count. This is the MiMo-V2.6 §5.4
definition, so values compare directly with the paper.
## Why
MiMo-V2.6 §5.4 uses these three numbers to show that a trainable router
collapses expert load during RL (CV 0.78→2.0, cold experts 0.5%→22%
within 20 steps) and that freezing the router prevents it. We need the
same evidence to validate #3797 (freeze the router by default for RL) on
our models. The metrics also help catch EP load imbalance.
## How
- The MoE layers already add routed-token counts into the
`tokens_per_expert` buffer inside the forward pass. This uses the
existing `record_moe_routing_statistics` custom op, so it works with
compile without graph breaks. It covers both the torch and DeepEP
dispatch paths because the counts come from the router. **No model or
compiled code changes.**
- `get_global_moe_stats` now also returns this rank's raw per-layer
counts for the micro-step, captured before the existing EP reduction and
reset. The train loop sums them over the step. At step end, one
`all_reduce(SUM)` over `dp_cp` (which includes the EP ranks) produces
global counts, and the stats are computed from them. Extra cost: one
`[num_moe_layers, num_experts]` add per micro-step and one all-reduce
per step.
- Only aggregates over layers are logged, with no per-layer keys. This
follows the existing `max_vio`/`routing_confidence` convention, which
also reduces over layers. It also keeps the key count fixed for 75-layer
models. The max over layers catches a single collapsing layer, like
MiMo's layer 9.
- `max_vio` and `routing_confidence` are unchanged: they are still
per-micro-step.
- `docs/training.md` describes the new metrics.
No breaking changes. Existing metric keys are unchanged;
`get_global_moe_stats` now returns `(stats, tokens_per_expert)`
(internal function).
## Validation
- `pytest
tests/unit/train/models/{test_moe,test_checkpointing,test_qwen3_moe,test_glm4_moe,test_gpt_oss,test_deepseek_v4_cpu}.py
tests/unit/train/test_model.py tests/unit/test_configs.py -m "not gpu"`:
243 passed. This includes one new CPU test of the metric computation.
- `ruff check .` and `ruff format --check .`
Not run: there is no GPU on this machine. GPU checks still needed:
- [ ] EP>1 run (torch and DeepEP dispatch): `expert_load/*` values are
identical across ranks and plausible.
- [ ] Compiled run: no new recompiles or graph breaks
(`TORCH_LOGS=recompiles`).
- [ ] A short RL run with a frozen router vs a trainable router: the
trainable run should show `cv`/`cold_frac` rising.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Logging-only path using existing routing counters plus one optional
all_reduce per MoE step; no changes to loss, routing, or model forward
behavior.
>
> **Overview**
> Adds **step-level MoE expert-load observability** aligned with
MiMo-V2.6 §5.4: trainers now log
`expert_load/{cv,max_mean,cold_frac}/{mean,max}` (coefficient of
variation, hottest-expert/mean ratio, and fraction of “cold” experts
under 0.1× mean load), aggregated as mean and max over MoE layers.
>
> **Implementation:** `get_load_balance_stats` captures each rank’s
per-layer `tokens_per_expert` before EP reduction; micro-steps
accumulate counts across the step; `get_expert_load_stats` sums globally
over `dp_cp` and computes the three stats. Existing per-microstep
`max_vio` and `routing_confidence` logging is unchanged. RL and SFT
training loops wire the new metrics into step logs; `docs/training.md`
documents how to read them (e.g. rising `cv`/`cold_frac` when a
trainable router drifts).
>
> A CPU unit test covers `compute_expert_load_stats`.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9dde6e6ac625b4469c67ad2d20350d1bfbde9311. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary
The weight-broadcast config (filesystem | nccl | nixl) was declared four
times: the inference `WeightBroadcastConfig`, the trainer
`*WeightBroadcastConfig`, the orchestrator `*WeightBroadcastConfig`, and
the rl.py `Shared*WeightBroadcastConfig`.
`RLConfig.auto_setup_weight_broadcast` then copied each field between
them by hand. Every new transport field had to be added in four places
and in the copy code.
Design: one discriminated union `WeightBroadcastConfig` (`FileSystem` /
`NCCL` / `NIXL` variants) in `configs/shared.py`. The trainer,
orchestrator, inference, RLConfig, SFTConfig and the online eval config
all use it.
- `auto_setup_weight_broadcast` now does `model_copy()` of
`[weight_broadcast]` into the trainer and orchestrator, and sets
`inference_world_size` for in-memory transports. Inference gets a plain
copy. The inference server still reads only `type`.
- `validate_shared_weight_broadcast` is deleted. All three sub-configs
are now copies of the same object, so their types can't differ.
- SFT assigns the whole object to inference instead of mutating
`inference.weight_broadcast.type`.
- All three transports are kept.
Net: 82 lines added, 223 removed. Three class hierarchies, the
field-copy mapping and one validator are gone. No new abstractions.
## Breaking changes (all minor)
- `[weight_broadcast]` in `rl` now accepts `inference_world_size`. Like
before, the value is ignored: rl computes it.
- `[inference.weight_broadcast]` now accepts the transport fields
(`host`, `port`, `timeout`, ...). The inference server ignores them. The
resolved `inference.json` now contains them.
- Standalone `trainer.weight_broadcast.inference_world_size` must now be
`>= 1`. This matches the orchestrator, which already enforced it.
Before, `0` was accepted.
- Import paths: the classes now live in `prime_rl.configs.shared`. They
are no longer in `prime_rl.configs.trainer`, `.orchestrator` or
`.inference`.
## Validation
- Throwaway script (not committed): for every TOML in `configs/` and
`examples/`, parse it with every config class, plus sibling-base
overlays such as `glm-5.3/swe.toml @ swe-llmd.toml`. Dump the resolved
config on base and on this branch, then diff. Also covered: CLI cases
for rl/trainer/orchestrator/inference/sft with nccl/nixl/filesystem and
custom host/port/timeout/session_id. The only differences are the
additive or tightened cases listed under breaking changes. The trainer
and orchestrator `weight_broadcast` values are identical everywhere,
including glm-5.3 `swe.toml`, `swe.toml@swe-llmd.toml` and
nemotron-3-super.
- `rl --dry-run` / `sft --dry-run` on base vs branch for glm-5.3 swe,
glm-5.3 swe+llmd, nemotron-3-super swe, minimax-m2.5 swe, glm-4.5-air
swe+2-node, reverse-text (nccl and nixl), reverse-text sft and dynamo.
After normalizing paths, `trainer.json`, `orchestrator.json`, env
configs and `rl.sbatch` are byte-identical. `inference.json` only gains
the extra `weight_broadcast` fields.
- `pytest tests/unit -m "not gpu"`: 683 passed. 1 failure
(`test_cpu_adam`) also fails on main.
- `ruff check` and `ruff format --check` pass.
- No GPU on this machine, so GPU and integration tests (actual NCCL/NIXL
transfers) were not run.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches how RL/SFT wire trainer–orchestrator–inference weight transfer
(NCCL/NIXL sizing and config propagation); behavior is intended to match
prior dry-runs but import-path and validation changes could break custom
configs.
>
> **Overview**
> **Consolidates trainer-to-inference weight broadcast settings** into a
single discriminated union (`filesystem` / `nccl` / `nixl`) in
`prime_rl.configs.shared`, removing parallel class hierarchies that
lived under trainer, orchestrator, RL `Shared*`, and manual per-field
copying.
>
> `RLConfig.auto_setup_weight_broadcast` now **`model_copy()`**s the
shared `[weight_broadcast]` onto trainer and orchestrator (auto-filling
`inference_world_size` for in-memory transports) and sets inference to a
type-only config. **SFT** does the same for inference instead of
mutating `.type` alone. **`validate_shared_weight_broadcast`** is
dropped because all components share one schema.
>
> Weight transport code (`transports/weights/*`, online eval) **imports
the shared types** instead of `configs.trainer`. Minor behavior/doc
shifts: RL rejects user-set `inference_world_size`, standalone trainer
enforces `inference_world_size >= 1`, and resolved `inference.json` may
include full broadcast fields the server ignores.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
937fc8a870e5559f40bc390653dd6c45dbd912d5. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Adds `length_weighted_baseline: bool = False` to `GRPOAlgoConfig`.
When enabled, the GRPO group baseline is the token-length-weighted mean
reward `b = sum_i(L_i * r_i) / sum_i(L_i)` instead of the plain mean.
`L_i` is the number of trainable (mask-True, policy-sampled) tokens of
rollout `i`, summed across all turns. Advantage is `r_i - b`. The
baseline is applied after the length penalty, same as the plain mean.
There is no fallback for a group with zero trainable tokens: then every
trace has `L_i = 0`, so `assign_advantages` writes no tokens, and no
metric, annotation or sample reads the (NaN) baseline.
Why: with token-level loss normalization, long rollouts carry more
gradient weight. A length-weighted baseline makes the per-token
advantage zero-mean across the group's tokens instead of across
rollouts.
- `routing.py`: pulls the trainable-node selection out of
`assign_advantages` into `trainable_nodes(trace)`, so `L_i` counts
exactly the tokens that receive the advantage.
- `echo` inherits the option because it subclasses GRPO.
- With the flag off, results are bit-identical to today: same `rewards -
rewards.mean()` computation.
- No breaking changes.
## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 301 passed. Includes the new
`test_grpo_length_weighted_baseline`, which covers the flag alone and
the flag combined with the length penalty (ordering).
- `ruff check .` and `ruff format --check .`: clean.
- GPU and integration tests were not run (no GPU on this machine).
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Opt-in GRPO baseline change with default off; touches advantage math
only on the orchestrator scoring path, with targeted unit tests.
>
> **Overview**
> Adds an opt-in **`length_weighted_baseline`** flag on GRPO-family
config (`GRPOAlgoConfig`, inherited by `echo`). When enabled, the group
baseline becomes the trainable-token-weighted mean of
(length-penalty-)shaped rewards instead of a plain rollout mean, so
advantages are **zero-mean per token** rather than per rollout—aligned
with token-normalized RL loss when long completions dominate gradient
mass.
>
> **`GRPOAlgorithm.score_group`** now computes `shaped_rewards` first,
then either `mean(shaped_rewards)` or `sum(L_i * r_i) / sum(L_i)` with
`L_i` counting mask-True policy tokens across turns.
**`routing.trainable_nodes`** is extracted so `L_i` matches the tokens
that receive broadcast advantages via `assign_advantages`. Default
`false` preserves the existing centered-mean behavior.
>
> Docs describe the math and ordering (after length penalty). Unit tests
cover the flag alone and combined with linear length penalty.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8f8d988d4957d02e61f28dfe0e46b1af3fefab7d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Unifies the local launch-and-monitor code in `rl_local` and `sft_local`.
Before this PR, both repeated the same machinery: Popen → log file →
monitor thread → error queue → SIGTERM/Ctrl-C/exception cleanup, GPU
partitioning from `CUDA_VISIBLE_DEVICES`, and the trainer torchrun
command. Each copy had small differences, which made the two launchers
drift.
## Design
`utils/process.py` already holds the launcher primitives
(`monitor_process`, `cleanup_processes`, env defaults). This PR adds
three small pieces there:
- `ProcessGroup`: a context manager. `start(name, cmd, env, log_path)`
starts a process with its log file and monitor thread. `wait(*names)`
blocks until the named processes exit and fails fast (exit 1) on the
first error from any process. SIGTERM, Ctrl-C, exceptions and normal
exit all clean up every process. The messages and ordering are the same
as the old inline code.
- `partition_gpus(num_infer, num_train)`: splits the physical GPUs into
inference GPUs followed by trainer GPUs, and raises the same
`ValueError` as before.
- `torchrun_cmd(module, config_path, nproc, log_dir, ranks_filter)`: the
shared single-node trainer command.
`rl_local` and `sft_local` keep their own commands and env dicts
unchanged. Only the plumbing moves. Net: −126 lines.
`inference.py` is not changed. Its only subprocess is the vllm-router.
The router inherits stdout (no log file), and its watcher SIGTERMs the
inference process itself. That does not fit the start/monitor/fail-fast
pattern, and forcing it in would change behavior. `eval.py` env servers
are also unmonitored on purpose, so they stay as they are. SLURM
rendering is not touched.
## Behavior
Behavior is the same: commands, env vars (including key order), log
paths, start order, kill order, exit codes and info/warning/error logs.
Two small differences:
- rl `--log-level debug` "command" lines now read `Inference command:
...` / `Train env server <name> command: ...` / `Trainer command: ...`
instead of `... start command: ...`.
- The rl wait loop is now the sft one: it checks errors before it checks
completion. Before, if the trainer failed *after* the orchestrator had
already exited, rl logged `Trainer failed with exit code N` from a
post-loop check. Now it logs `Error: Trainer failed with exit code N` /
`Terminating all processes...`. The exit code (1) and cleanup are the
same. The post-loop returncode checks could no longer be reached, so
they are removed. Side effect: if inference or an env server crashes in
the last ~1s, when the trainer and orchestrator also finish, the run now
fails instead of being ignored.
No config, metric, or checkpoint changes. No breaking changes.
## Validation
- I ran a throwaway (uncommitted) script against `rl_local`/`sft_local`,
once on `origin/main` and once on this branch, and diffed the results.
It fakes `subprocess.Popen` and `cleanup_process`, pins the free port,
uuid and `CUDA_VISIBLE_DEVICES=3,5,6,7`, and records each launch's exact
cmd, env delta, log path, kill sequence, exit code and logs. Configs:
reverse-text `rl.toml`, `configs/debug/multi-env/rl.toml`, reverse-text
`sft.toml` (online eval + inference), `configs/debug/fake/sft.toml`.
Scenarios: success;
trainer/orchestrator/inference/env-server/online-eval failure; trainer
failing after the orchestrator exits; SIGTERM; SIGINT; too many GPUs
requested. All records and exit codes were identical. The only log
differences are the two listed above.
- `pytest tests/unit -m "not gpu"`: 683 passed, 1 failed. The failure is
`test_cpu_adam.py::test_native_cpu_adamw_matches_fused_torch_and_preserves_gradients`,
which also fails on `origin/main` on this machine.
- `ruff check .` and `ruff format --check .` pass.
- No GPU on this machine, so I did not run any real launch or
integration test.
## Reviewer GPU checks (not run here)
- rl reverse-text e2e exits 0, and inference/env servers have no late
non-zero exits.
- SIGTERM and Ctrl-C mid-run leave no vLLM or torchrun workers.
- Trainer and inference logs are unchanged.
- sft with online eval waits for the eval to drain before it exits.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Touches core multi-process launcher lifecycle (spawn, monitor,
teardown) for training runs; behavior is mostly preserved but wait/error
ordering changes can alter exit outcomes at run end.
>
> **Overview**
> **Refactors local RL and SFT launchers** so they no longer duplicate
subprocess orchestration; shared behavior lives in
`prime_rl.utils.process`.
>
> Adds **`ProcessGroup`** (context manager with `start` / `wait`),
**`partition_gpus`**, and **`torchrun_cmd`**. Both `rl` and `sft`
entrypoints now start inference, env servers, orchestrator/online-eval,
and trainer through `ProcessGroup` instead of inline `Popen`, monitor
threads, error queues, and hand-rolled SIGTERM/Ctrl-C cleanup.
>
> Commands, env vars, log paths, and start order are intended to stay
the same. **Minor differences:** debug log lines drop the `"start"`
prefix on command logs; RL’s wait loop now checks the error queue before
completion (aligned with SFT), so late failures from non-terminal
processes (e.g. inference/env server in the last second) can fail the
run where RL previously might have exited successfully.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fb27b22cf76aa28b094caedb07a646b7d5db7c7e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Pure moves + import updates. No logic change.
**Design / target structure**
- `trainer/batch.py` -> `orchestrator/batch.py`. Only
`orchestrator/packing.py` uses it. Nothing in `trainer/` imports it. Its
test already lives at `tests/unit/orchestrator/test_batch.py`.
- `trainer/models/deepseek_v4/eager_reference.py` ->
`tests/unit/train/models/deepseek_v4_eager_reference.py`. Only the DSv4
tests import it. Its docstring says nothing in production calls it.
- `trainer/conversion_utils.py` (one 10-line function) is inlined into
`transports/weights/nccl.py`, its only user.
**Left as is (not equivalent)**
- FLOPs models: `orchestrator/batch.py` (forward-cost coefficients for
bin balancing) and `trainer/perf.py` `_get_num_flop_per_token` (train
FLOPs for MFU, LoRA-aware) give different numbers. For example, o_proj
is `2*h*h` vs `h*heads*head_dim`, router params are counted only in
perf, and attention uses `head_dim` vs `h/heads`. On Qwen3-0.6B/1.7B,
Qwen3-VL-4B, Qwen3.5-2B and debug-moe they differ by 4-11%, so merging
them would change either the packing or the MFU metric.
- `list_shards` duplicate in `tools/convert_fp8_to_bf16.py` and
`tools/convert_bf16_to_fp8.py`: kept so `convert_fp8_to_bf16.py` stays
standalone (torch + safetensors only, no `prime_rl` import).
- Blockwise FP8 dequant: the tools version takes the block size from
`quantization_config` and handles shapes that are not multiples of the
block (via ceil + slice). The DSv4 version infers the block size from
the shape ratio, needs exact divisibility, and also handles MXFP4. They
are not interchangeable.
- `tools/convert_dcp_to_fp8.py` sibling imports: these already work from
the repo root and from any cwd. Python puts the script's directory on
`sys.path`, and the same holds under `torchrun`. I checked `--help` from
the repo root and from `/tmp`. No change needed.
**Breaking changes**
- Import paths: `prime_rl.trainer.batch` ->
`prime_rl.orchestrator.batch`. `prime_rl.trainer.conversion_utils` and
`prime_rl.trainer.models.deepseek_v4.eager_reference` are removed from
the package.
**Validation**
- `pytest tests/unit/orchestrator/test_batch.py
tests/unit/train/models/test_deepseek_v4_cpu.py
tests/unit/train/models/test_deepseek_v4.py
tests/unit/train/models/test_deepseek_v4_kernels.py
tests/unit/transports tests/unit/train/test_perf.py -m "not gpu"`: 31
passed, 97 deselected. Both DSv4 test modules import fine. No GPU on
this machine, so the GPU DSv4 tests and integration tests were not run.
- `ruff check .` and `ruff format --check .` both pass.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Low Risk**
> Import-path-only refactor with inlined helper code; no training,
packing, or NCCL broadcast logic changes, aside from downstream breakage
if anything still imports the removed modules.
>
> **Overview**
> This PR reorganizes modules so orchestrator-only, test-only, and
single-use code no longer lives under `trainer/`. **Batch packing**
moves from `prime_rl.trainer.batch` to `prime_rl.orchestrator.batch`,
with `packing.py` and orchestrator unit tests updated to the new import
path.
>
> **DeepSeek V4 eager reference** implementations move out of the
production package into
`tests/unit/train/models/deepseek_v4_eager_reference.py`; DSv4 GPU tests
import from there instead of
`prime_rl.trainer.models.deepseek_v4.eager_reference`.
>
> **Layer counting for NCCL weight broadcast** drops the standalone
`trainer/conversion_utils.py` module: `get_max_layer_num` is defined
inline in `transports/weights/nccl.py`, its only caller. Behavior is
unchanged; callers must switch imports for batch and remove use of the
deleted trainer modules.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9287ae8ce22ba8731b80ebc1634ee0d5bbb25ea3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 13:42:11 -07:00
587 changed files with 36040 additions and 23511 deletions
@@ -61,5 +61,6 @@ Write tests as plain functions with pytest fixtures. Don't use class-based tests
## GitHub
- **Draft PRs**: always create PRs as drafts (`gh pr create --draft`) to avoid triggering CI unnecessarily.
- **GPU CI is opt-in**: pushes to a PR don't run GPU tests. The full GPU suite runs on the PR's current commit when someone applies the `gpu-ci` label. Only when the user asks, request a run with `gh pr edit <num> --add-label gpu-ci`. The workflow removes the label, so re-add it after new pushes.
- **Pull requests**: do not include a "test plan" section in PR descriptions unless you actually ran tests to verify the changes or the user explicitly asked for one.
- **Keep PR descriptions in sync**: every time you push commits to a PR, also update the PR description (`gh pr edit <num> --body-file ...`) so it reflects the current state of the branch — not just what was true when the PR was opened. Preserve any auto-generated blocks (e.g. `<!-- CURSOR_SUMMARY -->`).
RUN /app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'\
@@ -35,8 +32,8 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
2. Performant: built to train 1T+ MoE models on 1000+ GPUs with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) for training and [vLLM](https://github.com/vllm-project/vllm) for inference, with FP8 inference, PD disaggregation, EP and CP parallelism, and more.
3. Native integration with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments through the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars), including built-in support for SWE and agentic environments.
4. End-to-end post-training: SFT, RL training, and evals.
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
5. Multi-node deployment with Slurm support.
6. Multimodal support for Qwen3.5 and Qwen3.8 VLMs, with [image RL and SFT examples](examples/extra/vlm/README.md).
7. Hackable, modular, and extensible by design.
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.3/).
@@ -44,18 +41,19 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
## Models support
The trainer works with both Hugging Face and Prime custom `ModelForCausalLM` out of the box. For selected families (especially large MoE) we also ship highly optimized training code under `src/prime_rl/trainer/models/`, including expert parallelism (EP) for MoE layers and context parallelism (CP) for long sequences (see the table), and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels).
With `[model] impl = "auto"` (the default), the trainer selects that custom stack when the Hugging Face config type is registered.
The trainer runs the PrimeRL model implementations under `src/prime_rl/trainer/models/`: dense Llama, Qwen3 and Qwen3.5, plus the families in the table below, with expert parallelism (EP) for MoE layers, context parallelism (CP) for long sequences, and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels). Other architectures fail at trainer setup.
@@ -178,12 +176,12 @@ Follow this guide to learn the basics of prime-rl. You can train your own models
2. [**Wordle**](examples/basic/wordle/README.md): Train `Qwen3-1.7B` to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
3. [**Alphabet Sort**](examples/basic/alphabet-sort/README.md): Train `Qwen3-4B-Instruct-2507` to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
4. [**Wiki Search**](examples/basic/wiki-search/README.md): Train `Qwen3-4B-Instruct-2507` to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
5. [**Hendrycks Sanity**](examples/basic/hendrycks-sanity/README.md): Run a sanity check experiment on `DeepSeek-R1-Distill-Qwen-1.5B` using a filtered subset of MATH where the model already partially solves 20-80% of problems. Useful for algorithm ablations.
5. [**Hendrycks Sanity**](examples/basic/hendrycks-sanity/README.md): Run a sanity check experiment on `Qwen3-1.7B` using a subset of MATH filtered to problems that `DeepSeek-R1-Distill-Qwen-1.5B` partially solves (20-80%). Useful for algorithm ablations.
### Advanced Training: 32 - 2048 GPUs:
Follow this guide to train large models on hard reasoning and agentic tasks.
These guides are designed to be run from a Slurm cluster but can also be adapted to k8s deployments.
These guides are designed to be run from a Slurm cluster.
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
@@ -198,7 +196,7 @@ Check out the [docs](docs) directory for in-depth guides on how to use prime-rl.
- [**Training**](docs/training.md) - RL, SFT, checkpointing, observability, rules of thumb
- [**Eval**](docs/eval.md) - Standalone evals against any inference server, online evals, resume, platform upload
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
- [**Algorithms**](docs/algorithms.md) - Async training and staleness, the AIPO loss, advantage and filter plugins, trajectory merging
"error_reason":"[rank0]: torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 37.09 GiB. GPU 0 has a total capacity of 79.18 GiB of which 34.48 GiB is free. Including non-PyTorch memory, this process has 44.69 GiB memory in use. Of the allocated memory 43.38 GiB is allocated by PyTorch, and 103.94 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)",
"error_reason":"[rank4]: torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 8.00 GiB. GPU 4 has a total capacity of 178.36 GiB of which 7.20 GiB is free. Including non-PyTorch memory, this process has 171.05 GiB memory in use. Of the allocated memory 168.36 GiB is allocated by PyTorch, and 418.92 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)",
> :warning: indicates regression > 5% from baseline
> diffs shown when abs(change) >= 1.0% (except regressions, which always show diffs)
> :clock10: The Step Time shown is the time taken per micro batch. This differs from what gets displayed in the bench table which is the total step time.
## INTELLECT-3
| Type | SeqLen | AC | Attn | EP | CP | Hardware | MFU | TPS | Step Time | Peak Mem |
f"> :warning: indicates regression > {threshold*100:.0f}% from baseline",
f"> diffs shown when abs(change) >= {diff_display_threshold*100:.1f}% (except regressions, which always show diffs)",
"",
"> :clock10: The Step Time shown is the time taken per micro batch. This differs from what gets displayed in the bench table which is the total step time."
"",
]
formodel,model_resultsinsorted(by_model.items()):
lines.append(f"## {model.split('/')[-1]}")
lines.append("")
lines.append("| Type | SeqLen | AC | Attn | EP | CP | Hardware | MFU | TPS | Step Time | Peak Mem |")
# Minimal SFT config with a [slurm] section — fixture for the slim-wheel config
# parse check in cpu_tests.yaml. On the slim wheel the templates/ data dir is
# parse check in tests.yml. On the slim wheel the templates/ data dir is
# absent, so [slurm].template_path must resolve to None instead of erroring.
[slurm]
job_name="slim-sft-check"
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.