* chore: remove outdated config dirs
Prune four stale, unused config directories. None are referenced by
docs, skills, CI, or scripts, and each is a one-off experiment or
feature demo whose last substantive edit predates the recent config
sweeps:
- wordle: legacy v0-bridge demo, last real edit 2025-08-30
- deepscaler: old multi-stage experiment (README points at a
configs/deepscaler/eval.toml that no longer exists)
- glm5_disagg_inference: one-off disaggregated-inference demo
- elastic: alphabet-sort elastic/DNS-discovery demo
All four still parse against the current schema; removal is about
disuse, not breakage.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: remove outdated acereason_math configs
Prune the stale acereason_math experiment configs (stage1/stage2, last
real edit 2025-12-23). They reference the aime24-v1 eval taskset that is
no longer available, so they fail to load against the current schema.
The live nightly run (configs/ci/nightly/acereason_math.toml) is
unaffected; drop its now-dangling comment reference to the deleted dir.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: keep wordle, elastic and glm5_disagg_inference configs
Narrow this PR to only the deepscaler and acereason_math configs.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: remove acereason_math from nightly suite
Drop the nightly acereason-math config and its test. The nightly
workflow auto-discovers tests/nightly/test_*.py, so removing the test
file drops it from the matrix.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(deps): repoint scaleswe/swebench-verified/terminal-bench-2 v1 tasksets to research-environments
The three container-backed v1 SWE tasksets moved out of verifiers into
research-environments. Repoint their [tool.uv.sources] paths and bump both
submodules to match.
- deps/verifiers: drop the three envs
- deps/research-environments: add the three envs + advance to current main
- uv lock
Taskset ids are unchanged, so run configs that reference them by id need no changes.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(deps): bump verifiers + research-environments submodules to current heads
Picks up vf#1851 (swebench-verified ensures uv on PATH before scoring), now ported
into the research-environments copy of swebench_verified_v1.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(deps): repoint 6 more v1 tasksets to research-environments
Following their move out of verifiers, repoint math-env-v1, aime24-v1, r2e-gym-v1,
swelego-v1, wikispeedia-v1, and general-agent-v1 from deps/verifiers to
deps/research-environments, and bump both submodules to the updated heads. The
moved envs now pin verifiers>=0.1.15.dev381 (satisfied by the editable verifiers).
- uv lock
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(deps): bump research-environments (drop moved eval configs + scaleswe fix)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(deps): swap v0 aime for v1 tasksets + reference tau2-bench-v1
Following the aime/wikispeedia v0->v1 replacement in research-environments:
- drop aime2024, aime2025 (v0); reference aime24-v1, aime25-v1, aime26-v1
- add tau2-bench-v1
- bump deps/research-environments + uv lock
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(deps): repin verifiers + research-environments to merged main
verifiers#1853 (remove the moved v1 tasksets) and research-environments#527 (add them)
have merged; repin both submodules to the merged main commits. uv.lock unchanged
(already consistent — `uv lock --check` passes).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(configs): point aime eval envs at the v1 tasksets
The v0 aime2024/aime2025 packages were dropped from the `envs` extra + sources, so
`uv sync --extra envs` no longer registers them and eval sections using the legacy
ids fail at runtime. Switch those eval entries to the v1 tasksets (aime24-v1 /
aime25-v1; default `subprocess` harness), keeping the display names for metric
continuity.
- configs/acereason_math/{stage1,stage2}.toml
- configs/debug/hendrycks_sanity/rl.toml
- configs/math_group/rl.toml
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The CPU RAM usage warning in the activation offloader fired at 60%
virtual memory used, which is noisy on healthy runs. Bump the threshold
to 90% so it only warns when memory is genuinely close to exhaustion.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: add vf-nano as submodule
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump deps/vf-nano to feat/env-server (EnvServer)
Points the submodule at the vf-nano EnvServer branch so the orchestrator can
build on the env-server abstraction.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: run orchestrator on a vf-nano env server (reverse-text)
Switch prime-rl's env path to vf-nano: the orchestrator spawns a vf-nano
EnvServer per env (it never loads an environment), dispatches rollouts by task
index, and trains on the returned Trace dicts (branches + renderer tokens).
- pyproject: dep verifiers -> vf-nano; drop v1/research env packages; only the
vf-nano reverse-text example; override out the transitive v1 verifiers (pulled
by the prime CLI) so it can't shadow vf-nano's `verifiers` package; add orjson
/pandas/msgspec (were transitive via verifiers).
- EnvConfig inherits vf-nano's swappable agent/runtime (+ max_turns).
- envs.py: spawn EnvServer child + EnvClient, info() for num_tasks/group-scoring,
dispatch by task_idx, adapt Trace -> RolloutOutput-shaped dict.
- trajectories.py: trace_to_samples (one sample per Trace branch) + trace_to_output.
- train_source: index sampling; client pool builds vf-nano ClientConfig; lag
monitor vendored; env-server entrypoint repointed; ~14 files retyped off
vf.RolloutOutput / vf.ClientConfig.
- configs/debug/vf_nano_reverse_text.toml.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: consume vf-nano Trace natively (branches→samples, shared renderer config)
- trace_to_samples stitches each Trace branch's tokens into one TrainingSample
(prompt = branch start, then each turn's new context [masked] + generated
tokens [trained]); drop the RolloutOutput adapter — read the Trace's native
fields directly (reward, error{type,message}, timing generation/scoring,
num_turns, branches).
- envs returns the raw Trace; eval_sink / train_sink / dispatcher / metrics /
orchestrator read native Trace fields (no token_usage/completion/timing.total).
- client pool forwards the shared renderers.RendererConfig to the env server's
renderer client (so it uses qwen3, not the tool-less default fallback).
- debug config: tool_call_parser=hermes (vLLM accepts the agent's tools),
max_steps=20.
- bump deps/vf-nano.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: pass typed ClientConfig/SamplingConfig to the env client (no timeout)
- Env.run_rollout/run_group pass the vf-nano ClientConfig object and a
SamplingConfig (built from the env's sampling args) directly — no model_dump,
no per-rollout timeout forwarded to the server.
- debug config: max_steps=20.
- bump deps/vf-nano (typed env-server RPC).
* refactor: orchestrator holds a typed vf.Trace[EnvTask] (no dicts)
The env server returns a Trace minus its derived fields; the orchestrator resolves
the env's Task subclass (from config.id) and validates the wire dict into a strict
Trace[EnvTask], so the whole orchestrator works with a real, typed vf.Trace —
typed task fields included (e.g. task.answer), nothing subscriptable.
- envs.py: resolve_task_type(env_id); run_rollout/run_group validate -> Trace[EnvTask].
- trajectories/types/dispatcher/train_sink/eval_sink/metrics/filters/advantage/utils
/orchestrator: attribute access on the typed Trace (reward, error{type,message},
branches, timing.<span>.duration, num_turns, ...); derived fields recompute on the
consumer.
- Task/Trace/TimeSpan stay strict (StrictBaseModel) — no extra=ignore anywhere.
- bump deps/vf-nano.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: depend on vf-nano[serve]; bump submodule
The orchestrator spawns the env server, so request the serve extra
(zmq/msgpack) explicitly now that vf-nano keeps them out of core.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump vf-nano (client docstring cleanup)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: drop redundant forward-ref quotes in advantage.py
`from __future__ import annotations` already defers all annotations to strings,
so the quotes + `# noqa: F821` on the TYPE_CHECKING-only `vf.Trace` / `TrainRollout`
annotations are unnecessary (no import cycle — verifiers.nano never imports prime_rl).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: rename FinishedRollout.raw -> trace
The field holds a typed vf.Trace, so `trace` reads truer than `raw` (which
suggested an unparsed dict). Renames the field + every `.raw` access, the
`emit_rollout(trace=...)` param/kwarg, the to_dict field filter, and the
dispatcher cancel-path locals.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: simplify FinishedRollout, read straight off the typed Trace
- Drop the FinishedRollout proxy properties (error/reward/is_truncated and the
example_id field); consumers now read r.trace.{reward,is_truncated,task.idx,...}
directly. The trace is the single source of truth.
- Use vf.Trace.has_error for existence checks instead of `.error is not None`.
- Replace the prime-rl trace_* token-length utils with vf.Trace.{completion_len,
total_tokens,has_response} (now on the trace); keep trace_to_samples.
- Carry task_idx end-to-end (GroupState.task_idx, env.run_rollout/run_group(task_idx),
source dict key) instead of the example/example_id dict carrier; identity comes
off trace.task.idx.
- Mark the local-package env arrangement as a temporary/experimental TODO.
- Move the debug config to configs/debug/nano/reverse_text.toml.
- Bump deps/vf-nano (Trace/Turn accessors).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: spawn env server on an OS-assigned port, drop the startup poll
- The env server binds tcp://127.0.0.1:0 and reports its concrete address back
over a queue; the orchestrator connects to that. Removes _get_free_port and its
TOCTOU race (the OS assigns the port atomically).
- A spawned server has already bound + loaded by the time it reports its address,
so the untimed info() is enough — only poll wait_for_server_startup for an
external (config.address) server, which has no spawn handshake.
- Bump deps/vf-nano (port report + Trace/Branch token-length accessors).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: use vf.task_type instead of a local resolve_task_type
The Task-subclass introspection now lives in vf-nano (vf.task_type); drop the
prime-rl copy and build the typed Trace via vf.Trace[vf.task_type(env_id)]. Bump
deps/vf-nano.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: restore backfill_rollout_tokens for SFT (typed Trace)
SFT trains on a teacher served over the chat client, which returns no token ids,
so the trace's turns have tokens=None and trace_to_samples yields nothing. Restore
backfill: for each tokenless turn, render its prompt + assistant response with the
student chat template and split on the longest common prefix to fill TurnTokens
(masks/logprobs come from trace_to_samples). train_sink.process_rollout backfills
when any turn lacks tokens, before building samples.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: pass task_idx when building Cancelled traces on off-policy drop
drop_group's error_rollout_output calls omitted the required task_idx, so an
off-policy cancel (on_new_version) raised TypeError. Use the group's task_idx
(or -1 when the group is already gone), mirroring handle_completed_rollout.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: consume typed Trace[WireTask]; inline synthetic error traces
- envs.py: EnvClient now returns Trace[WireTask]; upgrade to this env's real Task
subclass via self.trace_type.model_validate(wire.to_wire()).
- dispatcher.py: drop the error_rollout_output helper — inline the synthetic error
Trace at each call site using vf.Error's field names (type/message/traceback); the
task-exception path carries a real traceback, cancels/empty-trajectory carry none.
- Bump deps/vf-nano.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: env-server file logging; align debug config batch/group to canonical
- Spawned env servers now route their output (logging + subprocess-runtime output)
to <output_dir>/logs/envs/<name>.log via a _run_env_server wrapper that redirects
stdout/stderr and sets up logging in the child. Previously the orchestrator-spawned
server logged nowhere.
- Debug config: batch_size 16->128, group_size 8->16, eval num_examples 8->128
(interval=1), matching configs/debug/training_modes/rl.toml.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: don't double the envs/ segment in the env-server log path
The orchestrator already passes a train/eval-split log_dir (.../logs/envs/train,
.../logs/envs/eval), so _spawn must drop the file directly under it
(<log_dir>/<name>.log) rather than re-adding an envs/ subdir — which had buried the
train/eval split under logs/envs/<kind>/envs/<name>.log.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump vf-nano (Error.traceback str | None)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump vf-nano (to_wire ordering)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: launch env servers as separate processes from the rl entrypoint
Instead of the orchestrator sidecar-spawning each env server as an mp child, the
rl launcher now spawns one `env-server` process per env (train + eval), each on a
free port, with output to logs/envs/{kind}/{name}.log and a crash monitor — same
model as inference/trainer. It sets env.address in the orchestrator config so the
orchestrator attaches (its existing external path) instead of spawning. Envs that
already set address (user-managed external server) are left alone; the orchestrator's
mp sidecar stays as the fallback for running `orchestrator` directly.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: env servers use fixed configurable ports, not get_free_port
Add RLConfig.env_server_base_port (default 5000); the i-th launcher-managed env binds
base_port + i. Drops the get_free_port dependency in the launcher.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: separate train/eval env-server port blocks
Train envs bind base_port + i; eval envs bind base_port + ENV_SERVER_KIND_STRIDE + i
(stride 1000), so each kind has headroom for many envs without the blocks colliding
(was a single running index — train and eval sat adjacent).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: env-server logs + sidecar queue cleanup; train-only debug config
- env_server entrypoint: intercept vf-nano stdlib logging so the server's own logs
(EnvServer up, request failures) land in logs/envs/<kind>/<name>.log — previously
only loguru output was captured, swallowing them.
- envs.py: close the address-handoff mp.Queue after use (no resource_tracker
leaked-semaphore warning on the sidecar path).
- configs/debug/nano/reverse_text.toml: drop the eval block, mirroring
examples/reverse_text/rl.toml (train-only smoke; eval path validated separately).
- bump deps/vf-nano (serve/types docstring trim).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump vf-nano (BaseRequest marker, no request_type field)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: env client uses client= (was client_config=); bump vf-nano
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump vf-nano (drop renderers dep comment)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump vf-nano (configs/ + cli/ split, serve/ runtime-only)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: drop FinishedRollout.to_dict; serialize the Trace to disk directly
The I/O boundary (save_rollouts + monitor sample tables) now dumps the typed
vf.Trace itself (r.trace.model_dump(mode="json")) instead of a Trace+metadata
merge — the on-disk rollout is just the trace.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: track vf-nano agent->harness rename
vf-nano renamed its rollout-driver abstraction Agent -> Harness. Update the
integration: EnvConfig.agent -> harness (HarnessConfig/DefaultHarnessConfig);
env.run_rollout/run_group spawn forwards harness_config; the env-server entrypoint
passes harness_config/harness_timeout; debug config uses `harness = {...}`. Bump
deps/vf-nano to the renamed branch.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: track vf-nano plugin reorg (reverse-text path + bump)
vf-nano reorganized examples into examples/{tasksets,harnesses}/; point the
reverse-text editable source at examples/tasksets/reverse_text and bump deps/vf-nano.
No prime-rl code change — EnvConfig.harness (default) resolves via vf-nano's built-in
harness registry. Verified: 3-step reverse-text smoke trains (0.26 -> 0.42, 0% error).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: reuse vf.EnvConfig in the orchestrator (typed taskset/harness, drop args)
prime-rl's EnvConfig now subclasses vf.EnvConfig and resolves taskset + harness to their
specific config types by id (taskset_config_type / harness_config_type), so env-specific
fields are validated against the real config — the untyped `args` dict and the top-level
`id` are gone (id/stripped_id/resolved_name are now properties off taskset.id). Timeouts
come from vf.TimeoutConfig (timeout.rollout / timeout.scoring), superseding prime-rl's flat
timeout. The env server is spawned with the typed taskset_config (no env_id/args).
- pyproject: install the vf-nano plugin packages (default/rlm harnesses, gsm8k taskset)
as path sources; bump deps/vf-nano to the plugin-packages branch.
- configs/debug/nano/reverse_text.toml: taskset = { id = ... }, harness.id (was harness.type).
Verified: custom taskset (gsm8k.split) + harness (rlm.ref) resolve to typed configs; bad
fields are rejected; the migrated TOML loads through RLConfig.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: inherit vf's shared plugin resolution; trim dead EnvConfig fields
EnvConfig drops its own _resolve_plugins (now inherited from vf.EnvConfig's shared
validator) and the dead v1-forwarding fields: extra_env_kwargs, max_total_completion_tokens,
state_columns (no readers on the vf-nano branch). Also drop stripped_id (no hub installs ->
no @version, so id == it) — callers use .id. Bump deps/vf-nano.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: require a configured taskset per env (no reverse-text default)
EnvConfig no longer auto-defaults its taskset to reverse-text; an env with no taskset id
errors at validation. Env-list defaults are empty (eval's non-empty check still fires only
when an eval block is configured). Bump deps/vf-nano.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump deps/vf-nano (dashboard taskset.id/harness.id fix)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump deps/vf-nano (sampling max_tokens fix)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(env-server): require a configured env; build EnvServer from the EnvConfig
EnvServerConfig.env was a bare EnvConfig() default, which now raises (no taskset) and
crashed the env-server at import. Make env required — the orchestrator always passes a
real env config. Build the server straight from config.env (vf-nano EnvServer takes the
EnvConfig). Bump deps/vf-nano (is_truncated computed field).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(nano): reverse-text uses default harness with enable_bash=false
The model answers directly (no bash tool), so the tool_call_parser is no longer needed.
Bump deps/vf-nano (enable_bash flag).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(nano): hendrycks-sanity config on the math-env taskset
Add configs/debug/nano/hendrycks_sanity.toml (vf-nano analog of configs/debug/hendrycks_sanity):
math-env train env on the sanity dataset (R1-distill, default renderer with think parser,
single-turn no-bash), aime24 eval env. Register math-env + aime24 in the envs group + sources.
Bump deps/vf-nano (math/aime tasksets, enable_bash, SerializeAsAny + is_truncated fixes).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump deps/vf-nano to merged main (math/aime tasksets, fixes)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: drop deps/verifiers, bump deps/vf-nano to merged main
vf-nano main (#8) adds the subprocess-runtime env passthrough (inherit host env
minus API_KEY, so UV_CACHE_DIR reaches rollout workers and lands the uv cache on
local disk) and the math-verify scoring fix (wrap gold + prediction in \boxed,
matching v1 math-env — fixes matrix/vector answers scoring 0).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(nano): hendrycks-sanity mirrors examples/hendrycks_sanity + slurm overlay
nano config is now a verbatim copy of examples/hendrycks_sanity/rl.toml with only
the env sections swapped to vf-nano taskset/harness syntax (math-env taskset,
default harness, subprocess runtime; aime24 eval). Adds a slurm overlay setting
the output dir, wandb run name, and partition.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(nano): fold wandb + slurm into hendrycks_sanity config
Move the [wandb] and [slurm] sections from the slurm overlay into the base config, so it
submits to slurm by default (run locally with --no-slurm). The overlay now only redirects
output_dir. wandb run name is vf-nano-subprocess.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(nano): fold output_dir into hendrycks_sanity config, drop slurm overlay
Everything (output_dir, wandb, slurm) now lives in the one config; remove the now-empty
slurm overlay. Run locally with --no-slurm.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(vf-v1): run on the unified verifiers package (v0 envs + v1=nano + legacy bridge)
Depend on the single verifiers package (deps/verifiers, nesting vf-nano) instead of standalone
vf-nano. EnvConfig is dual-mode: v0 envs via id+args (legacy bridge), v1 envs via taskset/harness
(native nano). The env-server spawn (standalone + mp) picks LegacyEnvServer for v0 and EnvServer
for v1; both return vf.Trace so the orchestrator is unchanged. Plugin sources repointed under
deps/verifiers; reverse-text is the v0 env, reverse-text-v1 the nano taskset.
Verified: uv run rl @ examples/reverse_text/rl.toml (v0, unchanged) trains via the bridge
(reward 0.14->0.79); vf-eval + vf-eval-v1 reverse-text both reward 1.0.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* test(v0): wire alphabet-sort (multi-turn) + bump verifiers (State scrub)
Add the v0 alphabet-sort env as an installable source; bump deps/verifiers to the State-scrub
commit. Verified the bridge on a multi-turn v0 env: alphabet-sort runs (Turns 2.0, 128/128
trainable, 0% error) alongside single-turn reverse-text.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* test(v0): wire wordle + add configs/wordle/rl.toml (2-GPU)
Wire the v0 wordle TextArena env (multi-turn game) as an installable source; add a 2-GPU
(1 trainer + 1 inference) wordle config. Verified through the legacy bridge: wordle trains
(Turns ~5.3, reward ~0.81, 128/128 trainable, 0% error).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump deps/verifiers (v1 hygiene: init.py/tests/docs)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor(v1): track de-vendored verifiers, rename nano -> v1
- Bump deps/verifiers to the de-vendored commit: vf-nano is now vendored as the
verifiers.v1 subpackage (no nested deps/vf-nano submodule).
- Repoint env-plugin sources from deps/verifiers/deps/vf-nano/... to
deps/verifiers/{examples,packages}/...
- Rename verifiers.nano -> verifiers.v1 across the orchestrator/utils/configs;
rename configs/debug/nano -> configs/debug/v1. "v1" is the name now (no "nano").
Verification: v0 reverse-text (legacy bridge) and v1 reverse-text-v1 (native)
both train over a 3-step smoke (reward present, 0% error).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers (eval/serve, v1 deps in base, bundled plugins)
- Bump deps/verifiers: v1 runtime deps moved to base (no `v1` extra), v1 CLIs
renamed eval/serve, shipped plugins bundled in the tasksets/harnesses umbrella
packages, verifiers/v1/harness.py (flattened harnesses subpackage).
- Depend on `verifiers` (was verifiers[v1]) and the `harnesses` umbrella package
(was standalone default/rlm).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers (Task.system_prompt); write full rollout jsonl
- Bump deps/verifiers to the system_prompt commit: Task.system_prompt + harness
APPENDS_SYSTEM_PROMPT support, reverse_text_v1 byte-identical to the v0 env (separate
system message), plus this branch's eval/serve, v1-deps-in-base, CI fixes, and the
retired semgrep policy.
- save_rollouts: drop exclude_keys={"trajectory"} for both train and eval rollouts so the
jsonl carries the full trajectory.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: drop semgrep from uv.lock (verifiers retired the policy group)
Follow-up to the deps/verifiers bump (00c7b77a removed the `policy` dependency
group); regenerates the lock to match.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: pin the env-server renderer tokenizer to the base model for LoRA runs
Wire `renderer_model_name` (the base model) into the renderer client config so
the env-server renderer builds its tokenizer from the base model instead of the
per-request LoRA adapter name, which has no published HF tokenizer and 404'd
once LoRA training set the served model name to the adapter. Mirrors the
`renderer_model_name` wiring already in `setup_clients` on main. Bumps
deps/verifiers to the matching fix.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(orchestrator): request vLLM token ids for MITO training (#2745)
On the MITO path (no renderer), set return_token_ids in the train env
sampling args so the openai_chat_completions client gets the prompt and
completion token ids back from vLLM and can carry them for training
instead of re-tokenizing the messages downstream. Scoped to
renderer is None so it never reaches the renderer /inference/v1/generate
endpoint (which forwards sampling params to vLLM verbatim).
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers submodule; restore v0 env catalog + v1 -v1 imports
- bump deps/verifiers to the feat/nano-as-v1 tip (token-parse #1585, bridge meta #1586,
taskset -v1 rename #1587, native retries #1588, runtime resource cleanup #1590)
- restore the full v0 env catalog in optional-dependencies.envs + [tool.uv.sources]
(init the research-environments submodule); the taskset -v1 rename freed the v0 names,
so v0 envs (legacy bridge) and v1 tasksets coexist
- point the v1 taskset sources at their -v1 names / _v1 paths (gsm8k-v1, math-env-v1,
aime24-v1; reverse-text-v1 already correct)
- update v1 configs to the -v1 taskset ids (hendrycks_sanity) and drop the superseded
standalone configs/debug/reverse_text_v1.toml
- relock
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers submodule to feat/nano-as-v1 tip (textarena #1592)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers submodule to feat/nano-as-v1 tip
Pulls in runtime resources named after the rollout id (#1596) and the
alphabet-sort-v1 taskset (#1595).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers submodule to feat/nano-as-v1 tip
Brings in env-hub ids (#1597), v0 envs on the eval CLI (#1598), modal runtime (#1594).
* chore(v1): add v1 alphabet-sort debug config (port of examples/alphabet_sort)
* fix: forward extra_env_kwargs to v0 legacy envs; drop dead trajectory tests (#2749)
Restores main's escape hatch for v0 (legacy-bridge) envs: a legacy env's extra_env_kwargs
is auto-populated (timeout_seconds <- timeout.rollout, max_total_completion_tokens <-
max_output_tokens, max_seq_len <- seq_len) and forwarded to LegacyEnvServer at spawn, so v0
rollouts again honor the wall-clock timeout, multi-turn completion budget, and seq-len
truncation (all were silently dropped on this branch).
Also removes tests/unit/orchestrator/test_{trajectories,sft_trajectories}.py, which imported
the deleted interleave_rollout and broke test collection.
* fix: install the bundled `tasksets` package (harbor-v1, textarena-v1)
The `envs` extra wired `harnesses` and the individual `*-v1` example tasksets but
never the bundled `tasksets` package, so the integration tasksets it ships
(`harbor-v1`, `textarena-v1`) couldn't be resolved — `import_taskset("harbor-v1")`
raised ModuleNotFoundError ("tried to import 'harbor_v1'").
Add `tasksets` to the `envs` extra + a path source, and bump the verifiers
submodule to the feat/nano-as-v1 tip (#1600), where the bundled tasksets live
under the `tasksets` namespace package (`tasksets.harbor_v1`) and the loader
resolves the namespaced module.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: consume the v1 message-graph trace (#2763)
* feat: consume the v1 message-graph trace (graph-walk trace_to_samples)
Walk the new message graph (verifiers feat/trace-message-graph, PR #1606): trace_to_samples
builds one TrainingSample per branch by concatenating each branch path's node token_ids /
sampled_mask / logprobs (graph.branch_token_sequences), splitting prompt|completion at the
first sampled token — identical training tensors to the old per-turn stitching, off a trace
that is now linear (not quadratic) in turns. backfill_rollout_tokens is a no-op (training is
renderer-only; `trajectory` is now a read-only view over the graph). Bumps the verifiers
submodule to the graph-trace branch.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump verifiers submodule (MessageNode.mask rename)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: wire alphabet-sort-v1 taskset
Add alphabet-sort-v1 to the `envs` extra + `[tool.uv.sources]` so
configs/debug/v1/alphabet_sort.toml resolves (it referenced an example taskset that was
never wired into prime-rl). Used to verify graph-based training-sample construction on real
RL runs — v0 (legacy bridge) and v1 (native renderer path) both train cleanly.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: consume nodes/branches directly (drop Turn/trajectory readers)
`trace_to_samples` already walks the graph; the remaining readers move off the removed
Turn/trajectory API: the gibberish/repetition filters iterate per-node completions,
advantage/dispatcher use `trace.num_turns`/`trace.completion_len`, `get_model_completion_len`
is dropped (use `trace.completion_len`), and the renderer-only train_sink drops the backfill
path (also removing `backfill_rollout_tokens`). Bumps the verifiers submodule.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump verifiers submodule (merge #1605 multiplex interception)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump verifiers submodule (dead-code cleanup)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers (readme highlight + ruff format)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: enforce renderer, SFT backfill, branch-first-class logging
Training is renderer-only now. RL/OPD roll out through the renderer client
(exact sampled token ids + logprobs); SFT rolls out against a chat-completions
teacher that returns no tokens and re-renders the conversation to backfill them
(`backfill_trace`). A renderer is required for every mode (`renderer=None`
rejected) — the oai client never produces correct training tokens for the
message graph. Drops the MITO no-renderer training path.
Logging consumes `trace.branches` as the first-class unit (`branch.token_ids` /
`branch.messages`) instead of the removed `trajectory` field; `trace_to_samples`
builds one sample per branch from the same accessors. Sample loggers take the
rollout objects so env_name/advantage are available.
Add configs/v1/training_mode (rl/opd/sft + lora/external) mirroring the v0
debug configs. Fix the v0 SFT debug configs + rlm_swe to validate under the
renderer requirement.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: flat TrainingSample (token_ids + mask), required renderer
Drop the prompt/completion split from TrainingSample — it doesn't fit a
multi-turn/agentic branch, where context and model-sampled spans interleave. A
sample now carries the branch's flat `token_ids` plus per-token `mask` (True =
trainable), `logprobs`, and `temperatures` (all aligned). `prepare_sample`
passes them straight into the MicroBatch (already flat), and the packer
validates against `token_ids` length.
Make `orchestrator.renderer` a non-optional type (drop the `enforce_renderer`
validator) — training is renderer-only, so the type carries the requirement.
Bump the verifiers submodule to feat/nano-as-v1 (merged #1606 + Branch.branches
inlined).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: SFT teacher rolls out through the renderer client (drop backfill)
Training is renderer-only across every mode, so the SFT teacher now rolls out
through the renderer client too — its rollouts carry tokens directly, the same
as RL/OPD. Drops the chat-completions backfill (`backfill_trace` + the SFT path
in TrainSink) and the now-unused TrainSink renderer.
This requires a self-hosted teacher that shares the student's tokenizer (the
student trains on exactly the ids the renderer feeds the teacher); distilling
from an external chat API is no longer supported. Remove the `sft_external`
debug configs.
Validated: SFT on reverse-text-v1 trains cleanly (Trainable 128/128, eval reward
~0.1 -> ~0.82 over 20 steps) with the teacher on the renderer client, no backfill.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: drop configs/v1/training_mode README
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: consolidate rollout types into Rollout(vf.Trace)
The trace *is* the rollout: replace the FinishedRollout/TrainRollout/EvalRollout
wrappers with a prime-rl Rollout(vf.Trace[TaskT]) subclass that carries the
orchestration metadata (kind, env_name, group_id, policy_version,
off_policy_steps, samples, advantage, is_filtered, filter_results, eval_step) as
exclude=True fields — so dumping a Rollout still yields a plain trace (on-disk
results.jsonl unchanged). envs.py validates the wire trace into Rollout; the
dispatcher stamps the metadata; train vs eval is the `kind` discriminator
(replacing the isinstance check). All consumers read rollout.X directly instead
of rollout.trace.X.
Drop the monitor's SampleRollout duck-type Protocol — the loggers take the real
Rollout (TYPE_CHECKING import) and read branch.token_ids / branch.messages. Also
drop the prime monitor's _split_branch_messages and _json helpers: the
conversation is the unit (no prompt/completion split — meaningless multi-turn).
Fix a latent dispatcher bug surfaced along the way: synthetic error traces used
`error=` / `r.error = ` (a read-only computed field) — now `errors=[...]` /
`r.errors.append(...)`.
Rewrite the (long-stale, dict/`raw`-based) advantage + filters unit tests to
build real Rollouts — they now exercise the current trace-based code (previously
all failing on import/construction).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* ci: allow verifiers + datasets in the slim-config dep check
The v1 config types (EnvConfig, Task, ...) extend `verifiers.v1`, which is a
declared, pure-pydantic dependency of prime-rl-configs (it pulls `datasets` for
the taskset/Task types but no GPU/ML deps). Drop `verifiers` and `datasets` from
the slim-install forbidden list — keep the real heavy training deps (torch,
vllm, transformers, ...).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers submodule to feat/nano-as-v1 tip
Picks up the v1 end-to-end eval test suite (#1609) and the v0 legacy
env-server group-scoring fix (#1612).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers submodule to feat/nano-as-v1 tip
Picks up the v0 legacy-bridge fixes: guard against non-renderer training
clients (#1613) and serve the eval split for eval-only v0 envs (#1614).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): fix stale sft.toml teacher comments
The SFT teacher rolls out through the renderer client (token-in/out) and
must share the student's tokenizer; drop the leftover oai-client / token
backfill description removed in the renderer-only refactor.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers (v0 eval chat-completions client)
Picks up verifiers#1615: the legacy bridge builds a chat-completions client
for v0 eval rollouts (renderer for training), instead of raising on the
non-renderer eval client.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(v1): scaleswe configs + taskset registration (#2765)
- register the scaleswe-v1 taskset (pyproject envs list + uv source)
- point the existing rlm-swe config (configs/rlm_swe/qwen35_4b.toml) at the
scaleswe taskset (task_type="scaleswe", train + eval)
- add configs/debug/v1/scaleswe.toml — a per-env v1 port of that config using
the scaleswe-v1 taskset via the rlm harness on the prime runtime
Companion to verifiers feat/scaleswe-v1 (scaleswe-v1 taskset + setup/workdir hooks).
Needs the deps/verifiers submodule bumped to that branch once it lands.
* feat(v1): multimodal training through the message graph + color-codeword-v1
Consume the v1 trace's multimodal sidecar. `trace_to_samples` builds, per branch,
`mm_kwargs` (the branch's per-image renderer items concatenated on dim 0 and
EncodedTensor-encoded) and `mm_token_type_ids` (the renderer's
`mm_token_type_id_map` applied to the branch tokens); `TrainSink` threads the
mapping through. The wandb sample logger now renders the task as a Table-safe JSON
string with image data elided — an image-bearing instruction crashed wandb's
Table type inference on the nested content list.
Adds `configs/v1/multimodal_color_codeword.toml` (Qwen3-VL-4B on color-codeword-v1,
2-GPU) and registers the `color-codeword-v1` taskset; bumps the verifiers submodule
for the multimodal message-graph support.
Verified end-to-end: the VLM trains through the mm path (eval 0.69 -> 0.78,
Trainable 256/256 — mm_kwargs reach the Qwen3-VL forward); v0 `color-codeword`
eval 0.625 ~= v1 `color-codeword-v1` eval 0.69 (faithful port).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Revert "feat(v1): multimodal training through the message graph + color-codeword-v1"
This reverts commit 85b27cfc0be12b84f9b36456675b10387d01dc8a.
* feat: multimodal training through the v1 message graph + color-codeword-v1 (#2766)
* feat(v1): multimodal training through the message graph + color-codeword-v1
Consume the v1 trace's multimodal sidecar. `trace_to_samples` builds, per branch,
`mm_kwargs` (the branch's per-image renderer items concatenated on dim 0 and
EncodedTensor-encoded) and `mm_token_type_ids` (the renderer's
`mm_token_type_id_map` applied to the branch tokens); `TrainSink` threads the
mapping through. The wandb sample logger now renders the task as a Table-safe JSON
string with image data elided — an image-bearing instruction crashed wandb's
Table type inference on the nested content list.
Adds `configs/v1/multimodal_color_codeword.toml` (Qwen3-VL-4B on color-codeword-v1,
2-GPU) and registers the `color-codeword-v1` taskset; bumps the verifiers submodule
for the multimodal message-graph support.
Verified end-to-end: the VLM trains through the mm path (eval 0.69 -> 0.78,
Trainable 256/256 — mm_kwargs reach the Qwen3-VL forward); v0 `color-codeword`
eval 0.625 ~= v1 `color-codeword-v1` eval 0.69 (faithful port).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin — multimodal review-pass cleanups
Picks up the verifiers feat/v1-multimodal head: the multimodal review-pass
(capability-flag docstrings, trimmed mm comments, color-codeword-v1 config
validator + module constants) and the merged malloc_trim worker-RSS fix (#1621).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (content-part mm attribution) + config/test sync
- Bump deps/verifiers to the content-part multimodal attribution (drops the unused
placeholder offset machinery).
- Drop max_turns/seed from the color-codeword-v1 taskset args in the config — the
taskset hard-codes them as module constants now, and passing them is rejected.
- Update the mm egress unit test to assert mm_items order (the new attribution),
not placeholder offsets.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(trainer): slice mm_kwargs on truncation so tokens match embeddings
When a sample exceeds seq_len, prepare_sample truncated input_ids and
mm_token_type_ids but passed mm_kwargs through whole — leaving more image
embeddings than surviving image placeholders. Now truncation cuts to a
whole-image boundary (never splitting an image's placeholder block) and slices
mm_kwargs (pixel_values + image_grid_thw) to the images that fully survive, so
image-placeholder count == image-embedding count.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to ruff-formatted graph.py
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): remove test_trajectories_mm.py
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: thread num_workers to the env-server worker pool (#2768)
* feat(v1): thread num_workers to the env-server worker pool
Wire the verifiers env-server worker pool into prime-rl: the orchestrator's
spawned env server (envs.py) and the `env-server` CLI now serve via
verifiers' serve_env with num_workers, so requests fan out across N worker
processes instead of one event loop. num_workers was already a config field but
dropped on the floor; it's now passed through and defaults to 4.
Companion to verifiers feat/v1-env-workers; needs deps/verifiers bumped to it.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(v1): default num_workers to 4
Make the worker pool the default: num_workers defaults to 4 (was "auto"->1)
across the per-env, train, and eval configs, so training/eval env servers fan
rollouts across 4 worker processes out of the box. "auto" stays a valid value
(scales per concurrency); set num_workers=1 for the old single-process server.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(v1): keep num_workers="auto" default on the orchestrator
Revert the orchestrator's per-env / train / eval num_workers defaults back to
"auto" (was 4) so they keep scaling 1 worker per 256 concurrent rollouts out of
the box. The standalone env server can't scale (no concurrency context — it's
driven by external clients), so its resolver collapses "auto" to a fixed 4.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to be76cbc3 (env-server worker pool)
Align the pin with #1623 (env-server worker pool: router + N workers),
which the just-merged #2768 (thread num_workers to the pool) requires;
the pin had lagged at the pre-#1623 multimodal tip.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(v1): register r2e-gym-v1 taskset
Add r2e-gym-v1 to the base v1 taskset deps + uv sources (editable from
deps/verifiers/examples/tasksets/r2e_gym_v1) so the id resolves through
the v1 loader, matching the other -v1 tasksets.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(swe): use r2e-gym for rlm_swe configs (v0 + v1)
- v0 configs/rlm_swe/qwen35_4b.toml: restore the train env to r2e and the
eval env to swebench-verified-quick (as on main), reverting the scaleswe switch
- v1: rename configs/debug/v1/scaleswe.toml -> r2e_gym.toml, point the train env
at the r2e-gym-v1 taskset, and drop the eval block
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(swe): point rlm_swe configs at r2e-gym (content)
Apply the edits the prior rename commit missed:
- v0 rlm_swe/qwen35_4b.toml: train -> r2e, eval -> swebench-verified-quick (as on main)
- v1 debug/v1/r2e_gym.toml: taskset -> r2e-gym-v1, eval block removed
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(v1): restore env-server worker logs to the env log file (#2770)
Env servers spawn their worker pool as fresh `spawn` processes with no logging
handlers (verifiers#1626), so per-rollout logs (rollout start/done, context-exceed
warnings) were silently dropped. Pass `setup_env_server_logging` to verifiers'
`serve_env` as `log_setup`; it runs in the broker and in every worker. A worker
inherits the broker's redirected stdout/stderr, so its logs land in the same
`envs/{train,eval}/<name>.log` as before — no new files or paths.
Bumps deps/verifiers to the worker-logging fix.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to 955b6cdf (dashboard token usage fallback)
Realign the pin onto origin/feat/nano-as-v1 and pick up #1627: the --rich
dashboard's token counts fall back to provider usage when the endpoint returns
no token ids (no more 0/0). The prior pin 3df34ba5 was a pre-rebase #1626
variant; 955b6cdf already contains the equivalent #1626 (env-server worker
logging) plus #1627.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to 8e4ad735 (clean env-server teardown)
Picks up the serve_env SIGTERM-teardown fix: pool/in-process env servers no
longer print a spurious KeyboardInterrupt traceback into the env logs on
shutdown.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(deps): bump verifiers (renderers floor 0.1.8.dev40)
Picks up the verifiers floor bump so the renderers offset-tokenizer fix (dev40,
PRs #72/#75) can't be undercut by a pre-fix PyPI resolution. Re-locks uv.lock to
the dev40 specifier.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to db82b38a (reap subprocess tree on cancel)
Picks up #1628 (reap the whole subprocess tree when a runtime run is cancelled).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: elastic env-server pool (inherit static/elastic pool config) (#2774)
* feat(v1): elastic env-server pool (inherit pool config from verifiers)
Companion to verifiers#1629. prime-rl's EnvConfig now extends vf.EnvServerConfig, so
each env inherits the `pool` discriminated union (static{num_workers=4} |
elastic{max_workers=None, multiplex=128}, default elastic) and the orchestrator's env
servers scale workers on demand instead of pre-spawning a fixed `auto` count.
- Drop the per-env / train-group / eval-group `num_workers` fields + the auto-resolution
(ceil(max_inflight/256)); the elastic pool self-sizes from load.
- envs.py / env_server.py pass `vf.pool_serve_kwargs(env.pool)` to serve_env.
- Bump deps/verifiers to the elastic-pool branch.
Breaking: `num_workers` is replaced by `pool`. Configs set `pool = { type = "elastic",
multiplex = N }` or `{ type = "static", num_workers = N }`; the rlm_swe + r2e debug
configs are migrated.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(v1): back-compat shim mapping legacy num_workers -> pool
EnvConfig forbids extra fields, so configs still setting the removed `num_workers`
would hard-fail. Add a `model_validator(mode="before")` that maps it onto `pool`:
an int -> a fixed `static` pool, `"auto"` -> the default `elastic` pool; an explicit
`pool` always wins. Keeps existing (incl. out-of-tree) configs parsing without edits.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): drop num_workers from rlm_swe + r2e configs (use default elastic pool)
The default `pool` is already elastic (multiplex 128), so an explicit `pool` here was
redundant — just remove the legacy `num_workers` and inherit the default.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to f404e97f (elastic env-server pool)
Realign the pin onto origin/feat/nano-as-v1: the prior pin d0c5bc98 was the
unsquashed #1629 feature branch, now squash-merged as f404e97f
(content-identical). Picks up #1629 (static/elastic env-server pool config).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to 88e9bedd
Picks up #1631 (per-rollout setup timing as a distinct phase) and #1632
(per-call model + runtime retries).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to 40a2e89f (fix trace.timing.*.duration to_wire validation)
Fixes RunRolloutResponse ValidationError 'trace.timing.setup.duration: Extra
inputs are not permitted' that crashed every rollout (#1636 drops computed
durations from to_wire).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to 5dc084f5
Picks up #1638 (add --resume for evals: re-run a previous run's
missing/errored rollouts).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to 472622ba
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: stop importing env modules in the orchestrator (always Rollout[WireTask]) (#2781)
* chore(v1): stop importing env modules in the orchestrator
The orchestrator built its per-env trace_type as Rollout[vf.task_type(env_id)] for v1 envs, and
vf.task_type imports the env package just to read its Task subclass for typing the wire trace.
Nothing reads typed env task fields - only task.idx and a full task.model_dump - and WireTask
(extra="allow") preserves those fields (incl. on disk). Always use Rollout[vf.WireTask], so the
orchestrator never imports an env package: the env's type and runtime both live only in the
server process.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): hoist the constant Rollout[WireTask] to a module-level ROLLOUT_TYPE
It no longer varies per env, so it doesn't belong as a per-instance attribute set in
Env.__init__ - lift it to a module constant used directly in run_rollout/run_group.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to 7270e69b
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to 66c87d5b
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to ef45f720
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (alphabet-sort host user sim, #1645)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (modal creates_per_sec 5 -> 40, #1646)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix: cap v1 hendrycks-sanity scoring at 10s (#2790)
* fix(v1): cap hendrycks-sanity scoring at 10s
Without a scoring timeout (the default is no limit), a wedged math verify holds its
rollout's permit forever — sympy can spin past the in-script alarm — and at 512
concurrency that starves the pool and stalls long runs. Set timeout.scoring = 10 on the
train and eval envs so the framework cancels and the subprocess runtime kills a runaway
verify, freeing the permit.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: drop inline comment on the scoring timeout
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers (eval/train client rename) + adopt config imports (#2792)
Bump deps/verifiers to feat/nano-as-v1 HEAD (8873a740), which includes verifiers#1654 — the v1
interception rework: role-named clients (EvalClient/TrainClient), route-detected wire dialects
(chat/responses/anthropic), 1:1 relay + streaming, reasoning preserved.
Adopt the renamed client config classes in prime_rl/utils/client.py:
OpenAIClientConfig -> EvalClientConfig, RendererClientConfig -> TrainClientConfig.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (subprocess cached-interpreter uv-scripts, #1660)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (codex built-in harness, #1661)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: track terminal-bench-2-v1 as a taskset dependency
It was only a manual editable install, so `uv sync` pruned it. Add it to the env dependency
group + [tool.uv.sources] (mirroring r2e-gym-v1) so it persists across syncs and is available
out of the box.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(v1): keep multimodal tensors out of rollout dumps (#2794)
verifiers#1653 (carry mm tensors across the env-server wire) is merged and pinned, so
`MessageNode.multi_modal_data` is no longer `exclude=True` — `model_dump(mode="json")` now
serializes the base64 pixel tensors into `train_rollouts.jsonl` and the wandb sample tables,
bloating every line. They're the training `mm_kwargs` carrier, not part of the rollout
record, so exclude them at the dump boundary (train + eval paths).
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): install all v1 example tasksets in prime-rl
Declare the remaining 7 verifiers v1 example tasksets (code-golf, deepwiki,
glossary, swelego, wiki-search, wikispeedia, wordle) as editable deps so uv sync
installs every example, matching the verifiers examples set. chromadb/textarena
were already present via the v0 wiki-search/wordle envs.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): install the compact example harness in prime-rl
The example harness (examples/harnesses/compact) was missing from prime-rl deps,
so the documented --harness.id compact branching example failed to resolve
(ModuleNotFoundError: harness compact not found). Declare it like the example
tasksets so uv sync installs it.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (v1 docs #1662 + Trace.info #1664)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(v1): encode router-replay routed_experts into transport (#2808)
* feat(v1): encode router-replay routed_experts into transport
Pack Branch.routed_experts ([tokens, layers, top_k]) into the transport
RoutedExperts the trainer replays, realigning the token axis to len(token_ids)
as a backstop. Bumps the verifiers pin to the companion router-replay commit.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (raw-bytes wire) + exclude routed_experts from disk dumps
Bumps deps/verifiers to the raw-bytes router-replay codec (RoutedExperts rename +
msgpack bin wire). routed_experts now rides the env-server wire as raw bytes, so it
can't round-trip the json disk dump — add it to ROLLOUT_DUMP_EXCLUDE alongside
multi_modal_data (both are training inputs, not part of the rollout record).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(v1): guard router-replay vs prefix caching + bump verifiers/renderers pins
- Add disable_prefix_caching_for_router_replay validator: prefix-cache hits skip
recomputing the cached prefix, so the engine returns no routed-expert decisions for
those tokens. Router replay needs routing for every token, so force
enable_prefix_caching=False (mirrors the existing kv_cache_offload guard).
- Bump deps/verifiers: tail-pad routed_experts so the final node aligns (the engine
omits the last position's routing).
- Bump deps/renderers: _get_offset_tokenizer immune to the global fastokens patch race.
Together these make v1 MoE router replay work end-to-end (Qwen3-30B-A3B): verified
mismatch_kl drops vs no-replay (0.0005/0.0002/0.0002 vs 0.0015/0.0015/0.0005 @ steps 0/1/2).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump deps/renderers pin (ruff format fix)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump deps/verifiers pin (ruff format)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump deps/verifiers pin to merged feat/nano-as-v1 (router-replay #1672)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Remove disable_prefix_caching_for_router_replay validator
Drops the guard that force-disabled inference.enable_prefix_caching under router replay.
Validating whether prefix caching is actually compatible with router replay (cache hits
may carry no routed-expert decisions); re-add if the A/B shows it drops routing.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(orchestrator): keep top-level advantage wiring after merge
The merge auto-resolved train_sink.py and the orchestrator's TrainSink
construction to main's per-env advantage design (#2721), but envs.py and the
configs were kept on the branch's top-level design — so TrainSink read
`train_envs.get(env_name).advantage_fn`, which TrainEnv no longer defines
(AttributeError at rollout time).
Restore the branch's top-level advantage: TrainSink takes `advantage_config`
and builds its own `self.advantage_fn` once. Verified end-to-end with a
reverse-text-v1 RL smoke (reward climbs 0.16 -> 0.40 over 6 steps).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to merged main (1b7736a8)
deps/verifiers feat/nano-as-v1 now includes origin/main merged in
(composable tasksets + sandbox/save utils). Pin moves 7a98b566 -> 1b7736a8.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: bump pydantic-config submodule to main (single-dash short flags)
deps/pydantic-config 896ade4 -> 99f47c6 (origin/main). Picks up #16
(single-dash short flags for single-character aliases, e.g. `eval -n -m`)
and upstreams the dict[str,str] preservation fix (#14). No uv.lock change
(editable path source).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to feat/nano-as-v1 tip (5fc0b295)
Picks up the py3.11 TypedDict CI fix and #1676 (prime-sandbox programs run for
the sandbox lifetime instead of the 15-min background-job default, + retry-log
wording). Pin moves 1b7736a8 -> 5fc0b295.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to 3af08c9b
Includes verifiers#1677 - scaleswe-v1 resolves task images via Prime's
Artifact Registry instead of the incomplete public Docker Hub mirror.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(orchestrator): trim glibc heap back to the OS each step (#2821)
Factor the existing end-of-run malloc_trim into a `trim_process_memory()`
helper and also call it at the end of `finalize_train_batch`. Each step frees a
step's worth of rollouts / traces / transport buffers, but glibc keeps those
pages in per-arena free lists, so orchestrator RSS climbs over a long run
without ever shrinking. Trimming per step returns them to the OS.
Mirrors the per-step trim in prime-rl #2807 — the trim only; that PR's
`.raw`-based retention helpers don't apply to this branch's typed Rollout/Trace.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to 7862985b
Includes verifiers#1678 - scaleswe-v1 Prime Artifact Registry is now opt-in
(`use_prime_registry`, default off), so the default Docker Hub image path works
on local docker runtimes again.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: route consistent_hash on X-Session-ID for cross-turn prefix reuse (#2822)
The vllm-router `consistent_hash` policy keys on request-id headers (default
x-request-id / x-correlation-id / x-trace-id / request-id). The v1 inference
clients send none of those per rollout, so a multi-turn rollout's turns hashed
to random DP shards and re-prefilled the growing prompt cold each turn (~40%
prefix cache hit rate on an agentic SWE run, where it should approach the
eviction-limited ceiling).
Launch the router with `--request-id-headers x-session-id` so it keys on the
per-rollout `X-Session-ID` header the v1 clients now emit (companion verifiers
change). Every turn of a rollout pins to one engine, keeping its cross-turn
prefix warm. Harmless for the random / round_robin policies, which ignore
request-id headers.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to 211faecb (session-affinity routing)
Picks up verifiers #1680 (session-affinity routing header for cross-turn
prefix reuse) — the counterpart to prime-rl #2822. Pin 7862985b -> 211faecb.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to 3f45f73b (scaleswe-v1 image filter)
Picks up verifiers #1679 (filter unavailable scaleswe-v1 images at load).
Pin 211faecb -> 3f45f73b.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to 44da378c (r2e-gym-v1 registry opt-in)
Picks up verifiers #1681 (r2e-gym-v1 Prime Artifact Registry opt-in, default
off). Pin 3f45f73b -> 44da378c.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to a723977c (scaleswe-v1 image_url filter)
Picks up verifiers #1683 (filter on Docker Hub image_url, not the resolved
image). Pin 44da378c -> a723977c.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to 0c8d0aa1 (rootless harness install)
Picks up verifiers #1685 (harnesses install/run without root, pinned
/tmp/vf-{harness}) and #1684 (remove Claude Code harness). Pin a723977c -> 0c8d0aa1.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to d4b054e3 (skip region-limited e2e test)
Picks up verifiers #1686 (skip test_multi_turn on prime — colocated user-sim
port exposure is region-limited). Pin 0c8d0aa1 -> d4b054e3.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: point verifiers env paths at the flattened environments/ dir (#2824)
* chore: point verifiers env paths at the flattened environments/ dir
Companion to verifiers #1695 (flatten examples/ into a single environments/).
Update the deps/verifiers editable source paths in pyproject.toml + uv.lock:
examples/tasksets/<x> -> environments/<x> and
examples/harnesses/compact -> environments/compact. Bump the verifiers pin to
the flatten branch (7ddc78b2) so the relocated paths resolve.
Re-pin to the merged commit once verifiers #1695 lands.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(deps): bump verifiers to 22b02e4b (flatten examples/ into environments/, #1695 merged)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): advance verifiers pin to feat/nano-as-v1 tip (Trace.state + DNS fix)
#2824 retargeted the env paths but pinned deps/verifiers at 22b02e4b (#1695,
just after the examples/->environments/ flatten), which predates the later
merges. Advance the submodule to the actual feat/nano-as-v1 tip bf30ae5f
(verifiers 0.1.15.dev298): adds Trace.state (#1711), the unconditional MCP
DNS-rebinding relax (#1715, fixes the in-prime tool 421 CI failures), and the
init scaffold (#1713).
bf30ae5f also dropped verifiers' self-referential `packages` extra, so drop
`[packages]` from the verifiers override-dependency (and refresh the stale
sources comment).
Smoke: `eval reverse-text-v1 -n 1` (subprocess, temp=0) runs clean — no errors,
not truncated, reward ~1.0.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to feat/nano-as-v1 tip (#1717 + #1719)
Advance deps/verifiers bf30ae5f -> f7fa7482:
- #1717 train-client prefix bridging + token-based message-graph branching
- #1719 default the harness runtime to subprocess
No prime-rl-side changes needed: every prime-rl v1 config already sets
harness.runtime.type explicitly (#1719's default flip is a no-op here), and the
consumed verifiers surface (serve EnvClient/serve_env/pool_serve_kwargs,
clients.config Eval/TrainClientConfig, task.TaskT, the Trace branch/token API) is
untouched by #1717. Imports resolve; reverse-text-v1 eval smoke clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to feat/nano-as-v1 tip (f7fa7482 -> bbfd5646)
New since the last pin: #1718/#1721 (CI + tests), #1723 (per-harness tool
disabling), #1666 (client consolidation + chat-completion header forwarding),
#1722 (warn on non-default subprocess harnesses). No prime-rl-side changes
needed: clients.config (the consumed surface) is untouched by #1666's client
refactor, #1722 only warns and exempts the default harness (what prime-rl's
subprocess configs use), and the rest is additive/CI-only. Imports resolve;
reverse-text-v1 eval smoke clean (reward 1.0).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: verifiers #1732 companion (model_dump traces, Task.prompt rename) (#2831)
* chore(v1): add prime CLI as deps/prime submodule (feat/nano-as-v1)
Tracks the companion PrimeIntellect-ai/prime#751 branch that adds verifiers v1
eval support to the prime CLI (run/view consume the v1 entrypoint + Trace format).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to feat/nano-as-v1 tip (bbfd5646 -> 220f21d4)
New: #1727 (per-rollout isolation for shared writable tool servers) and #1702
(trim verifiers runtime deps — modal/notebook/quest/pdf moved to extras). No
prime-rl-side changes needed: the only dropped transitive dep is pymupdf, used
solely by verifiers' experimental quest PDF tool via a lazy import behind the
quest extra (prime-rl never touches it). Imports resolve on dev307;
reverse-text-v1 eval smoke clean (reward 1.0).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: validate env-server traces via model_dump (companion to verifiers to_wire removal)
verifiers drops Trace.to_wire/from_wire and the derived computed fields (reward,
is_truncated, error, duration are plain properties now). Swap wire.to_wire() ->
wire.model_dump() when re-typing a returned Trace into ROLLOUT_TYPE; the .reward /
.is_truncated the metrics/eval code reads are the Trace properties, so they still work.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: rename vf.Task(instruction=) -> prompt= (verifiers #1732 companion)
verifiers #1732 renames Task.instruction -> Task.prompt; update the dispatcher's
error-rollout Task construction to match. Pin bump to the merged commit comes when #1732
lands.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to chore/v1-general-cleanup tip (220f21d4 -> d78d7474)
Pin #1732 (general v1 cleanup) so this companion's model_dump trace handling and the
Task.prompt rename round-trip against a verifiers that actually has them. Re-pin to the
feat/nano-as-v1 tip once #1732 merges.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to feat/nano-as-v1 tip (d78d7474 -> caaf0ff3)
#1732 (general v1 cleanup) merged into feat/nano-as-v1; re-pin off the chore branch onto the
integration tip. This companion's model_dump trace handling + Task.prompt rename now run
against merged verifiers.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: error-rollout placeholder task uses prompt=None
An error rollout has no prompt; None is the honest value (Task.prompt is str | Messages |
None) rather than an empty string.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(v1): drop removed enable_bash from harness configs (verifiers #1723) (#2833)
verifiers #1723 (in the current pin) removed the default harness's enable_bash
field — the default harness now exposes only the taskset's MCP tools (use an
agentic harness like mini-swe-agent for a shell). All v1 configs still set
`enable_bash = false`, which now fails config validation (Extra inputs are not
permitted). Drop it (no-bash is the default, so behavior is unchanged); no src/
code referenced it.
Verified: `uv run rl @ configs/debug/v1/reverse_text.toml` (Qwen3-0.6B, 2 steps)
runs end-to-end — orchestrator rollouts Error 0.0% (reward 0.117 -> 0.177),
trainer steps + checkpoint, 'Training finished!'.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to feat/nano-as-v1 tip (caaf0ff3 -> cc4afd52)
New: #1733 (robust env-server teardown, no leaked tunnels/sandboxes), #1734
(general-agent solver v1 taskset, additive/opt-in), #1735 (reject unsupported
task system_prompt). No prime-rl-side changes needed: consumed serve/clients
surface unchanged, default harness supports system_prompt, new taskset not
registered. Imports resolve; reverse-text-v1 eval clean (reward ~1.0, no errors).
Note: #1733's worker teardown throws KeyboardInterrupt on SIGTERM but run_server
doesn't swallow it, so a benign KeyboardInterrupt traceback prints at env-server
shutdown (cosmetic; verifiers follow-up).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(v1): add debug general-agent-v1 RL config + register the taskset
Add configs/debug/v1/general_agent.toml — the v1 general-agent-v1 taskset
(GeneralAgentSolverTaskset) on the default harness, with the agent and its tool
server colocated in a modal sandbox. Adapted from configs/general_agent/
rl_qwen3_4b.toml (Qwen3-4B, batch 256). Register general-agent-v1 in
[tool.uv.sources] + the envs extra so the id resolves.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(v1): add scaleswe-v1 RL config (Qwen3.6-35B-A3B, 65k ctx)
configs/debug/v1/scaleswe.toml — the v1 scaleswe-v1 SWE taskset on the rlm
harness + modal runtime (each row injects its own Docker image into the sandbox;
no MCP toolset). Qwen3.6-35B-A3B, batch 256, 65k context, qwen3.6 renderer with
thinking. Deployment/parallelism (cp=2, infer dp=2 tp=4, 1 train + 1 infer node)
seeded from the 30B-A3B reference — tune on the cluster for the 35B / 65k
footprint. Multi-node slurm; scaleswe-v1 was already registered.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (cc4afd52 -> 3c5f6586) + register swebench-verified-v1
New: #1738 (swebench-verified harbor taskset, prime prebuilt images), #1739
(don't retry program exec - fixes forked duplicate trace branches), #1736/#1737
(quest pdf sanitization, dashboard rotation). Register the new swebench-verified-v1
env (source + envs extra); no other prime-rl changes needed.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(v1): add SWE-Bench-Verified online eval to the scaleswe run (prime runtime)
Mirror the v0 rlm_swe SWE-bench eval on the v1 scaleswe config: [orchestrator.eval]
interval=20, an eval env on the swebench-verified-v1 taskset via the rlm harness on
the prime runtime (use_prime_registry=true -> prime's prebuilt instance images),
rollout timeout 3600s. Train stays on modal; eval runs on prime.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(v1): use public images for the scaleswe SWE-Bench-Verified eval
A debug eval showed use_prime_registry=true fails with IMAGE_PULL_FAILED on the prime
runtime: the SWE-bench Verified sweb.eval.* instance images aren't mirrored into prime's
prod-sandbox Artifact Registry. The same prime sandbox pulls r2e-gym-v1's prime-registry
image and the public swebench/sweb.eval.* image fine, so it's a missing-mirror issue, not
credentials. Drop use_prime_registry (default false -> public Docker Hub images) so the
online eval works on the prime runtime now; flip it back on once the images are mirrored.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin + re-enable use_prime_registry for the scaleswe SWE eval
Bump deps/verifiers 3c5f6586 -> 952b2a7d, which lands the swebench-verified-v1 prime-image
path fix (PrimeIntellect-ai/verifiers#1740): the mirror keeps the swebench/ org, so
use_prime_registry=true now resolves to prod-sandbox/swebench/sweb.eval.* and pulls. Flip the
scaleswe SWE-Bench-Verified eval back to use_prime_registry=true (verified to pull on a prime
sandbox), for the fast cached mirror instead of public Docker Hub.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): cap hendrycks-sanity at 256 in-flight rollouts + 30s scoring timeout
Set orchestrator max_inflight_rollouts=256 (below the 512 batch) and bump the per-env
scoring timeout 10s -> 30s on both the train and eval envs. Guards against the subprocess
env-server stall where unbounded concurrency + a hanging math-verify hold permits until the
run wedges.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (general-agent-v1 colocated toolset fix)
Bump deps/verifiers 952b2a7d -> 56a720ca: PrimeIntellect-ai/verifiers#1741 makes the
general-agent-v1 toolset work when colocated in a sandbox (ships the task's tools.py + db.json
over /task). Env-package only - no framework/config surface, no prime-rl changes.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump hendrycks-sanity scoring timeout to 5min
Raise the per-env scoring timeout 30s -> 300s on both the train and eval envs - 30s was too
tight for the math-verify scoring under load.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(orch): show avg branches next to turns in step + eval log lines
Add 'Branches {mean:.1f}' alongside 'Turns' in the per-step train head, the per-env
breakdown, and the eval line - the average trace branch count per rollout (1 = linear, >1 =
compaction/subagents).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): update tmux + monitor-run skill for flattened env log paths
Env logs are now one file per env (envs/{train,eval}/{env_name}.log)
instead of nested env_server/env_worker_* files.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (retry backoff + relay retries)
Bump deps/verifiers 56a720ca -> 6647fe0a: PrimeIntellect-ai/verifiers#1744 adds exponential
backoff + jitter to the per-call client/runtime retries (so concurrent rollouts don't
re-thunder a shared endpoint) and lets harness clients retry the relay. Internal/additive -
no config schema or API change, no prime-rl edits.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Fix routed SLURM inference DP rank client config (#2830)
Co-authored-by: Codex <codex@primeintellect.ai>
(cherry picked from commit 8dfe8734e3)
* chore(v1): scaleswe Qwen3.6 fixes — ulysses CP + qwen3_coder tool parser
Qwen3.6-35B-A3B is a hybrid/linear-attention MoE: ring CP is unsupported
(use ulysses), and the model id isn't matched by the auto tool-parser
resolver so set tool_call_parser=qwen3_coder explicitly (enables vLLM auto
tool choice for the SWE agent). Complements the cherry-picked #2830 DP-rank
client fix.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (usage tracking + Terminus 2 harness)
Bump deps/verifiers 6647fe0a -> a630d3b0:
- PrimeIntellect-ai/verifiers#1704: track cached/reasoning/cost usage in v1 (new Usage type +
Trace/Branch .usage properties; internal node prompt_tokens -> input_tokens rename).
- PrimeIntellect-ai/verifiers#1747: add the Harbor Terminus 2 harness (additive).
Additive for prime-rl - it consumes only stable Trace properties (completion_len, total_tokens,
num_turns, num_branches) + its own batch metrics, not the raw Usage. Verified: reverse-text RL
smoke (2 steps) trains clean (Error 0.0%, Trainable 128/128, Training finished).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): scaleswe — drop eval, prime train runtime, dist_timeout 3600, lm-head chunking
The multi-node trainer kept dying on an NCCL _ALLGATHER_BASE watchdog timeout while
it waited through the slow step-0 swebench eval (eval hogged all rollout slots →
trainer starved on the collective → timeout → SIGABRT). Fixes:
- drop the swebench eval (train-only) — this is what actually cleared the hang
- dist_timeout_seconds 600 -> 3600
- train harness runtime modal -> prime (matches eval; unique label per run)
- fused_lm_head_token_chunk_size = 1024 (activation-memory saver at 65k seq)
cp stays 2 (max for Qwen3.6's 2 KV heads under ulysses; cp=4 fails the divisibility assert).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (reuse pool tunnel for colocated state channel)
Bump deps/verifiers a630d3b0 -> 7bb546c2: PrimeIntellect-ai/verifiers#1752 makes colocated
tool/user servers reuse the harness's existing pool tunnel for the state channel instead of
opening a second per-rollout host tunnel (which swamps the tunnel service at high concurrency).
Backward-compatible (new state_base param defaults to None; own-runtime servers still bridge
themselves) - internal rollout/MCP path, no prime-rl edits.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (eval progress-bar reward/metric means)
Bump deps/verifiers 7bb546c2 -> b8fad841: PrimeIntellect-ai/verifiers#1753 shows per-reward/
metric running means under the eval progress bar. Eval CLI dashboard + format helper only -
no training/wire surface, no prime-rl edits.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (rollout error taxonomy + interception debug logs)
Bump deps/verifiers b8fad841 -> cd205eee:
- PrimeIntellect-ai/verifiers#1751: type v1 rollout errors by boundary (RolloutError +
Provider/Harness/Toolset/User/Sandbox/Taskset/Interception types, classified via boundary()).
The trace Error record (type/message/traceback) and stop_condition values are unchanged, so
prime-rl's consumed surface (vf.Error, errors/stop_condition, 'Cancelled'/'prompt_too_long')
is intact.
- PrimeIntellect-ai/verifiers#1754: INFO interception up/down + debug-log intercepted routes.
Verified: reverse-text RL smoke (2 steps) trains clean (Error 0.0%, Training finished).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor(orch): record caught rollout exceptions via Trace.capture_error
Use the canonical v1 Trace.capture_error(exc) for the dispatcher's caught-exception path
instead of hand-building a vf.Error record + stop_condition - same result (type=exc class
name, message, traceback, stop_condition='error') but routed through the framework's recorder,
so it picks up the #1751 RolloutError boundary types when one escapes. The synthetic Cancelled/
EmptyTrajectory markers stay explicit vf.Error records (not exceptions; the sink/metrics branch
on those exact type strings).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (SDK-owned retries; merged worker-SIGTERM fix)
Bump deps/verifiers fedfa570 -> 2474b054, moving off the pre-merge fix/worker-sigterm-teardown
branch commit onto the feat/nano-as-v1 tip:
- PrimeIntellect-ai/verifiers#1755 (merged): swallow SIGTERM KeyboardInterrupt in spawned
env-server workers.
- PrimeIntellect-ai/verifiers#1756: SDKs own retries; drop framework per-call model/runtime
retries (removes RetryingClient/RetryingRuntime/CallRetryConfig). RetryConfig + the rollout
retry (RolloutRetryConfig) are kept.
prime-rl imports none of the removed retry names and never references RetryConfig/.model/.runtime,
so no edits. Verified: config validates + reverse-text RL smoke (2 steps) trains clean
(Error 0.0%, Training finished).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (interception env isolation + in-sandbox channel retries)
Bump deps/verifiers 2474b054 -> e002e80d:
- PrimeIntellect-ai/verifiers#1758: keep the interception endpoint out of agent-inheritable env.
- PrimeIntellect-ai/verifiers#1759: retry in-sandbox /state + /task channel fetches; name us in
the prime expose error.
Internal to harnesses/runtimes/mcp - no prime-rl serve/client/trace surface, no edits. Verified:
reverse-text RL smoke (2 steps, default harness + subprocess runtime) trains clean (Error 0.0%,
Training finished).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (ModalRuntime read path fix)
Bump deps/verifiers e002e80d -> 8c9f284b: PrimeIntellect-ai/verifiers#1761 makes
ModalRuntime.read resolve relative paths and stops retrying the tail tool logs. Modal-runtime
internal only - no prime-rl surface, no edits.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump renderers pin to clean tag renderers-v0.1.8.dev49
057f0087 (renderers-v0.1.8.dev40-2) fails a fresh hatch-vcs editable build
("0.1.8.dev40 can't be bumped"), so only grandfathered venvs built. dev49 is an
exact tag → builds cleanly, unblocking fresh venvs (e.g. running from /shared).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): set partition=all + scaleswe prime-sandbox pre_run_command
The SlurmConfig default partition "cluster" doesn't exist on this cluster (only
"all"), so generated sbatches failed to schedule. Set partition=all in the
scaleswe + hendrycks-sanity sources. Add scaleswe's prime-sandbox cleanup as a
pre_run_command (runs on the head node before launch) instead of editing the
sbatch template.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(v1): scaleswe deployment 2+2 nodes
Source had num_train_nodes=1/num_infer_nodes=1 (the unconfirmed 30B-A3B starting
point); the run that reached step 36 used 2+2. A single train node OOMs the
35B-A3B trainer. Restore 2 train + 2 infer nodes (32 GPUs).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): hendrycks-sanity on modal runtime, 200 steps
Switch the hendrycks-sanity train + eval envs from subprocess to modal (offloads
scoring to modal sandboxes), cap max_steps at 200 (was 5000), rename job to
hendrycks-modal.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin to 94b7df1 (swebench /testbed workdir, malformed-json tool-args, container-test fix)
Brings in feat/nano-as-v1 #1762 (mark swebench_verified_v1 container-only),
#1763 (feed malformed tool-call JSON back to the model instead of crashing the
rollout), #1765 (pin swebench_verified_v1 task workdir to /testbed).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): scaleswe on mini-swe-agent + SWE-Bench-Verified eval (100 tasks)
Switch the scaleswe train harness rlm -> mini-swe-agent (prime sandbox), and re-add a
SWE-Bench-Verified online eval: mini-swe-agent on the prime runtime, use_prime_registry=true,
first 100 tasks (num_examples=100, group_size=1), interval 20, rollout timeout 3600s.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(rl): mkdir parent for namespaced env-server config path
A namespaced env id (e.g. "primeintellect/wiki-search") makes the env-server
config filename a nested path; setup_env_servers opened it for writing without
creating the parent dir → FileNotFoundError at launch (slash-free ids were fine).
mkdir(parents=True, exist_ok=True) before the write.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (sandbox lifetimes, reasoning state, tau2, harbor CLI)
Bump deps/verifiers 94b7df16 -> 6ac5a3b5:
- PrimeIntellect-ai/verifiers#1749: separate v1 sandbox lifetimes from rollout timeouts (caps
harness timeouts at the 24h sandbox max). TimeoutConfig fields (setup/rollout/finalize/scoring)
unchanged.
- PrimeIntellect-ai/verifiers#1748: preserve provider reasoning state across turns (dialects).
- PrimeIntellect-ai/verifiers#1692: migrate the Tau2 benchmark to v1 (new env, additive).
- PrimeIntellect-ai/verifiers#1745: install the pinned Harbor CLI on demand.
prime-rl consumed surface intact (TimeoutConfig, dialects via clients); no edits. Verified:
reverse-text RL smoke (2 steps) trains clean (Error 0.0%, Training finished).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): lock the tau2-bench-v1 editable env from the verifiers bump
uv sync picked up the new tau2_bench_v1 workspace member (verifiers#1692, in the last pin bump)
as an editable lock entry. Lockfile-only follow-up.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers (final touches #1770, v1 e2e CI green #1771)
#1771 greens the v1 e2e suite and runs it in CI (host+docker only; prime+modal local-only): per-axis matrix marks, assert reward not is_truncated, terminus refuses the host runtime, eval in-process by default. #1770 is the guide/config final touches (0.2.0).
* chore(v1): bump verifiers (ruff-format test_envs)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers (drop feat/nano-as-v1 CI trigger)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers (test triggers → main only)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers (code-golf-v1/aime24-v1 verifiers dep)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): add gsm8k v1 config (train + test eval) under configs/debug/v1; drop old configs/v1
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to latest feat/nano-as-v1 (276ed743)
30 commits — v1 performance optimizations (zero-copy ZMQ relay, off-event-loop trace persistence, lazy bridged prompts, reduced trace/completion copies) and stateless-JSON MCP servers (#1822). No dependency changes (uv.lock unchanged).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): point verifiers submodule to main (post feat/nano-as-v1 merge)
verifiers feat/nano-as-v1 was squash-merged to main; retarget the submodule (8d52bc8e) and .gitmodules branch to main. main's #1826 moved the built-in tasksets/harnesses into the verifiers package, so drop prime-rl's now-defunct standalone harnesses/tasksets deps + editable sources (provided by verifiers.v1 now); compact and the -v1 env pins are unchanged. uv.lock re-resolved (425 pkgs).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(tests): migrate unit tests to the bumped verifiers v1 API
The verifiers bump (8d52bc8e) changed several public APIs; these nano unit
tests still used the old surface and failed. Test-only changes:
- OpenAIClientConfig -> EvalClientConfig (test_teacher_logprobs)
- vf.Task(instruction=...) -> prompt=... (test_filters)
- client-config shape: client_type/api_base_url/extra_headers ->
EvalClientConfig/TrainClientConfig type/base_url/headers/renderer
(test_client, test_elastic)
- rebuild rollouts as v1 Trace objects with branches, asserting against
production's actual parquet columns (test_prime_monitor)
(test_advantage's equivalent fix landed in the merge commit.)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(trainer): restore main's bin_cost FLOP-balanced packing
The main->nano merge had over-reverted the trainer pipeline to its pre-bin_cost
version. Restore main's packing/distribution so the trainer tracks main; the
only nano-side trainer delta is now the token_ids TrainingSample interface plus
multimodal.
- batch.py: main's bins-based packing (_MicroBatchBin, _materialize_bin,
_expand_bins_by_splitting, bin_cost-weighted balanced_partition within each
modality group); keep nano's token_ids prepare_sample + _truncate_mm /
_slice_encoded image-block-aware truncation.
- transport/types.py: MicroBatch.sequence_lengths (the bin_cost weight input).
- packer.py: thread bin_cost through setup_packer -> prepare_batch; keep nano's
token_ids sample validation.
- data.py / train.py / token_export.py / utils.py: now identical to main -
build_bin_cost(model.config) wiring + the precomputed sequence_lengths logprob
split, dropping nano's redundant get_response_lengths path.
- tests: test_batch / test_packer pass bin_cost=build_bin_cost(None); the
balance test classifies real vs dummy micro-batches by content (the FLOP
balanced_partition interleaves dummies rather than appending them).
Verified: 484 unit tests pass (only the 4 GPU-toolkit tilelang model tests fail,
environmental); reverse-text-v1 RL smoke runs 3 clean steps end-to-end.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* test(trainer): carry over main's bin_cost packing tests
The bin_cost restore brought the packing code but the fork had patched nano's
test_batch instead of adopting main's, so main's bin_cost-specific tests were
left behind. Port them, token_ids-adapted: randomized packing invariants,
FLOP-aware balancing, FLOP-aware heavy-bin split-to-align, token-cost fallback
distribution, split-to-align avoids dummy micro-batches, and pad_micro_batch
preserves explicit sequence_lengths. 18 test_batch tests pass.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: drop deps/prime submodule, revert .gitmodules to main
deps/prime was only referenced from .gitmodules (not pyproject/uv.lock/code);
removing it and resetting .gitmodules to main's version so the PR carries no
submodule-metadata churn. deps/verifiers stays pinned at 8d52bc8e.
* chore: pin verifiers floor to dev357, drop compact env + narrating comments
- verifiers floor -> >=0.1.15.dev357 (latest dev on PyPI = current submodule pin):
root dependency + override-dependencies, plus prime-rl-configs dependency
- drop the `compact` example env (envs extra + its [tool.uv.sources] entry)
- remove edit-narrating comments (transitive-deps note, envs-list description)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: keep renderers/prime-pydantic-config sources below verifiers (match main order)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* revert: drop merged gc.collect() in orchestrator trim_process_memory (nano uses malloc_trim only)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: unquote forward-ref type annotations + small cleanups
- replace string-literal type annotations with real types via
`from __future__ import annotations` (+ existing TYPE_CHECKING imports):
Rollout in orchestrator/filters.py and utils/monitor/{base,multi,prime,wandb}.py,
EventLoopLagStats in utils/async_utils.py; drop the now-unneeded F821 noqa
- prime monitor: rollout.task/timing.model_dump_json() instead of
json.dumps(...model_dump(mode="json")) (single Rust-backed serialization)
- drop redundant comments (TrainingSample field comments, renderer passthrough)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: drop EnvConfig docstring + redundant id/args fields
id and args are already on vf.EnvServerConfig; prime-rl's bare redefinition of id was shadowing the base's _validate_env_id AfterValidator. Removing both restores inheritance (incl. id validation).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(advantage): adopt main's per-env Linear advantage (adapted to vf.Trace)
This PR is only about vf-v1 integration; the RL advantage should match main, not
nano's Tokens/Turns efficiency shaping.
- config: LinearLengthPenaltyConfig (coef, gate_by_correctness) +
DefaultAdvantageConfig(length_penalty, length_weighted_baseline); per-env
TrainEnvConfig.advantage + top-level OrchestratorConfig.advantage default
- advantage.py: main's default_advantage_fn / setup_advantage_fn(config, max_seq_len),
adapted to vf.Trace (r.reward / r.completion_len instead of dict access; Traces
passed through assign_advantages, advantage written back onto each Trace)
- per-env wiring: TrainEnv.advantage_fn = setup_advantage_fn(config.advantage,
max_seq_len); TrainEnvs(max_seq_len); train_sink does per-env
assign_advantages(survivors, env.advantage_fn)
- tests: main's Linear / length-weighted / per-env / max_seq_len-threading
advantage tests, adapted to nano's vf.Trace _make_rollout
- drop the now-unused get_tool_response_len (only served nano's Tokens advantage)
Verified: 486 unit tests pass; reverse-text-v1 RL smoke 3 clean steps end-to-end
through the per-env advantage path.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): relock flash-linear-attention to current HEAD
flash-linear-attention is an unpinned git source (tracks HEAD, as on
main); its HEAD moved e8e791f -> bd67d11, leaving the locked commit stale
so CI's `uv sync --all-extras --locked` re-resolves it and fails. Relock
to the current HEAD.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(rl): address e2e review findings
- env-server: forward legacy extra_env_kwargs (rollout timeout / completion
token budget / max_seq_len) for v0 envs on the rl.py path. The standalone
env-server CLI dropped them, so legacy envs ran uncapped; the orchestrator
_spawn path already passed them.
- envs: re-type the wire vf.Trace into Rollout via model_construct instead of
a model_dump -> model_validate round-trip, avoiding a per-rollout copy of the
node pixel_values / routed_experts tensors (the server already model_constructs).
- train_sink: keep a running token total for token-batched runs instead of
re-summing the uncached Trace.total_tokens over the whole pending batch on
every arrival.
- config: drop dead ClientConfig.timeout / connect_timeout (not wired into the
v1 rollout clients).
- restore gc.collect() before malloc_trim in trim_process_memory; emit
Trace.info in the prime-monitor parquet (both match main).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers submodule to main (b841e53a)
The v1 work merged into verifiers main; the prior pin 8d52bc8e is an ancestor
of main, so this is a clean fast-forward. verifiers is an editable path dep
with unchanged declared deps, so uv.lock is unchanged. Verified with the
reverse_text v1 debug run (reward 0.11 -> 0.77 over 20 steps, no errors).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(rl): correct gibberish/repetition filter logprob alignment
GibberishFilter paired masked completion token_ids with logprobs from the
start of node.logprobs (misaligned on nodes mixing context + sampled tokens);
RepetitionFilter streaked over all logprobs including context. Both now zip
token_ids/logprobs/mask together and process only sampled (mask=True) tokens.
Also document the v1 integration's breaking config changes (env taskset/
harness shape, empty train.env default, num_workers->pool, required renderer,
client timeout removal) in CHANGELOG.md.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(rl): require at least one training env at config time
TrainConfig.env defaulted to an empty list with no check (only eval envs were
validated non-empty), so a config with no [[orchestrator.train.env]] parsed
and only failed later in TrainSource during setup. Add a non-empty-env
validator (mirroring EvalConfig) and make OrchestratorConfig.train a required
field (no default), so the failure surfaces at parse / --dry-run.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(v1): scaleswe -> rlm harness + router replay
Switch the scaleswe debug config to the rlm harness on prime sandboxes for
both train (scaleswe-v1) and eval (swebench-verified) envs, and enable router
replay (trainer.enable_router_replay + inference.enable_return_routed_experts,
mirroring configs/debug/r3.toml) to cut trainer/inference MoE routing mismatch
on the A3B model. Rename run/job to the -rlm variant and sync the prime
sandbox cleanup labels. Header comment corrected (prime, not modal).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): revert config-time train-env-required check (too broad)
The train-required validation (60e824247) broke ~18 config-propagation tests
in test_configs.py that construct OrchestratorConfig/RLConfig without a train
env, plus two checked-in configs that omit one (configs/debug/orch.toml,
examples/glm5_pd_disag/rl.toml). A config-level validator is the wrong place —
the codebase widely constructs train-less OrchestratorConfigs. Reverting to
green CI; a non-empty-train guard belongs at orchestrator setup (fail fast
before TrainSource) instead.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers to latest main + drop stale prime-env TODO
- Bump deps/verifiers b841e53a -> 7169d02d (latest verifiers main, clean
fast-forward, ...#1838). Editable path dep with unchanged declared deps, so
uv.lock is unchanged. Verified with reverse_text v1 (reward 0.13 -> 0.75 over
10 steps, no errors).
- Remove the stale "no prime-env hub install" TODO from the orchestrator — it
never loads environments (the env server imports them in its child process),
so the note no longer applies.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): remove dead prime-env-install path
Namespaced legacy env auto-install was removed (the v1 env server loads envs
directly via serve_env), leaving dead code with no callers/readers: the
`env_install_prerelease` flags (OrchestratorConfig + EnvServerConfig), the
`install_env` helper, and `get_env_ids_to_install`. Drop them and the now-
orphaned `subprocess` / `EnvConfig`,`EvalEnvConfig` imports.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): drop in-process env-server spawn, require address
The orchestrator no longer spawns env servers in-process (the mp.Process +
os.dup2 fd-redirect path). It only attaches to a server at EnvConfig.address,
now mandatory at orchestrator runtime - Env.start errors if it's unset. The rl
launcher already spawns one env-server subprocess per env and assigns address,
so launcher-driven runs are unaffected; standalone `uv run orchestrator` must
now be paired with separately-launched env-server(s) and an explicit address
per env.
Removes _run_env_server, Env._spawn, Env/Envs.shutdown, _env_server_process,
and the now-dead mp/os/queue/sys/atexit imports + ENV_SERVER_SPAWN_TIMEOUT.
Updates the standalone-orchestrator docs (training.md, scaling.md --bench) and
the CHANGELOG.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (dashboard per-rollout timer includes setup)
51701f4c (#1846).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Revert "chore(v1): drop in-process env-server spawn, require address"
This reverts commit d77546155.
Restore the in-process env-server spawn (orchestrator sidecar-spawns when
address is unset) to mirror main for now. The address-required / attach-only
cleanup is deferred - revisit later.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): orchestrator always spawns env servers in-process (mirror main)
Drop the launcher's env-server management: setup_env_servers (which
pre-assigned each env an address + spawned an env-server subprocess), the
per-env subprocess spawn loop in rl_local, the ENV_SERVER_KIND_STRIDE constant,
and the env_server_base_port config field. With no address pre-assigned, the
orchestrator spawns its own v1 EnvServer in-process per env (Env._spawn),
exactly as on main. The env-server CLI and EnvConfig.address are kept for the
optional user-managed external-server path.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(trainer): contiguous routed_experts slice for glm4_moe under compile (#2860)
Router replay passes routed_experts[:, :, layer_idx, :] (a strided view of
[tokens, layers, topk], dim-1 stride = layers*topk) into the MoE forward. Under
torch.compile the inductor kernel asserts a contiguous input, so it crashed with
`assert_size_stride ... stride 8==368` on GLM-4.5-Air. Make the slice contiguous.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(v1): bump verifiers pin (robust _ENSURE_UV for old base images)
7c347f61 (#1848).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: rasdani <73563550+rasdani@users.noreply.github.com>
Co-authored-by: Codex <codex@primeintellect.ai>
The release bump (#2855) updated pyproject.toml but not uv.lock, so
`uv sync --locked` fails on main (CPU Tests, Docker Push).
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor: drop client-side DP-rank pinning for external-LB
With external-LB data parallelism each DP rank is its own API server on its
own port (the URL is the rank selector), so the client no longer needs the
hybrid-LB `X-data-parallel-rank` header to pin a rollout to an internal DP
shard. Remove the `dp_rank_count` client field + its auto-setup and the
per-rank client expansion: one client per base URL, no rank header. The
router (vllm-router or llm-d EPP) balances across the per-rank endpoints.
This also fixes llm-d routing: the EPP forwards the header to the dp=1
backend, which rejected it ("data_parallel_rank N is out of range").
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: llm-d (EPP+Envoy) router backend
Add llm-d as a second router backend alongside vllm-router, selected via
`[inference.deployment.router] type = "llm-d"`. Built on the external-LB
launch substrate — the per-rank vLLM engines launch identically; only the
router control plane differs.
- `LlmdRouterConfig`: discriminated-union member with `scorers` (base) +
per-profile `prefill_scorer_overrides`/`decode_scorer_overrides`,
`non_cached_tokens`, `decode_sidecar_port`, and a known-scorer validator.
- `launch_router` helper gains an llm-d branch: renders per-replica EPP +
Envoy + file-discovery endpoints and launches `epp` + `envoy` instead of
vllm-router. Call sites stay router-agnostic.
- pd-sidecar on each decode node (P/D) for remote-prefill orchestration + NIXL.
- Entrypoints pass the `router` config object to the templates.
- Reject `enable_return_routed_experts` with llm-d (breaks P/D, unverified
for multi-node).
- SLURM cleanup also clears stale `epp`/`envoy`/`pd-sidecar` processes.
- Presets under `templates/llmd/` + `scripts/install_llmd.sh`; docs + install skill.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(inference): mooncake-store + llm-d EPP coexistence on SLURM P/D
- per-rank VLLM_RPC_BASE_PATH: external-LB runs one engine per process (all
data_parallel_rank_local 0), so the mooncake-store lookup ipc socket collided
on a node-shared dir; key it by $port. Also avoids an absent submit-node TMPDIR.
- EPP --grpc-health-port 9003 -> 9013: 9003 collided with mooncake_master's
metrics server on the shared replica-head node, which killed the EPP.
- mooncake_master -default_kv_lease_ttl=3600000: KV blocks were expiring (5s
default) before the decode side reused them.
- envoy circuit_breakers raised to 100000 on backend + epp clusters: the default
(~1024) overflowed at high inflight concurrency -> "reset reason: overflow" 500s.
- pd-sidecar launches on every decode node (not just the replica head), else
decode nodes past the head advertise endpoints nothing serves.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Feat: dockerless llmd install
* chore(configs): add GLM-5.1 llm-d disaggregated RL config
End-to-end RL config used for the GLM-5.1-FP8 llm-d (EPP+Envoy) P/D run:
12 train nodes + 16 inference nodes (8 prefill x2 / 8 decode x2), mooncake KV
store, r2e env. Lives alongside the existing glm5 disaggregated inference preset.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(configs): move GLM-5.1 llm-d RL config to dedicated configs/glm5_llmd/
Relocate the end-to-end GLM-5.1-FP8 llm-d (EPP+Envoy) P/D RL config into its own
configs/glm5_llmd/rl.toml (out of glm5_disagg_inference) and refresh it to the
latest tuned version.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(inference): per-role prefill/decode vLLM overrides for disaggregated P/D
Add `prefill_vllm_overrides` / `decode_vllm_overrides` to the disaggregated
inference deployment config (mirrors the existing `*_env_overrides`): extra
vLLM config options merged into the per-role `--vllm-extra` JSON for prefill
vs decode ranks on SLURM. Rendered via a small `vllm_overrides_fragment` helper
into the `ROLE_EXTRA` string in the inference / multi-node-RL sbatch templates.
Needed by configs/glm5_llmd/rl.toml (sets `decode_vllm_overrides`), which
otherwise fails `extra="forbid"` validation in test_load_configs.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(configs): enable prefill dual-batch-overlap in glm5_llmd config
Set prefill_vllm_overrides = {enable_dbo = true} (the inference-side perf knob
tuned during the GLM-5.1 run). Batch size / num-concurrent / node-scale knobs
left as-is — those are run-specific, not portable config.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(configs): tune glm5_llmd prefill/decode replicas (4 prefill / 1 decode)
num_prefill_replicas 2->4, num_decode_replicas 2->1 — the disaggregation split
found to perform best for GLM-5.1 (prefill is the bottleneck; one wide decode
replica maximizes decode KV/batching).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* docs: add GLM-5 llm-d example (16-node / 131K trainer) (#2854)
* docs: add GLM-5 llm-d example (16-node / 131K trainer)
Move the glm5_llmd config from configs/ into examples/glm5_llmd/ with a
README, mirroring the other GLM-5 example. Frame llm-d as the faster
router for GLM-5 and document the placeholders users must tweak
(output_dir, slurm partition, mooncake device_name).
Tune the example for a 16-node trainer: seq_len=131072, num_train_nodes=16,
cp=4, and adamw optimizer.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* docs: reword GLM-5 llm-d example entry as one-line SLURM deploy
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* docs: highlight GLM-5 llm-d one-line SLURM deploy in Overview
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
* fix(inference): tolerate KV-transfer finish for already-freed (aborted) reqs
In disaggregated P/D (NIXL, optionally + a KV store), a request can be finished
— most often FINISHED_ABORTED from an off-policy cancel, client disconnect, or
request timeout — while it still has in-flight KV transfers. When such a
request's finished_recving and finished_sending both arrive in the same
Scheduler.update_from_output step, the stock
Scheduler._update_from_kv_xfer_finished frees it in the recving branch
(_free_blocks -> del self.requests[req_id]) and then the sending branch hits
`assert req_id in self.requests`, killing the EngineCore. On a DP deployment
that one death cascades to every rank via the gloo finish-state all-reduce and
takes down the whole decode pool.
Observed on two llm-d P/D runs: the genuine crash is always one rank asserting
in _update_from_kv_xfer_finished, the rest are gloo "Connection closed by peer"
cascade victims. It is abort-triggered, not pause/resume-related: it reproduced
during normal stepping (~19k log lines after the last resume, engine actively
running model batches) and on a run with max_off_policy_steps=80000 / zero
off-policy cancellations — driven purely by incidental client-side aborts.
Monkey-patch _update_from_kv_xfer_finished to skip request ids no longer in
self.requests instead of asserting. Their blocks are already freed, so dropping
the stale notification is safe. Installed via the vllm.general_plugins entry
point so it applies in the EngineCore process where the Scheduler runs.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* docs: link upstream vLLM issue #46240 in the KV-xfer patch
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* add glm 5.2 training support
* simplify
* chore: revert accidental research-environments submodule bump
The "add glm 5.2 training support" commit unintentionally moved the
deps/research-environments submodule pointer. Restore it to main's SHA.
---------
Co-authored-by: faresobeid <fares@primeintellect.ai>
* feat: support PRIME_RL_REF for runtime source override
Mirrors the existing VERIFIERS_VERSION hook so researchers can dispatch
a run against an arbitrary prime-rl commit/branch/tag without rebuilding
the image. Clones into a per-ref dir under /tmp, seeds the venv from
/app/.venv so heavy wheels (flash-attn, mamba-ssm) survive, then
uv sync --inexact re-installs prime_rl from the override source.
* fix: address bugbot findings on PRIME_RL_REF entrypoint
- Slugify ref for cache dir name so branch names with slashes work.
- Always fetch + checkout on cache hit so mutable refs (branches/tags)
pick up new commits between pod restarts.
- Move VERIFIERS_VERSION install after the PRIME_RL_REF swap so when
both are set the install lands in the override venv.
* fix: init submodules and hash-key the override cache dir
- git clone --recurse-submodules so deps/* (verifiers, renderers,
research-environments, pydantic-config) are populated on cold
checkout, and refresh on every entrypoint via
'git submodule update --init --recursive'.
- Rewrite git@github.com SSH URLs to https at runtime so the SSH
submodule URLs work from pods that have no ssh keys.
- Append md5 hash of the ref to the cache dir name so distinct refs
that slugify the same way ('feat/foo' vs 'feat-foo') get distinct
cache dirs.
* fix: drop hardlink seed and key cache on repo+ref
- cp -al hardlinked /app/.venv into the override tree, so the
subsequent uv sync wrote through to the baked venv on filesystems
shared with /tmp. Plain cp -a always copies.
- Include PRIME_RL_REPO in the cache-dir hash so the same ref on
different forks gets distinct cache dirs.
* fix: --all-extras on override sync
uv sync --inexact --no-dev only installed base deps, so env / gpt-oss /
modelexpress changes in the override branch were silently missed. With
--all-extras the override picks them up, and --inexact still keeps
flash-attn-3 / mamba-ssm from the seeded venv.
* fix: mirror image extras explicitly instead of --all-extras
--all-extras pulled in disagg/quack which the baked image does not
ship; their deps (deep-ep, deep-gemm, quack-kernels) would trigger
heavy source builds at pod startup. Mirror Dockerfile.cuda:82's set
exactly so the override venv lines up with the image.
* fix: submodule sync before update to pick up .gitmodules URL changes
The off-policy drain (cancelling rollouts past max_off_policy_steps) ran via
on_new_version *after* the inference engines resumed from the weight-update
pause. In a NIXL P/D deployment this reliably crashed the decode engines.
Aborting a rollout cancels its /generate request; vLLM marks the request
FINISHED_ABORTED and frees it, recording it in the NIXL connector's
_reqs_not_processed set so the worker suppresses its in-flight KV-transfer
completion. That suppression only propagates to the workers while the engine is
stepping. Pausing with mode="keep" (PAUSED_ALL) skips step(), so KV transfers
that complete during the pause are flushed on the first step after resume — at
the same moment the drain fires its aborts. The abort frees the request before
its suppression reaches the worker, so the flushed completion hits
`assert req_id in self.requests` in the decode scheduler's
_update_from_kv_xfer_finished, killing the engine and cascading to every DP
rank via the gloo finish-state all-reduce.
With max_off_policy_steps=8 the first mass drop lands at the 9th weight update,
which is why the run always died at step 8/9.
Move the drain to a new on_version_pending observer hook that the watcher calls
*before* update_weights (before the pause), so the aborts are processed under
normal stepping and the connector's native cleanup completes before the engine
freezes. on_new_version still runs post-update for the orchestrator's dispatch
gate, which needs the live policy version.
Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(inference): strip routed_experts from chat-completions responses
routed_experts are consumed only via the serialized /generate (serving_tokens)
path used for router-replay training, which emits them as a {data, shape, start}
object the PD router merges. The stock chat-completions path encodes them as a
base64 np.save string instead, which the PD router rejects ("prefill routed_experts
must be an object with base64 data and shape") — failing every eval rollout, since
evals go through chat completions. enable_return_routed_experts is a server-wide
model-config flag with no per-request toggle, so strip the field on the chat path.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: format routed experts chat patch
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Adds MultiNodeDeploymentConfig.orchestrator_on_inference (default False). When
False, the orchestrator launches on trainer rank 0 (unchanged behavior). When
True, it launches on the last inference node (a decode node) instead — useful
when trainer nodes are host-RAM-saturated (large CPU-offloaded optimizer state)
and the orchestrator's rollout buffer + env workers would otherwise exhaust
memory there; inference nodes keep weights/KV on GPU with ample free host RAM.
The orchestrator launch is now a single top-level block in multi_node_rl.sbatch.j2
gated on a flag-selected SLURM_PROCID (NUM_INFER_NODES for trainer rank 0, or
NUM_INFER_NODES-1 for the last inference node), so both placements share one code
path. No effect when num_infer_nodes == 0.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
The coordinator child spawns on the DP-rank-0 API server while every
engine-core rank on the node is importing and loading weights, so its
spawn-time re-import can exceed 30s under that CPU/IO contention (seen
on multi-node disaggregated GLM-5.1 launches). Patch _wait_for_zmq_addrs
with a configurable timeout via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT
(default 300s).
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
The DSA sparse-attention indexer runs its forward under torch.no_grad(), so its
params (wq_b, wk, k_norm, weights_proj) never receive a gradient. They were left
with requires_grad=True and handed to AdamW, which lazily creates per-param state
only on the first step where a grad exists -- so the indexer params stayed
stateless.
This breaks strict checkpoint resume. At save time DCP's _init_optim_state
returns early (optim.state already non-empty), so the stateless indexer params
are omitted from the saved optimizer state. At load time the optimizer is fresh,
so _init_optim_state runs a zero-grad step over every requires_grad param and
materializes exp_avg/exp_avg_sq/step for the indexer too. DCP then demands those
keys, the checkpoint doesn't have them, and load dies with:
RuntimeError: Missing key in checkpoint state_dict:
app.optimizers.state.model.layers.0.self_attn.indexer.wq_b.weight.step
With resume_step=-1 every restart re-picks the same checkpoint and crashes
identically -> crash-loop.
Fix:
- freeze_sparse_indexer(): set requires_grad=False on all Indexer params, called
unconditionally in setup_model (no-op for non-DSA models). The indexer is never
trainable anyway, so this only makes save/load state symmetric.
- _create_optimizer(): hand only trainable params to AdamW/SGD/SignSGD (Muon
already filtered internally), so frozen params carry no optimizer state.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(inference): restore usage block on /inference/v1/generate response
* fix(inference): apply ruff formatting
* fix(inference): drive _FinalOutputCapture through async-for, not __anext__
* fix(inference): always emit cached_tokens, drop enable_prompt_tokens_details gate
* chore: bump verifiers to fix/hatch-vcs-fallback-version
Pin to the fallback-version fix (PrimeIntellect-ai/verifiers#1650) so the
prime-rl Docker build resolves a version without VCS metadata. Temporary
pin to the PR branch; should move to verifiers main once #1650 lands.
* fix(inference): annotate _FinalOutputCapture source as AsyncIterable
* multiplex trainer output
* update skill
* test: cover multi-run token exports
* feat: export token metrics from orchestrator
* refactor: store token export run fields on microbatch
* refactor: send microbatches without payload wrapper
* test: cover orchestrator token-export metric collection
Adds an integration test asserting the orchestrator's per-step read path
(collect_token_export_metrics) surfaces finite mismatch_kl/entropy mean/max
from real multi-run exports. Complements the file-writing coverage in
test_token_exports_are_run_local; reuses the existing fixture.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix: defer token-export STABLE until run step fully consumed
A single orchestrator run_step can span multiple trainer steps when the
packer splits its samples across packs (token budget). mark_stable() ran
every trainer step and marked any dir touched that step, so the orchestrator
could read a run step's exports as complete from only the first pack's
sequences and advance its cursor, never aggregating the remainder.
Mark a run's export dir STABLE only once that run step is fully consumed —
gated on the same ready_to_update signal that drives its optimizer step.
Dirs for runs not yet ready carry over to a later trainer step. run_id=None
(single-run export) never spans trainer steps, so it is marked immediately.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat: stamp token-export metrics with their trainer step
Token exports lag the orchestrator step they're logged under (the trainer
runs behind), so on the default W&B step axis mismatch_kl/entropy appear
shifted right. Log the run step the exports actually belong to as
`trainer/step` so the metrics can be plotted against a lag-corrected axis.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: fold token-export metrics into MetricsBuilder under trainer/
Move the token-export collection from the orchestrator mainline into
MetricsBuilder.build, which now owns the last-logged-step cursor (seeded from
the resumed step via start_step). Namespace the metrics under trainer/
(trainer/mismatch_kl/*, trainer/entropy/*) alongside trainer/step so they
group in W&B and can be plotted against a lag-corrected axis.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: drop redundant max_step from token-export reader
Exports always lag the orchestrator (the current step's batch is shipped just
before metrics are built and trained afterward), so no stable export at or
beyond the current step can exist on disk. The `step <= max_step` filter was
always satisfied; the last_logged_step cursor alone drives correctness.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: return log-ready dict from token-export reader
Drop the TokenExportMetricsResult dataclass that was unpacked into a dict one
line later. collect_next_token_export_metrics now returns the trainer/-prefixed
metrics (including trainer/step) directly, so the builder just updates the log
dict and reads trainer/step back to advance its cursor.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: guard token-export log update under the truthiness check
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: drop redundant run_idx guard in SinglePacker
The receiver always stamps batch.run_idx from used_idxs (a key of idx_2_id),
so the is-not-None/in-idx_2_id check was always true. Index directly, matching
MultiPacker.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: mark token-export STABLE with a barrier instead of all_gather
The all_gather_object did barrier + dir-union + rank-0 write. Replace it with a
plain dist.barrier() (so STABLE only lands after every rank flushed its
rank_*.jsonl), then each rank touches STABLE for the dirs it wrote. touch is
idempotent, so ranks sharing a (run, step) dir converge harmlessly, and the
union is covered without shipping dir lists.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: barrier at the call site, drop participate_in_stable_marking
The barrier lived inside the exporter, so the disabled variant needed a
participate_in_stable_marking flag to opt into it. Move the barrier to the
single train-loop call site, gated on token export being enabled (uniform
across ranks): every rank barriers together, then writers touch STABLE and
disabled ranks no-op. DisabledTokenExporter is a pure no-op again and the
exporter does no collectives.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: drop dist.is_initialized guard before token-export barrier
train() always calls setup_torch_distributed before the training loop, so dist
is initialized by the time the barrier runs.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* chore: drop redundant comments around token-export barrier
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: derive token-export root from output_dir.parent
root_output_dir was just output_dir.parent of self.output_dir and used in one
place; drop the redundant attribute.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix: skip malformed token-export records instead of aborting the step
Token-export metrics are best-effort monitoring read inside MetricsBuilder.build
every step. A malformed JSONL line or a loss_mask/value length mismatch raised
ValueError, which would abort the orchestrator step. Guard each record, skip and
count failures, and warn once per step dir; good records still aggregate.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat: drain trailing token-export metrics after max_steps
Token exports lag the orchestrator, so the last shipped steps are finalized by
the trainer after the main loop ends — and build() no longer runs to log them,
dropping the tail. Add an end-of-run drain that polls for the remaining stable
steps up to max_steps-1 and logs each under its own trainer/step (a local W&B
step axis, leaving progress.step for the final checkpoint untouched). Gated on
token export being on for the run; early-returns when build() already kept up;
bounded by a timeout. Shared collection extracted to
MetricsBuilder.next_token_export_metrics.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* make token export a top-level trainer flag
* chore: fold token export into multi-run integration config
* chore: revert multi-run trainer config override
* chore: remove token export unit tests
* docs: document token export config migration
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
UCX's --with-verbs silently disables IB when the rdma-core dev headers
are missing, producing a TCP-only build that only fails much later at
runtime with NIXL_ERR_BACKEND. On hosts with RDMA devices, require the
headers before building and verify the rc_verbs transport made it into
the built UCX. Also pass --with-rdmacm so the rdmacm connection manager
is built when available.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
GLOO_SOCKET_IFNAME was hardcoded to bond0 and UCX_NET_DEVICES to all,
both of which break on clusters with different NIC naming or with RDMA
devices UCX cannot open (e.g. a non-functional Ethernet bond, which
fails NIXL backend creation with NIXL_ERR_BACKEND). Derive the gloo
interface from LOCAL_IP and enumerate RDMA ports from sysfs (ibv_devices
is not on the job PATH), preferring InfiniBand, falling back to RoCE,
and keeping "all" on hosts without RDMA devices.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
/resume and /update_weights previously had no retry and no per-attempt
timeout, so a transient failure or stuck server during a weight update
could leave engines paused indefinitely (the admin AsyncClient uses
timeout=None). Factor the /pause retry into a shared _admin_post helper
with a single default timeout, overridable per call; /update_weights
gets a longer one since the collective NCCL receive can take a while.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Remove the configs/private submodule (research-configs) and all
references to it throughout the codebase:
- Remove submodule from .gitmodules and git tracking
- Simplify install.sh: use plain git submodule update --init --recursive
now that no private submodule can fail for users without access
- Update skills/install/SKILL.md to reflect simplified submodule init
- Remove configs/private/ entry from skills/configs/SKILL.md key files
- Simplify test_configs.py: no longer need to filter out private/ path
The [tool.uv.sources] override for prime-pydantic-config was being ignored
because it was only a transitive dependency (via prime-rl-configs). uv only
applies source overrides for packages that appear in project.dependencies.
Adding it as a direct dependency makes uv resolve from the local editable
path (deps/pydantic-config) instead of PyPI.
* feat(fp8): fuse transpose into the dX block-fp8 weight cast
The dX backward built `weight.transpose(0, 1).contiguous()` and re-cast it to
fp8 every step, materializing a full bf16 transpose buffer plus an extra
read/write pass. Add `per_block_cast_to_fp8_tp_triton`, which produces the
block-fp8 of `weight.T` directly by reusing the existing per-block kernel with
swapped output/scale strides — no intermediate buffer.
128x128 block quantization is transpose-symmetric, so the result is
bit-identical to casting the materialized transpose; DeepGEMM receives an
identical B tensor. Verified byte-for-byte across shapes; ~14x faster on a
4096x4096 weight (373 -> 27 us).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* deslopified
* also add fused implementation for per-token
* Fix: skip tests on <Hopper
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
The aarch64 host install path was broken: `uv sync` installs flash-attn
from PyPI source but pyproject sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE,
so the compiled extension never builds. `scripts/docker-arm64-post-install.sh`
fixed it for Docker GB200 builds but hardcoded sm_100 and /app/.venv,
leaving Hopper hosts (H100/H200/GH200) without a recipe.
Changes:
- `scripts/docker-arm64-post-install.sh`: auto-detect compute capability
via nvidia-smi when available; parameterize venv path. Preserves the
sm_100 default when no GPU is visible (Docker buildx).
- `scripts/install.sh`: call the post-install for aarch64 hosts after
`uv sync --all-extras`. Previously the script ran uv sync and exited,
leaving aarch64 users with a broken venv.
- `README.md`: document the aarch64 post-install step (mirrors the
existing 3.1 Flash Attention 3 pattern).
Validated on GH200 (sm_90, aarch64):
- forward + backward parity vs torch SDPA (max diff < 0.05 / 0.25)
- 383/384 unit tests pass (the 1 failure is unrelated TileLang/MoE)
- SFT trainer smoke test (5 steps, Qwen3-0.6B) runs with flash_attention_2
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The dense multi-node external-LB weight-broadcast world size was computed as total_infer_nodes * api_server_count * tp. api_server_count can resolve to the global DP size (e.g. when parallel.dp is set, or via validator ordering), which double-counts the node dimension, so the trainer's NCCL broadcast waits for more ranks than exist and init deadlocks.
Every allocated inference GPU is one NCCL rank, and the external-LB launcher starts dp_per_node TP-sharded servers per node (gpus_per_node workers/node), so size the world directly as total_infer_nodes * gpus_per_node. This matches the disaggregated path.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: json logging for inference (vLLM)
Adds [log] config to InferenceConfig and routes vLLM's stdlib loggers
(plus uvicorn / fastapi / root) through a JSON formatter matching the
trainer/orchestrator shape. Driven via VLLM_LOGGING_CONFIG_PATH so the
config crosses the multiprocessing.spawn boundary into vLLM workers.
* chore: ruff format
* fix: force VLLM_CONFIGURE_LOGGING=1 when setting LOGGING_CONFIG_PATH
vLLM raises at import if VLLM_CONFIGURE_LOGGING=0 and
VLLM_LOGGING_CONFIG_PATH is set. Setting json_logging is an explicit
opt-in to configure vLLM's logger, so override the env var rather than
crash on jobs that have it preset to 0.
* fix: emit tz-aware UTC timestamps in JsonFormatter
Match loguru's tz-aware ISO output so the platform's JsonLogsViewer
parses inference timestamps correctly. Naive timestamps are interpreted
as the viewer's local time, off by the viewer-vs-pod offset.
* fix: propagate top-level [log] settings to inference subconfig
RLConfig.auto_setup_logs already mirrors [log] into trainer and
orchestrator subconfigs. Now that InferenceConfig has its own [log]
field, propagate there too — without this, an RL run with
[log] json_logging=true at the root still emits text vLLM logs because
inference.log defaults to non-JSON.
* fix: guard None inference in auto_setup_logs
RLConfig.inference is Optional and defaults to None for setups like
elastic-inference-pool runs. The previous commit propagated [log]
unconditionally, crashing the validator on any RLConfig without an
[inference] section (caught by the test_load_configs unit tests on
configs/elastic/rl.toml).
* fix: propagate top-level [log] settings to teacher_inference
Mirrors the auto_setup_logs propagation to inference, so teacher
inference servers also pick up shared level / json_logging when they
are configured separately or auto-created without a rollout inference
to deep-copy from.
* fix: map loguru-only levels (TRACE, SUCCESS) before dictConfig
Stdlib logging does not know TRACE/SUCCESS, so setting [log] level =
"trace" or PRIME_LOG_LEVEL=trace would crash setup_vllm_env when JSON
logging is enabled. Map TRACE→DEBUG and SUCCESS→INFO before building
the dictConfig payload.
* fix: route transformers logs through JSON handler
The docstring claimed transformers was covered but the named-loggers
tuple omitted it, so HF model-loading warnings/info were emitted as
plain text in otherwise-JSON inference logs (transformers sets
propagate=False on its own logger).
* fix: preserve per-component json_logging when shared [log] omits it
Codex P2: SharedLogConfig.json_logging defaulted to False, so auto_setup_logs would clobber any per-component (inference, teacher_inference) override back to text whenever the shared [log] section wasn't set. Mirrors the existing 'level' pattern: nullable on SharedLogConfig, gate propagation on the shared value being explicitly set.
* fix(trainer): don't crash trainer when validation hook fails
validate_lora_rank dereferenced student.model.lora without a None
check, so an orchestrator config with no LoRA section raised
AttributeError. The hook was called outside get_orchestrator_config's
try/except, so the exception propagated out of discover_runs through
the train loop, killed the master rank, and left worker ranks waiting
forever on rollouts that would never be written.
- Guard model.lora is None in validate_lora_rank so we reject cleanly
- Wrap hook calls in get_orchestrator_config in try/except so any
future hook bug returns the run to the retry path instead of taking
down the trainer
* fix(trainer): use safe fallback for hook name in error message
Validation hooks are typed as Callable, so hook.__name__ isn't
guaranteed (callable objects and functools.partial don't have it). If
such a hook raised, the exception handler itself would raise
AttributeError and defeat the try/except.
Per Codex review on #2698.
Path.mkdir(exist_ok=True) re-checks self.is_dir() after EEXIST and re-raises if
it returns False. On a parallel filesystem (beegfs) with concurrent mkdir from
every trainer rank, a non-master rank can hit EEXIST while its metadata cache
hasn't seen the new inode yet -> is_dir() returns False -> FileExistsError,
crashing the trainer mid-save (observed at weights/step_180).
Guard the three all-ranks mkdir sites behind world.is_master + a barrier so only
the master creates the dir and the others wait until it exists:
- CheckpointManager.save_to_path: dataloader_dir
- CheckpointManager.save: ckpt_path.parent
- WeightCheckpointManager.save: step_path
Mirrors the existing master-only guard in WeightCheckpointManager.save_to_path.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(slurm): use external-LB everywhere, drop hybrid-LB
Unify every router-fronted vLLM launch path on external load balancing:
one API server per DP rank on PORT+k, each pinned to its TP slice of GPUs,
with the router balancing across the per-rank endpoints. This removes the
hybrid-LB mode (data_parallel_hybrid_lb / data_parallel_start_rank /
--intra-node-data-parallel-size) from both the RL and standalone-inference
SLURM templates, across multi-node and disaggregated (P/D) deployments.
- Extract the duplicated per-rank vLLM launch into a shared
`_launch_rank.sh.j2` helper, included once and called from every launch
site in both templates.
- Build per-rank router worker URLs (BACKEND_PORT+k for multi-node;
PREFILL_PORT+k / DECODE_PORT+k for P/D).
- TP-correct DP group sizing (DP = nodes_per_role_replica * dp_per_node),
fixing the latent tp>1 bug where the disaggregated inference path sized
the group as nodes * gpus_per_node.
- Pass data_parallel_rpc_port + enable_expert_parallel to the multi-node
standalone-inference template so per-rank MoE EP groups rendezvous
node-locally.
- Drop the now-dead USE_DISTRIBUTED_EP gate (EP is decided directly by
enable_expert_parallel).
- Fix a latent apostrophe in a bash -c comment ("can't" -> "cannot") that
broke `bash -n` on multi-node non-disaggregated renders.
- Route DP rank 0 to the node-level log (node_<rank>.log, the target of the
top-level inference.log symlink) via a shared `rank_log` helper, so
inference.log captures real server output again instead of just the preamble;
ranks 1+ keep their own node_<rank>_rank<k>.log.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor(slurm): extract router launch into _launch_router helper
Pull the per-replica vllm-router invocation (repeated across the multi-node
and disaggregated launch sites in both templates) into a shared
`_launch_router.sh.j2` helper: `launch_router <mode:pd|regular> <worker_args>
<port> <policy> <log> [replica_idx]`. Call sites now resolve the worker URLs
and call the helper, instead of inlining the `vllm-router` command four times.
This localizes the router launch to one place — a future llm-d (EPP+Envoy)
backend slots in as a single branch inside the helper rather than touching
every call site.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(slurm): per-rank metrics roles + multi-node EP DP coordinator address
Two correctness fixes for the external-LB paths:
- inference_metrics_roles: external-LB exposes one admin client per DP rank,
but the role list was built per node. Expand it per rank
(stride = gpus_per_node / tp) so prefill/decode labels line up with the
per-rank ADMIN_URLS the orchestrator collects metrics from.
- multi-node MoE EP: data_parallel_address was chosen on the global DP rank,
so every local rank after the first on the replica head got the head
hostname instead of the head's own IP — non-zero local ranks on the head
could fail to rendezvous with the DP coordinator when dp_local > 1. Choose
the address per node (head ranks use LOCAL_IP, other nodes use the head
hostname), matching the disaggregated path.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Introduce a `RouterConfig` (currently just `vllm-router`, with `type`/`port`/
`policy`) and put `router: RouterConfig` on `BaseInferenceDeploymentConfig`,
alongside `backend_port`. Previously `router_port`/`router_policy` lived only on
the multi-node / disaggregated deployment types, so the RL launcher needed
`getattr(inference.deployment, "router_port", 8000)` to cover a multi-node
allocation running a single-node inference deployment (e.g. general_agent).
Now every deployment type carries the router config and the launchers read
`deployment.router.port` / `deployment.router.policy` directly. These are
external-LB serving config — only used when the inference is served as a fleet
behind the router (a multi-node allocation, or a standalone multi-node /
disaggregated inference); a co-located single-node server ignores them.
`RouterConfig` is a `type`-discriminated alias (single member for now), so other
router backends can be added to the union without touching call sites. The SLURM
templates are unchanged — the entrypoints still pass the same `router_port` /
`router_policy` template vars — so the rendered scripts are byte-identical.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
`validate_multi_node_requires_slurm` only checked `multi_node`, but a
disaggregated (P/D) deployment is equally multi-node (separate prefill/decode
node groups + NIXL) and needs SLURM. Without this, a disaggregated
`InferenceConfig` with no slurm passed validation and fell through to the local
launcher, which cannot run it.
The same `InferenceConfig` is also used nested inside `RLConfig`, where slurm
lives at the top level — so also forward top-level `[slurm]` into the nested
inference (RL P/D, e.g. examples/glm5_pd_disag, sets `[slurm]` but not
`[inference.slurm]`). The per-rank `inference.toml` already excludes `slurm`, so
each rank still runs locally — no SLURM-in-SLURM.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(inference): tiered KV cache offload (native + mooncake, CPU/disk)
Replace the flat `inference.kv_cache_offload` (single `cpu_bytes`) with a typed,
backend-swappable, tiered config discriminated on `type`:
- native: vLLM `OffloadingConnector` (cpu) / `TieringOffloadingSpec` (cpu+disk,
fs_python secondary). Fully self-contained.
- mooncake: per-node standalone-store (`mooncake_master` + `mooncake_client`, RDMA),
cpu and/or disk tiers.
Composable `cpu`/`disk` tiers (cpu required, disk-only rejected); `disk.num_bytes`
is mooncake-only (native fs tier is filesystem-bounded; warns if set on native).
Centralize the vLLM `kv_transfer_config` build in
`InferenceConfig.build_kv_transfer_config` (NIXL transfer + offload composed via
`MultiConnector`); both SLURM templates stop hand-rolling the JSON and launch the
node-local Mooncake store. New `src/prime_rl/inference/mooncake.py` launches the
master+client and writes `MOONCAKE_CONFIG_PATH`; `server.py` brings it up for local
runs.
Verified:
- Single-node (Qwen3-0.6B, H200): all four configs boot + serve; native-cpu and
mooncake-rdma both round-trip KV (store ~1.1GB / reload ~205MB).
- Multi-node 3-node SLURM disaggregated (Qwen3-30B-A3B): NIXL P/D transfer serves
coherent output; with mooncake offload, MultiConnector[Nixl, MooncakeStore] +
per-node RDMA store serves coherent output.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(inference): drop unused mooncake disk num_bytes and metadata_server
- DiskOffloadTier.num_bytes: removed. Neither backend enforces a disk byte quota
(capacity is bounded by the filesystem at disk.path), so it was a no-op knob.
- MooncakeKVCacheOffloadConfig.metadata_server: removed. The launcher always hosts
the HTTP metadata server on the node-local master and auto-derives the URL from the
master host.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor(inference): launch Mooncake store in sbatch bash; add CHANGELOG
Address PR review: replace the Python launcher CLI (+ env.sh round-trip) with an
explicit bash launch in the SLURM templates, and document the breaking config change.
- New `templates/_mooncake_store.sh.j2` partial (shared via `{% include %}` by
`inference.sbatch.j2` and `multi_node_rl.sbatch.j2`): launches the node-local
`mooncake_master` + `mooncake_client`, writes the config JSON, and exports
`PYTHONHASHSEED` / `MOONCAKE_CONFIG_PATH` inline — visible in the rendered script.
Removes the hacky orphan-process CLI, the `print`, and the unquoted-`env.sh` round-trip.
- Delete `src/prime_rl/inference/mooncake.py` and the `server.py` store-launch hook.
- Mooncake offload is now SLURM-only: `inference_local` errors (when no store env is
present) and an `RLConfig` validator rejects local RL + mooncake. Native offload is
unchanged and still works locally. Entrypoints pass `kv_offload_{cpu_bytes,disk_path,
device_name}` template vars.
- CHANGELOG.md: document the `inference.kv_cache_offload.cpu_bytes` -> discriminated
`type` breaking change (per .cursor/BUGBOT.md).
Verified single-node SLURM (Qwen3-0.6B): store launches via the template bash,
MooncakeStoreConnector (standalone-store) loads, and the server serves coherent output.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(inference): Mooncake shared distributed KV pool across nodes
Switch the Mooncake offload backend from per-node isolated stores to a single shared
distributed pool, so all inference nodes' CPU RAM (and disk) form one KV cache and a
prefix cached on any node is reusable by every other node/replica.
- `_mooncake_store.sh.j2`: the head inference node (first in the SLURM nodelist) runs the
one master + HTTP metadata server; every node runs a client pointing at the head and
contributes its segment. Store keys are model + parallel-rank + content-hash (no instance
id), so the pool is reused across nodes and replicas.
- Drop the now-unused `MooncakeKVCacheOffloadConfig.master_server_address` (auto head).
- docs: describe the shared pool (total pool ≈ num_bytes × #inference-nodes).
Verified on a 2-node SLURM job (Qwen3-0.6B): one master on the head, both clients join
(2 segments), and a prefix cached on node A is served from node B over RDMA
(load_get ~160 MB cross-node hit).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(inference): drop runtime mooncake-requires-slurm check
The RLConfig `validate_mooncake_offload_requires_slurm` config validator already guards
the misuse case; the per-request runtime check in `inference_local` (and its `import os`)
was redundant. Remove it.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore(deps): bump verifiers to v0.1.15.dev18 (latest main)
deps/verifiers -> e1d4f259 (v0.1.15.dev18, head of verifiers main).
This branch previously needed to pin *before* #1414 (per-token prompt
attribution to TrajectoryStep), which stuffed a non-JSON-serializable
RenderedTokens into trajectory state and broke v1's
state.assert_serializable(). That has since been fixed upstream by
#1471 (renderers <-> v1: serializable RenderedTokens), so we track
latest main again. Also includes #1462 (TasksetConfig rework) and
#1467 (typed RendererConfig).
Co-authored-by: Cursor <cursoragent@cursor.com>
* exp: reverse_text v1 smoke config
Minimal 2-GPU smoke config for the v1 path: `reverse-text` env via
`args = { v1 = true }`, in-process vf.Harness, no tools.
* refactor(orchestrator): fan out temperature at batch build
Single env-wide temperature per rollout — assume the config surface
(one [orchestrator.train.env.sampling] block per env), drop the
output -> trajectories round-trip:
- Drop `sampling_args` from REQUIRED_STATE_COLUMNS. The orchestrator
already knows each env's temperature from its TrainEnv.sampling_args,
so there's no reason to require envs to mirror it back through state.
This also unblocks v1 envs, which route sampling_args through
state["runtime"] and don't surface it at the top level.
- interleave_rollout no longer reads output["sampling_args"]["temperature"]
or fills `completion_temperatures`; it leaves the field empty.
- TrainSink.process_group fans the env's scalar temperature out across
each sample's completion tokens in the same loop that stamps
advantage / reward / env_name / training_mode, before the batch is
assembled.
TrainingSample / TrainingBatch wire format is unchanged. Trainer-side
per-token temperature scaling (scaled_logits = logits / temps) keeps
working as-is.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
The teacher's weights are frozen, so salting its prefix-cache with the
student's policy version forces unnecessary cache invalidation on every
weight update. Send no salt when train rollouts route to the teacher
pool; student (RL/OPD train + all eval) paths keep the policy-version
salt as before.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Feat: bump vllm to 0.22
* fix: regenerate uv.lock against merged verifiers submodule
The merge commit locked uv.lock while deps/verifiers was still checked out
at the pre-merge commit, so the verifiers package metadata (harnesses/
tasksets editable packages, dropped nltk/textarena) was stale and failed
'uv sync --locked' in CI. Re-locked with the submodule at the merged gitlink.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
The step-7 max_threshold=0.6 check pins an early reward value below a
boundary that run-to-run noise routinely crosses (reward bounces around
0.5-0.6 in the step 6-8 window), causing spurious failures. The
learning-curve property is already covered by check_reward_goes_up, the
final >= 0.65 check, and the step-7 >= 0.2 minimum, so the upper bound
adds no real coverage.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(orchestrator): add orchestrator v2 with shared train+eval scheduler
Opt-in via `orchestrator.experimental.use_orch_v2 = true`. Replaces the
step-driven outer loop of `prime_rl.orchestrator` with an async pipeline
backed by a single dispatcher that schedules both train and eval rollouts
through a shared concurrency limiter and rate limiter.
The dispatcher uses a level-triggered `SchedMode.PREFER_TRAIN | PREFER_EVAL`:
on each eval-trigger boundary it stops scheduling new train rollouts but
lets the in-flight tail drain naturally, then resumes train as soon as the
eval queue empties. Both transitions overlap on the same semaphore, so the
pool stays saturated and we recover the cost of the current "blocking eval"
behavior without cancelling work.
Module layout (src/prime_rl/orchestrator_v2/):
- `policy.py` — shared mutable `Policy(version, model_name)`
- `watcher.py` — polls broadcasts, calls `update_weights`, notifies observers
- `dispatcher.py` — shared semaphore + AsyncLimiter, PREFER_TRAIN/PREFER_EVAL,
off-policy cancellation, partial-group handling, per-env eval triggers
- `batcher.py` — pre_batch_filters → compute_advantages (in dispatcher) →
batch buffer → post_batch_filters → tokenize → ship; eval aggregator with
per-`eval_step` flush
- `log_loop.py` — `IntervalLogger` task writes dispatcher gauges +
event-loop lag to wandb on the `_timestamp` axis (async-native, decoupled
from step semantics)
- `ckpt.py` — lean `Progress(step, last_eval_step)` checkpoint manager
- `orchestrator.py` — wires everything in `asyncio.TaskGroup`, bounded
graceful shutdown
Config evolution (additive, non-breaking):
- `pre_batch_filters` and `post_batch_filters` fields added.
- `filters` is silently aliased to `post_batch_filters` via
`AliasChoices` — no deprecation warning, all existing TOMLs keep parsing.
- Default pre slot registers all three filter types in monitor mode;
default post slot is unchanged from today's `filters` default
(zero-advantage enforced, gibberish/repetition in monitor mode). Net
out-of-the-box behavior matches the legacy orchestrator.
- `OrchestratorExperimentalConfig.use_orch_v2: bool = False` flips the
`rl` entrypoint to launch `orchestrator-v2` instead of `orchestrator`.
- `OrchestratorExperimentalConfig.log_loop_interval: float = 5.0` controls
the gauge cadence.
- `BufferConfig` and `eval.cancel_inflight_rollouts_on_eval` are still
parsed (the legacy orchestrator still uses them) but v2 simply doesn't
consume them. Difficulty pools are replaced by `pre_batch_filters`;
eval transitions in v2 always use the drain-switch overlap.
Entrypoint wiring:
- New `orchestrator-v2` console script in `pyproject.toml`.
- `rl` launcher picks between `orchestrator` and `orchestrator-v2` based
on the flag.
- New `configs/debug/orch_v2.toml` overlay flips the flag for parity
testing against the same TOML.
Refs https://github.com/PrimeIntellect-ai/prime-rl/issues/2311.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(orchestrator_v2): address review feedback
- Make `Orchestrator` a proper class with `__init__` / `setup` / `start` /
`stop` / `shutdown` methods. No more module-level `orchestrate` coroutine —
the new `run_orchestrator` is a thin `@clean_exit`-wrapped helper that
instantiates the class and awaits `start()`.
- Replace the `Done` exception with a shared `orch.stopped: asyncio.Event`.
The batcher sets it when `max_steps` is reached; `Orchestrator.start()`
blocks on it and then drives the shutdown sequence. No more
exception-driven control flow / `except* Done` group-unwinding.
- Rename `run` → `start` across all async components (`RolloutDispatcher`,
`TrainBatcher`, `WeightWatcher`, `IntervalLogger`).
- Slim `TrainBatcher.__init__` to a single `orch: Orchestrator` arg
(previously 16 wiring args). The batcher reads shared state via
`@property` accessors on `self.orch` — no behavior change, just less
ceremony at construction time.
- Drop all leading-underscore "private" methods and attributes on the v2
classes — we're not designing an API. Notably, `_handle_train`,
`_ship_batch`, `_wait_barrier`, `_fill_inflight`, `_try_schedule_*`,
`_schedule_group_rollout`, `_handle_completed_rollout`,
`_maybe_finalize_group`, `_select_least_loaded_client`, `_acquire`,
`_release`, `_drop_group`, `_apply_policy_update`, `_compute_next_ckpt_step`,
etc. all lose the underscore. Internal state (`_stopped`, `_task`, etc.)
too.
- Remove `MAX_EMPTY_BATCH_ATTEMPTS`. If a batch has zero trainable signal,
the batcher logs a warning and just retries on the next batch instead
of crashing after N consecutive empties.
- Remove `drain_pending_eval` from `TrainBatcher` and the matching
`force_eval` from `RolloutDispatcher` — not a behavior we want to
support. Final evals at end-of-run still run via the legacy
`EvalEnv.evaluate` path (now called directly from `Orchestrator.start()`).
- Soften the barrier stall log: drop the speculative "Trainer may be
stuck." sentence. Most of the time inference is just faster than the
trainer, so the message was misleading. Bumped the first-warn threshold
from 30s → 60s while we're there.
- Revert `uv.lock` to `main` (the previous commit picked up a stray
`wikispeedia` workspace member from `uv sync --all-extras` that wasn't
part of this PR).
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(orchestrator_v2): decompose batcher into single-purpose components
Splits the previous catch-all ``TrainBatcher`` into four single-purpose
classes, each with explicit data-flow dependencies declared at construction
time. No more parent ``orch`` back-pointer / property-shim layer.
New module layout:
- ``batcher.py`` — ``Batcher``: pure in-memory accumulator with
``add / ready / pop / buffered_count``. Owns the pre-batch filters and the
per-batch pre-filter counters. No I/O, no async, no step tracking.
- ``postprocessor.py`` — ``PostProcessor``: takes a popped batch + step
number, runs post-batch filters, tokenizes, builds ``TrainingSample``\\ s,
computes teacher logprobs (opd), and ships via the sender. Returns a
``ProcessResult`` carrying the per-rollout stats the metrics builder
needs — so this class doesn't import pandas.
- ``eval_collector.py`` — ``EvalCollector``: buckets eval ``Trajectory``\\ s
by ``eval_step``; flushes per-env reward / completion-len / pass@k metrics
when the dispatcher's expected count comes back. Takes ``(expected,
fired_envs)`` as call args instead of reaching into the dispatcher.
- ``metrics.py`` — ``MetricsBuilder``: assembles the per-step W&B dict from
the rollout cohort + ``ProcessResult`` + dispatcher gauges. Pure-ish; only
state is the config.
``Orchestrator`` now owns the pipeline driver loop:
- ``main_loop`` pulls trajectories off the dispatcher queue, routes train vs
eval, drives ``batcher.add → batcher.pop`` and ``postprocessor.process``,
builds metrics, logs to the monitor, and increments ``progress.step``.
- ``process_one_step`` is the single shipping step (ckpt save → max_steps
check → pop → ship → barrier wait → metrics + log → step++).
- ``wait_barrier`` and ``maybe_save_ckpt`` are public helper methods on the
orchestrator (no leading underscores; the v2 classes deliberately don't
hide internals).
Dependency surface, post-refactor — every arrow is a real data-flow dep
declared at the call site, not a "shared context" smell:
Batcher ← config (batch_size / token_batch_size), pre_filters
PostProcessor ← config, tokenizer, renderer, mm_token_type_ids_mapping,
sender, teacher_inference, post_filters
EvalCollector ← config, monitor, eval_envs, post_filters
MetricsBuilder ← config
IntervalLogger ← dispatcher, policy, interval (no more batcher refs)
Orchestrator ← owns all of the above
Also:
- Rename ``TrainBatcher`` → ``Batcher``: ``EvalCollector`` is the eval-side
abstraction now, so the prefix is misleading.
- Drop the parent-pointer ``orch: Orchestrator`` constructor argument and
the ``@property`` shim layer it forced (``dispatcher``, ``policy``,
``progress``, ``monitor`` etc. all read off ``self.orch`` previously).
- ``IntervalLogger`` no longer reads ``batcher.last_*`` cached state — those
fields are gone. Step-aligned values plot fine via the per-step monitor
log; the time-axis emit just covers dispatcher gauges + event-loop lag.
- Remove ``wikispeedia`` from ``pyproject.toml`` (stray pickup from a local
``uv sync --all-extras`` during dev).
Smoke: 8-step reverse-text run under v2 with the new layout, reward
0.11 → 0.24, clean event-based shutdown via ``self.stopped.set()`` at
``max_steps``.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(orchestrator_v2): rollout-as-atom + train/eval sinks with flush signals
Redesigns the data flow to be signal-based. The atomic unit emitted by the
dispatcher is now a single Rollout (one completed rollout, never a group).
Grouping moves into the sinks. Each sink owns its own flush signal:
- TrainSink groups rollouts by (env_name, example_id). When
Rollout.is_group_complete=True arrives, the GRPO group is finalized:
compute_advantages over the survivors, then apply_filters for the
pre-batch pass, then drop filtered rollouts and extend batch_buf. The
flush signal is batch_ready() — the orchestrator polls it after every
add() and calls pop() to ship a batch.
- EvalSink groups rollouts by (env_name, eval_step). When
Rollout.is_group_complete=True arrives, the env's eval epoch is done.
add() returns an EvalFlush payload that the orchestrator logs.
Filters do not apply to eval — filters are train-only by design.
Dispatcher changes:
- Trajectory (group of rollouts) replaced by Rollout (single rollout).
maybe_finalize_group / emit_group push individual rollouts to out_q
instead of one Trajectory per group.
- Train: the last surviving rollout of each (env, example_id) group gets
is_group_complete=True.
- Eval: tracked per (env_name, eval_step) via eval_expected_per_env /
eval_emitted_per_env / eval_dropped_per_env. The last expected rollout
(emitted + dropped == expected) gets is_group_complete=True, flagging
the env's epoch as done.
- compute_advantages is no longer called here — that's a train-sink
concern now.
- Drops the cross-env expected_eval_counts dict and replaces it with
per-env tracking.
Orchestrator changes:
- main_loop consumes Rollout and routes by kind. Train rollouts go to
train_sink.add(); batch_ready() triggers process_one_step. Eval
rollouts go to eval_sink.add(); an EvalFlush return triggers
flush_eval (per-env metric logging on the orchestrator since it needs
self.monitor and the logic is small).
- flush_eval is a new public method that builds per-env reward / seq-len
/ pass@k metrics from an EvalFlush and logs them via the monitor.
- post_filters is now a member field used by PostProcessor only; the
eval path doesn't read it.
Removed:
- orchestrator_v2/batcher.py (replaced by train_sink.py)
- orchestrator_v2/eval_collector.py (replaced by eval_sink.py)
Smoke (eval.interval=5, max_steps=12, num_examples=16):
- Step 0 eval (eval_base_model) flushes cleanly: Reward 0.17.
- Step 5 eval triggers with inflight_train=121 — drain-switch overlap
intact. Eval flushes per-env (Reward 0.54) while train continues
(steps 6-8 ship during eval drain).
- Reward 0.14 → 0.60 over 12 steps; clean event-driven shutdown via
self.stopped.set() at max_steps.
* refactor(orchestrator_v2): three-level sinks (rollout / group / batch)
Both TrainSink and EvalSink now have a uniform three-level processing
structure. The dispatcher emits Rollout (atomic unit) with two boundary
signals; sinks dispatch each level to a named process function whose
logic naturally lives at that scope:
Level When Method What it does
-------- ----------------------- --------------------- -----------------------------
rollout every add() process_rollout train: backfill + interleave (eager tokenization)
eval: no-op
group is_group_done=True process_group train: compute_advantages + pre_batch_filters
eval: move per-example group into env batch bucket
batch batch_ready (train) process_batch train: post_batch_filters + assemble samples + metrics
is_batch_done (eval) eval: build per-env metrics (reward, pass@k, ...)
Dispatcher Rollout dataclass:
- is_group_complete split into two boundary signals:
- is_group_done: last rollout of the (env, example_id) group. Set for
both train (GRPO group) and eval (per-example group).
- is_batch_done: last rollout of an eval env-epoch (emitted+dropped ==
expected). Always False for train — the train sink decides batch
boundaries itself from batch_size / token_batch_size.
- emit_group sets both flags appropriately per kind.
TrainSink:
- async add(rollout) returns True when the batch is ready to pop.
- process_rollout is the eager-tokenize hook. Per-rollout tokenization
overlaps with the dispatcher producing more rollouts, removing the
parallel-tokenize-all-at-ship-time sync point.
- process_group runs compute_advantages, propagates advantage / reward /
env_name onto the already-tokenized TrainingSamples, then runs the
pre-filter pass.
- pop_batch(step, progress, gauges, ...) runs process_batch internally
and returns a TrainBatchResult { rollouts, samples, metrics, result }.
- Owns the MetricsBuilder reference; per-batch metrics are part of
process_batch, not a separate orchestrator step.
EvalSink:
- add(rollout) returns an EvalBatchResult when an env-epoch is complete
(is_batch_done arrived).
- process_rollout is a no-op (kept for structural symmetry with
TrainSink).
- process_group buckets the per-example group into the (env, eval_step)
batch.
- process_batch / build_metrics produces the eval/{env}/ metrics dict
(reward, pass@k, etc) — no filter calls; filters are train-only.
Orchestrator:
- main_loop is a thin router: await train_sink.add(...) — if True, run
process_one_step; eval_sink.add(...) — if EvalBatchResult, run
log_eval_batch.
- process_one_step is now I/O-only: save_rollouts, offload_images,
teacher_logprobs (opd), wait_barrier, sender.send, monitor.log,
heartbeat, ckpt save, step++. All processing already happened in the
sink.
- log_eval_batch is a small side-effect method: save_rollouts +
monitor.log_eval_samples + monitor.log; metrics dict comes pre-built
from EvalSink.
- postprocessor.py is gone — its work split across TrainSink (filter +
tokenize + samples + metrics) and orchestrator (ship I/O + opd
logprobs + disk side effects).
- ProcessResult moved into metrics.py to avoid a circular import.
Smoke (eval.interval=5, max_steps=12, num_examples=16):
- Step 0 eval flushes cleanly: Reward 0.14.
- Step 5 eval triggers with inflight_train=115 — drain-switch overlap
intact. Train steps 6/7/8 ship during eval drain. Eval flushes
per-env: Reward 0.48.
- Reward 0.13 → 0.64 over 12 steps; clean event-driven shutdown.
* refactor(orchestrator_v2): unify is_batch_done trigger across train and eval
Both sinks now use the same flag — ``Rollout.is_batch_done`` — to signal the
batch boundary. The orchestrator's main loop polls a single, uniform
condition; the only difference is who stamps the flag:
- Eval: the dispatcher stamps ``is_batch_done=True`` on the last expected
rollout of an env-epoch (emitted+dropped == expected). No change here.
- Train: ``TrainSink.add`` now stamps ``rollout.is_batch_done = True`` after
``process_group`` if its buffer has reached ``batch_size`` / token
budget. The polling counterpart is ``TrainSink.is_batch_done()`` (renamed
from ``batch_ready()`` for naming symmetry with the rollout flag).
Orchestrator main loop:
await self.train_sink.add(rollout)
while rollout.is_batch_done and not self.stopped.is_set():
await self.process_one_step()
rollout.is_batch_done = self.train_sink.is_batch_done()
Same predicate (``rollout.is_batch_done``) drives both sinks. The eval
path consumes the flag inside ``eval_sink.add``; the train path consumes
it in the main loop's ``while``.
Smoke: reverse-text 8-step run under v2, reward 0.13 → 0.36, clean
event-driven shutdown via ``self.stopped.set()`` at max_steps.
* chore(configs): replace orch_v2 debug overlay with hendrycks_math showcase
- Drop ``configs/debug/orch_v2.toml``. v2 is opt-in via a CLI flag —
``--orchestrator.experimental.use-orch-v2`` (or the equivalent TOML
key) — and a one-liner overlay TOML was overkill for that.
- Add ``configs/hendrycks_math/orch_v2_demo.toml`` — a small (2 GPU,
30 train step) eval-heavy run that makes the v2 overlap win visible
on wall clock. 6 AIME2024 eval epochs of 30 × 4 = 120 long-reasoning
rollouts each; under the legacy orchestrator each epoch pauses train,
under v2 they overlap. Comment block at the top of the file shows
how to run both side-by-side via the CLI flag.
* refactor(orchestrator_v2/ckpt): drop unused last_eval_step from Progress
The eval boundary is a strict function of ``progress.step``, ``eval.interval``,
``eval_base_model``, and ``skip_eval_on_resume`` — no extra persistent state
needed. ``progress.last_eval_step`` was only ever written (in
``log_eval_batch``) and never read; the dispatcher's own
``last_eval_step_per_env`` dict handles "don't re-trigger at the resumed
step" and is seeded from ``resume_step`` directly.
The ``Progress`` dataclass on the ckpt now carries just ``step`` + totals.
Old checkpoints containing the extra ``last_eval_step`` field load fine
— the ``hasattr(progress, key)`` guard in ``CheckpointManager.load`` skips
unknown serialized fields silently.
* refactor(orchestrator_v2): drop pre-baked metrics from batch result types
Rename `EvalBatchResult` → `EvalBatch`, `TrainBatchResult` → `TrainBatch`,
and rename `eval_step` → `step` on the eval payload. The dataclasses now
carry only the raw rollouts + per-rollout counters; the `metrics` dict is
a pure view computed at log time.
Why: the `metrics` field duplicated `rollouts` + a few scalars and forced
the orchestrator to build with a `step_time=0.0` placeholder inside
`TrainSink.pop_batch` and mutate the dict after the post-barrier wait.
Building at log time with the real timings keeps one source of truth.
- Drop `metrics` from both batch payloads; orchestrator calls
`MetricsBuilder.build` (train) and `EvalSink.build_metrics` (eval) when
ready to log.
- Drop `parallel_preprocess_time` / `teacher_logprobs_time` from
`ProcessResult` (never read in v2 — tokenization is per-rollout;
teacher logprobs is an orchestrator scalar passed to `build` directly).
- `TrainSink` no longer holds a `MetricsBuilder` ref; single-purpose
ingest + payload assembly.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(orchestrator_v2): consolidate dataclasses + types into types.py
Move every dataclass / type alias / protocol from the orchestrator_v2
modules into a single ``types.py``. Behavioral modules (dispatcher, sinks,
watcher, log_loop, ckpt, metrics, orchestrator) now import their payloads
from one place instead of from each other.
Moved:
- ``Policy`` (was policy.py — file deleted, only contained the dataclass)
- ``Progress`` (was ckpt.py)
- ``Kind``, ``SchedMode``, ``Rollout``, ``RolloutMeta``, ``GroupState``
(were dispatcher.py)
- ``EvalBatch`` (was eval_sink.py)
- ``TrainBatch`` (was train_sink.py)
- ``ProcessResult`` (was metrics.py)
- ``VersionObserver`` (was watcher.py)
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore(configs): drop max_completion_tokens cap from orch_v2_demo
Let train/eval rollouts use the full 8k max_model_len so the demo
showcases the overlap on realistic long-reasoning AIME completions
instead of capping them at 4k.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(orchestrator_v2): move group/batch boundary signals into the sink
Previously the dispatcher stamped ``is_group_done`` / ``is_batch_done``
flags on whichever rollout it happened to iterate last in ``emit_group``.
But "last in a group" is whichever straggler finishes last — not knowable
at dispatch time — so the flag-on-rollout model was always derivative of
arrival ordering rather than a real signal.
Flip the design so the dispatcher emits every dispatched rollout (success,
env-error, empty-trajectory, task-exception, off-policy-cancel) exactly
once to ``out_q`` and the sinks own group/batch finalization by counting:
- Drop ``is_group_done`` / ``is_batch_done`` from ``Rollout``.
- ``TrainSink.add`` finalizes a group on the ``group_size``-th arrival,
returns ``bool`` for batch-ready (was: mutate ``rollout.is_batch_done``).
- ``EvalSink.add`` finalizes a group on the ``group_size``-th arrival,
finalizes the epoch when total arrivals reach
``num_examples * group_size``, returns ``EvalBatch | None``.
- Sinks decide drop / partial-train policy: filter errored rollouts before
``compute_advantages``; drop the whole group when the env
``requires_group_scoring`` and any rollout failed.
- Dispatcher synthesizes ``vf.RolloutOutput`` markers with ``error`` set
for task exceptions and off-policy cancellations, so the sink's count-
based finalization still fires when rollouts never produced real output.
- Drop ``eval_expected_per_env`` / ``eval_emitted_per_env`` /
``eval_dropped_per_env`` side-channel bookkeeping — pure dead weight
once the sink counts arrivals itself.
- Drop ``GroupState.completed_rollouts`` / ``failed_rollouts`` — the
dispatcher no longer accumulates rollouts before emit; ``emitted``
counter is enough to pop the group from ``self.groups`` once every
member has flowed out.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(configs): allow matching shared+sub values in propagator conflict check
The single-node SLURM launcher dumps the fully-resolved ``RLConfig`` to
disk and re-loads it inside the SLURM job. The dumped TOML has both the
shared-level keys (``output_dir``, ``model.name``, ``wandb.*``, ...) and
the matching sub-config keys (filled by the propagator on the original
load) populated to the same value. The old conflict check flagged
``shared is set, sub is also set`` regardless of values, so the re-load
failed with a ``Shared config conflicts with matching sub-config field(s)``
error.
Tighten the check to "shared and sub disagree" — matching values are a
harmless roundtrip (the propagator's fill-if-absent would have produced
the same thing). Genuine conflicts (e.g. shared ``model.name = "A"`` vs
``trainer.model.name = "B"``) still raise.
Covers the three sites that build ``conflicts``: the ``propagate``
helper, the ``output_dir`` block (matches against the per-target expected
value, including ``orchestrator.output_dir = f"{output_dir}/run_default"``),
and the ``wandb.name`` block (matches against the ``-trainer`` /
``-orchestrator`` suffixed form in non-shared mode).
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(orchestrator): replace legacy orchestrator with v2 implementation
Promote the v2 design to be the orchestrator. Clean deprecation — no
``use_orch_v2`` flag, no parallel ``orchestrator-v2`` console script, no
``prime_rl.orchestrator_v2`` module. The v2 sources move into
``prime_rl.orchestrator`` and the legacy files (``orchestrator.py``,
``scheduler.py``, ``buffer.py``, ``ckpt.py``) are deleted outright.
The legacy ``orchestrator`` console script keeps working — it now points
at the new ``Orchestrator(config).start()`` class. Existing TOML configs
work as-is (the public surface didn't move).
To compare against pre-v2 numbers, check out ``main`` and re-run any of
the existing configs head-to-head.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(orchestrator): UUID group IDs, pool-owned client selection, lean dispatcher inference dep
Three small cleanups that came out of post-merge review of the
orchestrator rewrite:
1. **UUIDs for dispatcher group IDs.** ``RolloutMeta.group_id`` and
``self.groups`` are now keyed by ``uuid.UUID`` (drop the ``self.next_group_id``
counter + ``new_group_id`` helper). One less piece of state to reason about
across dispatcher restarts / resume paths and zero risk of stale-counter
collision.
2. **Client selection moves onto ``InferencePool``.** ``client_identity`` is a
module-level helper next to the pool definitions in ``utils/client.py`` and
``InferencePool.select_train_client(load)`` is the public hook (implemented
on both ``StaticInferencePool`` and ``ElasticInferencePool``). The dispatcher
builds the load ``Counter`` from its own in-flight tracking and calls the
pool — load tracking stays caller-side, but "wait for clients + pick least
loaded" is now pool-side where the clients actually live.
3. **Dispatcher takes ``inference: InferencePool`` directly.** The
``training_mode == "sft"`` resolution (``rollout_inference = teacher_inference
if sft else student_inference``) moves up into ``Orchestrator.setup`` where
both pools are already in scope; the dispatcher only knows about the one
pool it actually uses.
Also drops a few stray "v2" mentions in log strings / proc title / docstrings
that survived the previous cleanup pass.
Co-authored-by: Cursor <cursoragent@cursor.com>
* revert: restore validation.py to main
Roll back the propagator conflict-check loosening from this branch. The
single-node SLURM dump-then-reload bug it was working around is a
pre-existing issue on the launcher path; will be addressed in a separate
PR rather than ride along with this orchestrator rewrite.
Local launcher (the default ``rl_local`` path) is unaffected by the
validator either way.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(orchestrator): factor TrainSource + EvalSource out of dispatcher
Mirror the ``Train*`` / ``Eval*`` naming used everywhere else in the
orchestrator (``TrainEnvs`` / ``EvalEnvs``, ``TrainSink`` / ``EvalSink``,
``TrainBatch`` / ``EvalBatch``). Both abstractions answer the same
question — "what's the next example to schedule?" — with the asymmetry
their roles demand:
- ``TrainSource`` (was inline ``TrainEnvCycle``) — infinite pull. Same
weighted round-robin over training envs as before; just renamed and
moved into its own module.
- ``EvalSource`` (new) — trigger-driven finite-per-epoch pull. Owns the
per-env example lists, per-env intervals, the per-(env, step) FIFO
queue, ``last_eval_step_per_env``, ``eval_base_model`` startup
handling, and ``skip_eval_on_resume`` gating. Exposes
``trigger(step)`` / ``trigger_at_start()`` for the dispatcher to poke,
and ``peek`` / ``pop`` / ``bool(source)`` / ``len(source)`` for it to
pull.
Dispatcher net loss: ~150 lines and 5 fields (``eval_queue``,
``eval_examples``, ``eval_intervals``, ``eval_step_envs``,
``eval_at_zero_pending``, ``last_eval_step_per_env``, ``resume_step``)
plus two methods (``fire_eval_epoch``, ``enqueue_eval_env``).
``RolloutDispatcher.on_new_version`` is now a 3-line delegation:
``fired = eval_source.trigger(step) ; if fired: switch_mode + log``.
Also drops ``eval_step_envs`` entirely — pure dead state: only ever
written, never read.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(orchestrator): slim dispatcher, move eval triggers to per-batch, add eval cancellation
A bundle of orchestrator/dispatcher cleanups all sitting in this PR:
**dispatcher → just a scheduler**
- ``__init__`` takes explicit params (``train_source``, ``eval_source``,
``inference``, ``policy``, ``max_inflight_rollouts``,
``tasks_per_minute``, ``group_size``, ``max_off_policy_steps_train/eval``,
``training_mode``) instead of the full ``OrchestratorConfig``. Sources
are now orchestrator-owned and passed in.
- Drops ``resume_step`` — it's purely an ``EvalSource`` concern now and
the orchestrator passes it directly to ``EvalSource``.
- ``DispatcherMetrics`` dataclass on ``types.py`` consolidates all the
per-poll counters (cancellation by kind, error/empty by env,
errors-by-type, total arrivals, eval_epochs_started, mode_transitions)
with ``record_*`` helpers and ``drained()`` that returns the wandb
shape + clears the drain counters in one shot. Replaces 6 dict/int
fields previously scattered on the dispatcher.
- Drops the redundant ``inflight_total_permits`` property (was just an
alias for ``inflight_permits``).
- Unifies ``try_schedule_train`` + ``try_schedule_eval`` into a single
``try_schedule(kind)`` + ``next_fresh_group(kind, envs)``. Same
"continue existing group → otherwise open a fresh one" algorithm for
both; the only asymmetry (train pulls from an infinite source vs. eval
peeks+pops a finite queue) sits in two clearly-labeled branches of
``next_fresh_group``.
**eval triggers move to per-batch (orchestrator-side)**
- ``Orchestrator.process_one_step`` calls ``maybe_trigger_eval(step)``
at the end (after ``progress.step += 1``); ``Orchestrator.start``
calls ``maybe_trigger_eval(at_start=True)`` once before the main loop.
- ``RolloutDispatcher.on_new_version`` now does only the off-policy
bookkeeping (bump counters, cancel stale groups). Eval epoch
triggering is no longer tied to "we just got new weights"; it's tied
to "we just completed a training step", which matches the conceptual
model.
**eval cancellation + cancelled-as-errored**
- ``max_off_policy_steps_eval: int | None = None`` (default uncapped —
preserves current behavior) on ``OrchestratorConfig``. When set, eval
rollouts older than the cap get cancelled via the same drain-and-
switch path as train (synthetic ``Cancelled`` rollouts flow to the
eval sink). Train and eval caps can now diverge.
- ``EvalSink.build_metrics`` filters errored rollouts out of all stats
(reward/seq_len/pass@k) and reports them as ``cancelled_count`` /
``errored_count`` / ``valid_rate`` separately. Counting failed
attempts as reward=0 would silently bias scores down.
**``eval.eval_base_model`` renamed to ``eval.skip_first_step``**
- New default is False (no step-0 eval — opt in instead of opt out).
The legacy ``eval_base_model`` key still parses via a silent
``AliasChoices`` (same boolean semantics), so configs that explicitly
set ``eval_base_model=true|false`` keep working. Configs that relied
on the implicit default get the new no-step-0-eval behavior.
**misc**
- Drop ``OrchestratorConfig.seed`` (hardcoded ``seed=42`` for
``TrainSource`` in the orchestrator — was effectively the default
anyway).
- Drop ``eval_step_envs`` dead state (write-only).
- Drop ``record_dropped_group`` from ``DispatcherMetrics`` — group
dropping is a sink concern now (see prior commit).
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(configs): move off-policy caps to per-side {train,eval}.max_off_policy_steps
Drop the global ``OrchestratorConfig.max_off_policy_steps_eval`` field and
instead make off-policy caps a per-side override, matching the same
shared-default / per-side-override pattern used everywhere else in the
config (e.g. ``train.sampling`` vs per-env sampling):
- ``OrchestratorConfig.max_off_policy_steps`` (already existed, default
8): the shared default for both train and eval.
- ``TrainConfig.max_off_policy_steps: int | None = None``: per-train
override; ``None`` inherits the global.
- ``EvalConfig.max_off_policy_steps: int | None = None``: per-eval
override; ``None`` inherits the global.
The orchestrator resolves both sides to plain ints before passing to the
dispatcher, so the dispatcher's signature tightens from ``int | None`` to
``int`` for ``max_off_policy_steps_eval`` (caps are never "unset" by the
time they reach the dispatcher — they either come from the per-side field
or fall back to the global default).
Behavior change worth flagging: the previous ``max_off_policy_steps_eval
| None = None`` defaulted to *uncapped* (eval was never cancelled). The
new pattern defaults eval to the same cap as train (``8`` by default),
so eval rollouts that lag past the cap will now be cancelled by default.
Set ``eval.max_off_policy_steps`` to a large value if the previous
uncapped behavior is preferred.
* refactor(eval_sink): build metrics in process_batch + rename expected_for→batch_size_for
Two follow-ups from review that didn't ride along the previous commit:
- ``EvalSink.process_batch`` now builds the per-env metrics dict inline
and stamps it on the returned ``EvalBatch.metrics`` field. Was an
awkward two-step (``process_batch`` returned just rollouts, then the
orchestrator separately called ``build_metrics(batch)``); per-batch
derivations belong in the per-batch hook. ``build_metrics`` as a
standalone method goes away.
- ``EvalSource.expected_for`` → ``batch_size_for`` (it's the same number
the train sink calls ``batch_size`` — total rollouts per epoch).
* revert: collapse per-side off-policy caps back to global max_off_policy_steps
Roll back ``TrainConfig.max_off_policy_steps`` / ``EvalConfig.max_off_policy_steps``.
Keep just the global ``OrchestratorConfig.max_off_policy_steps``; it applies
to train and eval rollouts the same way. Eval cancellation behavior
(introduced earlier in this branch — cancelled rollouts surface as
``Cancelled`` markers, sink filters them out of stats) stays in place;
this commit only reverts the per-side override scaffolding.
* chore(config): remove wandb.shared deprecation shim
The ``SharedWandbConfig.deprecate_shared_field`` ``model_validator(mode="before")``
introduced in #2649 popped ``wandb.shared`` from input dicts with a
``FutureWarning`` so older configs that still set ``shared = true`` (or
``false``) kept loading.
The ``rl`` entrypoint always uses shared W&B mode now, the legacy split with
``-trainer`` / ``-orchestrator`` suffixes is gone, and the in-tree configs no
longer set ``shared``. Drop the shim so configs that still carry the field
fail loudly via the default ``extra = "forbid"`` instead of silently warning.
Docs and CHANGELOG updated.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(config): honor --no-wandb / --no-ckpt across shared and sub-configs
pydantic-config's CLI negation (``--no-wandb`` / ``--no-ckpt``) writes the
string ``"None"`` into the override dict, which only becomes real ``None``
later via ``BaseConfig._none_str_to_none``. ``RLConfig``'s subclass
``mode="before"`` validators run *before* that conversion, so the bare-block
enablement in ``propagate_shared_fields`` used to see the string and
re-enable ``trainer.wandb`` / ``orchestrator.wandb`` (or the ``ckpt`` pair)
with defaults — silently undoing the CLI's intent.
Tighten the bare-block check from ``get(key) is not None`` to
``isinstance(get(key), dict)``. A bare ``[wandb]`` block in TOML is ``{}``
(dict, still enables); ``--no-wandb`` produces ``"None"`` (string, now
correctly skipped). Same logic applies to ``ckpt``.
Verified end-to-end with ``cli(RLConfig, args=[..., "--no-wandb"])``:
``cfg.wandb``, ``cfg.trainer.wandb``, ``cfg.orchestrator.wandb`` are all
``None``. ``--wandb None`` and ``--no-ckpt`` behave the same. Bare
``[wandb] {}`` / ``[ckpt] {}`` blocks still enable the sub-configs.
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore(changelog): drop --no-wandb fix entry
It's a bug fix, not a breaking config change, so it doesn't belong in
CHANGELOG.md (which documents breaking config changes only).
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore(comment): trim bare-block enablement comment
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(wandb): drop legacy-mode reference; add AGENTS rule
``docs/`` should describe the current state of the codebase, not its
history. Strip the "the legacy split has been removed" sentence from
``docs/training.md`` — readers on ``main`` don't care that there used to
be a non-shared mode — and add a ``## Docs`` rule to ``AGENTS.md`` to
codify it.
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore(agents): trim docs rule
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(eval_sink): drop redundant batch_arrivals counter
``EvalSink.batch_arrivals[(env, step)]`` was an arrival counter that
duplicated ``len(pending_batches[bkey])`` at the epoch-completion check
point. They could diverge mid-epoch (counter includes rollouts still
parked in ``pending_groups``; bucket only includes finalized groups), but
at the trigger point — when the last expected rollout arrives — its
group hits ``group_size``, ``process_group`` flushes the group's members
into ``pending_batches``, and the two are equal. Since ``process_group``
flushes every member of a finalized group without filtering, the bucket
size IS the arrival count at end-of-epoch.
Replace the check with ``len(self.pending_batches[bkey]) >=
self.batch_size_for(env_name)``; drop the counter field and its
matching pop in ``process_batch``.
* refactor(sinks): symmetrize TrainSink + EvalSink API; non-optional EvalSink deps
Four small alignment cleanups so the two sinks expose the same shape:
- ``EvalSink`` constructor takes ``eval_envs: EvalEnvs`` (non-optional);
the orchestrator only constructs the sink when ``config.eval`` is set.
Drops ``assert self.eval_envs is not None`` from ``group_size_for`` /
``batch_size_for`` and the conditional fallback in ``process_batch``.
``Orchestrator.eval_sink`` is now ``EvalSink | None``; the main loop
only reaches the sink for ``rollout.kind == "eval"`` which only fires
when eval is configured anyway.
- ``TrainSink.batch_buf`` → ``TrainSink.pending_batch``. Matches
``EvalSink.pending_batches`` naming (singular here because train has
one batch buffer at a time; eval has multiple ``(env, step)`` epochs).
- Collapse ``TrainSink`` level 3 to just ``process_batch()`` — the same
shape ``EvalSink`` exposes. Drops ``is_batch_done()``, ``pop_batch()``,
and ``pop_cohort()``; the readiness check inlines into ``add()`` and
the cohort pop inlines into ``process_batch()``. ``add()`` now returns
``TrainBatch | None`` directly (was ``bool`` + caller calls
``pop_batch``), matching ``EvalSink.add()``'s ``EvalBatch | None``.
- Drop ``self.logger`` from sink ``__init__``; inline ``get_logger()``
at call sites instead.
Orchestrator main loop simplifies from
``batch_ready = add(); while batch_ready: process_one_step()`` to
``train_batch = add(); if train_batch is not None: process_one_step(train_batch)``.
The previous ``while``-loop's draining behavior is preserved by the
batch-threshold check: a single rollout's group adds at most ``group_size``
survivors, which can't overflow a ``batch_size`` buffer twice in one
``add()`` call (``group_size`` << ``batch_size`` in practice).
* refactor(orchestrator): quiet filter per-group logs; add per-group summary line
Two log-volume cleanups in the sinks + filter module:
- ``apply_filters`` per-group detection log (``Detected N/M rollouts
(gibberish=…)``) drops from info → debug. It fires once per group
finalization (4+ lines per training step at typical batch sizes), so
is too noisy for default verbosity. Per-filter breakdowns are still
available at debug-level.
- ``TrainSink.process_group`` and ``EvalSink.process_group`` each emit
a single info-level summary line per finalized group with: env name,
example_id, total rollouts, errored count, filtered count (train
only), avg reward across survivors, and a compact per-filter
breakdown (``filters: zero_advantage=2, gibberish=1`` or ``—``).
Eval format adds ``eval_step`` and omits the filters slot (filters
are train-only).
The previous train-side warning lines for partial / all-failed /
group-scored-dropped groups are folded into the new summary line at
info-level with an explicit ``dropped: …`` suffix where appropriate
(no more separate warning + summary).
* refactor(rollout): key sinks by group_id UUID, not (env, example_id)
``(env_name, example_id)`` was the de-facto group key in the sinks, but
isn't actually unique: ``TrainSource.next_example`` cycles a shuffled
dataset and the same example can be re-sampled while an earlier group is
still in flight (small datasets, fast wrap). Two physical groups for
``(env, 42)`` would have conflated in ``pending_groups[(env, 42)]``.
Carry the dispatcher's group UUID on the ``Rollout`` instead:
- Add ``Rollout.group_id: uuid.UUID`` (passed through by
``RolloutDispatcher.emit_rollout`` from ``meta.group_id``).
- Drop ``Rollout.env_name`` / ``Rollout.example_id`` / ``Rollout.eval_step``
from the dataclass — they're already available via ``raw["env_name"]``,
``raw["example_id"]``, and a new ``raw["_eval_step"]`` (stamped on raw
by ``emit_rollout`` for eval rollouts, mirroring how ``_samples`` /
``_policy_version`` are stashed).
- ``TrainSink.pending_groups`` / ``EvalSink.pending_groups`` re-key on
``rollout.group_id`` (truly unique per dispatched group).
- ``EvalSink.pending_batches`` keeps the ``(env_name, eval_step)`` key
because multiple groups need to roll up into a single epoch bucket;
read from ``raw`` instead of dataclass fields.
- ``drop_group``'s cancellation-marker emission goes through
``emit_rollout`` for consistency (one stamping path instead of two).
* refactor(types): rename ProcessResult→TrainBatchMetrics, add typed EvalBatchMetrics
Two parallel typed metric dataclasses, one per sink:
- ``ProcessResult`` → ``TrainBatchMetrics`` (rename only, same fields).
``TrainBatch.result`` → ``TrainBatch.metrics``. The dataclass holds
per-batch counters that ``MetricsBuilder.build`` reads alongside the
raw rollouts cohort and orchestrator-side timings.
- ``EvalBatch.metrics`` changes from ``dict[str, Any]`` to a typed
``EvalBatchMetrics`` dataclass (n_rollouts / n_cancelled / n_errored /
valid_rate / reward_mean / completion_len_{mean,max,min} /
truncation_rate / no_response_rate / n_examples / group_size +
``pass_at_k: dict[str, float]``). The dataclass exposes a
``to_wandb_dict(env_name=…, step=…)`` method that materializes the
flat ``eval/{env}/...`` wandb shape on demand — keeps the dataclass
typed while preserving the existing wandb keys.
``Orchestrator.log_eval_batch`` calls ``to_wandb_dict()`` before
``monitor.log`` and reads ``reward_mean`` / ``n_rollouts`` / ``n_examples``
off the typed view for the success line.
Note on ``TrainBatch.rollouts`` vs ``samples``: they're not redundant.
``samples`` is the trainer-bound subset (filtered survivors) sent via
``sender.send``; ``rollouts`` is the full cohort needed for
``save_rollouts`` (disk), ``log_samples`` / ``log_distributions`` (wandb),
``offload_images_to_disk`` (memory hygiene), and ``MetricsBuilder.build``
(per-rollout walk). Two different consumers, both required.
* chore(filters): drop per-group detection log from apply_filters
The sink's per-group summary line already reports the per-filter
breakdown (``filters: zero_advantage=2, gibberish=1`` etc); the debug
line in ``apply_filters`` was redundant. Also drop the now-unused
``counts`` / ``total_detected`` / ``total_enforced`` accumulators.
* refactor(periodic_logger): distribute per-component; no defensive wandb
Replace the standalone ``IntervalLogger`` with a per-component
``PeriodicLogger``:
- Each async component owns its own ``PeriodicLogger`` (one for the
dispatcher, one for the watcher, one for the orchestrator's main-loop /
event-loop-lag concerns). Each logger has its own ``snapshot()``
callable returning the component's live gauges.
- The shared interval comes from a single config field
(``experimental.log_interval``, renamed from ``log_loop_interval``).
- Lifecycle is tied to the owning component: ``periodic_logger.start()``
inside the component's ``start()`` (right after the task is registered),
``periodic_logger.stop()`` inside the component's ``stop()``. No more
standalone ``log_loop`` task on the orchestrator.
W&B handling tightens:
- ``import wandb`` at the top of ``periodic_logger.py`` (no try/except).
- ``wandb.define_metric(key, step_metric="_timestamp")`` is called at
``PeriodicLogger.__init__`` for each explicit metric key the snapshot
will emit — no glob patterns, no lazy first-call registration.
- ``wandb.log`` is called without try/except; gated only on the explicit
``wandb_enabled`` flag the component passes in (``config.wandb is not
None``).
- ``EventLoopLagMonitor`` moves out of the old ``IntervalLogger`` and is
owned by the orchestrator directly (its ``get_metrics()`` is the
snapshot for the orchestrator's periodic logger).
Console output is now part of the spec: each emit logs a compact
``[<name>] key=value …`` line at info-level so steady-state component
state is visible between per-step lines, even with ``--no-wandb``.
Also: ``WeightWatcher.metrics()`` → ``WeightWatcher.gauges()`` to match
the dispatcher's ``gauges()`` convention; surface ``policy_version`` /
``update_count`` / ``last_*`` timings.
* refactor(metrics): drop dispatcher gauges/drain from step-aligned MetricsBuilder
Step-axis metrics (``MetricsBuilder.build`` → ``monitor.log(step=N)``)
and time-axis metrics (``PeriodicLogger`` → ``wandb.log`` on
``_timestamp``) now live on disjoint metric key sets. Mixing the same
key across two axes was both confusing (which axis does wandb pick?) and
wrong (``wandb.define_metric`` only supports one ``step_metric`` per key).
Changes:
- ``MetricsBuilder.build`` no longer takes ``dispatcher_gauges`` /
``dispatcher_drain``. The step-axis dict carries only per-batch /
step-aligned metrics (rewards, seq_lens, filter rates, timings, ...).
- ``Orchestrator.process_one_step`` no longer calls
``dispatcher.drain_metrics()`` at step boundaries. The dispatcher's
periodic logger is now the sole consumer of drained counters.
- ``RolloutDispatcher.drain_metrics`` removed; replaced by
``RolloutDispatcher.snapshot`` (= ``gauges() + metrics.drained()``).
``DispatcherMetrics.drained`` now returns a fixed key set
(``DRAIN_KEYS``: cancelled_train_rollouts / cancelled_eval_rollouts /
empty_rollouts_total / errored_rollouts_total / total_rollouts) so the
periodic logger can pre-declare every key at init via
``wandb.define_metric``. Per-env and per-error-type drain breakdowns
intentionally drop here — per-env appears in the step-aligned dict
already (via the rollout walk).
- Dispatcher's ``PeriodicLogger`` snapshot uses ``self.snapshot`` and
``metric_keys = list(self.gauges()) + list(DispatcherMetrics.DRAIN_KEYS)``.
- Drop ``inference.get_metrics()`` from periodic flow (was previously
merged into drain). Static pool returns ``{}`` anyway; elastic users
can add a separate periodic logger if needed.
* chore: revert stray uv.lock edit to match origin/main
A previous commit on this branch overwrote the
``[options].exclude-newer`` timestamp with the
``0001-01-01T00:00:00Z`` backwards-compat sentinel. Restore the actual
timestamp from ``origin/main`` — ``uv sync --all-extras`` then produces
no further diff, so this single revert is all that needs to land.
* refactor(orchestrator): tighten APIs + collapse dead state
A wave of follow-up cleanups on top of the orch redesign.
API rename + co-location:
- ``Orchestrator.process_one_step`` → ``ship_train_batch``. Mirrors
``log_eval_batch`` on the eval side and removes the verb collision
with ``TrainSink.process_rollout / group / batch`` (which are pure
data transformations; the orchestrator method is I/O + lifecycle).
- Split ``sources.py`` into ``train_source.py`` + ``eval_source.py``.
Two distinct abstractions deserved two files.
- Co-locate ``DispatcherMetrics`` and ``SchedMode`` with
``RolloutDispatcher`` in ``dispatcher.py``. ``types.py`` is now
reserved for cross-module dataclasses; module-local types live next
to their consumer.
- ``self.sched_mode`` → ``self.mode`` on the dispatcher.
Config collapse:
- Merge ``eval.skip_eval_on_resume`` into ``eval.skip_first_step``.
Resume and cold start go through one path: the startup eval fires
on whatever model state the orchestrator starts from, unless
``skip_first_step=True``. The old field is gone (not aliased — it's
the boolean opposite, so silent aliasing would flip behavior).
- ``EvalConfig.skip_first_step`` semantics inverted to match its
name: ``False`` (default) = run a startup eval; ``True`` = skip it.
Drain on max_steps (no out-of-band final eval pass):
- ``ship_train_batch`` flips the orchestrator into drain mode at
``max_steps``: ``RolloutDispatcher.disable_train_scheduling()`` stops
new train, in-flight + any triggered eval finish through the normal
pipeline, ``main_loop`` exits once ``dispatcher.is_idle``.
- Dropped the legacy ``await eval_env.evaluate(...)`` shutdown block —
interval-aligned eval at the final step completes through the sink.
Dead-state removal:
- ``asyncio.Semaphore`` for the inflight cap is gone. Dispatch is
single-task and every ``acquire`` is gated by an
``available_permits`` precheck, so a plain integer counter is the
whole story. ``release(n)`` collapses to a single subtraction.
- ``EvalSource.last_eval_step`` + the ``step <= last_eval_step``
monotonicity guard removed; ``trigger`` only has one (monotonic)
caller.
- ``EvalSource.resume_step``, ``trigger_at_start``'s resume-step
short-circuit, ``trigger``'s ``skip_eval_on_resume`` short-circuit,
and the dead "stale env" branch in ``next_fresh_group`` all gone.
- ``example_id`` backfills in train + eval sources and the
``raw.setdefault("example_id", -1)`` fallback in
``RolloutDispatcher.emit_rollout`` removed — verifiers guarantees
``example_id: int`` on both ``BaseRolloutInput`` and ``RolloutOutput``.
- Removed the per-instance ``self.logger`` cache on the orchestrator,
dispatcher, watcher, ckpt manager, inference-metrics collector, and
event-loop-lag monitor; all use ``get_logger()`` at the call site.
API symmetry:
- ``EvalSource.peek``/``pop`` collapsed into a single
``next_example(available_permits)`` that mirrors
``TrainSource.next_example()``: one call commits. The per-env cost
check lives inside the source (it owns the ``EvalEnvs`` reference);
the dispatcher just consumes the result.
Smoke: 5-step reverse-text run completes cleanly — startup eval at
step 0, eval epochs at steps 1–5, eval interval-aligned with
max_steps=5 completes after drain starts, ``Pipeline drained,
exiting main loop`` then clean trainer shutdown.
* fix(dispatcher): emit Cancelled markers for un-scheduled rollouts on drop_group
Off-policy cancellation of a non-group-scoring eval group lost any
not-yet-dispatched rollouts. ``drop_group`` only emitted a synthetic
``Cancelled`` marker for each in-flight task, then popped the
``GroupState``; rollouts still parked in ``group.rollouts_to_schedule``
silently disappeared. The sink's per-group arrival count never reached
``target_rollouts``, so ``process_group`` never fired for that group,
the per-epoch bucket never hit ``num_examples * group_size``, and no
``EvalBatch`` was emitted — no ``Eval @ step=N env=...`` log line, no
wandb metric for that epoch.
This bit the cluster ``hendrycks_math/sanity`` run: ``aime2024`` is
non-group-scoring with ``group_size=32`` and ~3-min epochs. During each
epoch the trainer crossed enough versions to exceed
``max_off_policy_steps=8`` (default), ``drop_group`` fired mid-dispatch
on at least one group, the un-scheduled remainder was lost, the sink
starved, and the eval epoch never logged anywhere visible to the user.
Group-scoring envs were immune: they dispatch the whole group as a
single task with ``rollout_count = group_size``, so after dispatch
``rollouts_to_schedule == 0`` and the existing in-flight-task loop in
``drop_group`` emits all ``group_size`` markers in one shot.
Fix: after the in-flight loop, emit ``group.rollouts_to_schedule`` more
synthetic ``Cancelled`` markers using the last seen meta, so the sink
hits ``target_rollouts`` and both the per-group and per-epoch
finalizations fire. The cancellation count returned by ``drop_group``
includes the un-scheduled remainder too, so the off-policy metric +
warning log reflect the full cancellation.
Reproduced + verified with the rl debug config + ``--orchestrator
.max-off-policy-steps 0`` (forces cancellation on every weight update).
Before fix: epochs with any cancellation would never emit.
After fix: all 6 epochs fire, ``Eval @ step=3 ... Rollouts: 128 |
Examples: 126`` shows 2 cancelled rollouts surfaced via ``n_cancelled``
while the epoch finalizes normally.
* refactor(sources): unify next_example API + relax over-strict train precheck
- Rename ``SchedMode`` → ``DispatcherMode`` (and the wandb metric
``dispatcher/sched_mode`` → ``dispatcher/mode``). The "Sched" prefix
was redundant inside the dispatcher's own namespace.
- ``self.sched_mode`` → ``self.mode`` on ``RolloutDispatcher`` (an
earlier turn renamed only the docstring strings; this lands the
actual identifier too).
- Unify ``TrainSource.next_example`` / ``EvalSource.next_example``
signatures: both now take ``available_permits: int`` and return
``dict | None`` carrying ``env_name`` (and, for eval, ``_eval_step``)
baked into the dict. The eval queue is ``deque[dict]`` instead of
``deque[tuple[str, dict, int]]``; ``enqueue`` copies the row and
stamps ``_eval_step`` so the same example can be enqueued at multiple
steps over the run without aliasing.
- Push the per-env cost lookup into each source. ``TrainSource``
precomputes ``env_costs[env.name] = group_size if env.requires
_group_scoring else 1`` at construction. The dispatcher's
``next_fresh_group`` collapses to a single symmetric body:
example = source.next_example(self.available_permits)
if example is None:
return None
env_name = example["env_name"]
Dropped the standalone ``available_permits < self.group_size``
precheck for train: it was right for group-scoring train envs (single
task acquires ``group_size`` permits) but over-strict for per-rollout
envs that only need 1 permit to open a fresh group. With the new
cost-aware precheck, per-rollout train envs become responsive in the
``1 ≤ available_permits < group_size`` window — they can start
dispatching immediately instead of waiting for a full group-sized
window. Group-scoring envs unchanged.
Verified end-to-end with the rl debug config (5 train steps, eval every
step, both happy path and ``--orchestrator.max-off-policy-steps 0``
forced-cancel variant). All 6 expected eval epochs fire in both, the
mode-transition log lines use ``DispatcherMode``, and the off-policy
cancel path still surfaces ``n_cancelled`` correctly (step 3 in the
forced-cancel run shows ``Rollouts: 128 | Examples: 126``).
* refactor(orchestrator): log overhaul + drain-cancel + multi-env support
A wave of log-readability cleanups + a few small functional changes
that landed alongside.
Functional:
- ``ship_train_batch``: ``step_time`` now measures the **pipeline cycle
time** (sink-emit → next sink-emit) instead of the orchestrator's
ship-side I/O cost. The previous value was misleading — it overlapped
asynchronously with rollout generation, so it always looked like
step time was 10ms when actual throughput was several seconds per
batch. New value is the meaningful throughput-per-step axis and
feeds both the success log and ``time/step`` in the wandb dict.
- ``RolloutDispatcher.cancel_inflight_train_rollouts``: kill in-flight
train rollouts at ``max_steps`` so wasted inference stops
immediately. Eval in-flight is preserved so any interval-aligned
eval at the final step still completes through the normal pipeline.
- ``TrainEnvConfig.group_size``: per-env group_size on the train side
(mirrors ``EvalEnvConfig.group_size``). Propagated from the top-level
``OrchestratorConfig.group_size`` in the post-init validator —
existing TOMLs unchanged.
- ``DispatcherMetrics``: dropped ``mode_transitions`` +
``eval_epochs_started`` (not interesting in practice).
- Silence the broader ``verifiers.*`` namespace by default; keep
``verifiers.serve`` routed through our loguru handler so env-server
lifecycle logs still surface with our formatting.
- New ``configs/debug/multi_env/reverse_text.toml`` (2 train envs + 2
eval envs at different intervals) to exercise multi-env paths in
the debug suite. Old ``configs/multi_reverse_text/rl.toml`` removed.
Log format:
- New ``format_time`` helper in ``utils/logger.py``: ``<1s → "50ms"``,
``<60s → "12.3s"``, ``<1h → "1m 13s"``, ``<1d → "2h 5m"``,
``≥1d → "1d 3h"``. Applied across every user-facing time log.
- Train success log rewritten as ``Train step N | dt | Reward X |
Error X% | Trainable A/B (C%) | Max Off-Policy N``, with per-env
``╰─ env_name | Ratio X% | Reward X | Error X% | Max Off-Policy N``
rows joined with ``\n\t\t`` for column alignment in multi-env.
- Eval success log: ``Eval step N (env) | dt | Reward X | Error X% |
Valid A/B (C%) | Max Off-Policy N``. Per-env elapsed via
``Orchestrator.eval_triggered_at[(env, step)]``.
- ``PeriodicLogger`` API: single ``collect()`` returns ``(body,
wandb_dict)`` so drain-on-read counters fire exactly once per emit.
Console format: ``Name | k=v | k=v | …`` with padded name
column so columns align across ``Event Loop`` / ``Dispatcher`` /
``Watcher`` rows.
- Dispatcher mode-switch log: ``Switching dispatcher mode to prefer
{eval,train} rollouts because {reason}``. Reasons rewritten as
full-sentence fragments.
- Eval trigger log: ``Starting evals in env1, env2 (N total
rollouts)`` — replaces verbose ``Eval @ step=N for env(s) …``.
- ``setup_filters`` takes ``kind: str`` so the setup log distinguishes
pre-batch vs post-batch (was identical for both).
- Stamped ``_off_policy_steps`` on each rollout's raw at emit time so
the train/eval success log can compute per-env Max Off-Policy from
``batch.rollouts`` (the ``Rollout`` wrapper's ``policy_version``
wasn't preserved through the sink).
- Added per-env ``arrivals_by_env`` + ``errors_by_env`` counters in
``TrainSink`` (reset per ship), carried on ``TrainBatchMetrics``
for the Error% field. Train errored rollouts are dropped at the
group level and don't reach ``batch.rollouts``, so they needed a
separate counter.
Smaller log demotions / renames:
- ``Initializing {env} ({verbose config})``, ``Loaded N
{train,eval} environment(s)`` → debug
- ``Reached max_steps`` → info (was success)
- Eval/train sink per-group ``Group | env=X example_id=Y | ...`` →
debug; per-rollout dispatch/completion/drain events on the
dispatcher → new debug logs ``dispatch/complete/drain {kind} |
group=<8> env=<env> | …``
- ``Shutting down N env server(s)`` → debug
- ``Orchestrator finished.`` gets trailing newline so the rl
entrypoint's ``Training finished!`` visually separates
- ``RL training finished!`` → ``Training finished!``
- ``EvalConfig.skip_first_step``: docstring shortened, field moved
next to ``interval`` (semantic neighbor).
Smoke: single-env (5 steps) and multi-env (4 steps) configs both
complete cleanly with the new format. Periodic logs render as Draft 1
from the design discussion.
* refactor(eval_source): unify trigger + trigger_at_start
Collapses the two trigger methods on ``EvalSource`` into one. The
first ``trigger(step)`` call (orchestrator startup) fires every env
unconditionally — that's the startup-eval semantics, evaluating
whatever model state we begin from (base model or resumed checkpoint)
before any train rollouts. Subsequent calls use the usual ``step %
interval == 0`` per-env gating.
``eval.skip_first_step`` is now exactly what its name says: a guard on
the very first ``trigger`` call. Nothing else changes.
Tracked via ``self.first_trigger: bool = True`` flipped on the first
call. ``Orchestrator.maybe_trigger_eval`` loses its ``at_start: bool``
/ ``step: int | None`` dual-mode signature in favor of a single
``step: int`` arg; both callers (startup + post-ship) pass
``self.progress.step``.
* refactor(orchestrator): tighten attr typing, drop event_loop_lag, polish
Five small follow-ups bundled together:
- Drop the local ``EventLoopLagMonitor`` and use the verifiers one
(``verifiers.utils.async_utils.EventLoopLagMonitor`` +
``EventLoopLagStats``). The verifiers monitor has the same shape —
``deque(maxlen=1000)`` + async ``run()`` — and adds a typed stats
snapshot. Dropped our local warn-threshold path; the periodic log
already surfaces lag values every interval, so a separate WARN was
redundant.
- ``Orchestrator`` typing cleanup: declare instance attributes as
class-level annotations instead of ``= None`` defaults, so pyright
sees ``self.dispatcher`` etc. as non-Optional at call sites. Dropped
seven type-narrowing asserts (``assert self.dispatcher and self
.train_sink``, etc.). The remaining three asserts capture real
invariants.
- ``EvalSource`` constructor takes non-Optional ``eval_envs`` /
``eval_config``. The orchestrator constructs it only when
``config.eval is not None``, so the source body is free of "is eval
configured?" branches. Dispatcher's ``eval_source: EvalSource | None``
parameter; the read sites (``queued_eval_examples`` / ``is_idle``)
null-check, the scheduling paths assert (only reached when eval is
configured).
- ``EvalConfig.validate_non_empty_envs``: model_validator asserting
``len(env) > 0`` so the invariant "``eval is not None`` ⇒ at least
one eval env" holds at the config layer.
- ``EvalSource.trigger`` unified: dropped the separate
``trigger_at_start``. The first call to ``trigger`` (orchestrator
startup) fires every env unconditionally — that's the startup-eval
semantics; ``skip_first_step`` gates that one call and nothing else.
Subsequent calls keep the ``step % interval`` per-env gating. The
helper is also tightened to a 7-line body via tuple-swap + list
comprehension.
- Config move: ``log_interval`` migrated from
``OrchestratorExperimentalConfig`` to ``LogConfig.interval`` (shared
with trainer's ``TrainerLogConfig``). The now-empty
``OrchestratorExperimentalConfig`` class + ``OrchestratorConfig
.experimental`` field are removed.
Log polish:
- Renamed ``ship_train_batch`` → ``finalize_train_batch`` and
``log_eval_batch`` → ``finalize_eval_batch`` so the two terminal
per-batch methods share a verb.
- ``Train step N | dt | …`` and ``Eval step N (env) | dt | …``
right-pad ``dt`` to 7 chars (``format_time``'s max width) so the
``|`` columns visually align across consecutive lines regardless of
whether ``dt`` is ``57.4s`` or ``1m 14s``.
- Eval trigger reason strings rewritten as full-sentence fragments
so ``Switching dispatcher mode to prefer {eval,train} rollouts
because {reason}`` reads naturally.
- ``Orchestrator finished.`` no longer gets a trailing newline.
- ``EvalConfig.skip_first_step`` docstring shortened to only explain
the ``True`` case.
* refactor(orchestrator): consolidate periodic logs, per-env breakdown, polish
- Unified ``PeriodicLogger`` on the orchestrator replaces the three
separate ones (Event Loop / Dispatcher / Watcher). Single
``Orchestrator.collect_pipeline_view`` reads dispatcher gauges +
drain, watcher gauges, sink batch progress, and lag stats in one
shot. Headline carries the aggregate (total inflight, total
finished this tick, train-batch fill); indented ``╰─`` rows break
it down per env, with the eval rows also reporting their epoch
progress (``batch=arrivals/expected``). Eval rows appear only when
an epoch is accumulating.
- New ``RolloutDispatcher.inflight_by_env`` property: ``dict[(kind,
env), count]``. ``finished_by_env`` for the same axis comes from
the existing ``DispatcherMetrics.total_rollouts_by_env`` (drained
per tick) — the pipeline view snapshots it before calling
``metrics.drained()`` so the orchestrator is the sole drain
consumer.
- ``EvalSource.trigger`` now interleaves enqueueing across fired envs
(round-robin via ``itertools.zip_longest``): the queue becomes
``A_ex1, B_ex1, A_ex2, B_ex2, …`` instead of ``A_*, then B_*``.
Combined with ``try_schedule``'s "continue existing group" branch,
per-example ``group_size`` rollouts still ship back-to-back
(prefix-cache locality preserved); only the across-env ordering
changes.
- Per-batch success logs gain ``Turns`` (avg ``len(trajectory)``) and
``Truncation`` (``mean(is_truncated)``) — shown in headline + per-env
``╰─`` rows on train, plus in the eval headline. ``EvalBatchMetrics``
gains ``num_turns_mean`` so ``eval/<env>/num_turns/mean`` ships to
wandb too.
- ``post_batch_filters``: dropped the ``Field(... validation_alias=
AliasChoices("post_batch_filters", "filters"))`` shim + the
``OrchestratorConfig.filters`` @property. Replaced with a
``@model_validator(mode="before")`` that renames ``filters`` →
``post_batch_filters`` for TOML/CLI input. Runtime code accesses
``cfg.post_batch_filters`` only.
- Restored the (now empty) ``OrchestratorExperimentalConfig`` class +
``OrchestratorConfig.experimental`` field so adding a future
experimental toggle doesn't need to re-introduce both at once.
- Inference engine pause/resume logs: renamed
``Pausing inference engines for weight update`` →
``Updating policy in-flight to v{step}``; demoted the ``All inference
engines paused / resumed`` bookends to debug.
- ``Reached max_steps=N, draining pipeline`` → ``Draining pipeline``;
the "any triggered eval will complete" tail is now "any in-flight
evals will complete".
- ``Shutting down N env server(s)`` log trimmed (no more "waiting for
sandbox cleanup..." trailer).
* fix(orchestrator): pipeline log per-env reconciliation + step-0 step time
- ``Orchestrator.collect_pipeline_view`` headline: drop the ``finished N``
per-tick-delta term and replace the per-env ``dispatched / finished``
pair with ``inflight / batch``. Per-env values now sum to the
aggregate (``inflight`` totals match headline ``train=…, eval=…``;
``batch`` totals match headline ``train batch X/Y``). Previously the
headline mixed cumulative state with tick-delta counters, so per-env
rows visibly disagreed with the aggregate.
- Per-env ``╰─`` rows now only render when there's more than one train
env (or more than one eval env). For single-env runs the aggregate
already is the per-env view, so the rows were pure noise.
- Single-eval-env case folds the active epoch's progress into the
headline (``| eval <env>@<step> batch=arrivals/expected``). Multi-eval
still uses the per-epoch rows.
- ``TrainSink.pending_batch_by_env`` returns the per-env post-error-
filter survivor counts currently in ``pending_batch`` — fuel for the
per-env ``batch=…`` column above. O(pending_batch) walk; pending
batch is bounded by ``batch_size`` so it's cheap.
- ``Orchestrator.start`` now anchors ``self.last_batch_at`` to
``perf_counter()`` right before ``main_loop`` (after spawning the
dispatcher / watcher / lag tasks). Step 0's ``step_time`` now
measures startup → first-batch wall-clock instead of reporting
``0ms`` — verified at ``9.3s`` on the multi-env smoke run.
* chore(orchestrator): move Error/Truncation to end of success log lines
Train + eval ``SUCCESS`` lines now order the columns by relevance:
``Reward → Trainable/Valid → Turns → Max Off-Policy`` first, then
``Error``/``Truncation`` (lower-priority diagnostics) trailing. Applies
to the train headline, train per-env ``╰─`` rows, and the eval
success line.
Before:
Train step 0 | 9.3s | Reward 0.08 | Error 0.0% | Trainable 96/128
(75.0%) | Turns 1.0 | Truncation 89.8% | Max Off-Policy 0
After:
Train step 0 | 9.3s | Reward 0.08 | Trainable 96/128 (75.0%) |
Turns 1.0 | Max Off-Policy 0 | Error 0.0% | Truncation 89.8%
* chore(trainer): use format_time for per-step success log
Per-step ``Step N | Time: …`` line in ``trainer/rl/train.py`` and
``trainer/sft/train.py`` now goes through ``format_time`` so durations
> 60s render as ``1m 5s`` / ``1h 5m`` instead of ``65.34s``. Matches the
formatting already used by the orchestrator's success lines.
* fix(dispatcher): keep dispatching eval group tails after queue empties
``RolloutDispatcher.fill_inflight`` had a bug where, once the eval
source's queue emptied, the second ``if not self.eval_source: return``
guard short-circuited ``try_schedule("eval")`` entirely — including its
step-1 branch that continues *existing* eval groups one rollout at a
time. For non-group-scoring eval envs (``requires_group_scoring=False``,
e.g. ``aime2024``), this orphaned the last group's tail: when the final
``next_example`` call popped the queue and opened group N with
``rollouts_to_schedule = group_size - 1``, the next ``fill_inflight``
iteration saw an empty queue + nonzero ``inflight_eval`` and returned
before reaching the continuation branch. The remaining ``group_size -
1`` rollouts were never dispatched, so the eval sink's per-epoch bucket
reached only ``num_examples × group_size − (group_size − 1)`` arrivals
and ``process_batch`` never fired. The epoch silently disappeared (no
``Eval step …`` log, no wandb point), and ``DispatcherMode`` eventually
flipped back to ``PREFER_TRAIN`` once inflight cleared — taking the
unfinished epoch's bookkeeping with it.
Fix: drop the early return. ``try_schedule("eval")``'s step-1 branch
continues existing eval groups regardless of source state, and step 2
(``next_fresh_group``) already returns ``None`` when the source is
empty — so an empty source naturally results in ``scheduled = False``
and ``fill_inflight`` bails on the next line.
Added a debug invariant: when the dispatcher flips
``PREFER_EVAL → PREFER_TRAIN``, walk ``self.groups`` for any eval group
with ``rollouts_to_schedule > 0`` and log an error. With this fix in
place this should never fire — but if a future change re-introduces
the orphan behavior it'll fail loudly instead of silently dropping the
epoch.
Verified on the multi-env smoke (``configs/debug/multi_env/
reverse_text.toml``): both eval epochs finalized cleanly at
``Valid 64/64 (100.0%)``, no orphan-error lines.
* feat(configs): rlm_swe qwen3-4b-thinking on 2-node slurm
Minimal RL config: Qwen3-4B-Thinking-2507 on rlm_swe default taskset
for train, SWE-Bench-Verified-Quick for eval. 65k context, 2-node SLURM
multinode (1 train × 1 infer × 8 GPUs each). Trainer cp=2 / FSDP=4 +
``flash_attention_2`` (default); inference dp=8 with hermes tool
parser. Validated via ``rl --dry-run``.
* fix(orchestrator): pipeline-view accounting + drain-switch overlap finish
Two related bugs in the eval-side pipeline view:
1. ``DispatcherMode.PREFER_EVAL → PREFER_TRAIN`` was gated on
``inflight_eval_count == 0`` in addition to ``not eval_source``.
That meant once every eval example was *dispatched* but a long tail
was still in flight (e.g. 480/480 dispatched, ~30 permits idle),
the remaining permits stayed idle until the entire eval drained.
The PR's drain-switch overlap explicitly promises the opposite:
when the eval source is exhausted, train resumes scheduling while
the eval tail completes naturally. New gate is
``not bool(eval_source) and no eval group has rollouts_to_schedule
> 0`` — i.e. nothing more to dispatch for eval. The previous
``orphan`` sanity-check is no longer needed because that's exactly
the new gate's invariant.
2. ``EvalSink.epoch_progress`` only counted ``pending_batches``
(groups that have already hit ``group_size`` and been moved to
the per-epoch bucket). Rollouts sitting in ``pending_groups``
(partial groups not yet at ``group_size``) were invisible, so
the pipeline log showed ``inflight 408 + batch 0 = 408`` instead
of ``= 480 = expected``. Now ``epoch_progress`` aggregates both
``pending_batches`` and the per-(env, eval_step) sum across
``pending_groups``, so ``inflight + batch == expected`` holds
tick-by-tick as the user expects.
Also: ``configs/rlm_swe/qwen3_4b.toml`` drops ``seq_len`` from 65536
to 4096 (orchestrator + inference ``max_model_len``) so individual
rollouts finish faster during initial dev iteration. Bump back up
for production runs.
* fix(sinks): pipeline view fills per-rollout for non-group-scoring envs
Both ``TrainSink.batch_progress`` / ``pending_batch_by_env`` and
``EvalSink.epoch_progress`` previously counted only rollouts that had
already moved from ``pending_groups`` (per-group buffer) into the
batch / per-epoch bucket — so the pipeline view ticked in ``group_size``
increments rather than per-rollout, even though the underlying envs
are per-rollout scored.
Now both counters add in-progress ``pending_groups`` rollouts for envs
where ``env.requires_group_scoring == False``. Group-scoring envs
(rubric has group-level reward funcs) still only contribute via the
finalized bucket — their rollouts only make sense as a unit, so the
counter should still jump by ``group_size`` for them.
``TrainSink.in_progress_groups`` is the shared helper that walks
``pending_groups`` with the group-scoring gate, used by both
``batch_progress`` (aggregate count + token count) and
``pending_batch_by_env`` (per-env breakdown that sums to the aggregate).
* chore(configs): drop hendrycks_math/sanity seq_len 8192 → 4096
Restores ``rlm_swe/qwen3_4b`` seq_len back to 65536 (the previous
drop was meant for the sanity config, not the rlm_swe one).
* refactor(eval_sink): rename epoch_progress → batch_progress
Mirrors ``TrainSink.batch_progress`` for consistency. Same shape and
semantics — returns a list (one entry per accumulating ``(env, eval_step)``
batch) since eval can have multiple batches in parallel.
* chore(orchestrator): reformat pipeline log + drop avg@k wandb metric
Pipeline ``PeriodicLogger`` line is now a single sentence:
Currently {train_inflight}/{max} [(env=N, …)] inflight train
rollouts[ and {eval_inflight} [(env=N, …)] eval rollouts]; got
{train_batch}/{batch_size} [(env=N, …)] rollouts in training batch
[ and {n}/{target} in {env}[, {n}/{target} in {env2}…]]
Per-env ``(env=N, …)`` breakdowns inline behind the corresponding
aggregate and only appear when ``len(train_envs) > 1`` /
``len(eval_envs) > 1``. The eval halves drop entirely when nothing
is accumulating.
Drops the redundant ``eval/<env>/avg@<group_size>`` wandb scalar from
``EvalBatchMetrics.to_wandb_dict`` — it was just ``reward/mean`` under
a different name (the ``group_size``-tagged ``avg@k`` aggregate is
semantically meaningless when ``group_size`` doesn't match the
pass-at-k denominator). ``reward/mean`` still ships.
* chore(configs): bump default LogConfig.interval 5s → 10s
Shared periodic-logger interval. 5s was a bit chatty for steady-state
RL/SFT runs; 10s keeps the pipeline view useful without dominating the
log file.
* chore(orchestrator): reword train + eval success log prefixes
- ``Train step N | …`` → ``Step N | …`` (the "train" qualifier was
redundant; the trainer side already prefixes its log with
``[trainerN]`` and the orchestrator side is the only other place
this fires).
- ``Eval step N (env) | …`` → ``Finished evaluating env from step N | …``
(more explicit about what ``N`` is — the policy version when the
eval epoch was triggered, not when it finished).
* chore(periodic_logger): drop name-column prefix from console emit
There's only one ``PeriodicLogger`` instance now (the orchestrator's
unified pipeline view), so the padded ``Pipeline | …`` column
prefix is just noise. Log the ``collect()`` body verbatim instead.
Also drop ``NAME_WIDTH`` and refresh the module docstring to reflect
the single-instance design.
* chore(orchestrator): pipeline log puts batch progress before inflight
Step progress leads:
Got {train_batch}/{batch_size} [(env=N, …)] rollouts in training
batch[ and {n}/{target} in {env}, …]; currently {train_inflight}/
{max} [(env=N, …)] inflight train rollouts[ and {eval_inflight}
[(env=N, …)] eval rollouts]
Reads top-down: what we're working toward (the batch) before what's
in flight (the means to get there).
* chore(orchestrator): show batch-progress percentages in pipeline log
``Got 5/512 (1.0%) rollouts in training batch and 29/480 (6.0%) in
aime2024; …`` — percentages make it easier to glance-read how close
we are to shipping the next batch / closing the eval epoch.
* chore(configs): hendrycks_math/sanity batch 512 → 256, keep max_inflight 512
2× oversampling so the dispatcher always has rollouts pre-cooked when
one ships, instead of running at exactly batch_size and stalling.
* chore(orchestrator): drop /max from train-inflight pipeline log
``currently 61/512 inflight train rollouts`` → ``currently 61
inflight train rollouts``. The global cap doesn't add meaningful
context in steady state (and the cap is shared with eval, so the
``X/max`` reading was misleading anyway).
* chore(orchestrator): drop env list from eval-trigger mode-flip reason
``Switching dispatcher mode to prefer eval rollouts because eval was
triggered for aime2024 at step 0`` → ``…because eval was triggered at
step 0``. The next-line ``Starting evals in aime2024 (...)`` log
already names the fired env(s); no need to repeat it in the mode
transition reason.
* chore(configs): drop verbose comment on EvalConfig.validate_non_empty_envs
* chore(configs): drop verbose docstring on OrchestratorExperimentalConfig
* chore(configs): drop orch-v2 references from pre_batch_filters docstring
* chore(configs): trim verbose comment on train group_size propagation
* chore(configs): generic LogConfig.interval docstring
* chore(eval_source): drop TrainSource cross-reference from docstring
* chore(filters): revert setup_filters docstring to one-liner
* refactor(orchestrator): typed rollout dataclasses, raw stays pristine
Replace the magic-string ``raw["_x"]`` stamping pattern with typed
fields on dedicated dataclasses. ``vf.RolloutOutput`` is no longer
mutated by prime-rl; all prime-rl bookkeeping lives on the wrapper.
New types in ``orchestrator/types.py``:
- ``InflightRollout`` (was ``RolloutMeta``) — per-task scheduling state
held by the dispatcher while a rollout is being generated.
- ``FinishedRollout`` (was ``Rollout``) — the atomic unit on the
dispatcher's output queue. Holds ``raw`` + ``env_name`` /
``example_id`` / ``group_id`` / ``policy_version`` / ``off_policy_steps``
on typed fields. Convenience properties: ``error``, ``reward``,
``is_truncated`` (read from ``raw``).
- ``TrainRollout(FinishedRollout)`` — adds ``samples`` (populated by
``TrainSink.process_rollout``), ``advantage`` (set by
``compute_advantages``), ``is_filtered`` + ``filter_results`` (set
by ``apply_filters``).
- ``EvalRollout(FinishedRollout)`` — adds ``eval_step`` (policy version
at trigger time; the eval sink's bucket key).
``FinishedRollout.to_dict()`` materializes the dataclass + ``raw``
back into a single ``vf.RolloutOutput``-shaped dict at I/O boundaries
(``save_rollouts``, ``monitor.log_samples`` / ``log_eval_samples``),
so the JSONL on disk and the wandb sample tables are unchanged
shape-wise.
Knock-on changes:
- ``RolloutDispatcher.out_q: Queue[FinishedRollout]``. ``emit_rollout``
builds ``TrainRollout`` / ``EvalRollout`` directly — no more
``raw[...] = ...`` lines.
- Sinks accept ``TrainRollout`` / ``EvalRollout``; pending buffers are
typed lists. ``main_loop`` discriminates via ``isinstance``.
- ``apply_filters(rollouts: list[TrainRollout])`` + ``RolloutFilter
.check(rollout: TrainRollout)``: filters read ``rollout.raw`` for
trajectory inspection, ``rollout.advantage`` for the zero-advantage
check; they write ``rollout.is_filtered`` / ``rollout.filter_results``.
- ``compute_advantages(rollouts: list[TrainRollout])`` writes to
``rollout.advantage``. The public ``AdvantageFn`` API
(``AdvantageInputs.rollouts: list[vf.RolloutOutput]``) is unchanged
— custom advantage functions still receive raw vf dicts.
- ``MetricsBuilder.build`` and the orchestrator's train/eval success
log lines read attributes off the dataclasses; ``r["env_name"]`` /
``r["advantage"]`` / ``r.get("_off_policy_steps", 0)`` all become
attribute accesses.
No public API or wandb / TOML config surface change. The on-disk
rollout JSONL keeps the same shape via ``.to_dict()``.
* fix(trajectories): thread env_name as kwarg into interleave_rollout
Followup to the typed-rollout refactor: ``raw`` no longer carries
``env_name`` (prime-rl metadata moved to the dataclass), but
``interleave_rollout`` → ``make_sample`` was still reading
``output["env_name"]`` to populate ``TrainingSample.env_name``,
which now KeyErrors.
Pass ``env_name`` as an explicit kwarg from ``TrainSink.process_rollout``
(reads ``rollout.env_name``) so the helper doesn't depend on
prime-rl-stamped fields on ``raw``. ``TrainingSample.env_name`` still
gets overwritten by ``process_group`` later, but having it set
correctly at ``make_sample`` time avoids the empty-string window for
log/debug paths that introspect samples before group finalize.
Smoke verified: 3 train steps + 2 eval epochs on
``configs/debug/multi_env/reverse_text.toml`` — both ``Finished
evaluating`` lines and ``Step N`` lines render cleanly, no errors.
* chore(types): drop ``_``-prefix from rollout metadata keys in to_dict
The ``_``-prefix convention used to mark "prime-rl-stamped, not env-
provided" fields on the in-memory raw vf dict. Since the typed-rollout
refactor those fields no longer live on ``raw`` at all — they're
dataclass attrs — so the public-key prefix is meaningless. Rename in
``to_dict`` (used at I/O boundaries):
- ``_policy_version`` → ``policy_version``
- ``_off_policy_steps`` → ``off_policy_steps``
- ``_eval_step`` → ``eval_step``
Also rename the internal-queue handoff key from ``EvalSource`` →
``RolloutDispatcher`` for symmetry:
- ``example["_eval_step"]`` → ``example["eval_step"]``
Verified on the multi-env smoke: JSONL on disk now uses the public
keys (no leading underscore), and downstream rollout consumers can
introspect prime-rl metadata without the magic-string convention.
* feat(types): add FinishedRollout.rollout_id; fix advantage grouping
- New per-rollout UUID ``FinishedRollout.rollout_id`` (default
``uuid.uuid4()``). The only safe key for tracing a specific rollout
through its lifecycle (dispatch → sink → batch → JSONL on disk).
Neither ``(env_name, example_id)`` nor ``group_id`` is unique on
its own — the same example can be re-sampled as multiple groups,
and one group contains ``group_size`` rollouts. ``to_dict()`` now
emits ``rollout_id`` + ``group_id`` (both as strings) alongside the
rest of the prime-rl metadata.
- ``compute_advantages`` was grouping rollouts by ``(env_name,
example_id)`` — wrong when the same example is concurrently in
flight as two distinct groups (small datasets, multi-epoch eval).
Two distinct groups would have been merged into one for advantage
computation, polluting the GRPO baseline. Switched to grouping by
``group_id`` (the dispatcher's UUID — unique by construction).
Smoke verified on the multi-env config: 64 rollouts in step-0 eval
have 64 distinct ``rollout_id``\\ s and 16 distinct ``group_id``\\ s
(64 rollouts / 4 group_size = 16 groups), all visible in the JSONL.
* chore(orchestrator): reword eval success log 'Finished evaluating' -> 'Evaluated X (Step N)'
* refactor(advantage): drop grouping logic, cache advantage_fn on the sink
``TrainSink.process_group`` already calls ``compute_advantages`` with a
single group's survivors, so the internal ``defaultdict[group_id]``
re-grouping was always a no-op (always one bucket). Rename to
``assign_advantages``, drop the grouping, and just call ``advantage_fn``
on the rollouts as one cohort.
Also cache the ``advantage_fn`` once at ``TrainSink.__init__`` via
``setup_advantage_fn(config)`` — previously it was rebuilt per
``process_group`` call, which for ``CustomAdvantageConfig`` does an
``import_object`` per group. Now built once.
``AdvantageInputs.rollouts: list[vf.RolloutOutput]`` (public API)
unchanged.
Verified on the multi-env smoke: 3 train steps + 2 eval epochs ship
cleanly; advantage shape preserved.
* chore(orchestrator): drop Valid X/Y from eval success log (redundant with Error %)
* chore(orchestrator): bump per-env success-log indent by one space
* fix(orchestrator): drop_group orphan, empty-batch spin, resume eval dup
Three legit bugs from the recent audit:
1. ``RolloutDispatcher.drop_group`` orphaned the unscheduled tail of a
group when ``last_meta`` was ``None`` — reachable via the multi-group
off-policy-cancellation race (group A's drop yields at
``out_q.put``, group B's last inflight task completes naturally
between ``on_new_version``'s snapshot and ``drop_group(B)`` running,
so by the time we reach group B's drop, ``self.inflight`` has no
entries for B). For non-group-scoring envs with
``rollouts_to_schedule > 0`` on B, the sink waits forever for
``group_size`` arrivals. Fix: synthesize a minimal
``InflightRollout`` from the ``GroupState`` when ``last_meta is
None`` and emit the markers; sink finalizes the partial group.
2. ``Orchestrator.finalize_train_batch`` spun forever when every batch
yielded ``n_trainable == 0`` (e.g. zero-advantage enforce on a
homogeneous-reward dataset, mis-configured pre/post filters). Added
a ``consecutive_empty_batches`` counter; abort after
``MAX_CONSECUTIVE_EMPTY_BATCHES = 10`` with a clear error pointing
at the filter / difficulty configuration. The counter resets on
the first non-empty batch.
3. ``EvalSource.trigger`` re-fired interval-aligned envs on resume
from a checkpoint (e.g. resume at step 50 with ``interval=50`` →
the eval that already completed pre-checkpoint runs again). Two
complementary guards:
- ``Progress.last_eval_step_by_env: dict[str, int]`` (new field,
persisted via the existing ``CheckpointManager``) records the
last fired step per env. ``EvalSource.trigger`` reads + writes
this dict via a shared reference; envs are skipped when
``step <= last_eval_step_by_env[env]``.
- ``EvalSource.__init__`` takes ``is_resumed: bool`` (wired from
the orchestrator's ``resume_step is not None``). On resume the
startup-eval "fire all" behaviour is suppressed entirely so the
user doesn't get a duplicate baseline at the resumed step.
The ``Progress`` change is backwards-compatible with existing
checkpoints — the load loop uses ``setattr`` on a fresh ``Progress()``
that already has the default ``{}``, so an old checkpoint without
the field just leaves it empty.
Verified on the multi-env smoke run: 3 train steps + 2 eval epochs
ship cleanly with the new wiring.
* chore(orchestrator): drop 'Starting orchestrator step N' info log
* refactor(dispatcher): rename + slim down wandb metrics
Periodic-axis metric shape changes (``_timestamp`` axis):
Removed:
- ``dispatcher/inflight_permits`` (redundant with ``inflight_train``+``eval``)
- ``dispatcher/available_permits`` (derivable from ``max_inflight``)
- ``dispatcher/total_rollouts`` (was unused after the pipeline-view
refactor stopped reading it)
- ``dispatcher/empty_rollouts_total`` (empty trajectories are folded
into ``errored`` — they're flagged with ``error.error = "EmptyTrajectory"``
already, so the separate counter was redundant)
Renamed:
- ``dispatcher/queued_eval_examples`` → ``dispatcher/queued/eval``
- ``dispatcher/cancelled_train_rollouts`` → ``dispatcher/cancelled/train``
- ``dispatcher/cancelled_eval_rollouts`` → ``dispatcher/cancelled/eval``
- ``dispatcher/errored_rollouts_total`` → ``dispatcher/errored/train`` +
``dispatcher/errored/eval`` (split by kind)
- ``watcher/last_update_weights_time_s`` → ``watcher/last_update_weights_time``
- ``watcher/last_wait_for_ckpt_time_s`` → ``watcher/last_wait_for_ckpt_time``
Added: per-env breakdowns under each cancelled/errored prefix:
- ``dispatcher/cancelled/<env>`` (sum across kinds, per env name)
- ``dispatcher/errored/<env>``
``DispatcherMetrics`` now tracks ``(kind, env_name) → count`` instead
of separate ``cancelled_train_rollouts`` / ``cancelled_eval_rollouts``
ints and a flat ``errored_rollouts_by_env`` dict. ``record_cancellation``
and ``record_error`` take ``env_name`` explicitly. The static
``DRAIN_KEYS`` constant becomes a ``drain_keys(train_envs, eval_envs)``
classmethod so the orchestrator can pre-register the per-env keys for
``wandb.define_metric`` at construction time.
``handle_completed_rollout`` no longer calls ``record_empty`` —
empty trajectories are promoted to ``error.error = "EmptyTrajectory"``
and counted via the regular ``record_error`` path.
Verified on the multi-env smoke run: 3 train steps + 2 eval epochs,
no errors.
* chore(orchestrator): drop verbose attribute-schema comment block
* chore: trim excessive code comments + docstrings
Pass over every file in the diff to drop comments that just narrate the
code or repeat what the names already say. Kept comments only where
they add non-obvious intent / constraints / invariants.
Removed leftover references to pre-PR / legacy logic (e.g. the
``orchestrator v2`` naming, ``no asyncio.Semaphore needed``, ``no buffer
state`` rationales, the multi-paragraph rationale for the
``filters → post_batch_filters`` alias, the ``client`` / ``model``
shortcuts rationale, etc.). The aliases themselves are retained as
documented current backward-compat behaviour, just without the
historical justification.
No behaviour change; smoke verified on the multi-env config.
* refactor(types): trim types.py 255 → 212 lines
- Consolidate three ``to_dict`` overrides into one ``FinishedRollout``
method that walks ``dataclasses.fields(self)`` so train-only fields
(``samples`` / ``advantage`` / ``is_filtered`` / ``filter_results``)
and eval-only fields (``eval_step``) pick themselves up via subclass
inheritance. UUID fields stringify automatically; ``filter_results``
still renames to ``filters`` for the JSONL view; ``samples`` and
``raw`` stay skipped.
- Drop section dividers and the multi-paragraph module docstring.
- Slim per-dataclass docstrings to single lines / single paragraphs.
Verified the JSONL output keys are unchanged (``rollout_id``,
``group_id``, ``env_name``, ``example_id``, ``policy_version``,
``off_policy_steps``, ``advantage``, ``is_filtered``, ``filters``)
on the multi-env smoke run.
* test: fix unit tests for typed rollouts + dropped modules
- Delete ``test_buffer.py`` and ``test_scheduler.py`` — the
``Buffer`` / ``Scheduler`` modules were removed entirely.
- Update ``test_filters.py`` to construct ``TrainRollout``\\ s instead
of raw dicts: ``apply_filters`` and ``RolloutFilter.check`` now take
typed rollouts, assertions read ``r.filter_results`` /
``r.is_filtered`` / ``r.reward`` / ``r.raw["..."]``.
- Update ``test_advantage.py``: ``compute_advantages`` was renamed to
``assign_advantages`` and no longer groups internally (the sink
groups by ``group_id`` upstream and calls ``assign_advantages``
per group). Replaces the old grouping tests with three single-group
tests; the ``default_advantage_fn`` tests over ``AdvantageInputs``
are unchanged.
- Update ``test_orchestrator_setup.py``: patch the renderer factory
at its source (``renderers.base.create_renderer``) since
``setup_student_inference_pool`` does a deferred import; drop the
``logger=`` arg that no longer exists.
- Update ``test_trajectories.py``'s ``interleave_rollout`` shim to
pass ``env_name`` as a kwarg (the helper no longer reads it from
the rollout dict).
CPU unit suite: 443 passed, 6 skipped. Trainer-side GPU tests
(``test_qwen3_5_moe`` / ``test_qwen3_5_moe_vlm``) still fail without
CUDA, which is the same on ``main``.
* refactor(configs): drop obsolete buffer + cancel-inflight fields
Remove four config surfaces that the new orchestrator never reads:
- ``EvalConfig.cancel_inflight_rollouts_on_eval`` — the drain-switch
overlap (PREFER_TRAIN ⇄ PREFER_EVAL transitions level-triggered on
``EvalSource`` emptiness) replaces it.
- ``OrchestratorConfig.buffer = BufferConfig()`` field — default-
instantiated, never accessed.
- ``BufferConfig`` class (seed / easy_threshold / hard_threshold /
easy_fraction / hard_fraction / online_difficulty_filtering /
hash_keys + the threshold validator) — replaced by
``pre_batch_filters``.
- ``CheckpointConfig.skip_buffer`` — no buffer to skip-load.
Public TOMLs (``configs/{math_group, nemotron_debug, wiki_search,
hendrycks_math, nemotron_4node}/rl.toml``) had inert
``[orchestrator.buffer]`` blocks that would now fail
``extra=forbid``; stripped them.
The private submodule (``configs/private/``) still references these
keys in several files — those need to be updated separately.
## Breaking
Existing configs that set any of the four removed keys will now
raise ``ValidationError: Extra inputs are not permitted``. Migration:
- ``cancel_inflight_rollouts_on_eval``: delete (drain-switch handles it).
- ``buffer.online_difficulty_filtering = true`` → set
``pre_batch_filters`` with ``ZeroAdvantageFilterConfig(enforce=True)``
(the default) and drop the buffer block.
- ``buffer.easy_threshold`` / ``hard_threshold`` / ``easy_fraction`` /
``hard_fraction`` / ``hash_keys`` / ``seed``: no replacement.
- ``ckpt.skip_buffer``: delete.
CPU unit suite: 76 passed in the orchestrator subset.
* refactor: read seq/completion lens from vf.RolloutOutput.token_usage
Drop get_prompt_len / get_seq_len / get_completion_len from vf_utils
and read final_input_tokens / final_output_tokens directly from
vf.RolloutOutput["token_usage"] at the call sites. Verifiers populates
these for every real rollout; synthetic error markers set them to 0.
Semantically equivalent to the old trajectory-walking helpers (final
context size at end of rollout) but a direct field read from the source
of truth.
* fix(orchestrator): revert eval reward key to avg@N; migrate example buffer blocks
- EvalBatchMetrics: log eval reward as avg@{group_size} (matches main),
drop n_rollouts/n_examples/valid_rate from wandb output, add
num_turns/{min,max} alongside num_turns/mean.
- examples: replace removed [orchestrator.buffer] blocks. Configs that used
online_difficulty_filtering migrate to an enforced zero_advantage
pre-batch filter; threshold-only (difficulty-pool) blocks are dropped.
* feat(configs): warn + migration guide for removed [orchestrator.buffer]
Add a before-validator that pops the removed buffer block so legacy
configs still parse, and emits a FutureWarning. When
online_difficulty_filtering was set, the warning includes the direct
replacement (enforced zero_advantage pre-batch filter); otherwise it
notes difficulty pools are removed with no replacement.
* chore(configs): restore unchanged docstrings/comments to minimize diff
Revert incidental docstring/comment trims in fold_student_shortcuts and
the renderer/pool_size validators (and max_off_policy_steps) back to
main's wording. These functions' logic is unchanged; only their comments
had been reworded, adding review noise.
* feat(rlm-swe): single-node qwen3.5-4b config; pin rlm-swe as workspace member
- New configs/rlm_swe/qwen35_4b.toml: 4+4 GPU single-node, seq_len=65536,
cp=2 + cp_style=ulysses (Qwen3.5 hybrid attention rejects ring style),
max_inflight_rollouts=512, pre_run_command that cleans matching sandboxes.
- Add deps/research-environments/environments/rlm_swe to the workspace +
the envs extra so `uv sync --all-extras` installs it; previously
runtime-installed via `prime env install`, so each sbatch's in-job sync
uninstalled it before `uv run rl` could import the env.
- Drop the now-superseded configs/rlm_swe/qwen3_4b.toml.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(rlm-swe): qwen3.5-4b config contents + workspace install for rlm-swe
Settings inside the renamed config:
- Single-node 4+4 GPUs, seq_len=65536, max_inflight_rollouts=512.
- trainer.model.cp=2 with cp_style="ulysses" — Qwen3.5 is a hybrid
linear-attention/SSM arch and rejects cp_style="ring".
- pre_run_command kills any sandboxes labelled rlm-swe-qwen35-4b so
stale sandboxes from a prior run never linger.
- Output under /beegfs/mika/ instead of /beegfs/outputs/.
Workspace plumbing for rlm-swe:
- Add deps/research-environments/environments/rlm_swe as a workspace
member with the corresponding tool.uv.sources entry.
- Add rlm-swe to the envs extra so `uv sync --all-extras` installs it.
Previously it was runtime-installed via `prime env install`, so each
sbatch's in-job sync uninstalled it before `uv run rl` could import.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix: eval metric correctness + integration-test log parsing
- eval_sink: completion_len/* uses final_output_tokens only (was
final_input+output), matching envs.py and the historical metric meaning.
- eval_sink: average each pass@k only over examples that produced it
(skip missing high-k), matching pandas NaN-skipping; fixes downward
bias on errored eval epochs.
- dispatcher: drop the per-rollout dispatch + per-group complete debug
logs (too fine-grained).
- tests/utils: parse the new orchestrator log format (Reward without a
colon; eval line reports Reward instead of Avg@K=).
* refactor(orchestrator): pipeline-log clarity, per-rollout offload, lifecycle + cleanup
- Pipeline log: split train batch progress (pending_batch, capped at target)
from a separate "(+N buffered)" partial-group count; unified inflight tail
"(train=, eval= | per-env)"; eval batch shown as "{env} done/total (pct)".
- Image offload moved from per-batch to per-rollout (TrainSink.process_rollout),
freeing base64 image memory as rollouts arrive instead of at ship.
- Consolidated vf_utils.py into orchestrator/utils.py (inlined trivial
get_num_turns); moved setup_student_inference_pool there too.
- Renamed Orchestrator.shutdown() -> stop() to match component start/stop.
- Per-group finalization logs now say "Finished group"; stripped trailing
periods from comments; dropped the Orchestrator class docstring.
- Moved configs/hendrycks_math/sanity.toml -> configs/debug/hendrycks_sanity/rl.toml;
multi_env config uses unique train/eval env names.
* feat(rlm-swe): multinode 1 train + 1 infer node, inference dp=8
Move qwen3.5-4b off single-node 4+4 to a 2-node split (1 train, 1 infer)
to relieve the inference decode bottleneck (KV ~57%, ~190 reqs queued on
capacity across only 4 infer GPUs). Trainer keeps cp=2 -> dp_shard=4 on
the full 8-GPU train node.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(rlm-swe): add 1h per-rollout timeout on swebench eval
Caps each eval rollout at 3600s wall-clock (-> timeout_seconds) so the
long-tail SWE-bench rollouts can't hold inference capacity indefinitely.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(rlm-swe): cp=4 to fix trainer OOM on step 1
22513 OOM'd in loss.backward() on the first step (4B, 8 GPU, dp_shard=4
cp=2, seq_len 65536, full AC; ~1GB over). Bumping context parallel to
cp=4 (dp_shard=2) splits the 65k sequence across 4 GPUs, ~halving
backward activation memory.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: update uv.lock to match pyproject (fix `uv sync --locked` in CI)
The lockfile went stale relative to pyproject.toml (openai-harmony
requires-dist spec drift), so the CPU CI's `uv sync --all-extras --locked`
install step failed. Regenerated via `uv lock`; `--locked` now passes.
* refactor(trainer): match orchestrator log format (drop colons after labels)
Trainer step / micro-step / validation lines now use `Loss 0.34` style
(space, no colon) to match the orchestrator's success-line format.
Updated the integration-test parsers (check_loss_goes_down,
check_avg_mismatch_kl_in_range) to colon-optional patterns, backward
compatible with the old format.
* refactor(trainer): drop "Time" label from step line (match orch)
Trainer step line now shows the time unlabeled and right-aligned to 7
chars (Step N | 44.5s | Loss ...), matching the orchestrator's success
line exactly. Also align format_time's docstring with vf.print_time.
* feat(rlm-swe): 2 inference nodes (dp=16) to double decode throughput
num_infer_nodes 1->2 and inference dp 8->16 (8/node x 2 nodes, tp=1).
data_parallel_size_local auto-derives to 8. Total alloc now 3 nodes
(1 train + 2 infer). Relieves the rollout-throughput bottleneck that
makes SWE batch fill (~36min/step) slow.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(rlm-swe): inference dp is per-node — set dp=8 (not 16)
dp in multi-node inference is per-node (data_parallel_size_local),
multiplied by num_infer_nodes internally. dp=16 double-counted →
inference_world_size=32. dp=8 × 2 infer nodes = 16 global ranks.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(rlm-swe): 2 independent inference replicas instead of cross-node DP
num_infer_nodes=2 builds ONE inference instance spanning 2 nodes
(cross-node DP coordinator → slow/fragile rendezvous). For a 4B model
on 1 GPU we want 2 independent single-node replicas behind the router:
num_infer_nodes=1 + num_infer_replicas=2 (dp=8/node → 16 infer GPUs).
Same 2x throughput, no cross-node coordination.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(orchestrator): warn (not success) when cleanup is forced
start()'s teardown now logs a forced-cleanup warning when main_loop is
interrupted (signal CancelledError / KeyboardInterrupt / error) instead
of the clean-exit success line, so an interrupted run is distinguishable
from a true completion.
* chore(orchestrator): remove dead print_benchmark from utils
print_benchmark was unused in the orchestrator package (the trainers use
the copy in trainer/utils.py); drop it and its now-orphaned pandas / rich
/ format_time / Any imports.
* fix(orchestrator): eval the student (not teacher) in SFT; ckpt drain off-by-one
- Eval rollouts now always go to the student inference pool + student
policy name. Previously the dispatcher used the single rollout pool for
both train and eval, so in SFT mode (rollout pool = teacher) eval
evaluated the *teacher* (fixed ~0.8), masking student progress. Add a
dedicated eval_inference pool to the dispatcher; train still uses the
rollout pool (teacher in SFT).
- maybe_save_ckpt: skip step >= max_steps - 1 (was == max_steps - 1) so
the drain-entry step (== max_steps, never shipped) doesn't double-save
a checkpoint at an interval boundary.
- CHANGELOG: document the orchestrator breaking config changes.
* fix(orchestrator): per-env group_size in solve rates; group by group_id
- MetricsBuilder: solve_all now compares each problem's summed reward to
its own env's group_size (was the top-level group_size), fixing
solve_all/effective_batch_size for per-env group_size overrides.
- Group all per-problem metrics by the rollout's group_id (UUID) instead
of (env_name, example_id), which collides across envs / oversampling.
- alphabet_sort integration test: run 10 steps (was 5).
* chore(configs): consolidate multimodal configs under configs/debug
Finish moving the color-codeword multimodal configs out of the
configs/multimodal/ dir: drop the unused rl_color_codeword.toml /
rl_color_codeword_test.toml and trim the renamed
configs/debug/multimodal.toml header. The dir is now empty.
* fix(orchestrator): eval through the eval (chat) client, not the renderer
Eval rollouts were generated via select_train_client (the renderer/token
train client) instead of get_eval_client (chat-completions). That changed
the eval generation path vs the legacy orchestrator (which used the chat
eval client), producing a consistent eval-score offset. Route eval groups
through pool.get_eval_client() so eval matches the legacy path; train
still uses the renderer/token train client.
* test(reverse_text): lower min reward threshold 0.65 -> 0.6
* fix(orchestrator): restore checkpoint resume compat with pre-rewrite runs
- Drop Progress.last_eval_step_by_env (and its EvalSource plumbing). It
only suppressed a redundant eval epoch when resuming exactly at an
eval-interval step; the first_trigger/is_resumed guard already prevents
re-running the startup eval on resume. Progress is now back to main's
shape (step + totals).
- Rename the orchestrator checkpoint file state.pt -> progress.pt to match
the previous orchestrator. With the Progress shape restored, resuming via
ckpt.resume_step from an old checkpoint now works (no FileNotFoundError,
no migration needed).
* fix(orchestrator): gate dispatcher on lead instead of blocking ship
Replaces the ship-time async barrier with a dispatcher-side gate owned by
the orchestrator. The old wait_barrier blocked main_loop, which is also the
only consumer of dispatcher.out_q — when on_new_version (called by the
watcher under update_lock) emitted enough Cancelled markers to fill the
queue, its out_q.put blocked, the watcher never advanced policy.version,
and the barrier never released. With max_off_policy_steps=0 every version
bump cancels every inflight rollout, so the queue routinely overflowed.
The dispatcher now exposes a dispatch_allowed asyncio.Event; fill_inflight
returns early when clear. The orchestrator toggles it via the public
update_dispatch_gate based on (progress.step + 1) - policy.version vs
TARGET_LAG. It runs after sender.send (step advances) and from a new
on_new_version observer hook (policy advances). main_loop never blocks, so
on_new_version's puts always have a consumer.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(dispatcher): claim drop_group tasks atomically before emitting
drop_group used to interleave dict mutations with awaits on emit_rollout
(which yields when out_q is full). During a yield, handle_completed_rollout
could pop a task drop_group hadn't reached yet, leaving the snapshot stale.
drop_group then re-popped (returning None — discarded), double-released the
permits, and emitted a second set of Cancelled markers for that rollout.
Split into a sync claim sweep (pop + release, no awaits) followed by the
async emit loop. By the time we start awaiting, every dropped task is
already out of self.inflight, so handle_completed_rollout's existing
None-guard bails out cleanly. No defensive None-checks in drop_group itself.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(rlm-swe): enable prefix caching + language-model-only inference
- enable_prefix_caching=true ([inference] field): big win for SWE's long
shared multi-turn prefixes.
- language_model_only=true (via [inference.vllm_extra]; it's a vLLM
MultiModalConfig arg, no prime-rl field): Qwen3.5-4B is a VL model, so
skip the vision tower for text-only SWE.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(rlm-swe): disable thinking in the qwen3.5 renderer
Set [orchestrator.renderer] name="qwen3.5", enable_thinking=false
(Qwen35RendererConfig field) — text-only SWE, no <think> traces. Was
relying on the auto renderer (default thinking on for 4B).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(rlm-swe): bump main run to 400 steps (non-thinking)
The on-main config is the non-thinking version (enable_thinking=false)
+ prefix caching + language_model_only. Run length 100 -> 400.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(rlm-swe): re-enable thinking on the main config
Flip enable_thinking back to true on the on-main qwen3.5 config (keeps
prefix caching + language_model_only + 400 steps).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(orchestrator): only skip ckpt at the drain-entry step, not max_steps-1
maybe_save_ckpt's near_end guard skipped step >= max_steps - 1, which also
skipped the last *shipped* step (max_steps - 1). The trainer saves a
checkpoint there (its is_last_step is max_steps, so it only skips 0 and
max_steps), so the orchestrator skipping max_steps-1 left a trainer ckpt
with no matching orchestrator Progress -> ckpt.resume_step = max_steps-1
(when it's an interval boundary) hit FileNotFoundError. The only real
double-save is at max_steps (drain-entry + final save in start()), so skip
only that. Now aligns with the trainer's is_last_step.
* chore(orchestrator): review responses (rename Kind, drop config aliases, doc cleanup)
- Rename the Kind type alias to RolloutKind (types.py + dispatcher.py).
- Remove the `filters` -> `post_batch_filters` before-validator alias and the
`[orchestrator.buffer]` warn-and-drop validator. Both keys now hard-error
(extra_forbidden); migrate the two bundled configs that used `filters`
(configs/debug/multimodal.toml, examples/glm5_pd_disag/rl.toml) to
post_batch_filters.
- Trim docstrings that referenced old/removed code: assign_advantages,
TrainBatchMetrics (group-level error drop), post_batch_filters (filters alias).
* docs(changelog): filters/buffer are hard removals, not aliased/warned
The filters->post_batch_filters alias and the [orchestrator.buffer]
warn-and-drop before-validators were removed, so both keys now fail
validation (extra="forbid"). Update the CHANGELOG entries that still
claimed backward-compat parsing.
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
prime-rl already had exclude-newer = "7 days" and a partial exempt list
for prime/prime-sandboxes/prime-tunnel/prime-evals. This PR extends the
exempt list with the other PrimeIntellect packages now in prime-rl's
`uv tree` closure: verifiers, renderers, prime-pydantic-config.
The exempt entries are scoped to packages actually in this project's
dep graph — the resolver ignores entries for packages it never sees.
Pins `required-version = ">=0.11.1"` so older uvs fail loudly instead
of silently parsing "7 days" as an RFC 3339 date and proceeding
*without* the cooldown — see uv#17908.
Lock regenerated. Five third-party env packages were rolled back by the
existing cooldown (opencode-cp/math/science/swe and mini-swe-agent-plus
each released in the past 7 days), confirming the cooldown is doing
real protection work, not just sitting as config.
Part 1 of 3 in a coordinated supply-chain hardening across PI repos.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat: configurable grace period for SLURM cleanup
Add slurm.cleanup_grace_period_seconds (default 3600) so that when a
component exits — completion, crash, or SIGTERM — the multi-node RL and
inference sbatch teardown sends SIGTERM and then waits up to the grace
period for the remaining processes to exit before force-killing and
releasing the allocation. This gives in-flight work, notably trainer
checkpoint writes, a bounded window to flush. The wait ends as soon as
all processes exit, so it is only an upper bound; set to 0 for the
previous immediate force-kill behavior.
Closes#2664
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor: rename cleanup_grace_period_seconds to cleanup_grace_period
Drop the _seconds suffix; the unit is documented in the field docstring.
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore: drop CHANGELOG entry for cleanup_grace_period
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: make cleanup grace actually cover cross-node teardown
The previous SIGTERM-then-wait approach didn't help the target case
(inference dies while the trainer is mid-checkpoint on another node):
that teardown is driven by `srun --kill-on-bad-exit=1`, which reaps the
trainer task via SLURM's own KillWait path and never runs our in-task
grace loop.
Instead, on a non-zero exit the failing node now stays alive (signalling
nothing) for the grace period before propagating the exit. Because
--kill-on-bad-exit only fires when a task exits, holding the failing
task keeps peer nodes' checkpointing trainers running untouched until
they flush. Clean (zero-exit) completion is unaffected.
Scope to multi_node_rl only; the inference-only template has no trainer
checkpoints to protect, so it reverts to immediate teardown.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: note cleanup_grace_period is multi-node RL only
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: minimize cleanup_grace_period docstring
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Bumps the deps/renderers submodule 89ab3f0 (v0.1.8.dev35) -> 35c2407
(v0.1.8.dev37), pulling in PrimeIntellect-ai/renderers#75: apply the
config-build fallback to ``_get_offset_tokenizer`` too.
#72 only wired the fallback into ``load_tokenizer``;
``_get_offset_tokenizer`` still called ``AutoTokenizer.from_pretrained``
directly to avoid the fastokens shim and so kept hitting HF's RoPE
validator on Laguna-family models. Every rollout through a hand-coded
renderer (LagunaXS2, Qwen35, ...) crashed with the same KeyError #72
was supposed to fix.
Verified end-to-end against poolside/Laguna-XS.2 with reverse-text:
two RL steps complete cleanly (reward 0.36 / 0.31, ~100 tok/sample);
the run then hits an unrelated single-GPU FSDP OOM on the 256-expert
trainer, which is a config-sizing issue, not the renderers bug.
Also pulls in renderers#74 (``message_tool_names`` field for per-message
tool attribution).
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Support delta-only routed experts replay
* Pin routed experts replay dependencies
* fix(orchestrator): match longest active prefix in interleave_rollout
Drop `min_tokens`, `repetition_penalty`, and `seed` from `TrainSamplingConfig`
and `EvalSamplingConfig`. They distorted the on-policy sampling distribution
(min_tokens suppressed natural EOS, repetition_penalty introduced
train/serve mismatch) or weren't pulling their weight (seed). Hard
deprecation — no migration window.
Closes#2655
Co-authored-by: Cursor <cursoragent@cursor.com>
Bumps the deps/renderers submodule 2ec28a8 (v0.1.8.dev28) -> 89ab3f0
(v0.1.8.dev35), pulling in PrimeIntellect-ai/renderers#72: when
AutoTokenizer.from_pretrained fails while building the model config
(e.g. HF RoPE validation rejecting nested rope_parameters for
poolside/Laguna-XS.2), fall back to loading the repo's self-contained
tokenizer.json directly. Fixes the tokenizer load crash for the Laguna
model series; loads under the fastokens fast path.
Re-locks uv.lock: renderers now floors openai-harmony at >=0.0.4 (renderers#69).
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(config): remove wandb.shared deprecation shim
The ``SharedWandbConfig.deprecate_shared_field`` ``model_validator(mode="before")``
introduced in #2649 popped ``wandb.shared`` from input dicts with a
``FutureWarning`` so older configs that still set ``shared = true`` (or
``false``) kept loading.
The ``rl`` entrypoint always uses shared W&B mode now, the legacy split with
``-trainer`` / ``-orchestrator`` suffixes is gone, and the in-tree configs no
longer set ``shared``. Drop the shim so configs that still carry the field
fail loudly via the default ``extra = "forbid"`` instead of silently warning.
Docs and CHANGELOG updated.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(config): honor --no-wandb / --no-ckpt across shared and sub-configs
pydantic-config's CLI negation (``--no-wandb`` / ``--no-ckpt``) writes the
string ``"None"`` into the override dict, which only becomes real ``None``
later via ``BaseConfig._none_str_to_none``. ``RLConfig``'s subclass
``mode="before"`` validators run *before* that conversion, so the bare-block
enablement in ``propagate_shared_fields`` used to see the string and
re-enable ``trainer.wandb`` / ``orchestrator.wandb`` (or the ``ckpt`` pair)
with defaults — silently undoing the CLI's intent.
Tighten the bare-block check from ``get(key) is not None`` to
``isinstance(get(key), dict)``. A bare ``[wandb]`` block in TOML is ``{}``
(dict, still enables); ``--no-wandb`` produces ``"None"`` (string, now
correctly skipped). Same logic applies to ``ckpt``.
Verified end-to-end with ``cli(RLConfig, args=[..., "--no-wandb"])``:
``cfg.wandb``, ``cfg.trainer.wandb``, ``cfg.orchestrator.wandb`` are all
``None``. ``--wandb None`` and ``--no-ckpt`` behave the same. Bare
``[wandb] {}`` / ``[ckpt] {}`` blocks still enable the sub-configs.
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore(changelog): drop --no-wandb fix entry
It's a bug fix, not a breaking config change, so it doesn't belong in
CHANGELOG.md (which documents breaking config changes only).
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore(comment): trim bare-block enablement comment
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(wandb): drop legacy-mode reference; add AGENTS rule
``docs/`` should describe the current state of the codebase, not its
history. Strip the "the legacy split has been removed" sentence from
``docs/training.md`` — readers on ``main`` don't care that there used to
be a non-shared mode — and add a ``## Docs`` rule to ``AGENTS.md`` to
codify it.
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore(agents): trim docs rule
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(rl-config): accept matching shared/sub duplicates so materialized config round-trips
The single-node SLURM launcher (``rl_slurm`` for
``deployment.type == "single_node"``) dumps the fully-resolved ``RLConfig`` to
``<output_dir>/configs/rl.toml`` and the sbatch script re-runs
``uv run rl @ rl.toml``. ``propagate_shared_fields`` writes both shared keys
(``output_dir``, ``wandb.project``, ...) *and* the matching sub-config keys
(``trainer.output_dir``, ``orchestrator.wandb.project``, ...) during the
first-load propagation; ``model_dump`` preserves both. On re-load the
``if sub_set: conflict`` check fired even though both keys had the same
value — treating a no-op round-trip as ambiguity.
Tighten the check to ``if sub_set and sub != shared_value``: genuine
conflicts still raise (a CLI-shared override silently no-opping against
an inconsistent sub-config value still surfaces), but matching values are
accepted so the materialized config re-loads cleanly. ``output_dir`` and
``wandb.name`` compare against their *transformed* sub-config values
(``output_dir → /run_default`` and ``-trainer``/``-orchestrator``
suffixes in non-shared mode).
Verified end-to-end on the hendrycks-sanity example for all three RL
deployments: local dry-run, single-node SLURM (submitted job 21902 from the
materialized rl.toml — config re-loaded, all three subprocesses spawned,
wandb shared run id preserved across trainer + orchestrator), multi-node
SLURM dry-run (write_subconfigs path).
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore(rl): deprecate wandb.shared, hardcode shared W&B mode
Shared W&B mode (single run for trainer + orchestrator) has been the default
on the rl entrypoint since #1330 and is the only mode anyone uses. The
non-shared mode — two separate runs suffixed ``-trainer`` /
``-orchestrator``, gated on ``wandb.shared = false`` — was kept around as
the legacy fallback and as the reason the validator's ``wandb.name``
propagation needed custom asymmetric ``expected``/conflict logic.
Drop the non-shared path:
* ``SharedWandbConfig.shared`` is removed from the schema. A
``mode="before"`` validator pops the field from input dicts with a
``FutureWarning`` so existing configs that still set ``shared = true``
(or ``false``) keep loading.
* ``validate_shared_not_offline`` becomes ``validate_not_offline``:
``wandb.offline = true`` at the shared level is rejected because shared
mode is always on and needs server connectivity. The escape hatch is to
set ``offline`` per sub-config (``[trainer.wandb] offline = true``,
``[orchestrator.wandb] offline = true``).
* ``propagate_shared_fields`` collapses the ``wandb.name`` block into a
plain ``propagate("wandb.name", "trainer.wandb.name",
"orchestrator.wandb.name")``. The ``expected``/conflict-against-
transformed-value machinery is gone; only ``output_dir`` still needs the
custom block because of its asymmetric ``/run_default`` suffix.
* ``rl_local`` always sets ``WANDB_SHARED_MODE`` / ``WANDB_SHARED_RUN_ID``
for subprocesses (no ``if config.wandb and config.wandb.shared`` gate).
* The multi-node SLURM template (``multi_node_rl.sbatch.j2``) drops the
``{% if wandb_shared %}`` gates and always exports the shared env vars
+ ``WANDB_SHARED_LABEL``. The ``wandb_shared`` template variable is
removed from both call sites in ``rl_slurm``.
* Configs that still set ``shared = true`` (``configs/nemotron_debug``,
``configs/nemotron_4node``) are cleaned up.
* Docs + the runtime info log are updated.
Verified end-to-end on hendrycks-sanity (job 21919, single-node SLURM): the
materialized rl.toml round-trips through the validator, both trainer and
orchestrator log ``Using shared W&B mode (label=…, primary=…)``, and the
W&B run name is the verbatim shared name (no ``-trainer``/``-orchestrator``
suffix). 234 config-related unit tests pass.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Ignore FileExistsError from mkdir when the token export step path is already a directory.
(cherry picked from 5ee18c884bec295c77bfe6d9d276197985b01a38)
* Consume the typed RendererConfig surface
Reshapes the orchestrator / SFT renderer plumbing around
``renderers.RendererConfig`` (the typed discriminated union) instead of
flat strings + booleans.
- ``configs.shared.RendererConfig`` now composes ``renderers.RendererConfig``
as a single ``settings`` field; ``pool_size`` stays as a separate
prime-rl-side concern. The flat ``name`` / ``tool_parser`` /
``reasoning_parser`` / ``preserve_*`` fields are gone.
- ``setup_inference_pool`` / ``setup_clients`` / ``StaticInferencePool``
/ ``ElasticInferencePool`` collapse their six-arg renderer surface to
a single ``renderer_config: RendererConfig | None`` plus the orthogonal
``renderer_model_name`` / ``renderer_pool_size`` fields.
- Orchestrator + SFT trainer call sites pass the typed config straight
through to ``create_renderer(tokenizer, config.renderer.settings)``.
- Cross-env / unmapped-model validators rewritten to inspect
``renderer.settings`` (discriminated-union shape) instead of the flat
field names.
- Tests updated to construct typed configs (``Qwen3VLRendererConfig()``,
etc.) and assert against the new call shapes.
Pins ``deps/renderers`` and the ``prime-rl-configs`` ``renderers`` dep to
the renderers PR's tip
(``4c9099debbc9bc4fcc3eb6a118bbfa5c364ec395``) until it merges and a dev
release ships.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Bump renderers pin to the merged v0.1.8.dev27
The typed-config refactor landed on renderers main as ``c86c50b``
(tag ``renderers-v0.1.8.dev27``). Switching:
- ``deps/renderers`` submodule pointer → ``c86c50b``
- ``prime-rl-configs`` git URL pin → ``@renderers-v0.1.8.dev27``
Same commit, more readable, and stable to anyone reading the diff
after the feature branch is deleted. PyPI dev release for the same
version is pending a publisher-config fix; once it lands the git URL
pin can collapse to a plain ``renderers>=0.1.8.dev27`` PyPI pin.
* Migrate in-repo TOMLs to the typed renderer schema
The new RendererConfig accepts only `settings` (typed
`renderers.RendererConfig` discriminated union) and `pool_size`, so
flat `name`/`reasoning_parser`/`preserve_*` keys under
`[orchestrator.renderer]` now fail pydantic validation. Move those
keys under `[orchestrator.renderer.settings]`. `pool_size` stays in
the outer block. Two configs that only set `preserve_all_thinking`
gain an explicit `name = "auto"` since the discriminator is required.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Use renderers.RendererConfig directly; None means MITO
Per Mika's review: drop prime-rl's RendererConfig wrapper that nested
the renderers' discriminated union under a ``.settings`` field. The
wrapper bought a parallel ``pool_size`` attribute but cost a clunky
two-level TOML layout and made every call site dereference ``.settings``.
Use ``renderers.RendererConfig`` (the typed discriminated union) as
the field type directly. Pool size moves up one level to
``orchestrator.renderer_pool_size``. ``use_renderer: bool`` is gone —
``renderer: RendererConfig | None`` with ``None`` for MITO replaces it
(consistent with how SFT, optimizer, and other optional sub-configs
express absence). TOML callers spell MITO with ``renderer = "None"``,
which ``prime_pydantic_config.BaseConfig._none_str_to_none`` coerces
back to Python None.
Net effect on TOMLs is a wash with the previous commit: 26 in-repo
configs lose the ``.settings`` indirection they gained yesterday, and
one (multimodal) splits ``pool_size`` out of the renderer block.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Pin renderers via PyPI now that 0.1.8.dev27 is published
The slim ``prime-rl-configs`` wheel (installed standalone, outside the
workspace) now resolves ``renderers`` from PyPI instead of the git tag
URL it used while the dev release was waiting on PyPI trusted-publisher
config. The full ``prime-rl`` workspace still pulls renderers from the
``deps/renderers`` submodule, so this only affects downstream slim
consumers.
Re-locks to refresh the lockfile against the same workspace state.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Lazy-import renderers in the typed config schema
The slim ``prime-rl-configs`` install path (configs only, no GPU
deps) asserts that importing the config classes doesn't pull in
``transformers``. ``from renderers import RendererConfig`` at the top
of ``orchestrator.py`` / ``sft.py`` broke that: ``renderers/__init__``
eagerly imports every concrete renderer module (DefaultRenderer,
Qwen3Renderer, …), each of which imports
``transformers.tokenization_utils.PreTrainedTokenizer``.
Defer the renderers import via:
- ``TYPE_CHECKING``-guarded ``from renderers import RendererConfig``
so static type checkers still see the typed discriminated union.
- ``renderer: Any`` field annotation at runtime, so no resolution
happens at class definition.
- ``model_validator(mode="before") _resolve_renderer`` that
lazy-imports ``renderers``, fills the orchestrator default
(``AutoRendererConfig()``), and coerces dict input through the
typed union via ``TypeAdapter``. SFT's default stays ``None``.
End-user semantics unchanged; class import is now transformers-free.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Restore typed renderer field; pin renderers to dev28
dev28 lazy-loads concrete renderer classes via PEP 562
``__getattr__`` (renderers#64), so ``from renderers import
RendererConfig`` no longer drags ``transformers`` into ``sys.modules``.
The slim-install CI gate is satisfied without the prior workaround.
Drop the ``Any`` annotation and the ``_resolve_renderer``
model-validator that lazy-resolved the discriminated union from
``OrchestratorConfig`` and ``SFTConfig``. The fields are typed
``RendererConfig | None`` again, and pydantic does the full
discriminator validation at class definition.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Bump deps/renderers (dev28) and deps/verifiers (typed ClientConfig)
- deps/renderers c86c50b -> 2ec28a8 — picks up the PEP 562
``__getattr__`` so the workspace install path also lazy-loads
concrete renderer classes.
- deps/verifiers 04651be -> d107442 — adds the typed
``ClientConfig.renderer_config`` field that ``setup_clients``
forwards. Fixes the unit-test
``test_setup_clients_assigns_renderer_and_dp_rank_headers``
AttributeError on ``renderer_config``.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Preserve MITO across orch.toml round-trip; drop RendererConfig alias
Two cleanups on the typed renderer surface:
1. Per Samsja: drop the ``RendererConfig as RendererSettings`` alias
in ``client.py`` / ``elastic.py``. The alias was a workaround for the
former local ``RendererConfig`` wrapper class; with that gone, we
just import ``RendererConfig`` from renderers directly.
2. Per Cursor bugbot: ``OrchestratorConfig.renderer = None`` (MITO) was
silently dropped by ``model_dump(exclude_none=True)``, so any saved
``control/orch.toml`` would reload as the default
``AutoRendererConfig()`` (TITO). Add a wrapping ``model_serializer``
that re-injects ``renderer = "None"`` (string) when the field is
``None``, matching what ``BaseConfig._none_str_to_none`` accepts on
reload. MITO and TITO now round-trip through TOML.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Address mika review on #2635: rename pool_size, drop factory, trim docstring
- renderer field uses direct AutoRendererConfig() default (frozen, no
factory needed)
- renderer_pool_size -> pool_size on OrchestratorConfig; cascade through
client.py, elastic.py, orchestrator.py call sites and the test;
vf.ClientConfig kwarg name (verifiers-side) stays renderer_pool_size
- shorter docstring on the renderer field
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Bump deps/verifiers to f9c68eb2 (both renderer PRs merged to main)
Picks up verifiers main with PR #1463 (surface every parsed tool_call,
drop status filter) and PR #1468 (pipe chat_template_kwargs into typed
RendererConfig) now that both are merged. verifiers 0.1.15.dev11.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Eli Gottlieb <eli@primeintellect.ai>
* docs: rewrite into 8 task-oriented pages with auto-generated reference
Replaces 22 small/uneven docs files with 8 longer pages modeled on the
verifiers docs: each page opens with a TOC, content is grouped by task
(configure, train, scale, …) instead of by feature, and a single
auto-generated reference page covers every config field.
New pages: overview, configuration, training, scaling, algorithms,
advanced, faqs, reference. reference.md is generated by
scripts/generate_docs_reference.py from the Pydantic config models;
regenerate with `uv run python scripts/generate_docs_reference.py`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: fix stale claims found in source verification pass
- algorithms.md: max_async_level default is 1 (not 2); default loss
includes the Kimi-K2.5 KL regularizer (was wrongly claimed to drop
it); update the formula to show the full L = -PG + tau_KL * KL form;
filter table is `[[orchestrator.filters]]` (plural)
- training.md: checkpoint paths nest under `checkpoints/step_N/{trainer,
orchestrator}/` rather than separate hierarchies; --inference-gpu-ids
/ --trainer-gpu-ids don't exist — use --deployment.num-{infer,train}-
gpus and pin physical GPUs via CUDA_VISIBLE_DEVICES; update
max_async_level prose to match the new default
- scaling.md: same GPU-flag fix throughout the single/multi-GPU
examples; correct the claim that Muon + optim_cpu_offload is
unsupported (only fsdp_cpu_offload is blocked)
- configuration.md: there is no generic PRIME_* env var override
mechanism in pydantic-config — rewrite the env vars section to list
the specific named vars that individual fields read as defaults
- advanced.md: add the qwen3_vl_moe entry to the VLM registry table;
the small-scale MoE RL config lives at
configs/ci/integration/reverse_text_moe/start.toml, not .../rl/
- faqs.md: update the max_async_level Q&A to match the new default
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* ci: enforce docs/reference.md stays in sync with configs
Adds two safety nets so the auto-generated reference can't silently
drift from the Pydantic config models:
- Pre-commit hook (local): re-runs scripts/generate_docs_reference.py
whenever a config class or the generator itself is staged. If the
generated file changes, pre-commit fails the commit so the contributor
re-stages the regenerated reference.
- GitHub Actions (CI): a small workflow runs the generator and
`git diff --exit-code docs/reference.md`. Catches anyone who bypassed
the pre-commit hook.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: rename pre-commit hook id to docs-reference
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs(overview): tighten landing page
- Quick run now uses examples/reverse_text/rl.toml; the env is bundled
with the verifiers submodule so no prime env install is needed, and
the tmux helper is documented elsewhere instead of duplicated here
- Architecture bullets advertise the SOTA features per process: vLLM
multi-node + FP8 + P/D disaggregation for inference; FSDP2 + EP
(incl. DeepEP) + CP + selective AC + FP8 + LoRA + multi-run for the
trainer
- Drop the "Use prime-rl when you want to" bullets and the CPU-only
SFT smoke check — the landing page reads cleaner without them
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs(configuration): trim and reorganize
- Drop the env-vars section entirely (and the precedence callout that
referenced it) — the page is now strictly TOML + CLI. The few named
env vars that individual fields read as defaults are out of scope for
the config docs and stay in the per-feature pages (training.md, etc.)
- Drop the entrypoint enumeration and the W&B/output-dir recommendation
blurb in the intro
- Reword "@ introduces a TOML file" so the sentence doesn't lead with
an inline code token; convert the "Mind the space" hint to a
blockquote
- Drop --output-dir from the convenience-flag list (it's just another
override, not a special flag)
- Note that --dry-run is available on rl, sft, and inference only —
the standalone trainer and orchestrator configs don't have a dry_run
field
- Split "Booleans, None, and lists" into one section each, matching
the pydantic-config README style; add a Dicts section
- Drop the "Prefer --ckpt" convention bullet — checkpointing is
covered in training.md and didn't belong in the config conventions
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs(training): drop redundant OpenAI-compatible prefix on vLLM server
vLLM is an OpenAI-compatible server by default; the prefix in the
entrypoints table was just noise. Other mentions of "OpenAI-compatible"
describe the API surface or third-party endpoints and stay.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs(training): trim and restructure per review
- Quick-start now uses examples/reverse_text/rl.toml; drop the prime
env install and tmux preamble (covered elsewhere)
- Add a "Useful CLI flags" subsection: --ckpt, --wandb, --orchestrator.
prime-monitor (Prime Lab), --clean-output-dir, --output-dir,
--max-steps, --dry-run
- Mention the env-server / env-worker fan-out in the orchestrator
bullet under "What each process does at runtime"
- Restrict the Key knobs table to orchestrator-only args; drop
max_async_level, max_completion_tokens, inference, trainer rows;
rename rollouts_per_example row to lead with "Group size"
- SFT Launch now uses examples/reverse_text/sft.toml; drop the CPU
fake-data smoke alternative
- "two distillation modes" -> "three training modes" (rl/opd/sft)
- Drop the long-run checkpoint-combo recommendation
- Drop the trainer+orchestrator lockstep note from Resuming a run
- Swap order: Platform monitoring now appears before Prometheus +
BetterStack under Observability; show --orchestrator.prime-monitor
CLI invocation
- Rename "Metrics that matter" -> "Important metrics"; drop the live
vLLM curl snippet
- Drop "Eyeball the reward distribution", "Match inference.parallel.tp",
and "Set max_async_level deliberately" rules of thumb
- Add new rules of thumb: batch size >= 64; group size >= 8 with the
reasoning that all-succeed / all-fail groups give the trainer no
signal because the within-group advantage collapses
- Drop the Common Issues section entirely
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: trim scaling layout table and move multi-node logs to training
- scaling.md: drop the 1-GPU row and the "Production MoE with long
contexts" row from the "Choosing a layout" table; the disaggregated
prefill/decode page section is still findable via its own H2
- scaling.md: drop the trailing "Multi-node logs" section (heading +
TOC entry); the content now lives next to single-node log layout
- training.md: fold the multi-node tree into "Log files" with the
single-node skip note inlined; add live-tail recipes and the
per-rank torchrun debug note; mention the tmux helper works on a
SLURM head node
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs(algorithms): add Renderers section, trim renderer prose
- New Renderers section explains why best-effort interleaving works:
the renderer guarantees the exact-prefix invariant by construction
via bridge_to_next_turn. Lists the renderer API surface and the
hand-coded model coverage
- Drop the verifiers trajectories-design-note link from Discontinuous
trajectories and the --trajectory-strategy branching deprecation
- Drop preserve_all_thinking workaround mentions from algorithms.md
and faqs.md (reference.md still documents the fields)
- Leave a TODO(blog-post-url) for the PI site writeup
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: refresh FAQ + training W&B claim + recommend prime eval
faqs.md:
- Drop the "override an env var in TOML" Q&A (matches the configuration
page where env vars are no longer documented as a generic override)
- Drop the "max_async_level" Q&A; replace with a max_off_policy_steps
Q&A — the more impactful knob to tune on long agentic rollouts
- Drop the outdated "two W&B runs per RL job" Q&A; default is shared
now (wandb.shared = true)
- Drop the SFT-section Q&As that referenced preserve_all_thinking or
were too thin to keep
- Switch the "evaluate without training" recipe from vf-eval to prime
eval run (the Prime CLI is the recommended entrypoint)
training.md:
- Fix the W&B section to describe the new default: shared single run
(wandb.shared = true), with the legacy split as opt-out
- Add max_off_policy_steps to the Key knobs table
- Switch the eval example from vf-eval to prime eval run
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs(faqs): drop the CP <= 8 recommendation
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs(faqs): drop the vLLM log-quieting and KV-cache pressure Q&As
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs(faqs): drop the Environments Hub install Q&A
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs(faqs): drop the Models and environments section
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs(overview): second tightening pass
- Inference bullet now leads with the local default (token-in
/v1/generate via renderers; OpenAI-compatible routes called out
as the external-client path) and adds DP/TP/EP with deepep +
flashinfer all-to-all backends + EPLB, P/D disaggregation behind
vllm-router, CPU KV-cache offload, and router replay (FP8 MoE
numerical-parity feature). Weight broadcast is filesystem or NCCL.
- Orchestrator bullet now leads with "owns the data plane across
many verifiers training and eval environments" plus the per-env
isolated subprocess + variable-size env-worker pool.
- Trainer bullet drops "torchrun-launched" and surfaces the custom
modeling code as the enabler for advanced trainer parallelism
(EP with DeepEP, CP for long sequences).
- Drop the [AIPO] link in the async paragraph (off-policy-aware PG
+ KL regularizer, no paper handle); also drop the "AIPO loss"
mention from the Algorithms blurb in "Where to go next" so the
page is internally consistent.
- Quick-run command is now bare: uv run rl @ examples/reverse_text/rl.toml
(no --wandb.* / --ckpt).
- Drop the trailing scaling pointer (Scaling is already linked in
"Where to go next").
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(configuration): second tightening pass
- Drop the entrypoint-splitting paragraph ([trainer] / [orchestrator]
/ [inference] table lifting); covered elsewhere.
- Rename "TOML files and composition" -> "TOML composition", and
"Special syntax" -> "Syntax".
- Open "Sources and precedence" by naming the three sources (Pydantic
defaults, TOML files, CLI flags) up front, then layering them.
- Drop the "(-- is a kebab-case marker)" parenthetical from CLI
overrides; turn the snake/kebab note into a callout.
- Drop the --help / --dry-run convenience-flag block and the
"--dry-run is the single most useful debugging tool" prose; the
bash example is enough.
- Reorder Syntax subsections to mirror the pydantic-config README:
Booleans -> Lists -> Dicts -> Optional sub-configs -> None ->
Discriminated unions -> Environments. None moves down and is
cross-linked from "disabling an optional sub-config".
- Booleans example swapped from --ckpt (which is itself an optional
sub-config) to --clean-output-dir (a real bool = False field),
showing both --flag and --no-flag forms.
- Lists / Dicts now show TOML and CLI on the *same* field name so
the mapping is obvious (target_modules for lists, env.0.args for
dicts), and add the "lists are replaced wholesale" overlay note
+ "dicts deep-merge across sources" detail.
- Add a callout on validation aliases (rollouts_per_example still
works after the rename to group_size) — only material gap vs the
pydantic-config README that's relevant to end users.
- Worked example: --dry-run is now the final flag.
- Drop the Conventions section.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(training): second tightening pass
- Rename "RL training" -> "RL trainer" and "SFT training" -> "SFT
trainer" (and update the page intro accordingly).
- Entrypoints table: clarify that `uv run rl` wraps the trainer,
orchestrator, and inference server in one launch — runs locally
for single-node experiments and submits to SLURM for single- or
multi-node when [slurm] is set. Drop the trailing "rl is a
convenience wrapper" paragraph.
- RL trainer Launch: minimal command is now bare
`uv run rl @ examples/reverse_text/rl.toml` (no flags). Drop the
GPU-placement paragraph + multi-GPU example (covered in scaling.md).
- Replace "Useful CLI flags" + "Key knobs" + "What each process does
at runtime" with one consolidated "Useful knobs" section split into
three sub-tables: data-and-algorithm, monitoring, run management.
- Add training environments ([[orchestrator.train.env]] for
multi-env training)
- Add eval environments ([[orchestrator.eval.env]] +
orchestrator.eval.interval)
- Add monitoring entries: orchestrator.log.vf_level, --wandb,
--orchestrator.prime-monitor
- Move Training modes from a top-level section into RL trainer as
a subsection (it's RL-entrypoint-specific).
- Drop the standalone Evaluations section — eval syntax is covered
in configuration.md and the eval-knobs row in Useful knobs links
to `prime eval` for one-off evals.
- Drop the optimization_dtype / reduce_dtype rule of thumb.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(training): SFT trainer metrics + tools column + minor renames
- Drop "-via-orchestrator" from the Training modes heading and the
internal/cross-doc anchors. The mode value is just `sft` and the
short title reads cleaner.
- Drop "and the tmux helper" from the Console output subsection
title; the tmux helper is still documented in the section body.
- Important metrics is now split into RL trainer and SFT trainer
subsections so the SFT-only metrics (loss/mean, val/loss,
progress/{epoch,num_samples,num_tokens}, optim/zero_grad_ratio,
per-subset mixing ratios, MoE max_vio + routing_confidence,
perf/peak_memory + the time/* breakdown) are documented.
- SFT Dataset format gains a Tool definitions paragraph: rows can
carry a `tools` column (OAI function-calling format) or
`tool_defs` (verifiers rollout format), as either a list of dicts
or a JSON-encoded string. `tool_defs` is auto-converted to OAI
shape before being passed into the chat template's `tools=...`
argument. `chat_template_kwargs` rows pass through verbatim.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(training): rename 'Saving HF weights for serving' -> 'Serving checkpoints'
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: cross-link the agent skills from training + configuration
Adds a callout under the intro of training.md and configuration.md
pointing at the equivalent skill files for AI agents working in
this repo:
- training.md -> skills/training/SKILL.md (top-level routing) +
skills/training/start-run/SKILL.md (launch details) +
skills/training/monitor-run/SKILL.md (check-in / restart).
- configuration.md -> skills/configs/SKILL.md.
The skills aren't part of the published Mintlify nav, so the links
go to GitHub blob URLs.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(training): fold Important metrics into RL + SFT trainer sections
The standalone "## Important metrics" section is gone. Each
trainer subsection now ends with its own "### Important metrics"
covering only the metrics relevant to that flow:
- RL trainer / Important metrics: reward + rollout signals from the
orchestrator, mismatch_kl + entropy + grad_norm from the trainer,
and the trainer/orchestrator/vLLM performance grid.
- SFT trainer / Important metrics: loss/mean, val/loss, progress
counters, optim signals, MoE max_vio + routing_confidence, and
the perf/{throughput,mfu,peak_memory} + time/* breakdown.
TOC updated to point at #important-metrics (RL) and
#important-metrics-1 (SFT) — Mintlify de-duplicates with the same
-N suffix scheme it already uses for the two Launch subsections.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(training): drop Prometheus and BetterStack subsection
Not ready for end-user docs yet. Both knobs (trainer.metrics_server.port,
trainer.heartbeat.url) are still in reference.md for anyone who needs
them, just no narrative coverage.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(training): tighten Useful knobs language
- Use "task" not "prompt" for the conceptual unit ingested by the
orchestrator (rows for batch_size and group_size, plus the matching
Rules of thumb wording).
- group_size: drop the "Used for advantage normalization and pass@k
estimation" trailer; the row name is enough.
- max_off_policy_steps: rename "throughput-vs-noise dial" to just
"off-policy dial".
- eval row: drop the "Scores land in trainer logs and W&B as
eval/{env}/{avg@k,pass@k}" + `prime eval` trailer; keep the row
scoped to what the knob does.
- Add log.level to the Monitoring table (trainer/orchestrator process
log level, $PRIME_LOG_LEVEL fallback, per-process or global on rl).
- Drop --ckpt from Run management; checkpointing has its own section.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(training): trim RL Performance table to the bottleneck signals
Drop the throughput/MFU/async-lag/KV-cache rows from the RL trainer
Performance table — they're either generic perf metrics already
covered by the SFT trainer's perf table or vLLM-internal. The two
remaining rows (time/wait_for_batch, time/wait_for_ckpt) are the
useful diagnostic — they tell you which side is the bottleneck.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(training): refresh chat-template prefix-property paragraph
The old wording recommended only patched checkpoints / a custom
chat template as the fix for position-dependent templates. The
renderer-based path landed in SFT (use_renderer flag) and is now
the primary recommended fix, but it's still off by default
(use_renderer: bool = False on SFTConfig), so the patched-
checkpoint path also still works — and is what
examples/reverse_text/sft.toml uses today via PrimeIntellect/
Qwen3-0.6B.
Rewrite the paragraph to cover both fixes:
- Renderer path: use_renderer = true, lists the hand-coded
renderers, calls out the VLM unsupported case.
- Patched template path: the prime-rl-patched checkpoint or a
user-supplied template that preserves thinking.
Cross-link both to Algorithms § Renderers and § Multi-turn
trajectories.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(training): fix SFT data row (data.name, drop default data.type)
- data.type = "sft" is the discriminated-union default for
SFTConfig.data, so users don't need to spell it out.
- The dataset path field is data.name, not data.path. Confirmed
against SFTDataConfig.name in packages/prime-rl-configs/src/
prime_rl/configs/sft.py.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(training): drop loss/nan_count from SFT trainer metrics
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(advanced): drop the Environments section
Environment installation, authoring, and multi-env mixing are
already covered concisely in configuration.md (Environments syntax)
and training.md (Useful knobs row pointing at the same). The
advanced.md duplicate just spread the same material across three
subsections without adding anything material.
- Drop the section + its TOC entries.
- Update the page intro and overview.md "Where to go next" to stop
advertising "environments deep-dive" / "environments installation
and authoring".
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(advanced): rename "MoE models" -> "Custom modeling" + "LoRA" -> "LoRA training"
The first section was conceptually about our custom modeling stack
(model.impl = "custom"/"auto", the family registry, EP backends),
not about MoE specifically — even though the supported families
happen to be MoE-heavy. Rename so the section title matches the
defining feature.
Bump LoRA to "LoRA training" for parity with the trainer-oriented
section names elsewhere on the page.
Update the page intro and TOC entries to match. No external doc
links to the renamed anchors (#moe-models, #lora) so nothing else
to fix.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(advanced): drop 'Poolside' prefix from Laguna family row
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: rename Vision-language models -> Multimodal training
Standardize on "multimodal training" as the section title:
- advanced.md: "## Vision-language models" -> "## Multimodal training"
+ "### Multi-turn VLM training" -> "### Multi-turn training" (the
parent context is already multimodal). "### Enabling VLM mode" stays
because it's literally enabling the [model.vlm] config block.
- advanced.md page intro: "vision-language models" -> "multimodal
training".
- advanced.md custom-modeling cross-link to (#vision-language-models)
-> (#multimodal-training).
- overview.md "Where to go next" blurb: align the Advanced bullet's
language ("MoE training" + "VLMs") with the destination's section
titles ("Custom modeling" + "multimodal training").
reference.md still mentions "vision-language model" in auto-generated
descriptions sourced from Pydantic field docstrings. Those are
out-of-scope for this rename; would need a config docstring change.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(advanced): drop the DeepEP grad-clip-disable tradeoff aside
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(advanced): fix the freeze_vision_encoder + LoRA claim
The bullet said the combo "has no effect under LoRA (LoRA freezes
everything non-adapter regardless)". Source check:
packages/prime-rl-configs/.../trainer.py:591-597 now contains a
vlm_freeze_incompatible_with_lora validator that explicitly
*rejects* the combo with an error. So the user-facing behavior is
not silent-no-op, it's a config validation failure.
Other bullets in the Limitations list verified against source and
are correct as written:
- "No multimodal-safe truncation": confirmed in trainer/batch.py
(input_ids / mm_token_type_ids truncated to seq_len; mm_kwargs
passes through unchanged).
- "bfloat16 mandatory": confirmed by the vlms_require_bfloat16
validator in trainer.py.
- "Images aren't logged to monitors": confirmed — no image / pixel
handling in src/prime_rl/utils/monitor/.
The "Higher KL mismatch with multi-image inputs" bullet is left
unchanged for now — flagged for review separately because the cited
rationale ("minor numerical differences between trainer and vLLM
image processing") no longer matches reality after the renderer-
only multimodal path landed (#2473): the renderer now owns image
processing end-to-end and both sides consume the same pre-processed
pixel_values / image_grid_thw. The empirical observation may still
hold but the reason given would be stale.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(advanced): drop the Multi-turn training subsection
The render/pack/forward rendition lived close to internal code and
felt out of scope for the user-facing Advanced page; the spawn-method
hint that ended it can move elsewhere if needed.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(advanced): rename Multi-run manager -> Multi-tenant training
User-facing framing now leads with the actual use case: many
concurrent LoRA tenants sharing a single trainer + inference
deployment, which is the topology behind hosted training on the
Prime Intellect platform (Lab). The MultiRunManager class still
exists in code and is name-checked in the section body — only the
section title and surrounding prose change.
- advanced.md: rename TOC entry + H2 + open paragraph; drop the now-
redundant "primary use case today" trailer (Lab is in the intro).
- advanced.md LoRA section: reword the cross-link.
- overview.md: trainer description bullet now says "multi-tenant
training" instead of "multi-run manager"; "Where to go next"
Advanced bullet renamed similarly.
- scaling.md: parenthetical aside on optim_cpu_offload incompatibility
updated for consistency.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(advanced): trim multi-tenant training to user-facing surface only
Drop the per-run filesystem layout, Run discovery / Eviction / Hooks
subsections — these are MultiRunManager internals (run_* dir
discovery, evicted.txt protocol, hook lifecycle) that don't belong
in a user-facing Advanced page. The pointer to
src/prime_rl/trainer/runs/ still tells anyone who needs the API
where to look.
The remaining section is one paragraph: what multi-tenant training
buys you, that Lab is the production user, and the
trainer.max_concurrent_runs entry point.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: add a Development page; move "Testing MoE at small scale" off Advanced
Advanced was mixing user-facing features (custom modeling, multimodal,
LoRA, multi-tenant training) with developer-facing workflows
(building a tiny MoE for modeling-code iteration, adding a new
architecture). Split the latter into a new Development page so each
audience reads only what's relevant.
- New page: docs/development.md, scoped to "developing on prime-rl
itself". Contains the unchanged Testing MoE at small scale recipe
(build/verify mini model, SFT warmup, RL on reverse-text) and the
Adding a new architecture how-to.
- advanced.md: drop the section + TOC entry; rewrite the page intro
to point at Development for developer-side workflows.
- mint.json: insert "development" in the nav between "advanced" and
"faqs".
- overview.md "Where to go next": add the Development bullet, drop
"small-scale MoE testing" from the Advanced bullet.
- README.md docs index: same split (Advanced + Development as two
separate bullets).
No external links to the moved anchors needed updating; the only
existing cross-link was the relocated TOC entry in development.md
itself.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(algorithms): fold Renderers into Multi-turn trajectories
Renderers existed as a top-level section because they were added in
a follow-up, but conceptually they're the mechanism that makes
best-effort interleaving safe — splitting them apart forced a
forward-reference and duplicated the "exact-prefix invariant" framing.
- Demote "## Renderers" to "### Renderers" inside "## Multi-turn
trajectories", placed between Best-effort interleaving and
Discontinuous trajectories.
- Move the Qwen3 thinking-stripping example from Best-effort
interleaving into Renderers — it's the failure case the renderer
fixes, so it reads better adjacent to the family list / config
block.
- Drop the "Workaround: use a chat template that preserves thinking"
trailer; the patched-checkpoint workaround for SFT is already
documented in training.md and isn't relevant in the orchestrator
context (use_renderer defaults to true).
- Open Multi-turn trajectories with a forward-link to Renderers so
the reader knows the safety mechanism is coming.
- TOC updated; both #multi-turn-trajectories and #renderers anchors
preserved (only their nesting changes), so the existing cross-
links from training.md and faqs.md keep working.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(algorithms): drop max_async_level tuning + reframe as fixed one-step
max_async_level is being deprecated as a user-facing knob (hardcoded
to 1; matching reframe in docs/async.md on feat/deprecate-max-async-
level). Update algorithms.md so the long-form treatment matches.
- Drop the "### Tuning max_async_level" subsection (the k=0/1/2/>=3
table) and the NCCL-needs-max_async_level=1 line that follows it
— both become vacuous when k is fixed at 1.
- Reword the Async / off-policy training intro to describe the
one-step overlap directly instead of "up to k steps where
k = max_async_level".
- Step semantics: rho_inference is now pi_{max(0, n-1)}, with prose
"inference is exactly one step behind the trainer" replacing the
generic "gap is at most k steps".
- Drop the Tuning entry from the page TOC.
Other docs (overview.md intro, training.md rule of thumb, faqs.md
two entries, scaling.md NCCL-example comment) still mention
max_async_level and are now stale; will clean those up in the next
turn unless flagged otherwise.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(development): add Test suite + Pre-commit hooks sections
Pull in the testing- and contributor-workflow content from README and
the GitHub Actions configs so contributors don't have to dig through
.github/workflows/ to figure out what runs where.
New sections in development.md:
- Test suite
- Layout: tests/unit/, tests/integration/, tests/nightly/ — what
each tier is for, with the actual file names contributors will
encounter.
- Running tests locally: pytest one-liners (everything, unit-only,
integration-only, -m "not gpu", -m gpu, single file).
- CI workflows: a 3-row table covering cpu_tests.yaml,
gpu_tests.yaml (matrix list pulled verbatim from the workflow),
and nightly_tests.yaml — including the trigger conditions
(cpu = always, gpu = non-draft, nightly = scheduled +
workflow_dispatch) and the runners (ubuntu-latest, vm/4xa6000,
research-cluster).
- Markers: gpu + slow, both declared with --strict-markers in
pyproject.toml.
- Pre-commit hooks
- uv run pre-commit install
- Currently configured hooks: ruff check/format and
docs-reference (regenerator that fails the commit if
docs/reference.md would drift).
Plus update the Development pitch in overview.md "Where to go next"
and README.md docs index to mention the new scope.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(algorithms): fold Length penalties into Default advantage
Length penalties are configured under [orchestrator.length_penalty]
and layer on top of *any* advantage function — they're conceptually
not a standalone advantage variant. Move them into Default advantage
where readers will see the option while reading about advantages.
Drive-by: clean up the parenthetical hint in Default advantage. The
old version listed "length penalties tied to turn count" as a reason
to write a custom advantage, which conflicts with the actual
turn-count length penalty being a built-in. New wording points
length-penalty users at the now-adjacent built-in section, and
points custom-advantage users at trajectory-metadata-driven shaping
(sub-agents, relative-rank, …).
TOC entry for #length-penalties dropped; no external doc links to
that anchor.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(advanced): add Difficulty pools + Online difficulty filtering
Covers the two complementary buffer-side mechanisms for keeping the
trainer batch high-signal. Verified each claim against
src/prime_rl/orchestrator/buffer.py and packages/prime-rl-configs/
src/prime_rl/configs/orchestrator.py.
- Difficulty pools (buffer.easy_threshold / hard_threshold +
easy_fraction / hard_fraction): per-problem running-average reward
is compared to the thresholds; problems hitting either bound move
to easy/hard pool and stop being sampled. Pool assignments persist
across checkpoints (easy_examples.jsonl / hard_examples.jsonl);
*_fraction lifts a fraction of pooled problems back into normal on
resume / start.
- Online difficulty filtering (buffer.online_difficulty_filtering
bool): groups whose avg reward is exactly 0.0 or 1.0 are dropped
from the buffer because their within-group advantage is zero
(DR-GRPO produces no signal). Counted under filtered_rollouts/
{env}/{easy,hard} for visibility.
- The tradeoff bit the user asked for explicitly: with ODF on each
trainer step's effective batch is dense + predictable, but the
orchestrator pays for the throw-away rollouts and may need a
higher oversampling_factor; if time/wait_for_batch is already
high on the trainer, ODF can starve the loop.
- ODF is orthogonal to the pools — ODF reacts to the current
group's reward distribution, pools track the running per-problem
average. Configs often use both.
Plus a one-line page-intro update + TOC entries.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: relocate Difficulty pools + ODF from Advanced to Algorithms
Both are buffer-side controls over what reaches the trainer — same
conceptual category as Filters and the loss/advantage knobs.
Algorithms is the right home; Advanced is for orthogonal feature
sets (LoRA, multi-tenant, custom modeling, multimodal). Promote each
to its own top-level section.
- algorithms.md: new "## Difficulty pools" and "## Online difficulty
filtering" sections, inserted between Filters and Multi-turn
trajectories. TOC updated.
- advanced.md: section + TOC entries + page-intro mention removed.
Content unchanged from the previous commit on Advanced — same
threshold / fraction / persistence claims, same ODF tradeoff
explanation, same cross-link to oversampling_factor. ODF section
back-links to Difficulty pools for the orthogonality note.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(development): split MoE-debug recipe; promote "Adding a new architecture"
- "Adding a new architecture" promoted to its own top-level section,
placed *before* the renamed Debugging MoE recipe so the natural
reading order is "here's how to wire up a new arch -> here's how
to smoke-test it". Step 3 of the recipe now forward-links to
Debugging MoE instead of "the three steps above".
- "Testing MoE at small scale" -> "Debugging MoE". The page is
already titled Development, so the qualifier was redundant.
- Subsection titles drop the "Step N:" prefixes (the page-level TOC
already implies sequence) and switch to sentence case for
consistency with the rest of the docs:
- Step 1: build and verify a mini model -> Build and verify a mini model
- Step 2: SFT warmup -> SFT warmup (already correct)
- Step 3: RL on reverse-text -> RL on reverse-text (already correct)
- TOC updated; README docs index pitch swaps "small-scale MoE
testing" -> "debugging MoE" to match the new section title.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(development): tighten Debugging MoE subsections
- "### Build and verify a mini model" -> "### Create mini model".
The roundtrip-verify body covers the "and verify" half; the
shorter title is enough.
- Merge "### SFT warmup" + "### RL on reverse-text" into one
"### Smoketest training" subsection. The two were always run
together as a single end-to-end smoke test (warmup so KL is
meaningful, then RL stack), so a single subsection with two code
blocks reads better than two artificially-split ones.
- TOC updated. No external doc links to the old sub-anchors.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: rename Worked example -> Examples; update reference generator
User-facing docs no longer reference configs/ directly — examples/
is the only "we keep this up to date" surface, the rest is CI- and
debug-internal:
- configuration.md: launch line + worked-example switched to
examples/reverse_text/rl.toml. Section renamed "Worked example"
-> "Examples" with a curated tour of the 10 README examples
(basic 1-8 GPU + advanced SLURM tiers); the compose / override /
dry-run walkthrough lives as a "### Worked example" subsection.
- training.md: drop the "Debug configs for all variants ship under
configs/debug/training_modes/" pointer in the Training modes
section. The prose already explains how to set the mode.
- scaling.md: P/D inference now points at examples/glm5_pd_disag/
rl.toml (with a link to its README) instead of the configs/-side
inference-only TOML.
- faqs.md: install-verify and smoke-test recipes both switch from
configs/debug/sft and configs/gsm8k to examples/reverse_text.
Reference generator (scripts/generate_docs_reference.py):
- Drop "from the Pydantic config models" from the page header.
- Move the regenerate command + structural notes from the header to
a new "## About this page" footer.
- Wrap the Type column in code spans so list[int], int | None, etc.
render as code instead of plain text. fmt_type now emits literal
`|` (GFM accepts pipes inside code spans inside table cells; no
escaping needed).
- Walk list-of-BaseModel fields. Previously orchestrator.train.env
/ orchestrator.eval.env / orchestrator.filters were rendered as
one row showing the default repr; their leaf fields never showed
up. New _list_inner_models() detects both list[X] (single model)
and list[Annotated[Union[A | B], discriminator]] (discriminated
union of list items, e.g. filters: list[FilterConfig]). Index
placeholder rendered as <n> to match the CLI form
(--orchestrator.train.env.0.id ...).
Regenerate reference.md: +5k chars, mostly the new env/filter
list-item subsections that were missing before.
development.md still references two CI-tested configs/ paths
(configs/debug/moe/sft/train.toml, configs/ci/integration/
reverse_text_moe/start.toml) — those are validated by the
reverse_text_moe GPU integration test on every PR, so they don't
risk drifting. Flagging in case the user wants those swapped too.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(training): correct batch-size rule of thumb
128-512 is the range for quick ablations, not production. Production
RL often runs at 1024+.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: relocate "Disaggregated prefill/decode inference" to Advanced
P/D disaggregation is a feature you opt into for large-MoE serving,
not a step on the single-GPU -> 1000-GPU scaling ladder. It pairs
naturally with Custom modeling / multi-tenant / multimodal as a
specialized inference topology, so Advanced is the right home.
- scaling.md: drop the section + TOC entry + "disaggregated
prefill/decode inference" from the page intro. Page intro now
forward-links to Advanced for users who came in for P/D.
- advanced.md: append the section after Multi-tenant training,
unchanged content (P:D ratio table, glm5_pd_disag example link,
queue-depth monitoring snippet, UCX 1.19 build-from-source note).
TOC + page-intro list updated.
- overview.md "Where to go next": drop disagg from the Scaling
bullet, add to the Advanced bullet.
Anchor preserved (#disaggregated-prefilldecode-inference) — no
external doc links to it survived the move check.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(scaling): correct the Single GPU section
The previous claim "trainer and inference server can share a GPU"
via the rl launcher was wrong. Verified against
src/prime_rl/entrypoints/rl.py:86-99: the launcher partitions
visible GPUs strictly (inference 0..N-1, trainer N..N+M-1) and
raises ValueError when total_requested_gpus > len(physical_gpu_ids).
Setting CUDA_VISIBLE_DEVICES=0 + --num-infer-gpus 1 +
--num-train-gpus 1 makes total=2, visible=1, validation fails
before anything launches.
What actually works for single-GPU RL is the manual three-pane
launch: each of uv run {inference,orchestrator,trainer} is an
independent process with no cross-process GPU validation, so
pinning CUDA_VISIBLE_DEVICES=0 on inference *and* trainer lets
them share the same physical GPU.
- Drop the misleading `uv run rl` recipe.
- Promote the manual three-pane recipe to the canonical single-GPU
path, with CUDA_VISIBLE_DEVICES=0 spelled out on both the
inference and trainer panes.
- Lead with SFT (where single-GPU is the default and just works).
- Add an explicit "single-GPU RL is for debugging only" caveat.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(scaling): collapse Single GPU / multi-GPU / Multi-node manual into one umbrella
- New umbrella section "## Single-node vs. multi-node deployment"
framing the [deployment] discriminated union as the user-facing
knob: single_node runs locally; multi_node currently goes through
SLURM. Subsections nest beneath:
- ### Single GPU (unchanged content from "## Single GPU")
- ### Single-node multi-GPU (unchanged from "## Single-node multi-GPU")
- #### RL placement
- #### SFT and torchrun
- ### Multi-node (new short pointer to ## SLURM with two cross-
links to the existing RL / SFT-and-inference examples)
- The umbrella section opens with a callout that manual multi-node
launches are technically possible but reimplement what the SLURM
launcher does — the user's preferred framing.
- Drop "## Choosing a layout" entirely (the new umbrella section
conveys the same routing more naturally + the layout table was
going stale).
- Drop "## Multi-node (manual)" entirely (RL training, SFT training,
Multi-node inference subsections all gone). Anyone who needs the
manual recipe can replicate what the SLURM templates do.
Cross-link fixes:
- training.md SFT § Launch line previously pointed at
scaling.md#sft-training (under "## Multi-node (manual)"). Now
points at scaling.md#sft-and-torchrun for non-default single-node
layouts and scaling.md#slurm for multi-node.
- faqs.md "Multi-node without SLURM or K8s?" answer updated: from
"yes, see [Scaling § Multi-node (manual)]" to "not currently
documented; technically possible but reimplements the SLURM
launcher".
Page intro adjusted to match the new structure ("multi-node SLURM
and Kubernetes deployments" -> "single-node and multi-node
deployments").
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: drop Kubernetes coverage for now
The K8s Helm chart at k8s/prime-rl/ still ships, but the user-facing
docs are dropping coverage until the chart and the matching guide
are re-validated together.
- scaling.md: drop the "## Kubernetes" section + TOC entry. Page
intro already covered (was reworded earlier in the restructure).
- overview.md "Where to go next": drop "Kubernetes guides" from
the Scaling bullet.
- README.md docs index: drop "Kubernetes" from the Scaling bullet.
The two passing-mention "k8s" / "Kubernetes" lines in README
(Overview features list, Advanced Training Examples adaptability
note) are left as-is — they describe codebase capability, not docs
coverage. Reference.md still mentions Kubernetes liveness probes in
an auto-generated field docstring; that's source-side, out of scope
for this pass.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(development): tighten test-suite layout bullets
- Drop the example test filenames from the tests/integration/
bullet — they're a moving list and not the point.
- Reframe the tests/nightly/ bullet around what it does (runs the
examples/ configs to catch regressions) instead of listing the
individual nightly tests by name.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(development): drop the nightly 24h-timeout / research-cluster aside
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(development): polish 'Adding a new architecture' prose
- Replace the bare 'To add (e.g.) Kimi 2.5:' opener with a one-line
framing of the two-step contract: implement modeling code,
register a mini preset for smoke-testing.
- Bold the leading verb on each numbered step so the structure
reads as a checklist.
- Step 1 now nudges readers at glm4_moe/ and qwen3_moe/ as
templates for the modeling code.
- Step 2 explains *what* the preset is for ('build a ~0.5B test
model in your architecture') rather than just listing fields.
Path now links to scripts/mini_moe.py.
- Step 3 says what the smoke-test actually exercises (roundtrip +
SFT + RL stack) so users know what 'smoke-test' means here.
Co-authored-by: Cursor <cursoragent@cursor.com>
* ci(docs-reference): add minimal GITHUB_TOKEN permissions
CodeQL alert actions/missing-workflow-permissions
(security/code-scanning/19) flagged the new workflow for relying on
the repo's default GITHUB_TOKEN permissions.
The workflow only checks out code (contents: read), syncs deps via
uv, runs the doc generator, and runs git diff. None of that needs
write scope on any resource type. Pin to contents: read at the
workflow level — explicit minimum that satisfies the rule.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: refresh architecture + async diagrams
- assets/architecture.png: replace with the new diagram (trainer
+ orchestrator + inference deployment, GPU layout per process,
data + scheduling + weight-broadcast arrows). Was 511k 96dpi,
now 111k @ 200dpi from architecture.pdf.
- assets/two-step-off-policy.png removed; assets/async-pipeline.png
replaces it with the cleaner one-step-overlap diagram (trainer
steps g_0..g_n above, inference samples with theta_{n-1} below).
algorithms.md image reference + alt text updated to match the
post-deprecation "one-step overlap" framing.
- assets/rollout-timeline.png added but not yet referenced. It's a
continuous-time view showing rollouts spanning policy boundaries
(policies pi_{i-2}, pi_{i-1}, pi_i on the x-axis with rollout
bars crossing the boundaries) — that's the picture behind
max_off_policy_steps, not max_async_level. Want me to drop it
into algorithms.md (e.g. above the off-policy / max_off_policy
discussion) or save it for later?
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: normalize package mentions to [\`pkg\`](github-url)
User-facing prose mentions of verifiers / renderers / research-
environments / pydantic-config now consistently render as code-spans
with a github link to the package. Affected lines:
- overview.md: orchestrator-bullet [verifiers](url) (dropped the
bare-text variant), install paragraph (linked all three submodules
individually), quick-run paragraph.
- algorithms.md: "Since [\`verifiers\` v0.1.8]..." (added backticks
around the package name in the release-tag link).
- training.md: SFT \"verifiers submodule\" launch line, useful-knobs
vf_level row, tool-defs paragraph.
Intentionally left alone:
- algorithms.md \`verifiers.RolloutOutput\` (dotted-path code ref;
whole expression already in code).
- algorithms.md / training.md [renderers](#renderers) / [Renderers]
(#renderers) (internal anchors to the in-page section, more useful
than the github repo for a reader inside the doc).
- algorithms.md "Hand-coded renderers ship for ..." and "the
renderers writeup on the PI blog" — generic prose, not a package
mention.
- reference.md docstring-sourced mentions ("verifiers package",
"renderers package", etc.) — those come from Pydantic field
docstrings; would need source-side edits + regen.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(overview): drop the async-by-default + loss summary paragraph
Out of date with the max_async_level deprecation and duplicates
content already covered properly in algorithms.md (one-step overlap
framing + the AIPO/KL loss math). Architecture bullets above
already mention async semantics where relevant.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(overview): tighten 'Where to go next' to one-line pitches
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(readme): collapse test-suite commands into one code block
Was four separate code blocks separated by one-line prose; now a
single bash block with inline-comment annotations for each variant.
Reads cleaner and matches the test-suite block in development.md.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: review-pass cleanups (max_async_level fallout, anchor fix, smoke-test)
Self-review found a handful of small inconsistencies and stale claims
that survived earlier passes.
Stale max_async_level references (now hardcoded to 1, so any prose
that treats it as tunable is wrong):
- faqs.md: "If growing, drop max_async_level or LR" -> drop
max_off_policy_steps. NCCL FAQ no longer says "requires
max_async_level=1" — that constraint is vacuous.
- training.md Rules of thumb: NCCL/max_async_level=1 dropped from
the dry-run validator example; CP / flash-attention example
stays.
- scaling.md NCCL example: drop the trailing
"# synchronous; max_async_level forced to 1" comment.
Other accuracy / consistency fixes:
- faqs.md hardware FAQ: drop "you can co-locate both on a single
GPU" — verified earlier that the rl launcher rejects this; the
manual three-pane recipe is the actual single-GPU path. Cross-
link to Scaling § Single GPU.
- faqs.md max_off_policy_steps wording: "throughput-vs-noise knob"
-> "off-policy dial" to match algorithms.md / training.md.
- training.md sft.data.loss_mask cross-link: anchor was
reference.md#sft-data (the discriminated-union heading); the
loss_mask sub-table actually lives at #sft-data-sft-loss-mask.
- development.md "Smoketest training" -> "Smoke-test training" in
the section title and TOC anchor, matching the hyphenated verb
form ("smoke-test the new architecture") used in the page body.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: review-pass cleanup (drop FAQs, Title Case, smell fixes)
Four asks rolled in:
1. **Drop docs/faqs.md entirely.** Removed the file plus all its
cross-references: docs/mint.json nav, README.md docs index, and
docs/overview.md "Documentation" list. The standalone Q&A page
wasn't pulling its weight against the verifiers tone reference.
2. **Title Case all headings** across the user-facing pages so the
visual style matches deps/verifiers/docs/* (which uses
"Hosted Training" / "Performance Trade-offs" etc., not sentence
case). Anchors are slug-based (lowercase + hyphen), so internal
#links survive the case flip — only the link text in cross-doc
"§ Section" references needed updating (training.md → Algorithms
§ Multi-Turn Trajectories, training.md → Scaling § SFT and
Torchrun, scaling.md → Configuration § TOML Composition,
scaling.md → SLURM § RL Example / SFT and Inference Examples).
3. **Rename overview.md "Where to go next" → "Documentation"** for
symmetry with the verifiers landing page.
4. **Smell fixes**:
a. algorithms.md had two near-identically-named subsections ("###
The default loss" under Async with the loss math, and "###
Default loss" under Loss with the mode dispatch). Collapse:
the loss math now lives under "## Loss > ### Default Loss"
together with the rl/opd/sft mode-dispatch bullets; the Async
section is just intro + step semantics. One source of truth.
b. reference.md auto-generated docstring mentions of "verifiers
package" / "renderers package" / "renderers library" /
"renderers.parsers" / "Registered verifiers environment ID"
now render as [`pkg`](github-url) links. Source-side edits in
packages/prime-rl-configs/src/prime_rl/configs/{shared,
orchestrator,sft}.py, then regenerated reference.md.
Net: faqs.md deletion (-198) dominates; everything else is small
churn for case + anchor consistency.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: tightening pass after main merge
Restructure + accuracy fixes that were piled up locally during the
SSH-signing block earlier today.
- configuration.md: note that reusing an env id requires a unique
name; drop the "See each environment's README on the Hub" tail.
- development.md: collapse "Adding a New Architecture" + "Debugging
MoE" (with its Create Mini Model + Smoke-Test Training subsections)
into a single "## Adding a New Model" with three subsections —
Implement the Modeling Code, Register a Mini Preset, Run the
Smoke Test. Page intro updated.
- scaling.md: drop "## Single GPU" subsection; rename "## Single-Node
Multi-GPU" -> "## Single-Node" so "Single-Node vs. Multi-Node
Deployment" has just two clean children. Drop the manual-multi-
node prose. Drop the [slurm] field reference table; rename the
section to "## [deployment] Block" and link to reference.md.
Collapse the two example subsections into one "## Examples" with
pointers to examples/multinode/{rl,sft}.toml. Rename "## CPU
Optimizer Offload" -> "## Optimizer Offloading". Add new "## LM
Head Chunking" subsection covering the fused_lm_head_token_chunk_
size knob. Drop torchrun phrasing in the SFT scaling subsection,
the CP recommendation paragraph, "(offloads checkpoints to CPU)"
parenthetical, "RL gradient-accumulation amortization" line,
attn = "flash_attention_2" from the memory-tight recipe, dry-run
invaluable line.
- algorithms.md: drop the Step Semantics subsection heading (body
stays); replace the AIPO link with a plain "DPPO + KL similar to
Kimi-K2.5" framing.
- advanced.md: drop the "## Custom vs HF Implementations"
subsection heading; the body becomes the lead content under
"## Custom Modeling".
- overview.md + README.md: pitch updates ("adding a new
architecture" -> "adding a new model"; FAQs row already gone).
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs: drop the auto-generated reference page and its tooling
Removes everything in the reference-generation pipeline:
- docs/reference.md — the 197k-char auto-generated field reference.
- scripts/generate_docs_reference.py — the generator that walks
Pydantic config trees, discriminated unions, list-of-models, etc.
- .github/workflows/docs-reference.yaml — the CI guard that ran the
generator and failed on git diff drift.
- .pre-commit-config.yaml — drops the local docs-reference hook
that re-ran the generator on staged config-class edits.
Knock-on cleanup of cross-references:
- mint.json: drop the "reference" page from nav.
- overview.md / README.md: drop the Reference bullet from the
Documentation list / docs index.
- configuration.md: drop the two trailing "See [Reference] ..."
pointers (under Discriminated Unions and at the end of the
Examples section).
- training.md: drop the "for the full field reference see
[Reference]" tail in Useful Knobs; the loss_mask row no longer
cross-links and just lists the four roles.
- scaling.md: drop the [Reference § trainer.model] DeepEP pointer
and the [Reference § slurm] pointer in the [deployment] block.
- algorithms.md: drop the [Reference § orchestrator length
penalties] line.
- development.md: simplify the Pre-Commit Hooks section — only the
ruff hook remains, so the configured-hooks bullet list goes away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* revert: drop github-url docstrings on config fields
The earlier edits added [\`verifiers\`](github-url) / [\`renderers\`]
(github-url) markdown to a handful of Pydantic field docstrings so
the auto-generated docs/reference.md rendered them as code-spans
with links. With reference.md now removed, those annotations are
inert clutter inside the runtime config classes — they don't render
anywhere user-facing. Restore the three affected files to their
state on main:
- packages/prime-rl-configs/src/prime_rl/configs/orchestrator.py
- packages/prime-rl-configs/src/prime_rl/configs/sft.py
- packages/prime-rl-configs/src/prime_rl/configs/shared.py
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(sft): sync validation iteration to prevent FSDP deadlock
Variable-length packing yields different per-rank batch counts in the
validation dataloader. Under FSDP every forward is a collective, so the
first rank to exit run_eval_loop deadlocks the rest in the next
all-gather. Sync a has_data flag per batch and exit together as soon as
any rank exhausts its iterator.
Fixes#2515.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(sft): inline has_data tensor in eval sync loop
Drop the preallocated tensor + fill_; constructing a 0-d cuda tensor
per iteration is effectively free and reads more directly.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* exp: general-agent
* docs: update PR description guidance
* Revert "docs: update PR description guidance"
This reverts commit b8c33de68b7a2b924b43d8cbb508afef8571091c.
* feat(general-agent): add RLM behavior learning configs
* feat(general-agent): tune behavior reward shaping
* feat(general-agent): log behavior judge state for audits
* feat(general-agent): document split behavior rewards
* feat(general-agent): document pruned behavior metrics
* docs(general-agent): record behavior judge calibration runs
* feat(general-agent): define behavior learning ablations
* chore(general-agent): move behavior learning configs
* exp(behavior-learning): add labels, prime monitor, remove cp from ablation configs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* exp(behavior-learning): source ~/.env before run to fix auth
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(slurm): source ~/.env before uv run in single-node RL template
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* exp(behavior-learning): rename prefix, pin rlm_ref, prime sandbox kill in pre-run
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* revert(slurm): drop source ~/.env from single-node RL template
Source ~/.env directly in the shell before uv run rl instead; env vars
propagate to sbatch via --export=ALL.
Reverts 3703dc05f.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump verifiers submodule to main (dd89b5e9)
Picks up #1395 which fixes the ParsedToolCall subscription bug in
renderer_client.from_native_response — previously raised
'ParsedToolCall' object is not subscriptable on every rollout.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* exp(behavior-learning): switch model to Qwen3-4B-Thinking-2507
4B-Instruct hallucinated tool names and gave up after a few errors
(reward ~0.4% at step 2). Try the thinking variant which is better
at structured tool-use.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* exp(behavior-learning): log behavior metrics in baseline without affecting reward
Set behavior_judge_model + behavior_reward_alpha=0.0 so the judge runs
and behavior_<key> metrics get logged, but final_reward stays equal to
task_reward.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* exp(behavior-learning): log behavior metrics in prompt run without affecting reward
Same change as baseline: enable judge for metrics but alpha=0.0.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* exp(behavior-learning): cap ablations at 200 steps, log behavior metrics in prompt run
- prompt run: enable judge with alpha=0.0 so behavior_<key> metrics
get logged but final_reward stays equal to task_reward (same setup
as baseline)
- all four configs: max_steps 1000 → 200 to keep ablations bounded
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump research-environments to include behavior-judge team-id fix
Picks up PrimeIntellect-ai/research-environments@769298b1 which forwards
PRIME_TEAM_ID as X-Prime-Team-ID on behavior judge requests, so the judge
bills the team balance instead of the user's personal balance.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump research-environments to include final_reward fix
Picks up eaaabf3c which makes final_reward use state.get() so judge
failures don't zero out task_reward.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* exp(behavior-learning): bump context to 65K with cp=2 on all configs
Previous runs (cp=1, 32K) saw 6-9% truncation rate and output_tokens
hitting the 32K cap on long trajectories. Double the seq_len and
max_model_len; cp=2 keeps per-rank activation memory flat under the
2x context.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump research-environments to log un-gated behavior_reward
Picks up fdca6d76 which logs behavior_reward as the raw judge mean
(independent of task_reward) and moves the solution gate into
final_reward.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* exp(behavior-learning): extend max_steps to 400 for phase-3 continuation
All 4 phase-2 runs completed step 200 with promising trajectories.
Extend max_steps to 400 to continue training from the step_200
checkpoints.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* exp: move general-agent and behavior-learning configs into private submodule
The general-agent + behavior-learning configs are not meant for the public
prime-rl repo. Move them into the research-configs submodule mounted at
configs/private/ so they share access controls with the rest of our
internal experiment configs.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump configs/private to include phase-3 behavior-learning RESULTS.md
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* exp(general-agent): bump research-envs, add public RLM configs, rename eval-config helper
- Bump deps/research-environments to origin/main HEAD (general-agent 0.1.4)
- Add configs/general_agent/{rl_qwen3_0p6b_debug,rl_qwen3_4b,rl_qwen3_30b_a3b}.toml
using the general-agent-solver-rlm env
- Rename is_vf_eval_config -> is_eval_config in tests/unit/test_configs.py
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* exp(general-agent): rename 0p6b config, point all configs at general-agent-debug wandb project
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump configs/private to expand behavior-learning RESULTS
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump configs/private for tightened behavior-learning RESULTS
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* exp(general-agent): drop num_workers/max_retries/tool_call_parser, set step counts
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore: deprecate user-facing max_async_level, hardcode to 1
Removes `max_async_level` as a user-configurable knob on `OrchestratorConfig`,
`TrainerConfig`, and the shared `RLConfig`, and replaces internal usage with a
constant `MAX_ASYNC_LEVEL = 1` in `prime_rl.utils.utils`. This was the only
value compatible with NCCL weight broadcast, and exposing it invited
misconfiguration (the trainer/orchestrator values had to match, and bench mode
+ a few configs overrode it ad-hoc).
Drops the now-redundant NCCL validators on both sub-configs and the
shared-field propagation/validator for `max_async_level`. Also removes the
bench-mode `max_async_level = int(1e9)` workaround (no replacement flag).
Closes#2630.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(async): drop MAX_ASYNC_LEVEL mention, describe as one-step overlap
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor: simplify step logic now that async lag is fixed at one
Now that the trainer/orchestrator always run with a one-step async barrier,
inline the value where it actually appears (scheduler ckpt math, trainer
broadcast skip, filesystem cleanup) and drop the indirection through a
``MAX_ASYNC_LEVEL`` constant — the value is a design invariant, not a
configuration knob, and naming it as a constant just made it look tunable.
- scheduler: factor out ``_async_away_ckpt_step()`` so both ``_compute_next_ckpt_step``
and ``_apply_policy_update`` share a single source of truth, skip the
``get_latest_ckpt_step`` filesystem read entirely in strict mode, and clean
up the awkward ``>1 step(s) ahead`` log line.
- trainer: replace ``last_async_level_steps`` with a ``nccl_broadcast_unused``
flag that names the actual reason the broadcast is skipped (NCCL receivers
have torn down). Filesystem broadcast still writes through to the final step
for resume support.
- ``maybe_clean``: drop the ``async_level`` parameter (only one caller, fixed
value) and document why we delete the dir from two trainer steps ago.
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(scheduler): drop _async_away_ckpt_step helper, inline step math
The helper wrapped a single ``max(self.step - 1, 0)`` and was being called
three times across two methods, adding indirection without saving anything.
Inline it with a localized comment explaining the one-step lag invariant in
each method, and flatten ``_compute_next_ckpt_step`` so the strict path is a
guard around the latest-ckpt lookup rather than a separate early return.
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore: deprecate user-facing strict_async_level
The strict-mode branch existed to support an "always exactly one step
behind" reproducibility/ablation knob, but it's never been the default and
exposing it just complicated the scheduler. Drop the field on
``OrchestratorConfig``, the constructor parameter on ``Scheduler``, and
collapse ``_compute_next_ckpt_step`` to the single non-strict path
(``max(step - 1, 0, latest_ckpt)``).
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(scheduler): drop redundant 0 clamp in _compute_next_ckpt_step
``latest_ckpt_step`` already falls back to 0 (via ``... or 0``), so it
dominates the explicit ``0`` argument in every case — including
``self.step == 0`` startup, where ``latest_ckpt_step`` is also 0. Dropping
it makes the intent clearer: advance to at least step - 1, or to whatever
the trainer has broadcast if that's newer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* docs(changelog): note max_async_level / strict_async_level removal as breaking
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(logger): preserve traceback in JSON sink with enqueue=True
loguru's RecordException.__reduce__ unconditionally drops the
traceback object before pickling, so records dequeued by the
enqueue=True worker have exc.traceback=None and the JSON sink
emits only the exception type + message - no frames.
Pre-format the traceback into extra["_traceback"] via a loguru
patcher that runs at log time, while the live traceback is still
attached. The string survives pickling, and build_log_entry reads
it back into the "exception" field.
enqueue=True is kept because the trainer's torchrun workers all
write JSON lines to a shared inherited stdout, and loguru's docs
flag this as the case where the multiprocessing-safe queue is
required to avoid interleaved/corrupt output.
* refactor(logger): drop underscore prefix from traceback patcher/key
* chore(logger): tighten traceback patcher comments
* Add indexCache training support
* fix glm moe dsa index cache threading
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
* Delete tests/unit/train/models/test_glm_moe_dsa_index_cache.py
Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
* fix
* refactor: group IndexCache knobs into IndexCacheConfig sub-config
Replaces the three flat ModelConfig fields (use_index_cache,
index_topk_freq, index_topk_pattern) with a single
index_cache: IndexCacheConfig | None = None sub-config.
None signals "disabled" explicitly, so the brittle model_fields_set
check in get_model goes away. HF/vLLM-side flat fields stay flat —
they're written from the sub-config only when it's set.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
Co-authored-by: samsja <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The `rl` entrypoint now only manages student-policy inference. External
teachers (OPD, local-vLLM SFT) must be started manually and pointed at
via `[orchestrator.teacher.client]`.
Removed:
- `[teacher_inference]` block from `RLConfig`
- `deployment.num_teacher_gpus` (`SingleNodeDeploymentConfig`)
- `deployment.num_teacher_nodes` (`MultiNodeDeploymentConfig`)
- launcher code that spawned/monitored the teacher inference subprocess
- related validators (`auto_setup_teacher_inference`,
`_stub_orchestrator_teacher_for_auto_setup`,
`validate_no_teacher_in_multinode`,
`teacher_inference_not_supported`)
Fixes#2627
Co-authored-by: Cursor <cursoragent@cursor.com>
Each job referencing environment: ghcr-publish requires its own admin approval. manifest only combines arch-suffixed tags that build already pushed (and build was already approved), so a second approval doesn't add meaningful security but adds friction. Keep the gate on build.
* chore: also publish image to ghcr + add manual trigger
* chore: drop push/tag triggers, keep manual dispatch only
* chore: revert release.yaml, add manual ghcr build workflow
* fix: avoid script injection by passing inputs via env
* fix: trim trailing dash after tag truncation
* chore: dispatch build_image after creating dev tag
* multi platform builds (am64 and arm64)
* OCI metadata
* remove temporary push trigger
* trigger image builds when gh releases are published
* add step to init public submodules
* add pydantic-config to submodules
* should fail on failed image builds
* chore: gate ghcr publish on environment + ref/tag allowlist
- Require ghcr-publish environment for build and manifest jobs (admin approval)
- Reject refs other than main, v*, or *.dev*
- Disallow custom tag input unless ref=main, so a feature branch can't overwrite v1.2.3
* chore: allow tag input when it matches ref
Release events and the dev-tag auto-dispatch always pass ref==tag (e.g. v1.2.3/v1.2.3); the previous guard rejected those because tag was set and ref was not main. Only block when tag and ref diverge.
* chore: serialize same-tag builds and skip manifest job when single-arch
- Add concurrency group keyed on resolved tag so two runs for the same image queue rather than interleave (would otherwise mix arch digests in the unsuffixed manifest).
- Skip the manifest job when platforms != 'both' so a single-arch dispatch can't replace an existing multi-arch :tag with a single-arch index. The suffixed :tag-amd64 / :tag-arm64 are still pushed by build.
---------
Co-authored-by: eexwhyzee <13672394+eexwhyzee@users.noreply.github.com>
Pulls in PrimeIntellect-ai/pydantic-config#14, which stops
`BaseConfig._coerce_dict_str_values` from rewriting string values in
`dict[str, str]` fields. Configs like
`configs/private/rlm5/glm5-swe.toml` that set
`prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0"}` previously
failed validation because "0" was coerced to int(0); they now load.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: probe github ssh auth directly in install.sh
The previous `has_ssh_access` probe ran `git ls-remote` against the
public prime-rl repo, which can return success under SSH connection
multiplexing, cached creds, or other states without the local key
actually being registered with a GitHub user. When that happens, the
HTTPS `insteadOf` rewrite is never applied and private-submodule
clones fail with "Permission denied (publickey)".
Use `ssh -T git@github.com` and grep for the canonical
"successfully authenticated" string instead. This is a direct check
of the precondition (your key is registered with a GitHub user) and
matches the pattern git itself recommends.
* fix: capture ssh output to var so pipefail doesn't mask success
`ssh -T git@github.com` always exits 1 (GitHub denies shell access
after authenticating), and install.sh has `set -o pipefail` at the
top, so the previous pipeline made has_ssh_access return failure even
for developers with valid keys. Capture stdout/stderr into a variable
first, then grep — keeps pipefail intact for the rest of the script.
* fix: use universal ssh options in github auth probe
`StrictHostKeyChecking=accept-new` requires OpenSSH 7.6+ (Sep 2017).
On older systems ssh errors with 'Bad configuration option' and the
probe wrongly reports no SSH auth, forcing HTTPS even when SSH would
have worked.
Use `StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null`
instead, which works on all OpenSSH versions. Safe for a probe-only
flow: no key material is exchanged, and a hostile MITM at worst
makes the probe wrongly report 'no SSH', causing HTTPS fallback for
public repos.
* fix: rely on ensure_known_hosts and default ssh host key checking
Previous commit disabled `StrictHostKeyChecking` and `UserKnownHostsFile`
to side-step OpenSSH version requirements, but that made the auth probe
trust any host that returns the "successfully authenticated" string —
a MITM could steer the script into using their SSH for submodule
clones.
`ensure_known_hosts` already runs (line 116) before any
`has_ssh_access` call and populates github.com via ssh-keyscan, so
default host key checking is both safe and sufficient. Drop the
options entirely; keep `BatchMode=yes` to suppress prompts.
* fix: propagate insteadOf to submodule clones via GIT_CONFIG_* env
`git submodule--helper clone` spawns fresh `git clone` processes
that read only ~/.gitconfig and env vars — not the parent repo's
local .git/config. So setting `url..insteadOf` locally never reached
the submodule clones, and they kept attempting SSH despite the probe
correctly reporting no auth.
Use `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_0`/`GIT_CONFIG_VALUE_0` which
propagate the rewrite to every child git process for the duration of
this script, with no persistent state in ~/.gitconfig.
The docs and a couple of example READMEs described slurm usage that
no longer matches the real config system - users following them would
hit validation errors.
- docs/slurm.md: drop bogus `toml_files = [...]` (not a pydantic-config
feature) and document the real `@ base.toml @ overlay.toml` compose
syntax. Rename `[orchestrator.sampling]` and `[[orchestrator.env]]`
to the current `train`-scoped paths, swap `max_tokens` for
`max_completion_tokens`, repoint dead `examples/hendrycks_math/`
links to `examples/multinode/`, fix the inference example filename
and `--dry-run` flag usage
- examples/hendrycks_sanity/README.md: the slurm command was invoking
the overlay alone (which fails validation), compose base + overlay
- examples/wiki_search/README.md: stale `[[orchestrator.env]]` path
* chore(orchestrator): gate pretokenize_rollout_trajectory on SFT mode
Only call the pretokenize fallback in sft mode. The renderer-backed and
MITO rollout clients populate step["tokens"] from vLLM's prompt_token_ids
and token_ids extensions, so the call is a no-op there. sft from an
external teacher (e.g. openai/gpt-5-mini via PI inference) does still
need the fallback because external APIs return no token IDs.
Verified on examples/reverse_text/rl.toml @ 5 steps:
- renderer (default): reward 0.11 → 0.24
- MITO (--no-orchestrator.use-renderer): reward 0.11 → 0.20
- sft external (configs/debug/training_modes/sft_external.toml): reward ~0.92, all 5 steps complete
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(orchestrator): gate pretokenize on tokens-missing, log when it runs
Replace the training_mode == "sft" gate with a behavioral check on
step["tokens"] is None. This skips the 256-way to_thread fanout for
SFT against a local vLLM teacher too (vLLM populates tokens via
prompt_token_ids/token_ids), not just RL/OPD. Only the external teacher
API path (OpenAI/etc.) actually needs the fallback. Log inside the
guard so it's visible when the work runs.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(orchestrator): rename pretokenize_rollout_trajectory -> backfill_rollout_tokens
"Pretokenize" was misleading - the function is a backfill that fills in
step["tokens"] for any step where it's None, run only when the rollout
source (e.g. external teacher API) didn't return token IDs.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(orchestrator): default X-Session-ID header to trajectory_id
Switch the auto-injected `X-Session-ID` sticky-routing header from
`example_id` to `trajectory_id` so each rollout (rather than each
dataset example) pins to a single inference engine.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: bump configs/private submodule
Pin to the research-configs branch dropping the explicit
`X-Session-ID = example_id` override on `rlm5/{prod,glm5-swe}`
so they pick up the new `trajectory_id` default.
See: PrimeIntellect-ai/research-configs#2
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* perf(transport): offload TrainingBatch send to a worker thread
Make FileSystemTrainingBatchSender.send async and run the msgspec encode
+ disk write in asyncio.to_thread. Keeps the orch event loop responsive
during step transitions when the batch payload is large.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* perf(orchestrator): await async sender; to_thread advantages+filters+uvloop
- await training_batch_sender.send(training_batch) since sender is async (O1+O2)
- compute_advantages and apply_filters wrapped in asyncio.to_thread (O3+O4):
both iterate ~2k rollouts in pure Python and release the GIL on every
bytecode tick, so threading actually helps unlike the C-extension encode
- main() installs uvloop (O7) — lower scheduler overhead matters when the
orchestrator is juggling many concurrent rollouts + the HTTP client to
inference; measurably reduces tail latency.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* perf(orchestrator): log p99 event-loop lag in metrics + busy-loop warning
p90 alone undersells the long tail we see at step boundaries. p99 is the
metric we actually compare across runs, so surface it in the wandb dict
(`event_loop_lag/p99`) and in the busy-loop warning line.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* perf(orchestrator): defer routed_experts concat in interleave_rollout
extend_sample's previous implementation unpacked the accumulated
routed_experts bytes, mutated one boundary entry, np.concatenated the new
step's routings, then re-packed to bytes — every extension. For an N-turn
rollout reaching seq_len 60k, the accumulated buffer reached ~23 MB and was
fully read+written N times, giving O(N²) byte work (~2.3 GB of memcpy per
rollout). At 256 rollouts/step this dominated the orch's step-boundary
event-loop stalls more than the encode path we'd already fixed.
Defer the concat: track per-sample `chunks: list[np.ndarray]` during the
extension loop and finalize once at the end. The "boundary token" entry
that vLLM omits for each request is appended as its own one-entry chunk
between consecutive steps' contributions, so the final concat is a
straight join — no destructive writes to prior chunks.
Verified byte-exact against the old implementation on a 50-step extension
chain. Per-rollout work drops from O(N²) → O(N): ~100× less memcpy in the
realistic regime.
This makes use_process_pool unnecessary for the residual orch lag: each
rollout's process_rollout cost drops below the IPC pickle cost, so the
threaded path is strictly better.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* perf(orchestrator): orjson save_rollouts + dedup bool conversion
- save_rollouts: json.dump -> orjson.dumps + bytes write. The pure-Python
serializer held the GIL for the whole save phase (multi-second spikes
on big steps); orjson serializes in C and releases the GIL.
- prepare/make/extend mask handling: [bool(i) for i in mask] was the
remaining per-turn GIL-held Python loop. make_sample/extend_sample
swapped to list(...) / direct extend; prepare_step_tokens uses
list(map(bool, ...)). Together drops gather wallclock 5-10% on
long-tail rollouts.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* perf(orchestrator): skip pretokenize fanout when nothing needs work; 10Hz lag monitor
- Pretokenize was a no-op for router-replay (every step already has
tokens populated by the renderer client), but the 256-way to_thread
fanout starved the loop for ~2 s per step. Short-circuit when no
rollout's trajectory has unpopulated tokens. Offline attribution:
pretokenize lag drops 2050 ms → 11 ms.
- EventLoopLagMonitor sampling 1 Hz → 10 Hz (mirrors verifiers'
monitor). 1 Hz was missing sub-second spikes that show up clearly
at 10 Hz.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump verifiers submodule to a930f2e5 (post-1453 main)
Pulls in the env_worker / env_router event-loop lag fixes that just
landed on verifiers main via PR 1453 — required for the orch-side
gains in this PR to surface under realistic 256-rollout concurrency.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Sami <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Renames the orchestrator-level, [orchestrator.eval] group-level, and per-env
[[orchestrator.eval.env]] fields. The old name still parses as a validation
alias in both TOML and CLI, so existing configs keep working unchanged.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(scheduler): train on partial groups instead of dropping on rollout error
When an individual-scoring env returns N rollouts for a single example and one
errors out, scrap only the failed rollout — keep the survivors and ship the
group through as soon as every dispatched rollout has come back (success or
failure). Group-scoring envs still drop the whole group on any failure because
their per-rollout scores are computed against the now-missing rollouts.
To make variable-size groups round-trip through advantage computation, group
rollouts by (env_name, example_id) instead of positional slicing, and bucket
groups by size so each advantage_fn call still sees a uniform 2D rewards
tensor. Singleton groups produce zero advantage and get filtered out by the
existing zero-advantage filter — no special-casing.
Closes#2585.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(advantage): make advantage_fn per-group
Drop the bucket-by-size workaround in compute_advantages by changing the
advantage_fn contract: AdvantageInputs.rollouts is now a single group
(list[RolloutOutput]) and AdvantageOutputs.advantages is 1D. The framework
calls advantage_fn once per group, which works cleanly for variable-size
groups (partial-group training).
BREAKING: second change to this public API in three weeks. Custom advantage
functions must drop the outer list dim. Migration documented in CHANGELOG.md
and docs/bring-your-own-algorithms.md.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(advantage): return list[float] from advantage_fn
Drops the torch tensor from the public AdvantageOutputs contract; internal
math stays in torch and converts via .tolist() at the boundary. Same partial-
group support, simpler downstream consumers (no more .tolist() / no shape
gymnastics in custom advantages).
BREAKING (folds into the per-group change in the previous commit): custom
advantage functions must return AdvantageOutputs(advantages=[...]) rather
than a tensor. CHANGELOG entry and docs example updated.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(scheduler): log each rollout failure inline, drop GroupState.last_failure_reason
The reason is now logged at the moment the failure is observed (one warning
per failed rollout) instead of being stashed on the group and replayed at
finalization. Removes the per-group field entirely and avoids the "first vs
latest wins" semantic question that came up in review - each log line carries
its own actual reason. Finalization warnings only carry counts now.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(scheduler): drop verbose comment on GroupState.failed_rollouts
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(orchestrator): per-env state_columns for extra rollout fields
Adds `state_columns: list[str] = []` to `EnvConfig` so each env can
persist additional `State` fields into the saved JSONL rollouts on top
of the always-saved `trajectory` and `sampling_args`. Merged at the
call site (required first, deduped).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor: drop seen set from state_columns dedup
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The pre-launch cleanup block runs `pkill -9 -f "[v]llm"` to mop up
orphans from prior jobs. The `[v]llm` regex-trick relies on no literal
`vllm` appearing in the matching cmdline, but the surviving lines in the
same block do — `pkill -9 "vllm"`, `pkill -9 "vllm::.*"`, the
`/tmp/vllm-*` glob, and the closing `grep -E "...vllm..."`. With
`srun bash -c '<script>'` the entire script body lives in both srun's and
the inner bash's argv, so `[v]llm` matches them and SIGKILLs the cleanup
processes mid-flight. `set -e` then bubbles it up and the batch dies
before any component starts.
Switch to `srun bash -s <<'CLEANUP_SH' ... CLEANUP_SH`. The heredoc goes
over stdin, so the cmdline of srun and bash on every task is just
`srun bash -s` / `bash -s`. `pkill -f "[v]llm"` no longer self-matches
and the cleanup completes normally on every node.
Verified on cluster (multinode RL example): pre-fix the cleanup step
died with `9:0` in 6 s; post-fix the cleanup step exits `0:0` and the
log shows `[node-cleanup] <host> procs=1 gpu_mem=0MiB` from both nodes.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(orchestrator): deep-merge legacy model/client aliases; switch multinode template to canonical CLI path
`fold_student_shortcuts` previously skipped re-nesting top-level `client`
into `student.client` when the latter was already populated (and used
`setdefault` for `model`, so existing keys won). That meant a CLI override
like `--client.base-url URL` could never reach `student.client.base_url`
once the TOML provided `[student.client]` — pydantic's `extra="forbid"`
rejected the leftover top-level `client` with `Extra inputs are not
permitted`. Same shape for `--model.<k>` against TOML `[student.model]`.
Deep-merge with the legacy (top-level / CLI) side winning at the leaf.
TOML values that the CLI doesn't touch are preserved.
Also update `multi_node_rl.sbatch.j2` to use the canonical
`--student.client.{base-url,admin-base-url}` instead of the legacy alias.
The new path is a known leaf in pydantic-config, so single-value args
get list-wrapped correctly (the legacy alias goes through the unknown-leaf
branch and would still produce a raw string).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* nit: rename _deep_merge_into -> deep_merge, drop redundant comment
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(scheduler): drop group on rollout error instead of rescheduling
Raise per-env max_retries default from 0 to 3 so transient infra failures
are absorbed inside the env server. Drop any group whose rollout bubbles
up with an error or empty trajectory, log it, and let the rest of the
batch proceed — no in-orchestrator reschedule, no partial-group salvage.
Removes max_error_reschedule_attempts and the GroupState round/attempt
tracking. Closes#2475.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(scheduler): count every failed rollout in error metrics
Iterating over the rollouts and breaking on the first failure undercounted
errored_rollouts/empty_rollouts for group-scoring envs (which return N
rollouts per task), deflating the reported error rate.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat(scheduler): emit error/<type>/count metric per step
Adds errors_by_type tracking keyed by ErrorInfo["error"] (the outermost
exception class name from the verifiers error chain), surfaced to wandb
as error/<type>/count. Lets dashboards see which failure mode (e.g.
OverlongPromptError vs InterceptionError vs SandboxError) is driving
dropped groups, instead of one opaque errored_rollouts rate.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Each DP rank was dividing its summed token loss by its own local
loss_scale, then FSDP averaged the resulting gradients. Because ranks
process different sequence lengths, that mean is not the true per-token
mean over the global batch — ranks with fewer loss tokens get implicitly
upweighted.
Mirror the SFT trainer fix (src/prime_rl/trainer/sft/train.py:416-427):
all-reduce the local token count across dp_cp, divide by that global
denominator on every rank, and multiply grads by fsdp_gradient_divide_factor
after the microbatch loop so FSDP's per-rank averaging is undone and the
final gradient is the per-token mean over the global batch.
Closes#2358. Adapted from #2359, which first diagnosed the bias and
proposed the all-reduce-then-rescale approach.
Co-authored-by: irfanjamil <irfanjamil9@gmail.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat: drop use_renderer=True VLM skip; pack pixel_values from renderer
interleave_rollout now consumes renderer-emitted multi_modal_data on each
trajectory step (when present), packs the per-image pixel_values and
image_grid_thw onto the TrainingSample, and computes mm_token_type_ids —
no VLMImageCache lookup required when the rollout went through a
multimodal renderer. VLMImageCache stays as the fallback for
MITO/chat-completions rollouts.
build_trajectory_step (renderers package) was updated separately to
surface mm_data on its output, so the pretokenize-fallback path also
carries images through correctly.
Other changes:
- orchestrator config: removed validate_renderer_vs_vlm validator that
previously rejected use_renderer=True for VLMs (it's now supported).
- e2e test: a real Qwen3VLRenderer + RendererClient -> /inference/v1/generate
mock POST, plus a roundtrip through vllm's GenerateRequest pydantic
model and decode_mm_kwargs_item. Strongest end-to-end check we can
run without a GPU.
- 20-step A/B configs for color-codeword (feat-renderer vs main-mito),
both logging to W&B project 'multimodal-renderer'.
126 orchestrator unit tests pass (+2 new for renderer-mm packing).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(orchestrator): rip MITO multimodal path, renderer-only for VLMs
Delete the MITO chat-completions multimodal branch from the orchestrator
and the ~370 lines of image-cache/preprocess machinery in trajectories.py
that supported it. VLM training now goes through the renderer path
exclusively — the renderer owns the processor, ships byte-identical
pixel_values to both vLLM (via /inference/v1/generate features) and the
trainer (via mm_kwargs).
Renderer-shipped mm_token_type_ids: the orchestrator reads the renderer's
`mm_token_type_id_map` property (1=image_pad, 2=video_pad) and stamps a
per-token list onto each TrainingSample. Trainer's `_get_qwen3_vl_mm_token_type_ids`
auto-path remains as a fallback but the renderer is now the source of truth.
forward() now takes a generic `mm_kwargs: dict` (e.g. {pixel_values,
image_grid_thw}) instead of the Qwen3-VL-specific (pixel_values, image_grid_thw)
keyword pair, so adding new VLM families (Gemma3, LLaVA, etc.) doesn't
require touching forward.
Config validator: orchestrator.use_renderer must be true when model.vlm is
set — fail at config-load instead of producing cryptic runtime errors.
Test cleanup: drop 25 tests for removed helpers (VLMImageCache, _extract_images,
etc.); update the one remaining renderer-mm trajectory test to pass
`mm_token_type_ids_mapping` directly.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: align with renderer-multimodal PR surface (configs + deps + tests)
CI was failing for three reasons after the cherry-pick of the renderer
multimodal commits onto current origin/main. Three fixes:
1. Multimodal configs missing the renderer flag pair. The orchestrator
config validator (added in the same PR) requires
``use_renderer = true`` when ``model.vlm`` is set, AND it's mutually
exclusive with ``use_token_client`` (default ``true``). Three configs
(``rl_color_codeword_test.toml``, ``rl_color_codeword.toml``,
``ci/nightly/multimodal_color_codeword.toml``) needed both flags set
explicitly in ``[orchestrator]``. Delete
``rl_color_codeword_main_mito.toml`` — that was the A/B reference for
the legacy MITO path, which this PR rips out. With MITO gone the
config is no longer runnable; the ``rl_color_codeword_feat_renderer``
counterpart already covers the new renderer-driven path.
2. ``test_model_forward.py`` was still calling ``forward(...,
pixel_values=..., image_grid_thw=...)``. ``forward()`` now takes a
generic ``mm_kwargs: dict`` (so adding new VLM families doesn't
require touching the trainer signature) — update both tests to pass
``mm_kwargs={"pixel_values": ..., "image_grid_thw": ...}`` instead.
3. ``renderers`` / ``verifiers`` deps stale. The orchestrator imports
``MultiModalData`` from ``renderers.base`` (introduced in the
companion renderers PR) and threads ``multi_modal_data`` end-to-end
via the verifiers ``RendererClient`` changes. Pin both to their
feature branches until the upstream PRs merge and PyPI / git
rev-pins are bumped:
- renderers @ feat/multimodal-vlm
- verifiers @ feat/renderer-multimodal-passthrough
Drops the ``renderers==0.1.6`` PyPI pin (the new symbols are post-0.1.6).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: bump renderers + verifiers to latest feature-branch commits
Picks up:
- renderers c3feaa5: RendererPool implements Renderer protocol structurally
(callers can drop pool unwrap + isinstance branching), size=1 fast path,
is_multimodal helper with per-type cache.
- verifiers 64f2555a: bugbot pass — multimodal dispatch fix (was broken
for pooled renderers), tighter is_json_serializable, response-tokens
mm_data strip on intermediate steps.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: bump renderers + verifiers to pick up isinstance dispatch fix
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: drop renderers git source, pin to released 0.1.7
renderers v0.1.7 is now on PyPI with the multimodal feature set this
branch consumes (RenderedTokens, MultiModalData, MultimodalRenderer
protocol, mm_token_type_id_map, RendererPool delegation).
verifiers still pinned to feat/renderer-multimodal-passthrough until
that companion PR merges.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: repin verifiers to main + bump renderers to 0.1.8.dev2
The multimodal renderer-passthrough work has merged on verifiers
(verifiers#1346 → c7731bbb, on main since 2026-05-12), so we no longer
need the feature-branch pin. Switching to a `rev =` pin on main
(f633365f) — consistent with how every other git source in this file
is pinned — and bumping renderers to 0.1.8.dev2 to match what verifiers
main now requires.
Pin updates:
- verifiers: branch `feat/renderer-multimodal-passthrough`
(0.1.14 @ 397b8aa5) -> rev `f633365f` (0.1.15.dev7)
- renderers: `>=0.1.7` -> `>=0.1.8.dev2`
- prime-sandboxes: 0.2.22 -> 0.2.26 (transitive from verifiers main)
- fastokens added (transitive from renderers 0.1.8.dev1+; renderers
routes `load_tokenizer` through fastokens by default)
What's in the verifiers delta (397b8aa5..f633365f) that touches our
surface:
- `RendererClient.from_native_response` migrated to renderers'
`ParsedToolCall` dataclass shape and filters non-OK parse attempts
(verifiers#1366 / renderers#22). Internal — the Response we consume
is unchanged.
- Routed-experts payloads now flow as opaque bytes through the chat
completions clients (verifiers PRs around the `routed_experts`
changes). Prime-rl consumes the surface that emits these; no caller
change needed.
Test plan:
- [x] `uv run pytest tests/unit/orchestrator` — 101 passed against the
new pins, including `test_qwen3_vl_e2e` which exercises the renderer
-> RendererClient -> /inference/v1/generate roundtrip path.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: drop renderers version pin, defer to verifiers' transitive constraint
We import directly from `renderers` (orchestrator + tests), so the dep
needs to be declared — but pinning a floor here is just second-guessing
verifiers, which already requires `renderers>=0.1.8.dev2`. Let verifiers
be the source of truth for the version.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(trainer): drop mm_token_type_ids auto-compute, trust renderer
The auto-compute path (`_get_qwen3_vl_mm_token_type_ids`) was preferred
over the renderer-shipped `mm_token_type_ids` in `forward()`. For
Qwen3-VL the auto function never returns `None` (allocates
`torch.zeros_like(input_ids)` then masked_fills), so the explicit
orchestrator-shipped list was silently discarded — contradicting both
the "renderer is source of truth" design and the trajectories.py
comment noting the explicit list produces ~30x lower mismatch KL.
The new `vlm_requires_renderer` validator (this PR) mandates the
renderer for every VLM config, so the auto path is no longer reachable
as a real fallback. Deleting it. The renderer's `mm_token_type_id_map`
is now the sole source of truth, exactly as advertised.
Also adding the CHANGELOG entry the validator missed — removing the
`[model.vlm]` + `use_renderer = false` combo is a breaking config
change per CHANGELOG.md's stated policy.
The remaining `if "image_grid_thw" not in mm_kwargs` branch is *not*
renderer-replaceable: it skips `position_ids` for MRoPE families
because HF's Qwen-VL `forward()` internally recomputes 3D positions
from `image_grid_thw` and breaks if given the trainer's pre-computed
1D `position_ids`. Duck-typed against the kwargs schema so any future
MRoPE family that ships `image_grid_thw` is handled without a
`model_type` enumeration.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(orchestrator): union per-step delta mm_data across sample's step range
verifiers ≥ c7731bbb (PR #1346 merge) replaced ``_strip_intermediate_mm_data``
with ``_delta_intermediate_mm_data`` (commit 9aafa659): each trajectory
step now carries only the items whose ``mm_hash`` was NOT in the prior
step's cumulative set, with multiset-aware semantics. The intended
contract is that per-window assemblers union deltas to recover the
per-sample cumulative.
Prime-rl's ``interleave_rollout`` was that assembler but still read
``prepared_steps[last_step_idx].get("multi_modal_data")`` alone,
assuming the last step held the cumulative set. With the new delta
encoding, the last step often holds **0 items** (everything was a
duplicate of step 0's cumulative set) — so the trainer was given
pixel_values for only the first turn's images. For ``color-codeword``
with ``max_turns=2, images_per_turn=2`` (4 images total), the trainer
saw a subset → wildly wrong attention → mismatch KL jumped from
~0.04 to ~7 (>100× regression). On Qwen3-VL the model raised
``ValueError: Image features and image tokens do not match`` when the
delta drop left the trainer with fewer feature blocks than placeholder
runs.
Fix: track ``start_step_idx`` per active sample and concatenate
``mm_items`` / ``mm_hashes`` across ``[start_step_idx, last_step_idx]``
in step order. No dedup here — verifiers' delta already handled
cross-step dedup with multiset semantics (legitimate duplicate
placeholders, where the same image appears in two turns' separate
placeholder runs, are preserved).
Test plan:
- ``uv run pytest tests/unit/orchestrator/test_trajectories.py`` — 20 passed
- ``uv run pytest tests/unit/orchestrator tests/unit/train`` — 216 passed, 6 skipped, 1 xfailed
- ``uv run rl @ configs/multimodal/rl_color_codeword_feat_renderer.toml``
on 2× RTX PRO 6000: Step 0 KL **0.020** (was 7.0), Step 1 **0.090**,
Step 2 **0.253** — all within the baseline range published in #2473
(max 0.487 across 20 steps).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(orchestrator): track explicit step indices per sample for mm union
interleave_rollout used (start_step_idx, last_step_idx) to bound the
mm_data union per sample. When agents interleave (e.g. agent1 at steps
0,1,3 and agent2 at step 2), the range [0,3] over-collects step 2 and
agent2's delta mm_items leak into agent1's sample.mm_kwargs — placeholder
count vs. patch count mismatches at the VLM forward.
Replace the (start, last) pair with the explicit list of prepared_steps
positions merged into the sample. _union_step_mm_data iterates the list
directly, so non-owned steps are skipped by construction.
Non-interleaved trajectories produce step_indices = [0..N], iterating
identically to the old range — bit-for-bit unchanged for the common path.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: eligotts <78387377+eligotts@users.noreply.github.com>
Previously a trainer/inference/orchestrator/router crash left surviving
components running, holding the SLURM allocation until walltime. The
sbatch script propagates the failure now:
- srun uses --kill-on-bad-exit=1 so a non-zero exit on any task kills
tasks on the other nodes.
- All per-node components run in the background; `wait -n` turns the
first exit (success or crash) into the task exit code, surfacing
background crashes (router, orchestrator) that the previous foreground
layout silently ignored.
- `set -o pipefail` inside the task and `set -e` in the outer sbatch
keep failures from being swallowed by `| tee` or by setup commands.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(wandb): handle shared mode breakage from wandb v0.26.1
wandb v0.26.1 (PR #11759) changed `inform_init` to propagate
duplicate stream ID errors as `ServerResponseError` instead of
silently swallowing them. This breaks shared mode where multiple
processes intentionally call `wandb.init(id=same_run_id)`.
- Add `resume="allow"` when a run ID is provided so wandb attaches
to the existing run instead of rejecting it
- Catch `ServerResponseError` (alongside `CommError`) for non-primary
shared-mode processes to handle transient init races
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(wandb): teardown wandb-core between init retries
A failed wandb.init leaves the run_id registered in the local
wandb-core StreamMux. The next retry hits the same wandb-core,
finds the stream still there, and raises ServerResponseError
("run ID ... is in use") regardless of resume="allow" — the check
fires before reaching the server.
Tearing down the service before sleeping clears the StreamMux so
the retry starts fresh. Also catch ServerResponseError on the
primary side, since the race is symmetric: either side can win
the upsertBucket and the other can hit this path.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(release): add tag-and-release workflow, backfill release notes, expand release skill
Port the verifiers tag-and-release pattern: on version bump in pyproject.toml,
auto-tag main and create the GitHub Release using assets/release/RELEASE_v{tag}.md
as the body. Skip the PyPI publish steps since prime-rl is not on PyPI.
Backfill release-note files for v0.1 through v0.5.0 by copying each existing
GitHub Release body so the workflow has historical artifacts to compare against.
Expand skills/release/SKILL.md so an agent can prepare the full release PR
(version bump, release notes file, draft PR) — merging the PR is then enough
to publish the release.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(release): rename v0.1/v0.2 notes to v0.1.0/v0.2.0 for consistency
Aligns all backfilled release note filenames on a MAJOR.MINOR.PATCH suffix.
The historical GitHub tags (v0.1, v0.2) keep their original names; this only
touches the on-disk filenames.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(ci): rename release.yaml to docker-push.yaml; exclude dev tags from tag-and-release
The old release.yaml only builds and pushes the Docker image; the new
tag-and-release.yaml is now the canonical "release" workflow. Renaming
removes the ambiguity.
Add a trigger filter to tag-and-release so '*dev*' tags do not flow through
the release path. devx_tag.yaml creates dev tags via GITHUB_TOKEN, which
already does not retrigger workflows; this exclusion is defensive for any
manual dev-tag pushes. Skill note updated to clarify the two workflows
coexist.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(ci): check release notes before tagging, and retry on tag-without-release
Two bugbot fixes in tag-and-release.yaml:
1. Move the assets/release/RELEASE_*.md presence check into auto-tag-on-main,
before the tag is created and pushed. Missing notes used to fail in
release-from-auto-tag, but only after the tag was already on the remote,
blocking a clean retry.
2. If the target tag already exists (locally or on origin) but no GitHub
Release exists for it yet, still emit created=true so release-from-auto-tag
runs against the existing tag. This unblocks recovery from a partial
failure (e.g. the release step crashed after the tag push) without
requiring manual cleanup or workflow_dispatch.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* refactor(release): drop in-repo release notes; promote pre-existing draft release on tag
Pivot the release flow:
- Release notes live as a draft GitHub Release created via `gh release create
--draft` (no longer tracked in the repo). Removed assets/release/*.
- The release skill instructs an agent to (1) draft the release on GitHub
with the notes inline and (2) open a draft PR that only bumps `version` in
pyproject.toml.
- On merge, tag-and-release verifies the draft release exists for the new
tag, pushes the tag, then promotes the draft via `gh release edit
--draft=false --latest`. Recovery path: if the tag exists with a draft,
the next main push (or workflow_dispatch) re-promotes it.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(skills): slim skills, rename, regroup under training/
Rename `config` -> `configs`, `installation` -> `install`. Move
`entrypoints` (as `start-run`) and `monitor-run` under a new
`training/` skill. Slim each skill (~37% fewer lines overall) and
fact-check paths/commands against the current codebase — most
notably the config-class paths now live under
`packages/prime-rl-configs/`, and rollouts are saved to
`{output_dir}/rollouts/step_N/` (no `run_default` prefix).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(skills): drop tyro mention in configs skill
pydantic-config is now Pydantic-only (TOML + CLI), no tyro dependency.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(skills): drop unsupported `@ toml --help` example
`pydantic-config` doesn't merge TOML into `--help` output; only the
class-level defaults are shown either way. Keep the plain `--help`
and `--dry-run` examples instead.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(skills): summarize pydantic-config features in start-run; trim configs
- start-run: add a brief feature summary of `pydantic-config` so the
config primitives are visible alongside the launch commands.
- configs: drop the SFT/RL domain notes (they belong with the
respective training docs, not the config primer) and collapse the
two config-package paths in "Key files" into one line.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replace the ~100-entry MODEL_TOOL_CALL_PARSER dict + runtime resolver in
server.py with regex patterns in utils/parsers.py — new model variants
match automatically without a dict entry per checkpoint. Reasoning parser
gets the same treatment (previously only the tool-call side auto-resolved).
Resolution moves to a ModelConfig after-validator (auto_resolve_parsers),
not the entrypoint. It piggybacks on RLConfig's before-validator
propagation: the shared [model] name lands in inference.model.name BEFORE
ModelConfig is constructed, so the after-validator sees the resolved name.
Testable without a running server.
Also fixes INTELLECT-3 / Qwen3-Coder mapping from hermes to qwen3_coder,
which matches the upstream HF model docs.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
pydantic-config 0.3 (drop-tyro, #2564) removed the typed-default mirror
that previously round-tripped CLI args through tyro. With that gone, a
``mode="before"`` validator on RLConfig now sees a clean dict-of-dicts and
can propagate shared top-level fields into the right sub-config keys
*before* sub-configs are constructed. Sub-configs' own ``mode="after"``
validators then see the resolved values (e.g. ``OrchestratorConfig.auto_setup_tokenizer``
sees the propagated ``student.model.name`` at the moment it derives
``tokenizer.name``, instead of running with the stale class default and
then being patched up by a load-bearing RL-level re-derive).
Replaces eight per-field ``auto_setup_*`` ``mode="after"`` validators with
a single ``auto_setup_shared_configs`` ``mode="before"`` validator using a
``fill``-if-absent helper. The previous fix-up at the RL level
(``auto_setup_tokenizer``'s "no shared tokenizer: re-derive from
(now-correct) model names") silently overrode explicit
``[orchestrator.tokenizer] name = ...`` values; with the before-validator,
explicit sub-config values survive untouched.
Also:
- keep per-field mutex ``validate_no_shared_field_conflicts`` —
duplicating a field in shared + sub-config is still ambiguous and the
mutex catches it explicitly.
- drop ``RLConfig.max_model_len`` — declared but never wired to a
validator. Users set ``inference.model.max_model_len`` directly.
- move ``auto_setup_session_headers`` from RLConfig onto
``OrchestratorConfig`` (now ``self.student.client``), so the hosted
orchestrator entrypoint also enforces it when loading standalone.
- collapse the per-field ``validate_shared_*`` calls into a single
``validate_shared_configs`` ``mode="after"`` validator that runs the
full consistency suite post-construction.
- add ``validate_shared_seq_len`` to ``utils.validation`` and the
propagation map; ``seq_len`` now also goes through the same flow.
Tests (``tests/unit/test_configs.py``): 24 new cases covering propagation
of ``model.name`` / ``tokenizer`` / ``seq_len`` / ``max_steps`` /
``output_dir`` / ``[ckpt]`` / ``[wandb]``, the per-field mutex on every
shared key, the "empty shared block coexists with sub-block" rule, the
"disjoint shared + sub fields coexist" rule, and end-to-end CLI override
of ``--seq-len`` propagating through TOML.
Crucially, ``test_explicit_subconfig_tokenizer_name_survives_shared_model_propagation``
regression-tests the case that the old RL-level fix-up silently broke:
shared ``[model] name`` propagates everywhere it should, but an explicit
``[orchestrator.tokenizer] name`` is left alone.
Three in-repo configs were tripping the new mutex; same fixes:
- configs/hendrycks_math/sanity.toml: drop redundant ``[trainer.model] name``
- examples/hendrycks_sanity/rl.toml: drop redundant ``[trainer.model] name``,
move shared ``seq_len = 8192`` under ``[orchestrator]`` so the trainer
keeps its longer 16384 context
- examples/glm5_pd_disag/rl.toml: split shared ``[model] name`` into
per-component names (trainer = GLM-5 BF16, orchestrator + inference =
GLM-5-FP8 to satisfy ``validate_shared_model_name``).
Closes#2430. Supersedes #2517 — the same approach, rebased onto
post-tyro pydantic-config which removes the need for the
``_dump_preserving_discriminators`` workaround the original PR carried.
CPU suite (matches cpu_tests.yaml): 374 passed.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(configs): convert field descriptions to PEP 224 docstrings
Now that the pydantic-config bump supports attribute docstrings, switch
every config field from ``Annotated[T, Field(description=...)]`` to a
plain typed assignment plus a single-line docstring on the next line.
``Field(...)`` is kept only where it carries other metadata
(``ge=``/``gt=``, ``validation_alias=``, ``default_factory=``).
Descriptions are tightened: dropped redundant restatements of the field
name, dropped mentions of defaults and aliases (the help renderer shows
those automatically), and dropped pydantic model docstrings (mostly
redundant). Net change is ~1.4k fewer lines across the seven config
modules.
Bumps the pydantic-config submodule to pick up MRO-aware docstring
extraction (so inherited fields keep their description) and
``default_factory`` rendering in --help.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(configs): drop trivial sub-config docstrings, base DUV variants on BaseConfig
- Drop sub-config field docstrings that just restated the field name
(e.g. ``"""Logger configuration."""`` on ``log: LogConfig``). Without
the docstring the help renderer falls back to ``<path> options`` for
the panel title, which is just as readable. Keep docstrings that carry
real info (gating semantics, propagation, side-effects, etc.).
- Switch every discriminated-union variant (and standalone ``BaseModel``
configs like ``KVCacheOffloadConfig``) from ``BaseModel`` to
``BaseConfig`` and drop the per-class
``model_config = ConfigDict(extra="forbid")`` line — ``BaseConfig``
already bakes in ``extra="forbid"`` and the TOML ``"None"`` →
``None`` coercion, so this is both leaner and more consistent (some
variants previously had ``extra="forbid"``, others did not).
- Fix typo in ``examples/wordle/sft.toml`` (``micro-batch-size`` →
``micro_batch_size``) that was silently dropped under the old
``extra="ignore"`` and would now be rejected.
- Bump pydantic-config submodule to the merged upstream commit
(PrimeIntellect-ai/pydantic-config#12) for MRO-aware docstring
extraction and ``default_factory`` rendering in ``--help``.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump pydantic-config to merged help-rendering fixes
Picks up PrimeIntellect-ai/pydantic-config#13: per-panel flag column
widths, 60-char cap on the flag column with oversize flags rendered on
their own line, inline ``(default: X)`` in place of the right-aligned
annotation column, and title/flag wrapping so the box always fits the
terminal width.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump slim-wheel pydantic-config floor to 0.3.0.dev82
The PyPI floor on ``prime-pydantic-config`` only matters for the slim
wheel install (plain ``pip install prime-rl-configs`` outside the uv
workspace). Bump it to ``0.3.0.dev82``, the dev release auto-published
when PrimeIntellect-ai/pydantic-config#13 merged — the help-rendering
fixes prime-rl now relies on for clean ``--help`` output.
Workspace installs are unaffected; they keep resolving
``prime-pydantic-config`` editable from ``deps/pydantic-config`` via
the root ``[tool.uv.sources]`` override.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The 4-GPU step time test flaked at 55.50 vs an upper bound of 55.44 (10.13%
measured deviation) on run 26141695659. Slight bump to 15% to absorb runner
variance between hyperstack (baseline) and massed compute A6000s.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* perf(cli): defer heavy ML imports so --help short-circuits in cli()
The rl/sft/trainer/orchestrator entrypoints loaded torch, transformers,
torchtitan and friends at module top — so `--help` blocked on ~10s of
import work before cli() got a chance to exit. Mirror the inference
entrypoint pattern: keep module top light, push heavy imports into the
function body that actually uses them.
For `trainer` and `orchestrator`, add lightweight shim entrypoints under
src/prime_rl/entrypoints/ (the heavy implementation modules stay
runnable via `python -m` for torchrun).
--help timings:
inference 0.35s -> 0.14s
rl 9.96s -> 0.42s (24x)
trainer 10.21s -> 0.20s (51x)
sft 10.42s -> 0.20s (52x)
orchestrator 9.20s -> 0.24s (38x)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* perf(cli): drop redundant _compat import from rl/sft entrypoints
`prime_rl._compat` is already imported at the only two files that
directly pull in ring_flash_attn (`utils/cp.py:4` and
`trainer/models/layers/ring_attn.py:4`, both with ruff:noqa: I001 to
lock the order). Any transitive import path reaches one of those before
ring_flash_attn loads, so the entrypoint-level import is redundant.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump pydantic-config to refactor/drop-tyro tip (1659db2)
Point both the submodule and the pyproject.toml source at
PrimeIntellect-ai/pydantic-config @ 1659db2, the latest commit on
refactor/drop-tyro. The package is renamed to prime-pydantic-config,
so update prime-rl-configs and tool.uv.{sources,exclude-newer-package}
accordingly.
Brings in the legacy key remapping (via before-validators), so e.g.
`uv run orchestrator --model.name <name>` now routes to
`student.model.name`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): wire pydantic-config submodule as editable workspace member
Add deps/pydantic-config to [tool.uv.workspace] members and switch the
source from a pinned git rev to { workspace = true }. uv now installs
prime-pydantic-config editable from the submodule on disk, so local
edits propagate to .venv without re-syncing a wheel.
Drop the [tool.uv.exclude-newer-package] entry — that knob only matters
for non-workspace pins.
Bumps the submodule pointer to df5b38e to pick up the upstream ruff
bump (==0.5.0 -> >=0.12.1), which is required so prime-pydantic-config's
dev group unifies with prime-rl's (ruff>=0.12.1).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): pin slim-wheel prime-pydantic-config dep to a git rev
The slim wheel CI installs prime-rl-configs in a venv with no workspace
context, so it has to resolve prime-pydantic-config from somewhere
reachable. PyPI only has older 0.3.0.dev* wheels that pre-date the new
RLConfig schema, so the slim parse test was tripping on them.
Embed the git URL directly in the dep string (same pattern as before
the rename, just pointed at PrimeIntellect-ai's repo + the rev we
already track via submodule). In-workspace builds keep using the
editable submodule via the root [tool.uv.sources] override.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump pydantic-config to 7481096
Pulls in fix for --no-optional.field negation, "did you mean" hints,
and stale tyro refs.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump pydantic-config submodule to main (ab3a8e7), pin slim wheel to PyPI 0.3.0.dev80
refactor/drop-tyro merged into pydantic-config's main as ab3a8e7. Bump
the submodule to that tip and switch the slim-wheel dep from a git URL
to the PyPI release (`prime-pydantic-config>=0.3.0.dev80`, auto-published
on the merge). uv workspace install still uses the editable submodule
via the root [tool.uv.sources] override.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(ci): use [model] alias on CLI for multi_run orchestrator overrides
The orchestrator TOML uses the legacy `[model]` shortcut (which
`fold_student_shortcuts` re-routes to `student.model`). Pairing that with
`--student.X` CLI overrides triggers an alias-collision in the bumped
pydantic-config's `_normalize_alias_keys`: both `model` (from TOML) and
`student` (from CLI) survive the deep-merge, and the canonical-key pass
overwrites instead of merging — silently resetting `student.model.name`
to the default. Inference servers serve the wrong model and the
orchestrator times out before reaching Step 11.
Keep all layers on the `model` alias by using `--model.lora.name` and
`--model.client.base-url`. Pydantic-config side fix lands separately.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* test(ci): add reverse-text smoke tests for RL OPD + SFT training modes
Covers the rl-entrypoint training_mode = "opd" / "sft" paths on the
existing `vm` integration runner. The student inference deployment is
launched by the rl entrypoint; the teacher is started as a dedicated
`uv run inference` process by the test fixture (low gpu_memory_utilization
on GPU 0 so the student still fits), with orchestrator.teacher.client
pointing at it.
Both tests pass locally on 2× Blackwell GPUs in ~1m40s each.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* test(ci): match reverse_text training config + symmetric 0.4 gpu util
Aligns max_steps / seq_len / batch_size / rollouts_per_example / max_completion_tokens
with the existing reverse_text smoke test, and switches the student+teacher
overlap from asymmetric (0.85 + 0.1) to symmetric 0.4 + 0.4 — both fit on one
Blackwell GPU with the small Qwen3-0.6B models. Both tests still pass locally
(~2m10s each).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* test(ci): drop to 5 steps and remove [ckpt] for the OPD/SFT smoke tests
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* test(ci): drop [deployment] and enforce_eager from OPD/SFT configs
Matches the rest of `configs/ci/integration/` — the default
SingleNodeDeploymentConfig (1 train + 1 infer GPU, gpus_per_node=8)
works on the 2-GPU vm runner, and no other CI config sets
enforce_eager. OPD test still passes locally (2m18s).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* test(ci): assert eval reward goes up instead of loss goes down
Loss going down is a weak signal for distillation training modes — both OPD
(KL-style) and SFT (teacher-token CE) loss curves are noisy across the 5
smoke steps. Switch to checking that the per-step eval reward on the same
reverse-text env actually improves end-to-end.
- Add [orchestrator.eval] (interval=1, num_examples=16) to both configs.
- New `check_eval_avg_goes_up` helper greps the orchestrator log for
"Evaluated <env> ... Avg@K=X.XXXX" and asserts last > first.
Both tests pass locally (OPD 1m52s, SFT 1m42s).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
* feat: add student eval inference pool for SFT hard distillation
When teacher_rollout_model is configured for SFT distillation, the
orchestrator now supports a separate student inference pool for online
evals and weight sync. Previously, configuring [inference] alongside
teacher_rollout_model was forbidden — evals either ran on the teacher
or were skipped entirely.
Changes:
- Relax RLConfig validator to allow [inference] + teacher_rollout_model
- Create eval_inference_pool from config.client when teacher_rollout_model
is set, pointing at the student vLLM server
- Route eval calls and weight updates to the student pool
- Add eval_inference_pool param to Scheduler for weight sync targeting
- All existing RL/soft-distill paths are unchanged (eval_inference_pool
defaults to inference_pool when no teacher_rollout_model is configured)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: keep hard distill student eval pool optional
* fix: scope teacher rollout routing
* fix: address teacher rollout review comments
* fix: clarify teacher rollout client routing
* fix: honor teacher rollout client type
* refactor(orchestrator): rename model/teacher_model to student/teacher
Consolidates 3 training modes (rl, opd, sft) under a unified config
structure: `student` (always present) and `teacher` (optional, role
determined by `training_mode`). Removes scattered flags (`use_sft_loss`,
`update_student_inference_weights`) in favour of a single discriminator.
Backward-compat aliases (`model` → `student`, `teacher_model` → `teacher`)
keep existing TOML configs parsing without changes.
Also adds `configs/reverse_text/debug_{rl,opd,sft}.toml` for local
mode debugging.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(configs): cap reverse-text debug eval at 64 examples
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(configs): cap reverse-text debug eval completion tokens at 128
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(configs): use correct PI inference teacher model name
qwen/qwen3-4b-instruct doesn't exist on PI inference;
use Qwen/Qwen3-4B-Instruct-2507 instead.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(configs): use qwen3-30b-a3b-instruct as debug teacher model
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(configs): correct teacher model name to qwen3-30b-a3b-instruct-2507
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat(client): add headers_from_env to ClientConfig
Maps header names to env var names, resolved at client setup time.
Analogous to api_key_var but for arbitrary headers. Useful for e.g.
X-Prime-Team-ID when hitting the PI inference API.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat(client): auto-inject X-Prime-Team-ID header for PI inference
When ClientConfig.base_url targets pinference.ai, auto-add a
headers_from_env mapping for X-Prime-Team-ID -> PRIME_TEAM_ID so team
billing works without each config repeating the boilerplate.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(configs): set debug eval to 256 rollouts (64 examples x 4)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(configs): use local vLLM teacher for debug OPD instead of PI inference
PI inference is OpenAI-compatible but doesn't expose vLLM's
/inference/v1/generate prefill endpoint that compute_teacher_logprobs
needs - so OPD against PI inference 404s. SFT mode kept working
because that path only hits /chat/completions.
Switch debug_opd.toml to use the existing teacher_inference auto-setup:
set num_teacher_gpus = 1, and an empty [orchestrator.teacher] block to
satisfy the orchestrator validator (which runs before
auto_setup_teacher_inference can populate it). The validator chain
spins up a local vLLM teacher on port 8001 using the same reverse-text
student model.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* docs+validate: training modes grid + cross-config constraints
- Add docs/training_modes.md with the rl/opd/sft role grid, implications
(e.g. OPD needs local vLLM teacher, SFT teacher is any OAI-compatible
endpoint), and minimal config per mode. Linked from mint.json nav.
- Add validate_training_mode_loss_consistency on RLConfig enforcing:
sft mode <-> sft loss type, opd mode requires teacher_tau > 0,
non-sft modes forbid sft loss type. These cross orchestrator and
trainer fields so they live on RLConfig (per-component validators in
OrchestratorConfig already cover the within-orchestrator constraints).
- Fix debug_sft.toml to set trainer.loss.type = "sft" (was relying on
default loss which is now explicitly rejected).
- Make training_mode explicit in debug_rl.toml and debug_opd.toml.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat(configs): lift training_mode to RLConfig + point debug teacher at local vLLM
- Add shared training_mode field to RLConfig (rl | opd | sft). A mode="before"
validator propagates it into orchestrator.training_mode and (for sft)
trainer.loss.type before nested validation runs. Must be a before-validator
because OrchestratorConfig.validate_training_mode would otherwise reject
configs like training_mode = "opd" + [orchestrator.teacher] - the
orchestrator-level default of "rl" would conflict with the teacher block
before the after-validator could propagate the shared value.
- Point debug_opd and debug_sft at a manually-deployed teacher vLLM
(Qwen3-0.6B-Reverse-Text-RL on localhost:8001). Add a comment with the
exact teacher start command at the top of each config. Drop the
num_teacher_gpus auto-launch from debug_opd since we now use the
external teacher.
- Set student inference gpu_memory_utilization = 0.5 in all three debug
configs (matches the teacher's mem budget, leaves room when both are
co-located).
- Add configs/reverse_text/README.md with the start commands.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore: drop GPU-occupancy runtime check; teacher uses uv run inference
- Remove check_gpus_available in rl entrypoint - it raised RuntimeError
when other processes held GPUs, which blocked iterating with a
long-lived teacher inference server on a sibling GPU.
- Update debug_opd / debug_sft / README to start the teacher via
uv run inference (the prime-rl variant) instead of raw vllm serve.
Same port (8001), same model, same flags.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(configs): accept legacy flat [orchestrator.model.lora] layout
Pre-refactor, orchestrator.model was a ModelConfig directly (name, lora,
trust_remote_code, vlm). After the student/teacher rename it's a
RolloutModelConfig wrapping ModelConfig + ClientConfig, so existing
[orchestrator.model.lora] TOML sections stopped parsing because they
landed on the wrong nesting level.
Add a mode="before" validator on RolloutModelConfig that detects a flat
ModelConfig dict (any of {name, trust_remote_code, vlm, lora} at the top
level, no nested model/client keys) and re-nests it under "model". This
lets the three existing LoRA configs revert to their original syntax.
Also fix examples/alphabet_sort/sft_distill_hard.toml: hoist training_mode
to the top-level shared field so trainer.loss.type = "sft" gets auto-set
(previously the orchestrator-only flag triggered the new sft/loss
consistency validator).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* refactor(orchestrator): split into student_inference + teacher_inference pools
Replace the "one pool plus optional teacher-client overlay" model with two
explicit pools:
- student_inference: InferencePool | None
- Required for rl/opd, optional for sft (set iff [inference] is configured)
- Target for evals, weight broadcast, and inference metrics
- When None, online evals and policy updates are skipped automatically
- teacher_inference: InferencePool | None
- Set whenever orchestrator.teacher is configured (opd or sft)
- Source of teacher logprobs in opd
- Source of train rollouts in sft
- Always MITO (chat completions) for simplicity; external OAI-compatible
teachers (PI inference, OpenAI) work as drop-in endpoints
Scheduler now takes both pools and resolves the rollout target internally
(rollout_inference = teacher_inference if sft else student_inference).
The old _resolve_rollout_request_target overlay is gone - the rollout pool
serves rollouts directly. Fixes a latent bug where SFT-mode LoRA updates
would overwrite scheduler.model_name and route subsequent teacher requests
with the student's LoRA name.
Also:
- Drop setup_external_rollout_model (logic is now inline + clearer)
- Rename setup_rollout_inference_pool -> setup_student_inference_pool;
always handles only the student pool, teacher is plain setup_inference_pool
- Log the resolved training_mode + one-line description at orchestrator start
- Update tests: cover both sft (rollout != student) and rl (rollout = student)
LoRA paths; drop the now-obsolete teacher-overlay scheduler test
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* docs+configs: legacy [orchestrator.client] shim + merge OPD doc into training_modes
- Add _accept_top_level_client validator on OrchestratorConfig: legacy
[orchestrator.client...] re-nests under [orchestrator.student.client...]
matching the existing _accept_flat_model_layout shim pattern. Revert
configs/elastic/rl.toml back to the original [orchestrator.client.elastic]
syntax.
- Revert configs/ci/integration/reverse_text_multi_run/orchestrator.toml
[model.model] -> [model]; the flat-layout shim on RolloutModelConfig
already handles it (verified).
- Merge docs/on_policy_distillation.md into docs/training_modes.md. The
training_modes page is now the single entry point; OPD-specific details
(external teacher, pure distillation, monitoring, VLM, params) live as
subsections. Delete the standalone OPD page.
- Drop the redundant "Initializing static inference pool" / WandbMonitor /
PrimeMonitor init logs - they duplicate the immediately-preceding
per-pool init line.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat(orchestrator): probe teacher for prompt_logprobs before training
In OPD mode, send a tiny probe request to the teacher's /inference/v1/generate
endpoint after the pool is ready. If the endpoint 404s or doesn't return
prompt_logprobs, raise an informative error pointing at docs/training_modes.md
instead of crashing mid-training with a 404.
Verified that PI inference fails this probe on all three plausible routes:
- /inference/v1/generate -> 404
- /v1/chat/completions with logprobs=true -> logprobs:null in response
- /v1/completions with echo=true,logprobs=1 -> 404
Also add configs/reverse_text/debug_sft_thinking.toml: SFT from
qwen3-30b-a3b-thinking-2507 via PI inference (sft path needs only
chat completions, so PI inference is fine here).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(orchestrator): deprecate use_token_client (server-tokenized TITO)
Drop the server-tokenized TITO path (``openai_chat_completions_token`` /
``/v1/chat/completions/tokens``). The orchestrator now picks between
renderer-backed TITO (``use_renderer = true``, default) and MITO
(``use_renderer = false``, fallback for VLMs and external teacher rollouts).
- Remove ``OrchestratorConfig.use_token_client`` field and its validators
- Drop the TITO branch in ``setup_rollout_inference_pool``
- Drop the obsolete TITO warning in ``setup_inference_pool`` and flip the
default ``train_client_type`` to ``openai_chat_completions`` in
``StaticInferencePool`` / ``ElasticInferencePool``
- Strip ``use_token_client = false`` from configs/examples/docs that
carried the no-op fallback line
- CHANGELOG entry documenting the breaking removal
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(inference): remove server-side TITO route
Drop the ``/v1/chat/completions/tokens`` endpoint and the
``OpenAIServingChatWithTokens`` / ``ChatCompletionRequestWithTokens``
wrappers now that no client routes to them. Also drop the obsolete
``base()`` helper and unused imports from ``server.py``.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor: require student_inference in all training modes
Student inference was already required for rl/opd and optional for sft;
making it required everywhere simplifies the orchestrator + scheduler:
- Drop has_student_inference / enable_policy_updates gating
- student_inference: InferencePool (no longer Optional) in Scheduler.__init__
- Weight broadcast init, weight sync, metrics collector, eval routing, and
shutdown all unconditionally use student_inference
- Drop the now-stale OPD probe (will revisit in a follow-up PR)
- Add is_vlm property on BaseModelConfig; replace local is_vlm vars in the
orchestrator with config.student.model.is_vlm
- Merge the two legacy student-layout shims on OrchestratorConfig into one
before-validator (_accept_legacy_student_layout) covering both
[orchestrator.client.*] and flat [orchestrator.model.<k>] paths
- Drop redundant pool / WandbMonitor / PrimeMonitor init log lines
- Reorder OrchestratorConfig fields: training_mode > student > teacher
- Drop "OAI" from RolloutModelConfig.client description
- Update docs/training_modes.md: SFT student inference is now required;
evals and weight sync are unconditional
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat(configs): default OPD to pure distillation (teacher_tau=1, adv_tau=0)
auto_setup_training_mode now seeds trainer.loss defaults when training_mode
is opd: teacher_tau=1.0 and adv_tau=0.0 (pure distillation: drop the reward
signal, full weight on the teacher KL). User-provided values still win via
setdefault. Also accept training_mode set only inside [orchestrator] - same
auto-setup applies for both the shared top-level and orchestrator-local
forms.
Drop the redundant [trainer.loss] teacher_tau = 0.5 block from
configs/reverse_text/debug_opd.toml; verified the auto-setup applies
end-to-end (3 train steps, teacher logprobs computed each step, clean exit).
Also drop the now-redundant InferencePool type annotation on
self.rollout_inference - both branches assign a definite InferencePool now
that student_inference is non-Optional.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(configs): rename debug_sft_thinking -> debug_sft_external; drop examples/alphabet_sort/sft_distill_hard.toml
debug_sft_external describes the role better - external SFT teacher via
OAI-compatible endpoint (PI inference). The "thinking" label was about the
specific model the config picks (qwen3-30b-a3b-thinking-2507), not about
what the config demonstrates.
Drop examples/alphabet_sort/sft_distill_hard.toml: configs/reverse_text/
debug_sft* are the canonical SFT examples now.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(tests): unbreak CPU tests after student/teacher rename + headers_from_env
- tests/unit/train/test_runs.py: orchestrator config attribute access
changed from config.model.name to config.student.model.name after the
RolloutModelConfig rename.
- tests/unit/utils/test_elastic.py: MagicMock client_config needs
headers_from_env set to {} - the field was added in this PR and the
test's hand-built mock missed it (pydantic rejects MagicMock as a dict).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat(orchestrator): strip logprobs from train sampling in sft mode
The trainer in sft mode reconstructs teacher tokens via the student
tokenizer - it never reads inference-side logprobs from the teacher
endpoint. Stripping logprobs at runtime lets external reasoning-model
endpoints (openai/gpt-5*, etc.) accept the rollout request - they
reject logprobs with 400 invalid_request "logprobs are not supported
with reasoning models".
Done at orchestrator-startup time on each TrainEnv's sampling_args
rather than as a public config field, since this is a mode-specific
runtime concern.
Also: bump configs/reverse_text/debug_sft_external.toml to use
openai/gpt-5-mini (faster than qwen3-30b-a3b-thinking-2507).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(configs): bump debug_sft_external for gpt-5-mini reasoning budget
gpt-5-mini's max_completion_tokens budget includes reasoning tokens.
At 128 the model burned the whole budget on internal CoT before
producing the final answer, returning empty content. Raise to 2048
and set reasoning_effort=minimal so the chat-completions response
includes the actual output.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* docs: fix stale SFT references after the student/teacher refactor
- skills/config/SKILL.md: update the SFT hard distill section -
orchestrator.teacher_model -> orchestrator.teacher, drop the
"student inference is optional" guidance (the orchestrator now
unconditionally sets up student_inference), and add a note that
shared training_mode auto-propagates to trainer.loss.type.
- rl.py: auto_setup_inference_client docstring referenced the deleted
setup_external_rollout_model function. Rewrite to explain what the
validator actually does for each mode.
Also note the behavior change in the PR description: SFT now requires
[inference] (was previously optional).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat(loss): batch-driven loss dispatch via TrainingSample.training_mode
Replace TrainingSample/MicroBatch.sft_loss bool with training_mode literal
(rl|opd|sft). The trainer's compute_loss reads training_mode from the
micro batch and dispatches:
- "sft" -> sft_loss_fn (masked NLL on teacher tokens)
- "rl" -> default_loss_fn with (adv_tau=1.0, teacher_tau=0.0)
- "opd" -> default_loss_fn with (adv_tau=0.0, teacher_tau=1.0)
Taus move from trainer.loss config to compute_loss's mode->tau table and
flow into LossInputs per batch; DefaultLossConfig drops the teacher_tau /
adv_tau fields. The orchestrator stamps each sample with
config.training_mode at the same point it used to set sft_loss.
Packer enforces same-mode packing (samples with different training_mode
cannot share a micro batch). RLConfig drops the OPD tau auto-setup +
"opd requires teacher_tau > 0" validator + the validate_teacher_model
teacher_tau gate (all redundant under batch-driven dispatch).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* refactor(loss): dedicated opd_loss_fn instead of routing taus through inputs
Replace the per-batch adv_tau/teacher_tau routing through LossInputs with a
dedicated opd_loss_fn that lives alongside default_loss_fn and sft_loss_fn.
A bit of code dup in opd_loss_fn (clone of default's DPPO math) makes the
two paths read as separate losses rather than the same function with magic
multipliers.
- setup_loss_fn -> setup_loss_fns: returns a dict {training_mode: LossFn}.
rl uses the configured loss (default/custom). opd uses opd_loss_fn (only
available when loss_config is DefaultLossConfig). sft is always available.
- compute_loss takes loss_fns + training_mode, looks up the right fn.
- opd_loss_fn requires teacher_logprobs (raises otherwise).
- LossInputs no longer carries adv_tau/teacher_tau - those values are baked
into each loss fn.
- Add validator: opd mode requires trainer.loss.type = "default".
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* refactor(loss): drop trainer.loss type discriminator + shared training_mode
Now that loss dispatch is fully batch-driven (TrainingSample.training_mode),
the trainer.loss type union and the shared RLConfig.training_mode propagator
are redundant. Flatten:
- Delete SFTLossConfig (the mode implies it; no fields).
- trainer.loss: DefaultLossConfig = DefaultLossConfig() (flat, not a union).
- trainer.custom_loss: CustomLossConfig | None = None - optional override
for rl-mode loss only; opd and sft always use opd_loss_fn / sft_loss_fn.
- setup_loss_fns(loss_config, custom_loss) always returns all three keys -
mixed-mode batches dispatch correctly at the trainer level (orchestrator
still stamps a single mode per run; that's a separate concern).
- Drop RLConfig.training_mode shared field, the auto_setup_training_mode
before-validator, and validate_training_mode_loss_consistency. The
orchestrator-level [orchestrator] training_mode is the single source.
Move training_mode = "sft" out of top-level into [orchestrator] in the
three SFT debug configs.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(rl entrypoint): warn for missing [inference] in all modes (incl. sft)
After the always-require-student refactor, sft runs need a student
inference pool too (orchestrator unconditionally creates it for evals +
weight sync). The old "sft mode, using teacher for rollouts" info log
was correct under the old semantics but now silently puts the user on a
path where the orchestrator hangs waiting for a non-existent student
server at the default localhost:8000. Replace with a single warning
that prints the configured student base_url and flags the hang risk.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* refactor(loss): make opd_loss_fn's tau values explicit (adv_tau=0, teacher_tau=1)
Mirror default_loss_fn's structure literally: declare the two tau locals at
the top, then use them in the same `adv_tau * advantages + teacher_tau *
teacher_kl.detach()` expression. The "this is the default loss with those
specific knobs baked in" relationship is now visible in the code rather than
hidden in a substituted expression.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* refactor(loss): restore DefaultLossConfig.adv_tau + LossConfig union (rl-only)
- DefaultLossConfig regains adv_tau (= 1.0). default_loss_fn reads it.
- trainer.loss is back to a discriminated union of DefaultLossConfig |
CustomLossConfig (drop SFTLossConfig stays dropped). type discriminator
restored.
- trainer.loss only applies to rl-mode batches. opd and sft batches dispatch
unconditionally to opd_loss_fn / sft_loss_fn - they don't read trainer.loss.
- opd_loss_fn is self-contained: the DPPO/KL knobs (dppo_mask_*, kl_tau)
are baked in as module-level _OPD_* constants matching DefaultLossConfig's
defaults. No loss_config parameter.
- Drop the trainer.custom_loss sibling field (subsumed by the union).
Also add debug_opd_lora.toml + bump lr to 1e-4 in both lora debug configs.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* refactor(loss): inline opd_loss_fn knobs (no named locals/constants)
Drop the module-level _OPD_* constants and the local adv_tau/teacher_tau
bindings - inline the literal values into the math. Keeps the parallel
structure to default_loss_fn visible: `0.0 * advantages + 1.0 * teacher_kl`
in the same place default_loss_fn has `loss_config.adv_tau * advantages`.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* docs(loss): trim opd_loss_fn docstring
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* docs: update reverse_text README — add lora configs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* polish: auto-disable renderer in sft + CHANGELOG + log/shim cleanup
- OrchestratorConfig auto-sets use_renderer=False when training_mode='sft'
via an after-validator placed before the renderer validators in
declaration order, so the user doesn't have to set it. Drop the rejecting
branch in validate_training_mode + the explicit use_renderer=false lines
in the three sft debug configs.
- CHANGELOG: add a "first-class training_mode + batch-driven loss dispatch"
entry covering the breaking removals (orchestrator.use_sft_loss,
orchestrator.teacher_rollout_model, trainer.loss.type='sft' /
SFTLossConfig, trainer.loss.teacher_tau) with migration notes.
- _accept_legacy_student_layout: use set(ModelConfig.model_fields) instead
of hardcoding the field list, so new ModelConfig fields are picked up
automatically.
- Trim the orchestrator startup log to just '(<training_mode>)'; the
prose description was redundant with docs/training_modes.md.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(configs): unbreak OPD auto-wiring when num_teacher_gpus is set
Add a mode="before" validator on RLConfig that stubs an empty
[orchestrator.teacher] block when deployment.num_teacher_gpus is set and
the user didn't write one. Without this, OrchestratorConfig.validate_training_mode
("opd requires orchestrator.teacher") fires during nested validation - before
auto_setup_teacher_inference can wire the teacher from teacher_inference.
Repro that now passes:
RLConfig.model_validate({
"deployment": {"num_teacher_gpus": 1},
"trainer": {},
"orchestrator": {"training_mode": "opd"},
"inference": {},
})
-> auto_setup_teacher_inference fills in orchestrator.teacher.client.base_url
= ["http://localhost:8001/v1"] and model.name from teacher_inference.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* docs(training_modes): shrink mode-comparison table + add sft/opd teacher note
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(configs): move training-mode debug configs to configs/debug/training_modes/
The reverse-text debug configs are about exercising the training modes, not
about reverse-text specifically. Move to configs/debug/training_modes/ and
drop the debug_ prefix from each filename (the directory name carries it).
configs/reverse_text/debug_rl.toml -> configs/debug/training_modes/rl.toml
configs/reverse_text/debug_opd.toml -> configs/debug/training_modes/opd.toml
configs/reverse_text/debug_opd_lora.toml -> configs/debug/training_modes/opd_lora.toml
configs/reverse_text/debug_sft.toml -> configs/debug/training_modes/sft.toml
configs/reverse_text/debug_sft_lora.toml -> configs/debug/training_modes/sft_lora.toml
configs/reverse_text/debug_sft_external.toml -> configs/debug/training_modes/sft_external.toml
configs/reverse_text/README.md -> configs/debug/training_modes/README.md
Update path references in each TOML's header comment, the README, and
docs/training_modes.md.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* refactor(configs): drop auto pinference team-id, rename student-shortcut shim
- ClientConfig.auto_setup_pinference_team_header dropped. The hostname-sniff
was implicit magic. Configs that need the X-Prime-Team-ID header against
PI inference set it explicitly under [...client.headers_from_env] now.
Update configs/debug/training_modes/sft_external.toml accordingly and
drop the auto-injection note from the file header.
- Rename OrchestratorConfig._accept_legacy_student_layout (with leading
underscore + "backward-compat" framing) to fold_student_shortcuts. The
shim is more than a back-compat: it's the ergonomic path for rl configs
too, letting users write [orchestrator.model.name] / [orchestrator.client]
rather than [orchestrator.student.model.name] / [orchestrator.student.client].
Docstring reframed accordingly. Teacher has no equivalent shortcut on
purpose: rl mode forbids teacher, so the same shortcut routing to two
roles would be ambiguous.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(tests): update multi_run CLI args after student rename
test_reverse_text_multi_run.start_orchestrator passes --client.base-url
and --model.lora.name as CLI flags to `uv run orchestrator`. After the
student rename, those tyro args don't exist anymore (they're now
--student.client.base-url and --student.model.lora.name). tyro rejects
them before the fold_student_shortcuts before-validator can re-nest the
dict, so the orchestrator process exits immediately and the test times
out waiting for "Step 11" to appear in the log.
Rename both CLI args to their new student-scoped form.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Timothy Kostolansky <39891386+tim0120@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
#2547 cut step time ~27% (1-GPU: 65.87s -> 48.29s, 4-GPU: 68.34s -> 50.40s)
and peak memory (1-GPU: 31.81 GiB -> 24.25 GiB), pushing the regression tests
above the 10% tolerance. Refresh baselines from CI run 26067881101.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(orchestrator): deprecate use_token_client (server-tokenized TITO)
Drop the server-tokenized TITO path (``openai_chat_completions_token`` /
``/v1/chat/completions/tokens``). The orchestrator now picks between
renderer-backed TITO (``use_renderer = true``, default) and MITO
(``use_renderer = false``, fallback for VLMs and external teacher rollouts).
- Remove ``OrchestratorConfig.use_token_client`` field and its validators
- Drop the TITO branch in ``setup_rollout_inference_pool``
- Drop the obsolete TITO warning in ``setup_inference_pool`` and flip the
default ``train_client_type`` to ``openai_chat_completions`` in
``StaticInferencePool`` / ``ElasticInferencePool``
- Strip ``use_token_client = false`` from configs/examples/docs that
carried the no-op fallback line
- CHANGELOG entry documenting the breaking removal
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(inference): remove server-side TITO route
Drop the ``/v1/chat/completions/tokens`` endpoint and the
``OpenAIServingChatWithTokens`` / ``ChatCompletionRequestWithTokens``
wrappers now that no client routes to them. Also drop the obsolete
``base()`` helper and unused imports from ``server.py``.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* add per-env trainer metrics
* require env names for trainer batches
* address per-env metric review feedback
* reuse tensor stats for env metrics
* fix sft trajectory env-name fixture
* address trainer metric naming comments
* fix: reuse trainer ratio tensors for env metrics
* fix: derive dppo mask from shared ratio
* address PR review: drop precomputed loss inputs, use {all,env} keys
- compute importance-ratio / mismatch_kl inside the loss functions instead of
passing them in via LossInputs (per Mika)
- compute mismatch_kl inline in train.py only for per-env logging
- rename trainer aggregate keys to entropy/all and mismatch_kl/all to match the
orchestrator {all,env}/{mean,std,max} convention; drop the leftover bare
entropy/* and mismatch_kl/* keys
- drop the overly defensive env_names length check in DataLoader
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* guard mismatch_kl logging behind sft_loss flag
SFT batches don't have meaningful inference_logprobs (sft_loss_fn ignores
them), so computing and logging mismatch_kl for those microbatches is wasted
work and produces misleading numbers. Skip the inline mismatch_kl compute and
the per-env / debug-log emissions when sft_loss is True.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* address review: simplify probs_diff and move mismatch_kl/all to trainer loop
* reserve env_name='all' for aggregate metric keys
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Follow-up to #2459. Switches the default from `None` (retry indefinitely)
to `3`, so single-example hangs in agent envs no longer block step progress
out of the box. Users who want the legacy infinite-retry behavior can still
set `None` explicitly.
* chore: bump vllm
* fix: adapt dp pause patch for vllm 0.21
* Drop deep_gemm ep_scatter and silu_mul_quant int64 monkey patches
Both int64-addressing carries are fixed upstream in vLLM 0.21.0.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
numpy/pandas allocate array data via malloc() (outside Python's allocator),
so gc.collect() alone doesn't reclaim RSS after per-step DataFrames are freed.
glibc retains freed pages in its internal pool, causing ~+6 MB/step monotonic
RssAnon growth on the orchestrator process.
malloc_trim(0) forces glibc to return freed heap pages to the OS, producing
a stable sawtooth pattern (peak during rollout generation, drops after trim)
with no upward trend.
Verified on alphabet-sort (512 rollouts/step, 20 steps, no wandb):
- Without fix: 941 MB → 973 MB by step 3 (+6 MB/step, unbounded)
- With fix: 941 MB → 942 MB by step 5 (flat, sawtooth only)
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat(renderer): expose preserve_*_thinking flags in RendererConfig
Adds two new fields to RendererConfig:
- preserve_all_thinking
- preserve_thinking_between_tool_calls
The orchestrator forwards them in two places so train and infer stay
consistent:
1. create_renderer() — bound at construction on the training-side
renderer used by build_trajectory_step / render_ids.
2. setup_inference_pool() → setup_clients() → vf.ClientConfig — the
verifiers RendererClient picks them up and forwards to its
create_renderer_pool, so every inference render carries the same
thinking-preservation behaviour.
Both flags are off by default → zero behaviour change for existing
configs. Setting either without orchestrator.use_renderer=True is
rejected by validate_renderer_args, matching the existing renderer
knobs.
Bumps source pins:
- verifiers 3b77145 → a7516a1 (PR #1298: ClientConfig propagation)
- renderers (now a separate repo): pinned to fe67f9f (PR #4:
construction-time preserve flags)
Re-applies #2433, which was merged into feat/unify-inference-generate
by mistake.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(sft): forward preserve_*_thinking flags through SFT renderer path
The flags were added to the shared RendererConfig but only wired up
in the orchestrator. SFT also constructs a renderer via create_renderer
for training-side tokenization, so it must forward both flags or
silently ignore them.
Also tighten validate_renderer_args to reject either flag when
use_renderer=False, matching the orchestrator validator.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 17:38:53 -07:00
286 changed files with 18521 additions and 18424 deletions
If breaking changes are detected without a corresponding `CHANGELOG.md` update, request that the author add an entry.
Any PR that introduces a new custom model must also provide a table showing mean KL mismatch across 20 steps on math environment on this new model with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not present, request the author to add such a table.
@@ -35,6 +35,10 @@ Namespaces are one honking great idea -- let's do more of those!
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
## Docs
- **Docs reflect `main`, not history**: `docs/` describes the current state of the codebase only. Don't mention removed/legacy fields, migration paths, or "this used to be X" anecdotes.
## Skills
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs). When you make changes to the codebase, check if any skills need to be updated to stay accurate.
@@ -50,11 +54,10 @@ Write tests as plain functions with pytest fixtures. Don't use class-based tests
## Git
- **Branch prefixes**: use the following prefixes for branches: `feat/`, `fix/`, `chore/`
- **Branch prefixes**: use `feat/`, `fix/`, `chore/`; use `exp/` for experiment branches (configs, run summaries, pins, notes).
## GitHub
- **Draft PRs**: always create PRs as drafts (`gh pr create --draft`) to avoid triggering CI unnecessarily.
- **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 -->`).
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **verifiers v1 training integration** (collection of removals/renames). The orchestrator now trains against a v1 env server returning `vf.Trace` rollouts, renderer-only, with a unified token schema.
- **`[[orchestrator.train.env]]` is now a v1 `vf.EnvServerConfig`**: a v1 env is `taskset = { id = "<id>" }` + `harness = { id = "default", runtime = { type = "subprocess" } }`. A bare `id = "<id>"` (optionally with `args`) runs the v0 env through the verifiers legacy bridge — old flat `id`/`args`-only configs keep working as legacy envs; v1 envs must use the `taskset`/`harness` shape.
- **`orchestrator.train.env` no longer defaults to a `reverse-text` env**: the default is now empty (`[]`), so configs must declare `[[orchestrator.train.env]]` explicitly.
- **`...env[].num_workers` → `pool`**: per-env worker sizing moves to a `pool` config (`static`/`elastic`). Back-compat: `num_workers = N` maps to `pool = { type = "static", num_workers = N }` and `"auto"` to the default elastic pool; the group-level `orchestrator.train.num_workers` / `orchestrator.eval.num_workers` are removed.
- **`orchestrator.renderer` is now required (MITO removed)**: it was `RendererConfig | None`, where `renderer = None` selected the MITO path; training is now renderer-only, so `renderer` is non-optional. Drop `renderer = None` / `renderer = "None"`.
- **`...client.timeout` / `...client.connect_timeout` removed**: the v1 rollout client manages its own timeouts. Drop these from `[orchestrator.student.client]` and `[orchestrator.teacher.client]`. (2026-06-23)
- **`orchestrator.advantage` length-penalty overhaul + length-weighted baseline**: `length_penalty` is now a single shape — a linear penalty that subtracts `coef * pass_rate * (model completion tokens / orchestrator.seq_len)` from each reward before the baseline subtraction (`pass_rate` = group mean reward, so solved-often problems get the strongest concision pressure and never-solved groups get none), with an optional `gate_by_correctness` flag (default `false`) that restricts the penalty to correct rollouts (`reward == 1`). The previous discriminated `type = "tokens" | "turns"` efficiency-shaping variants and the per-penalty `max_length` field have been removed — configure `[orchestrator.advantage.length_penalty]` with `coef` (and optionally `gate_by_correctness`) instead; the denominator is always `orchestrator.seq_len`. Also adds `orchestrator.advantage.length_weighted_baseline` (default `false`): when enabled, the GRPO baseline is the token-length-weighted mean reward (`sum(len_i * reward_i) / sum(len_i)`) instead of the plain mean. (2026-06-03)
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
- **`orchestrator.eval.eval_base_model` → `orchestrator.eval.skip_first_step`** (semantics inverted): `eval_base_model = true` becomes `skip_first_step = false` (the default — run the step-0 eval before any train rollouts). No alias; configs setting `eval_base_model` must rename.
- **`orchestrator.eval.skip_eval_on_resume` (and its alias `skip_eval_on_restart`) removed**: folded into `skip_first_step`. Resume no longer re-fires an already-completed eval (deduped via per-env last-eval-step tracking in the checkpointed progress).
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval` removed**: the drain-switch overlap (stop scheduling new train, let in-flight train drain while eval queues) is now the only eval transition mode.
- **`ckpt.skip_buffer` removed**: there is no buffer to skip.
- **`[orchestrator.buffer]` removed** (difficulty pools): the whole block and every key (`seed`, `easy_threshold`, `hard_threshold`, `easy_fraction`, `hard_fraction`, `online_difficulty_filtering`, `hash_keys`) are gone, with no alias — `extra="forbid"` rejects the block, so existing configs must delete it. To preserve `online_difficulty_filtering = true`, enforce the zero-advantage pre-batch filter: `[[orchestrator.pre_batch_filters]]\ntype = "zero_advantage"\nenforce = true`.
- **`orchestrator.filters` → `orchestrator.post_batch_filters`** (renamed, no alias): existing configs setting `[[orchestrator.filters]]` must rename to `[[orchestrator.post_batch_filters]]` (`extra="forbid"` rejects the old key). A new `pre_batch_filters` list is also available. Filters are **train-only** now — eval rollouts are no longer filtered.
- **`orchestrator.max_off_policy_steps` now also applies to eval** (behavior change, field unchanged): eval rollouts that fall more than `max_off_policy_steps` versions behind the policy are cancelled, same as train. (2026-05-29)
- **`sampling.min_tokens`, `sampling.repetition_penalty`, `sampling.seed` removed**: Dropped from both `TrainSamplingConfig` and `EvalSamplingConfig` (group-level `[orchestrator.train.sampling]` / `[orchestrator.eval.sampling]` and per-env `[[orchestrator.train.env.sampling]]` / `[[orchestrator.eval.env.sampling]]`). `min_tokens` suppressed natural EOS, `repetition_penalty` distorts the on-policy sampling distribution, and `seed` wasn't pulling its weight — none belonged on the supported config surface. Existing configs setting any of these must delete the field. Hard-deprecation, no migration window. (2026-05-27)
- **`wandb.shared` removed**: The deprecation shim that popped `wandb.shared` from input dicts with a `FutureWarning` (introduced in #2649) is gone. The `rl` entrypoint always uses shared W&B mode now, and existing configs that still set `wandb.shared = true` (or `false`) will fail validation. Drop the field from your config. (2026-05-27)
- **`max_async_level` and `strict_async_level` removed**: The async-execution semantics between trainer and orchestrator are now design invariants, not config knobs. The trainer always runs exactly one step ahead of inference, and the orchestrator always adopts the freshest checkpoint that doesn't violate the one-step barrier. The shared top-level `max_async_level`, the per-sub-config `trainer.max_async_level` / `orchestrator.max_async_level`, and `orchestrator.strict_async_level` have all been removed. Existing configs setting any of these must drop the field; the previous defaults (`max_async_level = 1`, `strict_async_level = false`) match the new hardcoded behavior. Bench mode no longer bypasses the weight-ckpt wait (the `int(1e9)` workaround is gone) and `multimodal/rl_color_codeword_feat_renderer.toml`'s prior `max_async_level = 0` (fully synchronous on-policy) is no longer expressible. (2026-05-25)
- **`teacher_inference` removed from RL entrypoint**: The `[teacher_inference]` config block and the `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` fields have been removed. The `rl` entrypoint now only manages the student-policy inference server. External teachers (used by OPD and local-vLLM SFT) must be started manually (e.g. `CUDA_VISIBLE_DEVICES=1 uv run inference --model.name <teacher> --server.port 8001 ...`) and pointed at via `[orchestrator.teacher.client]`. Existing configs using `[teacher_inference]` or `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` must drop those fields and bring up the teacher out-of-band. (2026-05-25)
- **`rollouts_per_example` → `group_size`**: The orchestrator-level field, the group-level `[orchestrator.eval]` field, and the per-env `[[orchestrator.eval.env]]` field have all been renamed. The old name still parses as a validation alias (in both TOML and CLI), so existing configs keep working without changes; new configs should prefer `group_size`. (2026-05-22)
- **`AdvantageInputs` / `AdvantageOutputs` are now per-group, and `AdvantageOutputs.advantages` is a plain `list[float]`** (second breaking change to this API in three weeks). `AdvantageInputs.rollouts` is now `list[vf.RolloutOutput]` (a single group) instead of `list[list[vf.RolloutOutput]]`, and `AdvantageOutputs.advantages` is now `list[float]` instead of a 2D `Float[Tensor, "num_examples rollouts_per_example"]`. `compute_advantages` calls `advantage_fn` once per group, which lets partial-group training (groups smaller than `rollouts_per_example` after rollout errors) round-trip without the previous bucket-by-size workaround. Custom advantage functions must drop the outer list dimension and return a list of floats — e.g. `AdvantageOutputs(advantages=(rewards - rewards.mean(dim=1, keepdim=True)).tolist())` becomes `AdvantageOutputs(advantages=[r - mean for r in rewards])` (or `.tolist()` if you keep torch internally). (2026-05-22)
- **`[model.vlm]` requires `orchestrator.use_renderer = true`**: VLMs must go through the renderer path; the `vlm_requires_renderer` validator rejects `use_renderer = false` when `[model.vlm]` is set. The renderer owns the HF processor per-slot and ships generic `mm_kwargs` keyed by the model's forward signature. Since `use_renderer` already defaults to `true`, most VLM configs need no change. (2026-05-19)
- **First-class `training_mode` + batch-driven loss dispatch** (collection of removals/renames). Loss selection is now driven by `TrainingSample.training_mode` (`rl` / `opd` / `sft`), set under `[orchestrator]`. The trainer is mode-agnostic and dispatches per batch.
- **`orchestrator.use_sft_loss` removed**: replaced by `[orchestrator] training_mode = "sft"`. The orchestrator stamps each sample's `training_mode` and the trainer dispatches to `sft_loss_fn` per batch.
- **`orchestrator.teacher_rollout_model` removed (no alias)**: configs must rename to `[orchestrator.teacher]` (`teacher_model` is also accepted as a back-compat alias for `teacher`). Used in both opd and sft modes; the role is determined by `training_mode`.
- **`orchestrator.model` → `orchestrator.student`**: renamed for symmetry with `orchestrator.teacher`. Legacy `[orchestrator.model]` and a flat `[orchestrator.model.lora]`-style layout are aliased via a back-compat shim, so most existing configs still parse. New code should use `[orchestrator.student.*]`.
- **`trainer.loss.type = "sft"` removed (`SFTLossConfig` deleted)**: zero-field discriminator that is now implied by `training_mode = "sft"`. `trainer.loss` collapsed to a `DefaultLossConfig | CustomLossConfig` union. Existing configs setting `[trainer.loss] type = "sft"` must remove that line; the orchestrator-level `training_mode = "sft"` is enough.
- **`trainer.loss.teacher_tau` removed from `DefaultLossConfig`**: the teacher-KL term is now exclusive to `opd_loss_fn` (which inlines `teacher_tau = 1.0`). `default_loss_fn` only handles reward-driven RL and no longer accepts a `teacher_tau`. Configs that set `teacher_tau` on `[trainer.loss]` will fail validation — switch to `[orchestrator] training_mode = "opd"` (which uses `opd_loss_fn` with the value baked in).
- **`trainer.loss` only applies to rl-mode batches**: opd and sft don't read `trainer.loss`. `opd_loss_fn`'s knobs (dppo_mask_*, kl_tau) are inlined as literals; tweak them by editing the function. `CustomLossConfig` overrides the rl-mode loss only — opd and sft always use their dedicated fns. (2026-05-19)
- **`orchestrator.use_token_client` removed**: The server-tokenized TITO path has been deprecated end-to-end. The orchestrator-side config flag (`use_token_client`), the verifiers client_type (`openai_chat_completions_token`), and the inference server's `/v1/chat/completions/tokens` route (along with the `OpenAIServingChatWithTokens` wrapper) are all gone. The orchestrator now picks between renderer-backed TITO (`use_renderer = true`, default) and MITO (`use_renderer = false`, fallback). Existing configs with `use_token_client = true` must migrate to `use_renderer = true` (or `use_renderer = false` for MITO); configs with `use_token_client = false` can simply drop the field. (2026-05-19)
- **`orchestrator.advantage.length_penalty` → discriminated sub-config**: The scalar `length_penalty: Literal["tokens","turns"] | None` is replaced by a `LengthPenaltyConfig | None` discriminated on `type`. Token shaping now takes weighted completion + tool-response token costs. Migration: `length_penalty = "tokens"` becomes `[orchestrator.advantage.length_penalty]\ntype = "tokens"` (default weights `completion_weight = 1.0`, `tool_response_weight = 1.0` — total context). `length_penalty = "turns"` becomes `[orchestrator.advantage.length_penalty]\ntype = "turns"`. (2026-05-06)
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
@@ -38,6 +38,7 @@ PRIME-RL is a framework for large-scale reinforcement learning. It is designed t
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
7. Hackable, modular, and extensible by design.
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/glm5_llmd/README.md).
## Models support
@@ -52,13 +53,13 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
4.1. On aarch64 hosts: build flash-attn from source for your GPU
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`.
```bash
bash scripts/docker-arm64-post-install.sh
```
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
@@ -212,22 +222,19 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
3. [**Intellect-3.1**](examples/Intellect-3.1/README.md): Reproduce our `INTELLECT-3.1` training run.
4. [**MiniMax-M2.5 SWE**](examples/minimax_m2.5_swe/README.md): Train `MiniMax-M2.5` on agentic SWE tasks.
5. [**High-throughput GLM-5**](examples/glm5_pd_disag/README.md): Train `GLM-5` with PD disaggregation and FP8 inference on SWE.
6. [**High-throughput GLM-5 (llm-d)**](examples/glm5_llmd/README.md): One-line SLURM deployment for `GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload — the faster way to run `GLM-5`.
## Docs
Check out the [docs](docs) directory for in-depth guides on how to use PRIME-RL.
- [**Entrypoints**](docs/entrypoints.md) - Overview of the main components (orchestrator, trainer, inference) and how to run SFT, RL, and evals
- [**Configs**](docs/configs.md) - Configuration system using TOML files, CLI arguments, and environment variables
- [**Environments**](docs/environments.md) - Installing and using verifiers environments from the Environments Hub
- [**Async Training**](docs/async.md) - Understanding asynchronous off-policy training and step semantics
- [**Logging**](docs/logging.md) - Logging with loguru, torchrun, and Weights & Biases
- [**Checkpointing**](docs/checkpointing.md) - Saving and resuming training from checkpoints
- [**Benchmarking**](docs/benchmarking.md) - Performance benchmarking and throughput measurement
- [**Deployment**](docs/deployment.md) - Training deployment on single-GPU, multi-GPU, and multi-node clusters
Minimal end-to-end configs for the three training modes (`rl` / `opd` / `sft`) against the `reverse-text` env, using `PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT` as the student.
| Config | Mode | Teacher | Notes |
|---|---|---|---|
| `rl.toml` | `rl` | none | |
| `opd.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `opd_lora.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
| `sft.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `sft_lora.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
The student inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local teacher (used by everything except `rl.toml`) is **not** auto-launched — start it manually on GPU 1.
## Start the local teacher
Needed for `opd*.toml` and `sft.toml` / `sft_lora.toml`:
This is a reproduction of the [DeepScaleR](https://pretty-radio-b75.notion.site/DeepScaleR-Surpassing-O1-Preview-with-a-1-5B-Model-by-Scaling-RL-19681902c1468005bed8ca303013a4e2) experiments. They use RL to train from `Deepseek-R1-Distill-Qwen-1.5B` to 43.1% on AIME2024, surpassing OpenAI’s o1-preview with just 1.5B parameters.
## Setup
Install the environment using the `prime` CLI.
```bash
prime env install primeintellect/deepscaler
```
Verify that the environment is installed correctly.
```bash
uv run python -c "import deepscaler"
```
## Training
A key insight from the paper is that they train in **stages of increasing context length**. In stages 1, 2 and 3, they train with context lengths of 8192, 16384 and 24576 tokens, respectively. We match their training setup here.
They evaluate on a series of math benchmarks, including Math500, AIME24, AMC23, Minerva Math and Olympiad Math. We will focus on `math500` and `aime2024` for the reproduction, as these are already implemented as evaluation environments on the Environment Hub and also the most prominent benchmarks. We uploaded the weight checkpoints to HF as `DeepSeek-R1-Distill-Qwen-1.5B-DeepScaleR-XXX` and evaluate the base model and each checkpoint.
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, multi-tenant training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
`prime-rl` ships custom optimized model implementations for several MoE families. With `model.impl = "auto"` (default) the trainer picks the custom path when the HF config type is registered, falling back to plain HF otherwise. To force one:
The custom path enables you to set EP, CP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
### Expert Parallelism Backends
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
- **`torch`** (default): TorchTitan's all-to-all collective. Works everywhere, no extra install.
- **`deepep`**: Utilizes DeepEP's custom all-to-all collectives. This provides better performance if EP dimension spans multiple nodes. We provide pre-built binaries for H100/H200 with cuda runtime 12.9 installed, you can install them by running `uv sync --all-extras`.
DeepEP requires some careful tuning to achieve optimal performance, tuning parameters are `deepep_num_sms` and `deepep_token_chunk_size`.
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
For a model not in the table, look up the attribute paths on the loaded HF model with `model.named_children()` and set them under `[model.vlm]` directly.
### Enabling VLM Mode
Add `[model.vlm]` and bfloat16 dtypes:
```toml
[model]
name="Qwen/Qwen3-VL-4B-Instruct"
optimization_dtype="bfloat16"
reduce_dtype="bfloat16"
[model.vlm]
vision_encoder_attr="model.visual"
language_model_attr="model.language_model"
# freeze_vision_encoder = true # default; set false to fine-tune the encoder
```
The weight-broadcast key prefix is derived as `{language_model_attr}.layers.` automatically.
To add a new model family permanently, append an entry to `VLM_REGISTRY` in `src/prime_rl/utils/vlm.py`.
### Limitations
- **Vision encoder frozen by default.** Set `freeze_vision_encoder = false` to fine-tune it; in that case it's FSDP-sharded per block. The combination `freeze_vision_encoder = false` + LoRA is rejected by a config validator — LoRA freezes everything non-adapter, so unfreezing the encoder under LoRA would be a silent no-op.
- **No multimodal-safe truncation.** Token sequences are truncated to `seq_len`, but `pixel_values` and `image_grid_thw` pass through unchanged. If a sample's tokens overflow, image tokens may get dropped while image tensors still describe the full image set. Set `seq_len` to cover your longest sample.
- **bfloat16 mandatory.** The trainer config validator refuses any other `optimization_dtype` / `reduce_dtype` for VLMs — vLLM serves VLMs in bfloat16 and a mismatch breaks the importance ratio.
- **Higher KL mismatch with multi-image inputs.** Expect noisier `mismatch_kl` than text-only; this is from minor numerical differences between the trainer's and vLLM's image processing.
- **Images aren't logged to monitors.** Sample logging captures the prompt text but not the actual images.
## LoRA Training
LoRA is enabled by adding `[model.lora]`:
```toml
[model.lora]
rank=16
alpha=32
dropout=0.0
```
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
LoRA is supported across SFT and RL. For RL, `weight_broadcast.type = "nccl"` is **not** supported with LoRA — use the default filesystem transport. To save the raw adapter alongside the merged HF weights:
```toml
[ckpt.weights]
save_adapter_separately=true
```
LoRA pairs naturally with [multi-tenant training](#multi-tenant-training) — each tenant gets its own adapter and the backbone is shared across all of them in trainer memory.
## Multi-Tenant Training
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/src/prime_rl/trainer/runs.py).
## Disaggregated Prefill/Decode Inference
For large MoE serving, splitting prefill and decode onto separate vLLM groups can substantially improve throughput. Pick the prefill:decode ratio based on workload shape:
| Non-agentic (math, chat) | 1:2 | Short prompts, long generations → decode-heavy |
Example config: [`examples/glm5_pd_disag/rl.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/glm5_pd_disag/rl.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast (see the [README](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/glm5_pd_disag) for the launch story).
If prefill queues and decode is idle, add prefill nodes (and vice versa).
**UCX 1.19 requirement.** NVSHMEM needs UCX ≥ 1.19 for multi-GPU CUDA. If your cluster doesn't ship with UCX >=1.19, you can build it from source with the following command:
This page covers the math and the configurable algorithmic components: how off-policy training works, the default loss and advantage functions, how to plug in your own, the filters applied between rollout and training, and how multi-turn rollouts get merged into training samples.
`prime-rl` is asynchronous by default. The trainer and inference always run one step overlapped: while the trainer is producing $\pi_n$ from rollouts at step $n$, inference is already generating the rollouts for step $n+1$ using $\pi_{n-1}$. With matched trainer and inference step times this produces fully-overlapped pipeline parallelism — neither side ever idles.

At step $n = 1, 2, 3, \dots$:
- **Trainer** produces policy $\pi_n$ with weights $\theta_n$ from rollouts $(x_n, y_n)$.
- **Inference** produces rollouts $(x_n, y_n)$ from policy $\pi_{\max(0,\,n-1)}$.
Step indices are 0-indexed so the gap holds at startup — inference is exactly one step behind the trainer.
## Loss
### Default Loss
The default RL loss is a DPPO policy-gradient term combined with a KL regularizer similar to Kimi-K2.5. For each prompt $x_j$ we sample a group of $G$ rollouts $\{y_i\}_{i=1}^G$, score them to get $s_i$, then optimize:
$\mu$ is the policy that generated the rollout (inference), $\pi$ is the current policy (trainer), $\hat{A}_{i,t}$ is the token-level advantage, $\delta$ is the importance-sampling clipping ratio, and $\tau_{KL}$ is the KL temperature. The `min` clamps the importance ratio from above so a stale rollout assigning very low probability to a high-reward token doesn't produce a runaway gradient.
The knobs (under `[trainer.loss]` with `type = "default"`):
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 for pure distillation (no RL signal). |
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
The trainer dispatches automatically based on the batch's training mode (set by the orchestrator via `orchestrator.training_mode`):
-`rl` mode → DPPO + KL with the advantage signal.
-`opd` mode → KL distillation against the teacher's per-token logprobs. The teacher must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
-`sft` mode → standard token-level NLL on teacher-generated rollouts.
Set `[trainer.loss] type = "default"` and configure via the knobs above. SFT and OPD modes ignore the policy-gradient–specific fields.
### Custom Loss
The loss is computed **per sequence**: you write a function that takes one sequence's tensors and returns a scalar loss. The trainer iterates and aggregates.
teacher_logprobs:Float[Tensor,"seq"]|None# only set in OPD mode
advantages:Float[Tensor,"seq"]
loss_mask:Bool[Tensor,"seq"]
@dataclass
classLossOutputs:
loss:Float[Tensor,""]
metrics:dict[str,Tensor]
```
Anything you put in `metrics` is averaged across sequences and logged with the other trainer metrics.
## Advantage
### Default Advantage
The default advantage is per-group reward minus per-group baseline (DR-GRPO without std normalization). For each prompt's group of `group_size` rollouts, every token in rollout $i$ receives advantage $s_i - \bar{s}$ where $\bar{s}$ is the group mean.
This is intentionally simple — it does the right thing for most envs. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
A **length penalty** can be layered on top of the default advantage to discourage rambling. Configured under `[orchestrator.advantage.length_penalty]`, it subtracts a `coef * pass_rate * (completion tokens / orchestrator.seq_len)` term from every reward before the baseline subtraction, where `pass_rate` is the problem's mean reward across the group. The pass-rate factor means problems the model already solves reliably get the strongest push toward concise outputs, while rarely-solved problems are barely penalized (a never-solved group, mean reward 0, gets none). Set `gate_by_correctness = true` to apply the penalty only to correct rollouts (`reward == 1`), leaving incorrect ones untouched:
gate_by_correctness=false# when true, only penalize rollouts with reward == 1
```
By default the baseline is the plain group mean reward. Set `length_weighted_baseline = true` to instead use the token-length-weighted mean — `sum(len_i * reward_i) / sum(len_i)` — which centers advantages by per-token expected reward when rollouts vary a lot in length:
```toml
[orchestrator.advantage]
length_weighted_baseline=true
```
### Custom Advantage
Advantages are computed **per group**. You write a function that takes one group of rollouts and returns one advantage scalar per rollout. The orchestrator handles groups of varying size automatically — partial-group training kicks in when some rollouts in a group errored.
`AdvantageInputs.rollouts` is a list of `verifiers.RolloutOutput`, so you have access to the full rollout (turns, tool calls, custom metadata) — not just the reward. Use this for anything reward-shaping-like that needs trajectory context.
### Per-Env Advantage
`advantage` can be set per training environment. Each env inherits the top-level `[orchestrator.advantage]` when it doesn't set its own, so mixed-env runs can give each env its own advantage computation:
```toml
[orchestrator.advantage]
type="default"# the default every env inherits unless it overrides
Filters drop rollouts between scoring and training. Built-ins (composable):
| Filter | Effect |
|---|---|
| `gibberish` | Drops rollouts whose mean log-prob fall below a threshold — usually a sign of degenerate output. |
| `repetition` | Drops rollouts with high n-gram repetition. |
| `zero_advantage` | Drops rollouts whose advantage is zero, so the trainer doesn't waste tokens on them. |
The default `[orchestrator]` config already includes all three filters with their defaults. To override, set `filters` explicitly — the list replaces the defaults wholesale:
```toml
[[orchestrator.filters]]
type="zero_advantage"
[[orchestrator.filters]]
type="repetition"
threshold=0.4
```
Filtered rollouts still appear in W&B distributions, just not in the trainer batch — useful for spotting whether filtering is doing its job.
## Difficulty Pools
Difficulty pools gradually retire problems the model has solved or never solves. After each rollout, the average reward across a problem's group is compared to two thresholds:
-`buffer.easy_threshold` — at or above this, the problem moves into the `easy` pool and is no longer sampled.
-`buffer.hard_threshold` — at or below this, the problem moves into the `hard` pool and is no longer sampled.
- Otherwise the problem stays in `normal` and remains in the sampling rotation.
Pool assignments persist across checkpoints (`easy_examples.jsonl` / `hard_examples.jsonl` under each step's orchestrator checkpoint). When you resume — or want to broaden the curriculum mid-run — `buffer.easy_fraction` / `buffer.hard_fraction` randomly lift that fraction of pooled problems back into `normal` so they re-enter sampling.
```toml
[orchestrator.buffer]
easy_threshold=0.95
hard_threshold=0.05
easy_fraction=0.0# default; bump on resume to bring some easy problems back
hard_fraction=0.0# default; bump on resume to bring some hard problems back
```
Watch `pool/{env}/{easy,normal,hard}` (current pool ratios) and `evicted_examples/{env}/{easy,hard}` (per-step eviction rate).
## Online Difficulty Filtering
Online difficulty filtering (ODF) drops collapsed-advantage groups on the way *into* the buffer. Set `buffer.online_difficulty_filtering = true` (default `false`) to enable:
- Average reward across the group is **0.0** (every rollout failed) → drop the group, count under `filtered_rollouts/{env}/hard`.
- Average reward **1.0** (every rollout succeeded) → drop, count under `filtered_rollouts/{env}/easy`.
- Otherwise → into the buffer.
These are exactly the groups whose within-group advantage collapses to zero — DR-GRPO produces no gradient signal for them, so the trainer would burn step time on tokens it can't learn from.
```toml
[orchestrator.buffer]
online_difficulty_filtering=true
```
**Tradeoff: trainer stability vs. inference speed.** With ODF on, every rollout that reaches the trainer carries non-zero advantage — each trainer step's effective batch is predictable and the gradient signal is denser. The cost is paid on the inference side: rollouts get produced and then thrown away, so the orchestrator has to oversample to keep the trainer fed. If the orchestrator is your bottleneck (`time/wait_for_batch` high on the trainer), ODF can starve the loop. Bump `orchestrator.oversampling_factor` so inference produces enough groups per step to absorb the drops.
ODF is orthogonal to the [pools](#difficulty-pools): ODF reacts to the *current* group's reward distribution, the pools track the *running* per-problem average. Many configs use both — ODF for per-step density, pools for long-horizon curriculum cleanup.
## Multi-Turn Trajectories
Multi-turn rollouts (tool use, browser environments, long conversations) used to be stitched into a single fake "single-turn" sample, which silently corrupted the importance ratio when chat templates didn't roundtrip. Since [`verifiers` v0.1.8](https://github.com/PrimeIntellect-ai/verifiers/releases/tag/v0.1.8), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
### Extension Property
A sequence of trajectory steps has the **extension property** when each successive step's prompt contains all previous prompts and completions as an exact prefix. The trainer relies on this property — when it holds:
- Multiple steps merge into one training sample.
- Compute scales as $O(T)$ in the trajectory length.
When it breaks (chat template strips past thinking, environment compacts context, an agent hands off to a sub-agent, etc.), the trainer starts a new training sample from that step:
- Graceful fallback to multiple samples — no corrupted data.
- Worst case (every step breaks extension) is $O(T^2)$.
### Best-Effort Interleaving
Concretely:
```
5-step trajectory where extension breaks at step 4:
steps 1–3: extension holds → merged into Sample 1
step 4: extension breaks (e.g. thinking stripped from history)
steps 4–5: extension holds → merged into Sample 2
result: 2 training samples instead of 5
```
The orchestrator enforces an **exact prefix invariant**: the prompt at turn $t$ must be the exact concatenation of prior messages exactly as the LLM originally generated them. If turn 2's prompt is `U1, A1', U2` while `A1' ≠ A1`, the orchestrator can't safely merge — either choice produces logprob drift between trainer and inference. Starting a fresh sample is the only correct behavior, so that's what happens.
### Renderers
Best-effort interleaving works because the renderer guarantees the exact-prefix invariant *by construction* — it never re-renders prior turns, so it can't lose tokens to chat-template normalization, BPE retokenization drift, or thinking stripping. A renderer turns a model's chat template into a Python object that can:
-`render_ids(messages)` — tokenize messages to ids the inference engine accepts.
-`parse_response(completion_ids)` — recover structured `(content, reasoning_content, tool_calls)` from sampled ids.
-`bridge_to_next_turn(prev_prompt_ids, prev_completion_ids, new_messages)` — extend the previous turn's tokens verbatim with the new environment turn, instead of re-rendering history.
When `bridge_to_next_turn` succeeds, the trainer sees the exact token stream the sampler produced; when it can't be proven safe (e.g. the renderer is `DefaultRenderer` and the template's stop sequence is unknown), it returns `None` and the orchestrator falls back to a full re-render — which triggers the new-sample fallback above.
A common source of breakage in the absence of a hand-coded renderer is models like Qwen3 whose chat templates strip past `<think>` blocks across user turns:
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `glm5`, `glm4.5`, `minimax-m2`, `deepseek-v3`, `kimi-k2`, `kimi-k2.5`, `nemotron-3`, `gpt-oss`; anything else falls back to `DefaultRenderer` (a generic `apply_chat_template` wrapper). Pick one via:
```toml
[orchestrator.renderer]
name="auto"# detect from tokenizer; pass an explicit name for fine-tunes
```
For the full design rationale (failure modes ruled out, empirical token-identity comparison against `apply_chat_template`, when to write a hand-coded renderer), see [the renderers writeup on the Prime Intellect blog](https://www.primeintellect.ai/blog/renderers) — the canonical reference.
### Discontinuous Trajectories
Some envs are discontinuous by design — e.g. a main agent delegating to a sub-agent and getting back only a summarized result, not the sub-agent's whole conversation. Best-effort interleaving handles this naturally: each agent's contiguous turns merge, the handoff starts a new sample. The trainer never sees fabricated extension where there is none.
PRIME-RL implements asynchronous off-policy training, instead of the traditional synchronous on-policy training. This means that we allow inference to generate rollouts from a stale policy up to $k$ (in the code we call this `max_async_level`) steps ahead of the trainer. With `k=1` and trainer and inference step timings being equal, this allows to run without any idle time on either the trainer or inference. By default, we set `k=2` to allow overlap with a weight broadcast over the Internet, which is needed for decentralized training.
We adopt a loss objective capable of handling the natural distribution shift caused by the off-policy nature of the training. By default, we use a token-level loss variant of the [AIPO](https://arxiv.org/abs/2505.24034) training objective introduced in Llama-RL,
but omit the entropy and KL loss terms.
At each step, we sample $N$ prompts from our dataset. For
each prompt $x$, we sample a group of rollouts $\{y_i\}^G_{i=1}$
and use a verifier to assign scores $s_i$ to each $y_i$.
where $\mu$ refers to the policy that generated the rollout, $\pi$ refers to the current policy, $\hat{A}_{i,t}$ is the token-level advantage, and $\delta$ is the importance sampling clipping ratio.
## Step Semantics
PRIME-RL uses a global training step $n=1,2,3,\dots$ that is used to tag artifacts:
- **Trainer**: Produces policy $\pi_n$ with weights $\theta_n$ from rollouts $(x_n, y_n)$
- **Inference**: Produces rollouts $(x_n, y_n)$ from policy $\pi_{max(0, n-k)}$
Here, $k$ is the `max_async_level` parameter, which defaults to 2. Note that we use 0-indexed steps to cleanly indicate that at each step, the divergence off-policy gap is at most $k$ steps.
We provide a convenient way to benchmark the performance, mainly measured in throughput and MFU, of the inference engine and trainer using the `--bench` flag. It will run each module in isolation for a few steps and log performance benchmark results in a rich table to the console.
## SFT
Benchmark on the default fake data configuration
```bash
uv run sft ... --data.type fake --bench
```
Benchmark with variable-length, instead of fixed-length, fake data to more closely simulate real data.
```bash
uv run sft ... --data.type fake --data.length variable --bench
```
Benchmark different batch configurations, i.e. the (micro) batch size and sequence length
*Note, that it is not yet possible to benchmark the RL trainer against real data when benchmarking the RL trainer in isolation.*
### Inference
To benchmark the inference engine in isolation, start the inference server with the correct configuration file and run the orchestrator with the `--bench` flag.
```bash
uv run inference @ path/to/config.toml
```
```bash
uv run orchestrator @ path/to/config.toml --bench
```
*Note, that it is not yet possible to benchmark the inference engine against fake data.*
## Trainer + Inference
To benchmark the full RL training, you can add the `--bench` flag to your RL entrypoint. This will benchmark the RL trainer against fake data and the inference engine against real data from the orchestrator.
Prime-RL supports custom implementations for key algorithmic components, allowing you to experiment with different RL objectives and techniques.
## 1. Custom Loss Functions
The loss is computed **per-sequence** (per-sample). You provide a function that computes the loss for a single sequence, and the framework handles iteration and aggregation.
# Rollouts grouped by problem: rollouts[i][j] is the j-th rollout for problem i.
rollouts:list[list[vf.RolloutOutput]]
```
Each `vf.RolloutOutput` carries the full rollout (`reward`, `trajectory`, etc.), so custom advantages can read any metadata they need (e.g. completion-token counts, turn counts, tool calls).
Checkpointing is non-standard due to trainer/orchestrator separation and natural asynchrony.
- SFT+RL Trainer: Checkpoints FSDP model shard (using DCP), optimizer and scheduler state, and progress (training step, total samples, total tokens)
- Orchestrator: Checkpoints orchestrator progress (training step, total tokens, total samples, total problems)
- Inference: Inference is stateless. Upon restart, the orchestrator will reload the correct weights into the inference engine. No checkpointing is required.
The default checkpoint directory is `checkpoints` and each checkpoint step will live in a step subdirectory, i.e. `checkpoints/step_{step}`.
Checkpointing is configured with the config key `--ckpt`. One can specify the interval (`--ckpt.interval`), whether to save checkpoints asynchronoously (`--ckpt.save-async`), how many recent step checkpoints to keep on disk (`--ckpt.keep-last`), and keep checkpoints at every N steps permanently (`--ckpt.keep-interval`). By default, we do not checkpoint to save disk space.
## SFT
Let's split the reverse text training SFT example, which does 40 steps by default, into two runs of 20 steps each.
First, run the first 20 steps and append `--ckpt` flag will enable the default checkpoint configuration which will only write the final checkpoint to disk, but no intermediate checkpoints.
```bash
uv run sft ... --max-steps 20 --ckpt
```
Then, to resume the training from step 20, run the following command
```bash
uv run sft ... --max-steps 40 --ckpt.resume-step 20
```
## RL
Similarly, let's split the reverse text training RL example, which does 20 steps by default, into two runs of 10 steps each.
First, start the inference server. It can stay running across restarts as the orchestrator will automatically send the right checkpoint to the inference server when resuming.
```bash
uv run inference ...
```
Then, run the first 20 steps and write the final checkpoint to disk
```bash
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--max-steps 10\
--ckpt
```
And finally, resume the training to do the remaining 10 steps
We use `pydantic-settings` with some custom functionality for configuring runs. We support the following sources, in this order of precedence:
1.**Command-line arguments**: Pass (nested) arguments as `--key.subkey value` to the script. For example, to set the model name, set `--model.name <model-name>`
2.**Config files**: You can pass TOML config files using the `@` prefix. For example, to set a config, run `uv run inference @ path/to/config.toml`. (*You have to leave a space between the `@` and the config file*)
3.**Environment variables**: You can set environment variables to override the config values. All environment variables must be prefixed with `PRIME_` and use the `__` delimiter to nest the keys. For example, to set the model name you can run `export PRIME_MODEL__NAME=Qwen/Qwen3-0.6B`.
4.**Defaults**: For almost all config arguments, we have a default value which will be used if no other source is provided.
In general we recommend setting configurations via config files to define reproducible experiments and use command-line arguments to override the config values to run variants of the same experiment. Environment variables are usually only used in production settings to communicate with the [Prime Protocol](https://github.com/PrimeIntellect-ai/protocol) worker. In most cases, you should not need to use environment variables.
The precedence order will be important if multiple sources try to configure the same argument. For example, in the following command, all sources will define a model name
```toml
# qwen8b.toml
[model]
name="Qwen/Qwen3-8B"
```
```toml
# qwen14b.toml
[model]
name="Qwen/Qwen-14B"
```
```bash
PRIME_MODEL__NAME=Qwen/Qwen3-4B uv run ... @ qwen8b.toml @ qwen14b.toml --model.name Qwen/Qwen3-32B
```
In this example, the CLI argument `--model.name Qwen/Qwen3-32B` will take precedence and the script will use `Qwen/Qwen3-32B` as the model name. If the CLI argument wasn't set, then the second config file would take precedence and the script would use `Qwen/Qwen-14B` as the model name. If the second config file wasn't set, then the first config file would take precedence and the script would use `Qwen/Qwen3-8B` as the model name. Finally, if the first config file wasn't set, then the environment variable would take precedence and the script would use `Qwen/Qwen-4B` as the model name. If the environment variable wasn't set, then the default value would be used and the script would use `Qwen/Qwen3-0.6B` as the model name.
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
## Table of Contents
- [Sources and Precedence](#sources-and-precedence)
- [TOML Composition](#toml-composition)
- [CLI Overrides](#cli-overrides)
- [Inspecting and Validating](#inspecting-and-validating)
Field values come from three sources — Pydantic defaults, TOML files (passed with `@`), and CLI flags. They're layered in this order, with later sources winning:
1.**Defaults** declared on the Pydantic model.
2.**TOML files** passed with `@`, left to right — later files override earlier ones.
3.**CLI flags** in dotted, kebab-case form (`--model.name`).
## TOML Composition
The `@` token introduces a TOML file. Multiple `@` arguments compose left-to-right, deep-merged — unset fields in an overlay keep the base value:
```bash
uv run rl @ examples/reverse_text/rl.toml # one file
uv run rl @ base.toml @ overlay.toml # left to right
uv run rl @ base.toml --trainer @ trainer.toml # mixed
```
> Mind the space: `@ path/to/x.toml`, not `@path/to/x.toml`.
## CLI Overrides
CLI flags mirror the TOML tree using dots:
```bash
--max-steps 50# top-level
--model.name Qwen/Qwen3-4B # nested
--trainer.optim.lr 1e-5 # double-nested
--inference.parallel.tp 4
```
> Field names are snake_case in TOML (`max_model_len`) and kebab-case on the CLI (`--max-model-len`).
> Renamed fields keep their old name as a validation alias — e.g. `rollouts_per_example` is still accepted in TOML and CLI after being renamed to `group_size`. Mixing the two names across sources is safe.
CLI uses paired flags: bare `--flag` sets `True`, `--no-flag` sets `False`. TOML must be explicit:
```bash
uv run rl @ rl.toml --clean-output-dir # True
uv run rl @ rl.toml --no-clean-output-dir # False
```
```toml
clean_output_dir=true
```
### Lists
CLI accepts space-separated values or a JSON literal. TOML uses an array literal. Both forms target the same field:
```bash
uv run rl @ rl.toml --trainer.model.lora.target-modules q_proj k_proj v_proj
uv run rl @ rl.toml --trainer.model.lora.target-modules '["q_proj", "k_proj", "v_proj"]'
```
```toml
[trainer.model.lora]
target_modules=["q_proj","k_proj","v_proj"]
```
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables (e.g. environments), see [Environments](#environments-orchestratortrainenv).
### Dicts
CLI takes a JSON literal. TOML uses a table or inline-table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
```bash
uv run rl @ rl.toml --orchestrator.train.env.0.args \
Many sub-configs are typed `SomeConfig | None`. Two patterns enable them:
- **Bare flag with defaults**: `--model.compile` or, in TOML, an empty section `[model.compile]`. The sub-config materializes with all-default values.
- **Enable and set fields together**: `--model.compile.fullgraph` (CLI) or any populated `[model.compile]` table (TOML).
To **disable** a sub-config that's on by default, use `--no-<name>` on the CLI or assign the string `"None"` in TOML (see [None](#none)). This is how `[ckpt]`, `[model.lora]`, `[model.compile]`, `[trainer.wandb]`, etc. are turned on and off.
### None
TOML has no `null`. Use the string `"None"`, which the loader coerces:
```toml
[inference.model]
max_model_len="None"
```
On the CLI: `--inference.model.max-model-len None`.
### Discriminated Unions
Loss, advantage, optimizer, scheduler, weight broadcast transport, and several others are discriminated unions. Set the `type` field to pick a variant:
```toml
[trainer.optim]
type="muon"
lr=1e-5
mu=0.95
```
Omit `type` to keep the default variant.
### Environments (`[[orchestrator.train.env]]`)
Training environments are an array of tables — set one per env, optionally with sampling weights:
`args` is forwarded verbatim to the environment's `load_environment(**args)`.
The same `id` can appear multiple times across train and eval (or with different `args`) — useful for evaluating on a held-out split of the env you're training on, or comparing two configurations of the same env side by side. When `id` is reused, set a distinct `name` on each entry; `name` defaults to `id` and must be unique across all envs in the same group.
## Examples
The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples) are the canonical, kept-up-to-date references — the rest of the repo's TOMLs (under `configs/`) are CI- and debug-internal and may drift. Each example directory has its own README with the full launch story.
**Basic** (1–8 GPUs):
- [**Reverse Text**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/reverse_text) — `Qwen3-0.6B` reversing a chunk of text. Tiny single-turn SFT + RL; runs on a single consumer GPU in minutes.
- [**Alphabet Sort**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/alphabet_sort) — `Qwen3-4B-Instruct-2507` sorting names alphabetically. Multi-turn LoRA RL without SFT warmup; one H100.
- [**Wiki Search**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/wiki_search) — `Qwen3-4B-Instruct-2507` answering trivia by web-searching Wikipedia. Multi-turn with tool use.
- [**Hendrycks Sanity**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/hendrycks_sanity) — `DeepSeek-R1-Distill-Qwen-1.5B` on a filtered MATH subset. Useful for algorithm ablations.
**Advanced** (32–2048 GPUs, SLURM):
- [**Qwen 3 30B – A3B Math**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/qwen30b_math) — `Qwen3-30B-A3B` on hard math.
- [**Qwen 3 30B – A3B SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/qwen30b_swe) — `Qwen3-30B-A3B` on hard SWE.
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/Intellect-3.1) — reproduces our INTELLECT-3.1 training run.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/minimax_m2.5_swe) — `MiniMax-M2.5` on agentic SWE.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/glm5_pd_disag) — `GLM-5` with P/D disaggregation and FP8 inference.
### Worked Example: Compose, Override, Dry-Run
Start from a shipped base config, override two fields on the CLI, and dry-run:
Each per-process TOML reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/configs/trainer.toml`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
You can deploy PRIME-RL on a single GPU and larger multi-node clusters.
## SFT
### Single-GPU
For training on a single GPU, no communication orchestration is required and you can choose whether to start your trainer using our trainer entrypoint or using `torchrun`.
To start with our `sft` entrypoint
```bash
uv run sft ...
```
To do the same thing, but using `torchrun`
```bash
uv run torchrun src/prime_rl/trainer/sft/train.py ...
```
### Multi-GPU
For training on multiple GPUs, use `torchrun` with the `--nproc-per-node` flag.
```bash
uv run torchrun \
--local-rank-filter 0\
--nproc-per-node 8\
src/prime_rl/trainer/sft/train.py ...
```
*The `--local-rank-filter` flag is used to only log the logs from the master rank, as detailed in [logging](logging.md).*
### Multi-Node
For training on multiple nodes, use `torchrun` with the `--nnodes`, `--node-rank`, and `--rdzv-endpoint` flags.
First, decide which node will be your head node and find a reachable private IP address for it. If your nodes are not colocated, you will likely need to setup VPN (e.g. [Tailscale](https://tailscale.com)) for the nodes to reach each other.
(*Skip this step if the default network interface is sufficient.*) Make sure to set the network interface for GLOO and NCCL to one that allows all nodes to reach each other.
```bash
# On both nodes
exportGLOO_SOCKET_IFNAME=...
exportNCCL_SOCKET_IFNAME=...
```
Then, configure the rendezvous endpoint to allow the nodes to find each other. Here, `MASTER_ADDR` is the private IP address of the head node and `MASTER_PORT` is a free port on the head node, typically port 29500 for `torchrun`.
```bash
# On both nodes
exportMASTER_ADDR=...
exportMASTER_PORT=...
```
Then, on the head node, run
```bash
# On node 0
uv run torchrun \
--nnodes 2\
--node-rank 0\
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT\
--local-rank-filter 0\
--nproc-per-node 8\
src/prime_rl/trainer/sft/train.py ...
```
And on the second node, run
```bash
# On node 1
uv run torchrun \
--nnodes 2\
--node-rank 1\
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT\
--local-rank-filter 0\
--nproc-per-node 8\
src/prime_rl/trainer/sft/train.py ...
```
### SLURM
See the dedicated [SLURM guide](slurm.md).
## Inference
For SLURM-based inference deployment, see the [SLURM guide](slurm.md#inference-examples). Each node runs an independent vLLM replica — no manual coordination needed.
For manual multi-node deployment without SLURM, we rely on vLLM's multi-node data parallel deployment primitives ([docs](https://docs.vllm.ai/en/v0.10.0/serving/data_parallel_deployment.html)).
First, decide which node will be your head node and find a reachable private IP address for it. If your nodes are not colocated, you will likely need to setup VPN (e.g. [Tailscale](https://tailscale.com)) for the nodes to reach each other.
(*Skip this step if the default network interface is sufficient.*) Make sure to set the network interface for GLOO and NCCL to one that allows all nodes to reach each other.
```bash
# On both nodes
exportGLOO_SOCKET_IFNAME=...
exportNCCL_SOCKET_IFNAME=...
```
Then, configure the data parallel address as the private IP address of the head node.
```bash
# On both nodes
exportDATA_PARALLEL_ADDRESS=...
exportDATA_PARALLEL_RPC_PORT=...
```
To run TP=4 and DP=4 with DP ranks 0 and 1 on the head node and DP ranks 2 and 3 on the second node, run
```bash
# On node 0
uv run inference \
--data-parallel-size 4\
--tensor-parallel-size 4\
--data-parallel-size-local 2\
--data-parallel-address $DATA_PARALLEL_ADDRESS\
--data-parallel-rpc-port $DATA_PARALLEL_RPC_PORT
```
```bash
# On node 1
uv run inference \
--data-parallel-size 4\
--tensor-parallel-size 4\
--data-parallel-size-local 2\
--data-parallel-address $DATA_PARALLEL_ADDRESS\
--data-parallel-rpc-port $DATA_PARALLEL_RPC_PORT\
--data-parallel-start-rank 2\
--headless
```
## RL
### Single-GPU Training
If you only have access to a single GPU, you may still be able to run small RL experiments. To do so, configure your inference server to use only a fraction of the available memory to leave some space for the trainer.
For example, to run an RL training on a single GPU while using 50% of the available memory for the inference server, run
```bash
bash scripts/tmux.sh
```
```bash
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--inference @ path/to/infer.toml \
--trainer-gpu-ids 0\
--inference-gpu-ids 0\
--inference.gpu-memory-utilization 0.5
```
*Make sure to tune the `--gpu-memory-utilization` value such that you have enough GPU memory for the RL trainer.*
You can also set this up by starting each submodule manually.
```bash
# Run this in the `Inference` pane
uv run inference @ path/to/infer.toml --gpu-memory-utilization 0.5
```
```bash
# Run this in the `Orchestrator` pane
uv run orchestrator @ path/to/orch.toml
```
```bash
# Run this in the `Trainer` pane
uv run trainer @ path/to/train.toml
```
### Multi-GPU Training
For single-node training, we recommend using the `rl` entrypoint to conveniently start all components, i.e. the inference server, the orchestrator, and the trainer.
By default, the inference server starts on GPU ID 0 and the trainer on GPU ID 1.
```bash
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--inference @ path/to/infer.toml \
```
You can configure the GPU IDs to use for the inference server and the trainer. For example, to run the inference server on GPUs IDs 0-5 with data parallelism and the trainer on GPUs IDs 6-7
```bash
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--inference @ path/to/infer.toml \
--inference-gpu-ids 0,1,2,3,4,5 \
--trainer-gpu-ids 6,7 \
--inference.parallel.dp 6
```
### Parallel Experiments
For quick ablations, it can be more efficient to parallelize experiments within a node (e.g. split your GPUs to run two experiments in parallel). For example, if you have access to 4 GPUs and your experiment fits on 2 GPUs, you can parallelize two experiments as follows:
Start the first experiment in a tmux session `exp1` with outputs directory `outputs1`. Specify it both in the tmux script, as well as in the start command (*will use the first 2 GPUs*)
```bash
bash scripts/tmux.sh -s exp1 -o outputs1
```
```bash
# Run this in the `Trainer` pane
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--inference @ path/to/infer.toml \
--output-dir outputs1
```
For the second experiment, start a second tmux session named `exp2` with outputs directory `outputs2`. In addition, specify a new server port for the inference engine and orchestrator (*will use the last 2 GPUs*)
> We currently require a shared file system for multi-node RL training.
To facilitate multi-node RL training, ensure that all nodes have access to a shared file system and that the node that will run the inference server is reachable from the orchestrator via a private or public IP address. Then, set the following environment variables on all nodes:
```bash
# On all nodes
exportOUTPUT_DIR=... # Path to directory in shared file system
exportINFERENCE_SERVER_IP=... # Reachable IP address of the inference node
exportINFERENCE_SERVER_API_KEY=... # API key for the inference server
Finally, start the trainer on one as described in the [Trainer](#trainer) section.
```bash
# On other node
uv run torchrun \
--nproc-per-node 8\
--local-rank-filter 0\
src/prime_rl/trainer/rl/train.py ... \
--output-dir $OUTPUT_DIR
```
Of course, you can further scale up the number of nodes used by the trainer and inference server, as described in the sections above. However, make sure that there is only a single orchestrator instance.
### SLURM
See the dedicated [SLURM guide](slurm.md).
## Kubernetes
For deployments on Kubernetes clusters, PRIME-RL provides a Helm chart that manages the entire training infrastructure including orchestrator, trainer, and inference components with automatic pod scheduling, GPU allocation, and shared storage.
See the dedicated [Kubernetes guide](kubernetes.md) for complete documentation including:
This page covers workflows for developing on `prime-rl` itself — running the test suite, contributing changes, and adding new model architectures with the small-scale tooling we use to iterate on MoE families without booting up a 100B+ run.
## Table of Contents
- [Test Suite](#test-suite)
- [Layout](#layout)
- [Running Tests Locally](#running-tests-locally)
- [CI Workflows](#ci-workflows)
- [Markers](#markers)
- [Pre-Commit Hooks](#pre-commit-hooks)
- [Adding a New Model](#adding-a-new-model)
- [Implement the Modeling Code](#implement-the-modeling-code)
- [Register a Mini Preset](#register-a-mini-preset)
- [Run the Smoke Test](#run-the-smoke-test)
## Test Suite
The test suite is split into three tiers, each with its own CI workflow.
### Layout
- **`tests/unit/`** — fast-running, hermetic tests for isolated logic: config parsing and validation, advantage / loss / scheduler / packer math, individual dataset paths, model-conversion roundtrips, etc. Tests that need a GPU are tagged with the `gpu` marker.
- **`tests/integration/`** — full-stack RL/SFT runs on a tiny model end-to-end through inference + orchestrator + trainer.
- **`tests/nightly/`** — runs the configs in [`examples/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples) every night to catch regressions in the shipped examples.
### Running Tests Locally
```bash
uv run pytest -v # everything
uv run pytest tests/unit -v # unit only
uv run pytest tests/integration -v # integration only
uv run pytest -v -m "not gpu"# CPU-only subset (mirrors CPU CI)
uv run pytest -v -m gpu # GPU-only subset
uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenario
```
### CI Workflows
| Workflow | Trigger | What runs | Where |
|---|---|---|---|
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_multi_run`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
### Markers
Two pytest markers are declared in `pyproject.toml` (`addopts = "--strict-markers"`):
-`gpu` — gate a test that needs CUDA. CPU CI uses `-m "not gpu"`; the GPU unit job uses `-m gpu`.
-`slow` — gate a test that's expensive enough you'd usually skip it locally. Deselect with `-m "not slow"`.
## Pre-Commit Hooks
Install the [pre-commit](https://pre-commit.com) hooks before your first commit so ruff check + format run on staged Python files automatically:
```bash
uv run pre-commit install
```
## Adding a New Model
Bringing up a new model family is three steps: implement the modeling code, register a mini preset, and run the smoke test. The preset and smoke test let you iterate on the modeling code at ~0.5B scale on 1–2 GPUs instead of paying the cost of the full-size model — useful for catching bugs in modeling code, state-dict conversions, and pipeline integration before scaling.
### Implement the Modeling Code
Drop the modeling code under `src/prime_rl/trainer/models/<arch>/` (HF-compatible config, modeling, and weight conversion). Mirror the layout of an existing family — `glm4_moe/` or `qwen3_moe/` are good starting points.
### Register a Mini Preset
Add an entry to [`scripts/mini_moe.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/scripts/mini_moe.py) so the smoke-test workflow can build a ~0.5B test model in your architecture. The preset names the config class, picks small dimensions, and wires up the HF + PrimeRL model classes plus a tokenizer source:
Build the mini model. This creates a ~543M-parameter GLM-4 MoE (1024 hidden, 24 layers, 8 experts) with random weights, copies the tokenizer from the original GLM-4 model, and verifies the HF↔PrimeRL roundtrip is lossless:
```bash
uv run python scripts/mini_moe.py --arch glm4_moe --output-dir ./mini-glm-moe
```
To re-verify the roundtrip after a modeling-code change without re-creating the model:
```bash
uv run python scripts/mini_moe.py --arch glm4_moe --output-dir ./mini-glm-moe --verify-only
```
Warm up the random-weight mini model with SFT on reverse-text so KL divergence becomes meaningful in the RL phase. Loss drops from ~12 to ~2.5 — the output won't be coherent, but the distribution is non-trivial. A pre-built SFT'd checkpoint lives at [samsja/mini-glm-moe](https://huggingface.co/samsja/mini-glm-moe) if you want to skip this step:
```bash
uv run sft @ configs/debug/moe/sft/train.toml \
--model.name ./mini-glm-moe \
--data.name PrimeIntellect/Reverse-Text-SFT \
--data.type null \
--max_steps 200\
--optim.lr 1e-4 \
--ckpt.weights
```
Then run the full RL stack on reverse-text:
```bash
uv run rl @ configs/ci/integration/reverse_text_moe/start.toml \
--model.name samsja/mini-glm-moe \
--trainer.model.impl custom \
--inference.gpu-memory-utilization 0.7 \
--inference.model.max-model-len 2048
```
What to look for:
- **No crashes.** Validates the full inference + orchestrator + trainer pipeline end-to-end.
- **Finite, non-zero KL.** Confirms the reference distribution is meaningful.
- **Loss reasonable.** Not NaN, not stuck.
Don't expect reward to climb meaningfully in 20 steps on a random model.
### Requirements for merging a new model
Before merging a new model, you need to ensure the following:
- The model is correctly registered and defines and all the required methods - such as `convert_hf_layer_to_tt` and `convert_tt_layer_to_hf`.
- The small smoke test passes.
In the PR that adds the new model, you also need to provide a table covering the KL mismatch across 20 steps on `math` environment with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not met, the PR will not be merged (unless reasonable justification is provided). This is to ensure all our models are consistent and their implementations match the implementations in the inference framework.
The main usecase of PRIME-RL is RL training. Three main abstractions facilitate RL training: the **orchestrator**, the **trainer**, and the **inference** service.

### Orchestrator
The orchestrator is a lightweight CPU process that handles the core data and scheduling logic, serving as an intermediary between the trainer and inference service with bidirectional relays. In one direction, it collects rollouts from the inference server, assembles them into packed batches, and dispatches them to the trainer; in the other direction, it relays updated model weights from the trainer to the inference service. The orchestrator utilizes `verifiers` environments to abstract multi-turn rollout generation and scoring. Each training and evaluation environment is exposed as a `vf.EnvServer` as a sidecar to the orchestrator process (default) or as a standalone process (e.g. used in hosted training to run environments in containers).
### Trainer
The trainer is responsible for producing an updated policy model given rollouts and advantages. We use FSDP2 as the backend with compatibility for any HuggingFace (HF) model. For some models we also provide custom implementations, mostly for performance reasons. FSDP shards model parameters, gradients, and optimizer states, allowing training large models with data parallelism and minimal GPU memory footprint. We support a variety of popular training objectives, such as GRPO, GSPO, OPO, RLOO and [CISPO](https://arxiv.org/abs/2506.13585). The trainer is inspired by [`torchtitan`](https://github.com/pytorch/torchtitan) and relies on native PyTorch features to implement advanced parallelism techniques, such as tensor, context or expert parallelism.
### Inference
The inference service in its simplest form is a standard OpenAI-compatible server with a vLLM backend. The API specification is extended with a custom `update_weights` endpoint to reload model weights from a HF-compatible checkpoint on disk. Otherwise, we rely on vLLM's optimized kernels, parallelism strategies, and scheduling for fast rollout generation. Given the disaggregated nature of the service architecture, it can be directly extended to include multiple engines with a shared request pool, allowing operation across multiple clusters and straightforward integration of alternative inference engines (e.g. SGLang, Tokasaurus). We also heavily rely on native data parallelism in vLLM (also available in SGLang) for orchestrating the fleet of nodes dedicated to inference.
### RL
For doing RL training all components need to be started. One can do this manually:
```bash
uv run inference ...
```
```bash
uv run orchestrator ...
```
```bash
uv run trainer ...
```
Or, alternatively on a single node, use the `rl` entrypoint to start all components.
```bash
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--inference @ path/to/infer.toml \
...
```
For more details on multi-node deployment options, see the [deployment](deployment.md) documentation and see the [examples](examples) for concrete training configurations. To see all available configuration options, run `uv run rl --help`.
## SFT
We provide a fairly straight-forward SFT trainer which is capable of fine-tuning any conversational model on multi-turn conversation with tool calling. It shares a lot of components with the RL trainer, such as the modeling code, parallelism techniques, checkpoint format, logger, etc. which ensures a seemless post-training workflow.
To start an SFT training, you need to prepare a conversational dataset in either [prompt-completion format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion) or raw `messages` format. If `messages` is provided, the trainer interprets the full conversation as a single sample with an empty prompt and applies role-based loss masking across the whole chat. If both `messages` and `prompt` / `completion` are present, `messages` takes precedence. Single-turn fine-tuning should be compatible with the chat templates of most models. However, to properly handle loss masking, we require that the tokenizer's chat template satisfies a prefix property: the tokenization of any conversation prefix must be a prefix of the tokenization of the full conversation. For instance, tokenizing message 1 should yield a token sequence that forms a prefix of tokenizing messages 1 and 2, which in turn should be a prefix of tokenizing messages 1, 2, 3, and so forth. An example of a chat template that *does not* satisfy this property is Qwen3's chat template, as it strips away past think sections.
On a single GPU, start the training with the `sft` entrypoint
```bash
uv run sft ...
```
If you have access to multiple GPUs, use [`torchrun`](https://docs.pytorch.org/docs/stable/elastic/run.html) with `--nproc-per-node` to start the training.
```bash
uv run torchrun --nproc-per-node 8 src/prime_rl/trainer/sft/train.py ...
```
For more details on multi-node deployment options, see the [deployment](deployment.md) documentation and see the [examples](examples) for concrete training configurations. To see all available configuration options, run `uv run sft --help`.
PRIME-RL can train and evaluate in any [`verifiers`](https://github.com/willccbb/verifiers) environments. To train in a new environment, simply install it from the [Environment Hub](https://app.primeintellect.ai/dashboard/environments) or install a local environment.
This page covers the inference configuration and the supported features/deployment shapes. It covers how to scale the inference server from a single GPU to 1000s of GPUs that run agentic workloads at the speed of light with all the bells and whistles configured.
`prime-rl` chooses to use `vLLM` as the inference engine. We aim to stay up-to-date with the latest vLLM features, being at-most 1 version behind the latest stable release. This allows us to use the latest features from vLLM as soon as they are released - such as router replay, CPU KV cache offload, and more.
We support 3 distinct deployment shapes:
- [Single-Node](#single-node) - Runs the inference server on a single node. Useful for debugging, small scale experiments or smaller models. The default deployment shape.
- [Multi-Node](#multi-node) - Runs the inference server on multiple nodes. Useful for large scale experiments or larger models, where latency is not a concern - i.e. single turn inference, long context inference, etc.
- [Disaggregated](#disaggregated) - Runs the inference server on multiple nodes, but disaggregates the prefill and decode stages. Useful for large scale experiments or larger models, where latency is a concern and multi-node deployment creates very high E2E rollout latency, such as agentic workflows.
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `backend_port`, and a `[...deployment.router]` block, etc.
```toml
[inference.deployment]
type="single_node"# or "multi_node" or "disaggregated"
```
To configure the inference server, you can use the `InferenceConfig` field. This is a config-field that allows you to set the inference server-specific knobs. Most of these are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
```toml
[inference]
model="PrimeIntellect/INTELLECT-3"
...
```
We will now walk through the supported features and deployment shapes in detail, starting with the single-node deployment.
## Single-Node
The single-node deployment is the default deployment shape. It runs the inference server on a single node. It is useful for debugging, small scale experiments or smaller models. You can configure the single-node deployment with the `SingleNodeInferenceDeploymentConfig` config-field.
```toml
[inference.deployment]
type="single_node"
```
This deployment shape runs the inference server on a single node, if configured with NVLink enabled, it allows you more freedom in terms of parallelism configurations.
```toml
[inference]
enable_expert_parallel=true# defaults to False
[inference.parallel]
tp=2
dp=4
[inference.deployment]
type="single_node"
```
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required `orchestrator.max_inflight_requests`. Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.enable_expert_parallel` or `inference.parallel.tp` to maximize the available GPU memory.
You can also increase the available KV cache memory by enabling `inference.kv_cache_offload`. More details in the [Advanced Configuration](#advanced-configuration) section.
## Multi-Node
This deployment shape branches into 2 sub-shapes:
- [Multi-replica](#multi-replica) - Runs the inference server on multiple nodes, but each node runs an independent vLLM replica. You can think of this as a for-loop over single-node deployments.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
### Multi-replica
This deployment shape runs the inference server on multiple nodes, but each node runs an independent vLLM replica.
Parallelism configuration is the same as the single-node deployment. The shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.deployment.num_nodes` to the number of nodes you want to run the inference server on.
```toml
[inference.deployment]
type="multi_node"
num_nodes=2
[inference]
model="PrimeIntellect/INTELLECT-3"
[inference.parallel]
tp=2
dp=4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a router instance running on the same node as the 1st replica — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[...deployment.router]` block. You can read more about the supported routing options in the [router](#router) section.
### Wide-EP
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.enable_expert_parallel = true`.
```toml
[inference.deployment]
type="multi_node"
num_nodes=2
[inference]
model="PrimeIntellect/INTELLECT-3"
enable_expert_parallel=true
[inference.parallel]
tp=2
dp=8
```
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tp = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
## P/D Dissagregation
This is the most advanced deployment shape. It allows you to disaggregate the prefill and decode stages, with KV cache flowing between them. This is useful for large scale deployments, where there are high requirements on latency, such as agentic workflows spanning 100s of turns.
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and `inference.deployment.num_prefill_nodes` and `inference.deployment.num_decode_nodes` to the number of nodes you want to run the prefill and decode stages on.
```toml
[inference.deployment]
type="disaggregated"
num_prefill_nodes=2
num_decode_nodes=2
```
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode node groups. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of replicas you want to run.
```toml
[inference.deployment]
type="disaggregated"
num_prefill_nodes=2
num_decode_nodes=2
num_prefill_replicas=2
num_decode_replicas=1
```
Now the total deployment will span 6 nodes - 2x2 for prefill and 1x2 for decode. 2 prefill replicas will run on 2 nodes each - total of 4 nodes for prefill. 1 decode replica will run on 2 nodes for decode.
We also allow you to configure the total amount of inference replicas - this is useful if you'd like to multiply the above configuration by a factor of `k`, each running behind a separate `vllm-router` instance.
```toml
[deployment]# this is a top-level RL deployment, not inference.deployment!!
type="multi_node"
num_train_nodes=4
num_infer_nodes=6# this is per-replica
num_infer_replicas=3
```
This will run 3 inference replicas, each running on 6 nodes. Each replica will run on 2x2 nodes for prefill and 1x2 nodes for decode. The total deployment will span 18 nodes. This will also spin-up 3 separate `vllm-router` instances.
## Router
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
```toml
[inference.deployment.router]# or [deployment.router] for the standalone inference entrypoint
type="llm-d"# "vllm-router" (default) or "llm-d"
# llm-d-only knobs (all optional):
scorers={"prefix-cache-scorer"=3.0,"active-request-scorer"=2.0}# base, applied to every profile
prefill_scorer_overrides={"queue-scorer"=2.0,"kv-cache-utilization-scorer"=2.0}# merged onto the P/D prefill profile
decode_scorer_overrides={}# merged onto the P/D decode profile
non_cached_tokens=16# below this many non-cached prompt tokens, skip remote prefill (P/D)
```
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy. Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
Both backends support the 2 most important things:
- Request routing - KV cache re-use and balanced routing
- P/D disaggregation - handling the prefill and decode stages separately
### Routing policies
The 2 policies you might want to configure are:
-`consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - this works by hashing a request header to determine where to route the request to. You can configure what to hash by setting
`orchestrator.student.client.extra_headers_from_state` to the header the `router` expects to be set.
We set it to a sensible default, that works with all verifiers environments.
X-Session-ID="trajectory_id"# this is the default - each rollout has a unique trajectory_id and router expects X-Session-ID
```
-`round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
## Advanced Configuration
### KV Cache Offload
Maximizing KV-Cache space is crucial to support high-concurrency workloads. You can offload the KV cache to CPU memory (and, behind it, disk) by setting `inference.kv_cache_offload`. It is a discriminated config with two composable tiers, `cpu` and `disk`: a `cpu` tier is always required, and an optional `disk` tier is layered behind it (GPU → DRAM → disk). Disk-only is not supported.
The `type` field selects the backend:
-`native` — vLLM's built-in offloading. CPU-only uses `OffloadingConnector`; CPU+disk uses `TieringOffloadingSpec` (a CPU primary tier with a filesystem secondary tier). Fully self-contained — no extra processes.
-`mooncake` — a [Mooncake](https://github.com/kvcache-ai/Mooncake) **shared distributed store** (SLURM only). One `mooncake_master` + metadata server runs on the head inference node; every inference node runs a `mooncake_client` that contributes its DRAM (and, with `disk`, SSD) segment to that *single* pool. Because blocks are keyed by model + parallel rank + content hash (no instance id), a prefix cached by one node/replica is reusable by all of them over RDMA — pooling every node's CPU RAM into one KV cache. Use `native` for local/single-process runs.
```toml
# Native CPU offload (reserves 128GB of CPU KV cache for this instance)
[inference.kv_cache_offload]
type="native"
[inference.kv_cache_offload.cpu]
num_bytes=128_000_000_000# 128GB
# Native CPU + disk tiering (self-contained)
[inference.kv_cache_offload]
type="native"
[inference.kv_cache_offload.cpu]
num_bytes=128_000_000_000
[inference.kv_cache_offload.disk]
path="/scratch/kv"# disk capacity is bounded by the filesystem
# Mooncake CPU + disk (per-node distributed store, RDMA)
[inference.kv_cache_offload]
type="mooncake"
[inference.kv_cache_offload.cpu]
num_bytes=128_000_000_000
[inference.kv_cache_offload.disk]
path="/scratch/kv"
```
For `native`, `cpu.num_bytes` is the aggregate CPU KV pool for the instance (vLLM shards it across workers). For `mooncake`, `cpu.num_bytes` is the DRAM each node contributes to the shared pool (so the total pool ≈ `num_bytes × #inference-nodes`); the store uses RDMA, so it requires an RDMA-capable fabric. Enabling offload automatically enables prefix caching.
### Optimized P/D disaggregation deployment
For optimal P/D disaggregation deployment, we automatically set the decode `all2all_backend` to `deepep_low_latency` and the prefill `all2all_backend` to `deepep_high_throughput`. We currently don't support customizing all2all backends for P/D disaggragation out of the box. You can do this by overriding the slurm template only.
For KV cache transfer, we utilize the NIXL connector. This is the default and only currently supported connector. We aim to support more advanced options, such as D->P transfer, or Mooncake Connector in the future.
For configuring various knobs with environment variables, we enable you to configure prefill and decode environment variables separately. This is useful if you want to configure different environment variables for the prefill and decode stages.
We support various other vLLM features. Some of those, such as `enable_dbo`, `enable_eplb` are exposed as a top-level config fields. For those that are not, you can configure them by setting `inference.vllm_extra` to the desired value.
```toml
[inference.vllm_extra]
headless=true
```
### Router Replay
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.enable_return_routed_experts = true`.
```toml
[trainer]
enable_router_replay=true# this will also auto-set the inference.enable_return_routed_experts = true
[inference]
enable_return_routed_experts=true
```
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend increasing `orchestrator.*.env.num_workers` to allow for more parallelization on the verifiers side.
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
prime-rl uses [loguru](https://loguru.readthedocs.io/en/stable/) for logging with a global logger pattern. All logs are captured at the deployment level (stdout/stderr redirection for local, `tee` for SLURM) under `{output_dir}/logs/`. For RL training, we recommend streaming logs into tmux panes (as set up by `tmux.sh`).
## Logger Architecture
### `setup_logger` and `get_logger`
We use a **singleton pattern** with a module-level global logger instance (`_LOGGER`).
1.**`get_logger()`** - Returns the global logger instance. Always works — if `setup_logger` hasn't been called yet, it initializes a default logger automatically. Safe to call from any module at any time.
2.**`setup_logger(log_level)`** - Configures (or reconfigures) the global logger:
- Creates an isolated loguru `Logger` instance (not the default `loguru.logger`) to prevent third-party code from hijacking our logs
- Adds a stdout handler with colorized output (or JSON output if `json_logging=True`)
- Can be called multiple times — cleans up the previous logger before creating a new one
3.**`reset_logger()`** - Resets the global logger to `None`:
- Used in subprocesses that inherit parent state (e.g., env workers)
- Used in tests between test cases
## Log File Structure
Logs are captured at the deployment level — the entrypoint redirects subprocess stdout/stderr to files (local) or `tee` captures them (SLURM). The structure is consistent across deployment types: `logs/trainer.log` and `logs/inference.log` always exist, regardless of whether the run is local or multi-node SLURM.
Environment logs live under `logs/envs/train/{env_name}/` and `logs/envs/eval/{env_name}/`. Env log verbosity is controlled by `orchestrator.log.vf_level`.
Only rank 0 output is shown in `trainer.log`. Per-rank logs from all ranks are available under `logs/trainer/torchrun/{rdzv_id}/attempt_0/{rank}/{stdout,stderr}.log`, written by torchrun's `--log-dir`.
## tmux helper (`scripts/tmux.sh`)
`scripts/tmux.sh` sets up a tmux session for RL runs with **four panes**:
While most of our parallelism techniques in prime-rl are designed to scale training up (FSDP, EP, CP, ...), we also provide many tools to scale training down that allow training large MoE models on a limited amount of GPUs.
These techniques target the trainer part of prime-rl.
## TLDR: config to use for maximum memory usage reduction with correct throughput
```toml
[trainer.model]
impl="custom"
attn="flash_attention_2"
fused_lm_head_token_chunk_size=1024
ep=8
cp=2
optim_cpu_offload=true
[trainer.model.compile]
[trainer.model.ac]
freq=1
[trainer.model.ac_offloading]
max_inflight_activations=1
```
## Activation checkpointing
Activation checkpointing discards intermediate activations during the forward pass and recomputes them during the backward pass, trading compute for memory.
To enable it, use:
```toml
[trainer.model.ac]
freq=1
```
`freq` controls how often layers are checkpointed: every `freq` layers. Lower values yield lower memory usage (e.g. `freq = 1` checkpoints every layer).
## Activation offloading
Activation offloading offloads the activations to CPU to reduce the memory usage of the trainer. It can be used in combination with activation checkpointing.
To enable it, use:
```toml
[trainer.model.ac]
freq=1
[trainer.model.ac_offloading]
max_inflight_activations=5
```
## Chunk loss
Chunk loss splits the loss computation into smaller chunks to reduce the memory usage of the trainer.
To enable it, use:
```toml
[trainer.model]
fused_lm_head_token_chunk_size=auto
```
## Expert parallelism
While expert parallelism splits the weights of the experts across all GPUs like FSDP, using EP still reduces memory usage by reducing the communication size and therefore the FSDP buffer.
EP is only available for models with MoE layers using the custom model implementation.
```
[trainer.model]
impl = "custom"
ep = 8
```
## Context parallelism
Context parallelism splits the context into smaller chunks to reduce the memory usage of the activations. We don't advise using CP across multiple nodes (i.e., increasing CP beyond 8).
CP is only available for certain models and only with the custom model implementation.
```
[trainer.model]
impl = "custom"
cp = 2
```
We recommend CP 2 or CP 4 for most 128K sequence length training runs. Can be pushed to 8.
## torch compile
Enabling torch.compile can reduce the memory usage for certain model architectures, especially MoE with the custom model implementation.
```
[trainer.model.compile]
```
## CPU Optimizer offloading
Offloading the optimizer states to CPU can reduce the memory usage of the trainer significantly, especially at low GPU counts where the optimizer states take a lot of memory as they won't be sharded enough.
In RL, in contrast with pretraining, we end up with many gradient accumulation steps, so the cost of offloading the optimizer states is not as high as in pretraining, and indeed barely noticeable.
```
[trainer.optim]
optim_cpu_offload = true
```
## :warning: FSDP CPU offloading
FSDP CPU offloading offloads the parameters, gradients, and optimizer states to CPU to reduce the memory usage of the trainer.
This will make training significantly slower and is not recommended most of the time.
```
[trainer.model]
fsdp_cpu_offload = true
```
## :warning: Lora training
LoRA training significantly reduces the memory usage of the trainer at the cost of smaller gradient updates.
For most runs we recommend logging metrics to [W&B](https://wandb.ai). Before enabling W&B, make sure that you have an account and are logged in.
```bash
uv run wandb login
# Or set `export WANDB_API_KEY=...`
```
### SFT
Logging to W&B is disabled by default. Enable the default configuration with `--wandb`
```bash
uv run sft ... --wandb
```
This will log to the `prime-rl` project with a random run name. You can specify which project and name to log to
```bash
uv run sft ... --wandb.project my-project --wandb.name my-run
```
The same settings also work for multi-node training with `torchrun`. Note, that we only log global metrics from the master rank (e.g. the all-reduced loss)
```bash
uv run torchrun --nproc-per-node 8 ... --wandb
```
### RL
For RL training, both the trainer and orchestrator log to W&B as separate runs. Again, logging to W&B is disabled by default. Enable the default configuration with `--wandb`
```bash
uv run rl ... --wandb
```
This will log to the `prime-rl` project with a random run name. The trainer run is suffixed with `-trainer` and the orchestrator run is suffixed with `-orchestrator`. You can specify which project and name to log to using the same flags as for SFT.
```bash
uv run rl ... --wandb.project my-project --wandb.name my-run
```
For the RL trainer, we support logging samples (e.g. prompt, completion, reward, advantage for selected rollouts) and distributions (e.g. reward, advantage, entropy distributions) as W&B tables using the `wandb.log-extras` subconfig. If W&B is setup, this is enabled by default and will log for the RL trainer and orchestrator every 10 steps.
You can configure this on the trainer and orchestrator separately. For example, to only log samples on the orchestrator every 50 steps, but not distribution on either
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.