* 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
2026-05-28 03:00:20 +02:00
174 changed files with 10588 additions and 9371 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.
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)
@@ -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
@@ -55,10 +56,10 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#vision-language-models) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
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,6 +222,7 @@ 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`.
@@ -9,9 +9,8 @@ Minimal end-to-end configs for the three training modes (`rl` / `opd` / `sft`) a
| `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) |
| `sft_external.toml` | `sft` | PI inference (`openai/gpt-5-mini`) | external OAI endpoint; no local teacher |
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` and `sft_external.toml`) is **not** auto-launched — start it manually on GPU 1.
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
@@ -38,10 +37,6 @@ uv run rl @ configs/debug/training_modes/opd_lora.toml
# SFT hard distill (needs teacher on port 8001)
uv run rl @ configs/debug/training_modes/sft.toml
uv run rl @ configs/debug/training_modes/sft_lora.toml
# SFT hard distill from openai/gpt-5-mini via PI inference
# (requires PRIME_API_KEY + PRIME_TEAM_ID in env; no local teacher needed)
uv run rl @ configs/debug/training_modes/sft_external.toml
```
See [docs/training.md](../../docs/training.md#training-modes-rl--opd--sft-via-orchestrator) for what each mode does.
The custom path enables EP, 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.
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`**: Custom kernels from DeepEP. Faster but requires DeepEP build (`bash scripts/install_deep_gemm.sh`, `bash scripts/install_ep_kernels.sh`) and tuning of `deepep_num_sms` (default 20) and `deepep_token_chunk_size` for your hardware.
- **`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`.
DeepEP intranode dispatch derives the RDMA channel count as `deepep_num_sms / 2`. Lower SM count leaves more for compute; higher speeds up dispatch. Useful starting points: 16–24 SMs on H100, 20–40 on B200.
When you enable DeepEP, gradient clipping is auto-disabled (`optim.max_norm` set to `None`) because the kernels don't currently support it.
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
# freeze_vision_encoder = true # default; set false to fine-tune the encoder
```
A bad attribute path errors immediately — no silent fallbacks. The weight-broadcast key prefix is derived as `{language_model_attr}.layers.` automatically.
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`.
@@ -116,7 +117,7 @@ LoRA pairs naturally with [multi-tenant training](#multi-tenant-training) — ea
## 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/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/src/prime_rl/trainer/runs).
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).
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. Most clusters ship UCX 1.17 via HPC-X, which manifests as `cuStreamCreate: invalid device context` errors during DeepEP internode dispatch. Check with `/opt/hpcx/ucx/bin/ucx_info -v` and, if needed, build from source:
**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:
@@ -136,10 +136,20 @@ The default advantage is per-group reward minus per-group baseline (DR-GRPO with
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, …).
Two built-in**length penalties** can be layered on top of any advantage to discourage rambling:
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:
-`[orchestrator.length_penalty] type = "tokens"` — penalizes long completions in tokens, with configurable target and slope.
-`[orchestrator.length_penalty] type = "turns"` — penalizes long multi-turn rollouts by turn count.
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
@@ -167,6 +177,22 @@ kwargs = { eps = 1e-8 }
`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
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 `token_export` flag) that aren't surfaced here.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
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.
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.
@@ -8,9 +8,9 @@ A `prime-rl` RL run is three cooperating processes:

- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). Supports data + tensor + expert parallelism (with `deepep` and `flashinfer` all-to-all backends and EPLB), FP8 inference, prefill/decode disaggregation behind a `vllm-router`, CPU KV-cache offload, and *router replay* (the routed-expert mask is returned to the trainer for FP8 MoE numerical parity). Weights are pushed in place through a custom `update_weights` endpoint over filesystem or NCCL transports.
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). We are trying to stay up-to-date with the latest vLLM features, you can read more about the supported features and deployment options in the dedicated [inference documentation](inference.md).
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment).
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses the filesystem (or NCCL for synchronous setups). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
@@ -20,7 +20,7 @@ The three processes communicate through configurable transports — by default t
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`research-environments`](https://github.com/PrimeIntellect-ai/research-environments) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, MoE-only installs (DeepGEMM / DeepEP / NIXL), or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`research-environments`](https://github.com/PrimeIntellect-ai/research-environments) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
You need at least one NVIDIA GPU (RTX 3090/4090/5090, A100, H100, H200, or B200). Single-GPU runs are supported for debugging; production RL is typically 1× inference node + 1+ trainer nodes.
@@ -38,6 +38,7 @@ The `rl` entrypoint reads `examples/reverse_text/rl.toml`, splits it into per-pr
This page covers how to scale `prime-rl` from a single GPU to a 1000-GPU cluster: single-node and multi-node deployments, FSDP / expert parallelism / context parallelism, and throughput benchmarking. For knobs that fit on one box, see [Training](training.md) first. For prefill/decode disaggregated inference, see [Advanced](advanced.md#disaggregated-prefilldecode-inference).
This page covers how to scale `prime-rl` from a single GPU to a 1000-GPU cluster: single-node and multi-node deployments, FSDP / expert parallelism / context parallelism, and throughput benchmarking. See [Training](training.md) for detailed documentation of the trainer configuration and [Inference](inference.md) for the inference configuration.
## Table of Contents
@@ -90,7 +90,7 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
### Expert Parallelism
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
```toml
[trainer.model]
@@ -103,14 +103,14 @@ ep_comm_backend = "torch" # or "deepep"
### Context Parallelism
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Only available with the custom impl and flash-attention.
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
```toml
[trainer.model]
impl="custom"
attn="flash_attention_2"# or fa3 / fa4
cp=2# CP degree
cp_style="ring"# "ulysses" for non-FA kernels
cp_style="ulysses"# "ring"
```
### Activation Checkpointing and Offloading
@@ -129,6 +129,13 @@ mode = "selective"
targets=["norm","attn_proj"]# see Reference for the full list per architecture
```
We reccomend also using `ac_offloading` and `ac_offloading.max_inflight_activations = 5` to further reduce the memory footprint in tradeoff for some throughput. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput:
```toml
[trainer.model.ac_offloading]
max_inflight_activations=5
```
### Optimizer Offloading
Offloading optimizer states to CPU is a near-free memory win at low GPU counts:
This example trains `GLM-5.1` with RL on agentic SWE tasks using P/D disaggregation, FP8 inference, and a Mooncake distributed CPU KV store — fronted by the upstream [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy).
**llm-d is the faster way to run GLM-5.** It is the recommended router backend for large GLM-5 runs: its `active-request-scorer` is an in-flight load balancer that spreads requests across ranks immediately, instead of relying on metrics that are scraped on a delay (as the default `vllm-router` does). Combined with prefix-cache affinity for grouped rollouts, this keeps prefill and decode ranks evenly loaded under the bursty request pattern of RL. If you want the simpler default router instead, see the [GLM-5 PD disaggregation example](../glm5_pd_disag/README.md).
## Requirements
You need access to a Slurm cluster with at least **32 nodes** (16 trainer + 16 inference, 8 GPUs each) and a shared filesystem. In this guide we assume the NFS is mounted at `/shared`; you can change it to your own path.
You also need prime-rl cloned on your cluster into the shared filesystem.
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
```bash
bash scripts/install_llmd.sh
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
The SWE environment is configured to use Prime Intellect Sandboxes. You can find more information about the sandboxes [here](https://docs.primeintellect.ai/sandboxes/overview). You will need to create a sandbox account and add the credentials to the `.env` file. Alternatively, you can adapt the code of the environment to use your own sandbox implementation.
## Tweak before launching
This config is tuned for our cluster — a few values **must** be adapted to yours before you run. Search the config for these markers:
- **`output_dir`** (`# FILL IN`) — point it at your shared filesystem.
- **`[slurm] partition`** (`# FILL IN`) — set it to your cluster's Slurm partition.
- **`[inference.kv_cache_offload] device_name`** (`# do it yourself`) — the list of RDMA NICs for Mooncake. Auto-detection is unreliable, so set it by hand from `nvidia-smi topo -m` on your nodes.
A few more knobs you may want to tune for your hardware:
- **Trainer parallelism** — this config assumes **16 trainer nodes** at **131K** sequence length with `cp = 4` (context parallel) and the `adamw` optimizer. If you have fewer trainer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` accordingly.
- **Scorer weights** (`[inference.deployment.router]`) — the `scorers` / `prefill_scorer_overrides` / `decode_scorer_overrides` weights follow the upstream llm-d P/D guide and are a good starting point; tune them if your prefill/decode balance drifts.
- **Mooncake CPU pool** (`[inference.kv_cache_offload.cpu] num_bytes`) — defaults to 1TB/node; lower it if your nodes have less RAM.
## Tmux session
We recommend using the tmux helper to start the run and look at the logs.
scorers={"prefix-cache-scorer"=3.0}# need some prefix-cache routing, however due to shared mooncake pool do low prio
prefill_scorer_overrides={"queue-scorer"=4.0,"active-request-scorer"=5.0}# prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
decode_scorer_overrides={"active-request-scorer"=5.0,"kv-cache-utilization-scorer"=4.0,"queue-scorer"=3.0}# decode doesn't really create queue, it fills in KV cache fast, give 4.0
non_cached_tokens=128# if <128 tokens, skip prefill go to decode immediately
[slurm]
job_name="glm5-llmd"
partition="all"# FILL IN: set to your cluster's partition
[trainer]
dist_timeout_seconds=1800
enable_token_export=true
[trainer.model]
name="zai-org/GLM-5.1"
impl="custom"
attn="flash_attention_2"# ignored with GLM5
fused_lm_head_token_chunk_size=1024
cp=4# context parallel for the 131K seq len
ep=8
optim_cpu_offload=true
fp8=true
[trainer.model.ac]
freq=1
[trainer.model.compile]
[trainer.model.ac_offloading]
max_inflight_activations=1
[trainer.optim]
type="adamw"
lr=1e-6
weight_decay=0.0
[orchestrator]
batch_size=256
rollouts_per_example=16
max_inflight_rollouts=2048
max_off_policy_steps=8# 16/32 can be better, 8 is more CPU stable
@@ -86,9 +86,71 @@ class WeightBroadcastConfig(BaseConfig):
"""Weight broadcast transport."""
classKVCacheOffloadConfig(BaseConfig):
cpu_bytes:int=Field(1_000_000_000,gt=0)
"""CPU bytes available for KV cache offloading per worker."""
classCPUOffloadTier(BaseConfig):
num_bytes:int=Field(...,gt=0)
"""CPU/DRAM offload capacity. For the ``native`` backend this is vLLM's aggregate ``cpu_bytes_to_use`` (scaled across workers internally). For the ``mooncake`` backend this is the per-node store client's DRAM segment (``-global_segment_size``)."""
classDiskOffloadTier(BaseConfig):
path:Path
"""Filesystem root for the disk tier. For ``native`` this is the ``fs_python`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
classBaseKVCacheOffloadConfig(BaseConfig):
cpu:CPUOffloadTier|None=None
"""CPU/DRAM offload tier. Always required — disk-only offload is not supported."""
disk:DiskOffloadTier|None=None
"""Optional disk tier, layered behind the CPU tier (GPU → DRAM → disk)."""
@model_validator(mode="after")
defvalid_tiers(self):
# Both backends support only two shapes: cpu-only or cpu+disk. Native disk
# tiering needs a CPU primary tier; Mooncake standalone-store needs a DRAM
# staging tier. Disk-only is rejected for both.
ifself.cpuisNone:
raiseValueError("inference.kv_cache_offload requires a cpu tier (disk-only offload is not supported).")
"""Mooncake distributed store offloading (SLURM only). One ``mooncake_master`` + metadata server runs on the head inference node; every node runs a ``mooncake_client`` contributing its segment to the single shared pool, so prefixes cached on any node are reusable by all. The cpu tier sizes each node's DRAM segment; the optional disk tier adds an SSD tier."""
device_name:str=""
"""RDMA device name(s) for the store (empty = auto-detect)."""
defto_connector_dict(self)->dict[str,Any]:
# Addresses/sizes/tiers are realized by the per-node store launch in the sbatch
# template (MOONCAKE_CONFIG_PATH JSON); blocks are keyed by model + parallel rank +
# content hash (no instance id), so the shared pool is reused across nodes/replicas.
# Known llm-d EPP scorer plugins (used to guard the ``scorers`` map against typos).
KNOWN_SCORERS=frozenset(
{
"prefix-cache-scorer",
"precise-prefix-cache-scorer",
"queue-scorer",
"kv-cache-utilization-scorer",
"active-request-scorer",
"load-aware-scorer",
"running-requests-size-scorer",
"token-load-scorer",
"latency-scorer",
"session-affinity-scorer",
"lora-affinity-scorer",
}
)
classVllmRouterConfig(BaseConfig):
"""PrimeIntellect vllm-router."""
type:Literal["vllm-router"]="vllm-router"
port:int=8000
"""Port the router listens on — becomes the client-facing router URL."""
policy:str="consistent_hash"
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
classLlmdRouterConfig(BaseConfig):
"""llm-d router backend (EPP + Envoy)."""
type:Literal["llm-d"]="llm-d"
port:int=8000
"""Port the Envoy gateway listens on — becomes the client-facing router URL."""
scorers:dict[str,float]={
"prefix-cache-scorer":3.0,
"active-request-scorer":2.0,
}
"""EPP scorer name → weight, applied to every routing profile (before the per-profile P/D overrides). Defaults to prefix-cache affinity plus in-flight (active-request) load balancing. Unknown scorer names are rejected."""
prefill_scorer_overrides:dict[str,float]={
"queue-scorer":2.0,
"kv-cache-utilization-scorer":2.0,
}
"""P/D only: scorer → weight merged onto ``scorers`` for the prefill profile (a per-profile weight overrides the base)."""
decode_scorer_overrides:dict[str,float]={}
"""P/D only: scorer → weight merged onto ``scorers`` for the decode profile (a per-profile weight overrides the base); empty by default."""
non_cached_tokens:int=16
"""P/D only: requests with fewer than this many non-cached prompt tokens skip remote prefill and run decode-only."""
decode_sidecar_port:int=8300
"""P/D only: port the decode-side llm-d sidecar listens on."""
@property
defprefill_scorers(self)->dict[str,float]:
"""Effective prefill-profile scorers: ``scorers`` merged with ``prefill_scorer_overrides``."""
"""CPU KV cache offload for inference workers. Standard inference uses vLLM's ``OffloadingConnector``. Disaggregated P/D deployments combine it with NIXL through ``MultiConnector`` in the SLURM launcher."""
"""KV cache offload for inference workers, as composable CPU/disk tiers. Discriminated on ``type``: ``native`` (vLLM ``OffloadingConnector``/``TieringOffloadingSpec``, self-contained) or ``mooncake`` (per-node Mooncake distributed store). Disaggregated P/D combines the chosen connector with NIXL through ``MultiConnector``."""
use_pd_kv_transfer:bool=False
"""Auto-set for disaggregated P/D: emit the NIXL transfer connector. Persisted into the per-node config (which drops ``deployment``) so the connector is still built per worker. Not meant to be set by hand."""
enable_return_routed_experts:bool=False
"""Return routed experts in responses. Forwarded as ``--enable-return-routed-experts``."""
enable_fp32_lm_head:bool=False
enable_fp32_lm_head:bool=True
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
vllm_extra:dict[str,Any]={}
@@ -289,8 +437,20 @@ class InferenceConfig(BaseConfig):
@@ -143,24 +142,12 @@ class EvalSamplingConfig(BaseConfig):
returndata
classEnvConfig(BaseConfig):
id:str="reverse-text"
"""Registered verifiers environment ID (e.g. ``math-env``, ``primeintellect/math-env``). May include an ``@version`` suffix for installation."""
classEnvConfig(vf.EnvServerConfig):
name:str|None=None
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the ``id`` without ``@version``. Must be unique across all envs in the same group."""
args:dict={}
"""Keyword arguments forwarded to ``vf.load_environment``. See the environment's docstring for accepted args."""
extra_env_kwargs:dict[str,Any]={}
"""Extra kwargs passed to the env (e.g. ``seq_len``, ``max_total_completion_tokens``). Auto-populated by the orchestrator; user overrides are generally discouraged. The main use case is matching ``extra_env_kwargs`` when running an env in an isolated environment server."""
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
address:str|None=None
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically."""
num_workers:int|Literal["auto"]="auto"
"""Worker processes for the spawned env server. ``auto`` scales to 1 worker per 256 concurrent rollouts. Ignored when ``address`` is set."""
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically. The ``pool`` sizes the spawned server."""
ratio:float|None=Field(None,gt=0)
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
@@ -168,26 +155,36 @@ class EnvConfig(BaseConfig):
max_retries:int=Field(3,ge=0)
"""Times the env server retries a failed rollout before returning an error."""
max_total_completion_tokens:int=-1
"""Maximum total completion tokens across all turns in a multi-turn rollout. ``-1`` disables. Auto-populated into ``extra_env_kwargs``."""
"""Per-rollout wall-clock timeout in seconds. None disables."""
state_columns:list[str]=[]
"""Extra ``State`` fields to persist into the saved rollout records (in addition to the always-saved ``trajectory`` and ``sampling_args``). Values must be JSON-serializable."""
@model_validator(mode="before")
@classmethod
def_migrate_num_workers(cls,data):
"""Back-compat: the removed ``num_workers`` maps onto ``pool`` — an int becomes a
fixed ``static`` pool, ``"auto"`` falls through to the default ``elastic`` pool. An
"""Scale on the linear length penalty. Each reward is reduced by ``coef * pass_rate * (model completion tokens / orchestrator.seq_len)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative."""
gate_by_correctness:bool=False
"""When True, scale each rollout's penalty by its reward (``penalty * reward``), so correct rollouts (``reward == 1``) are penalized and incorrect ones (``reward == 0``) are not. When False, every rollout is penalized equally."""
"""Length penalty applied during advantage computation. Subtracts a ``coef * pass_rate * (completion tokens / orchestrator.seq_len)`` term from each reward (``pass_rate`` = group mean reward) before the baseline subtraction, so solved-often problems get the strongest concision pressure and never-solved groups get none. None disables the penalty."""
length_weighted_baseline:bool=False
"""When True, the GRPO baseline is the token-length-weighted mean reward (``sum(len_i * reward_i) / sum(len_i)``) instead of the plain group mean, centering advantages by per-token expected reward."""
classCustomAdvantageConfig(BaseConfig):
type:Literal["custom"]="custom"
import_path:str
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
"""When resuming the orchestrator from a checkpoint, skip the (potentially redundant) online eval that would otherwise run immediately at the resumed step."""
cancel_inflight_rollouts_on_eval:bool=False
"""Cancel in-flight training rollouts before starting online evals. Avoids congestion (no training + eval rollouts at the same time) at the cost of slower training steps as the pipeline has to refill after each eval."""
classCheckpointConfig(BaseConfig):
interval:int|None=Field(None,ge=1)
@@ -366,81 +396,6 @@ class CheckpointConfig(BaseConfig):
skip_progress:bool=False
"""Skip loading the progress from checkpoint."""
skip_buffer:bool=False
"""Skip loading the buffer from checkpoint."""
classBufferConfig(BaseConfig):
seed:int|None=None
"""Random seed for the buffer. When set, sampling from the buffer is deterministic."""
easy_threshold:float|None=None
"""Average-reward threshold above which a problem is classified ``easy``."""
hard_threshold:float|None=None
"""Average-reward threshold below which a problem is classified ``hard``."""
easy_fraction:float=Field(0.0,ge=0,le=1)
"""Fraction of easy problems to convert to ``normal`` when resuming or starting training. Only problems with difficulty ``normal`` are sampled."""
hard_fraction:float=Field(0.0,ge=0,le=1)
"""Fraction of hard problems to convert to ``normal`` when resuming or starting training. Only problems with difficulty ``normal`` are sampled."""
online_difficulty_filtering:bool=False
"""Filter rollouts based on difficulty. When True, rollouts with average reward 0.0 or 1.0 are not added to the buffer."""
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
classCustomAdvantageConfig(BaseConfig):
type:Literal["custom"]="custom"
import_path:str
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
kwargs:dict[str,Any]=Field(default_factory=dict)
"""Kwargs forwarded to the advantage function."""
AdvantageConfig:TypeAlias=Annotated[
DefaultAdvantageConfig|CustomAdvantageConfig,
Field(discriminator="type"),
]
# Flags rare tokens generated at high entropy (Section 5.2, https://arxiv.org/abs/2510.02387).
classGibberishFilterConfig(BaseConfig):
@@ -538,30 +493,16 @@ class OrchestratorConfig(BaseConfig):
@@ -51,10 +51,10 @@ class RLExperimentalConfig(BaseConfig):
classSharedLogConfig(BaseConfig):
level:str|None=None
"""Log level for trainer and orchestrator. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
"""Log level for trainer, orchestrator, and inference. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
json_logging:bool=False
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.)."""
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.). Propagated to trainer, orchestrator, and inference."""
classSharedWandbConfig(BaseConfig):
@@ -167,6 +167,9 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
"""Shell command to run on the head node after cd, .env sourcing, and venv activation. Useful for cleanup like ``sudo pkill -f vllm``; wrap with ``srun bash -c '...'`` to fan out to all nodes."""
cleanup_grace_period:int=Field(3600,ge=0)
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
@property
deftemplate_vars(self)->dict:
"""Common template variables for all SLURM templates."""
@@ -47,6 +50,7 @@ class SlurmConfig(BaseConfig):
"account":self.account,
"time":self.time,
"pre_run_command":self.pre_run_command,
"cleanup_grace_period":self.cleanup_grace_period,
}
@model_validator(mode="after")
@@ -96,12 +100,6 @@ class ElasticConfig(BaseConfig):
classClientConfig(BaseConfig):
timeout:int=1200
"""Request timeout in seconds."""
connect_timeout:float=30.0
"""TCP connect timeout in seconds for inference API requests."""
wait_for_ready_timeout:int=1800
"""Seconds to wait at startup for the inference pool to become ready. Applies to both the static health check and elastic DNS-based discovery."""
@@ -154,6 +152,9 @@ class LogConfig(BaseConfig):
log_data:bool=False
"""Log the first data sample at startup."""
interval:float=Field(10.0,gt=0)
"""Interval (seconds) for periodic logs across components."""
All ranks: ${LOG_DIR}/trainer/torchrun/*/*/*/*.log
Orchestrator: ${LOG_DIR}/orchestrator.log
Inference: ${LOG_DIR}/inference.log
Envs: ${LOG_DIR}/envs/*/*/*.log
Train envs: ${LOG_DIR}/envs/train/*/*.log
Envs: ${LOG_DIR}/envs/*/*.log
Train envs: ${LOG_DIR}/envs/train/*.log
You are running inside tmux session \"${SESSION_NAME}\". The Launcher window (window 0) is where the user runs launch commands. You can read its contents with: tmux capture-pane -t ${SESSION_NAME}:Launcher -p
@@ -62,10 +62,10 @@ In TOML, an empty section header (`[ckpt]`) does the same.
## RL trainer token exports
For rollout debugging, enable trainer-side token export under`trainer.experimental.token_export` (or `experimental.token_export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
For rollout debugging, enable trainer-side token export with`trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
```toml
[trainer.experimental.token_export]
enable_token_export = true
```
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
@@ -74,5 +74,4 @@ Leave it unset for normal training. When enabled, it exports every sequence from
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
Do **not** run `git submodule update --init --recursive` without paths — it tries to clone the private `configs/private` submodule and aborts for users without access. `scripts/install.sh` walks submodules one at a time and skips failures, so it works for everyone.
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
```
The `envs` extra installs every env workspace listed in`[tool.uv.workspace]`. Adding a new env means adding it to `members`, the `envs` extra, and`[tool.uv.sources]`.
The `envs` extra installs environments listed under `[project.optional-dependencies].envs`, resolved through`[tool.uv.sources]`. Adding a new env means adding its package name to `envs` and its editable source path to`[tool.uv.sources]`.
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
### llm-d router backend
Multi-node / disaggregated deployments can route through the upstream llm-d Endpoint Picker instead of `vllm-router` (set `[...deployment.router] type = "llm-d"`). It needs three native binaries — install once:
```bash
bash scripts/install_llmd.sh # builds epp + pd-sidecar from a pinned llm-d-router commit (vendored Go), fetches envoy
```
Binaries land in `third_party/llmd/bin/{epp,envoy,pd-sidecar}` (a shared path, so SLURM nodes see them). `epp` is pinned to the commit that includes the `vllmhttp-parser` (PR #1248) so prime-rl's renderer/TITO `/inference/v1/generate` path routes correctly. Override the pin with `LLMD_ROUTER_REF=<sha>`. The EPP + Envoy + endpoints configs are rendered from `templates/llmd/*.yaml.j2` (included into the SLURM script); only the per-node IPv4 addresses are filled in inline at launch time.
## Key files
- `pyproject.toml` — dependencies, extras, dependency groups
@@ -71,9 +71,7 @@ After a restart, verify all processes are back up and progress resumed before th
├── inference/
│ ├── node_*.log # per-node (multi-node only)
│ └── router_0.log # vllm-router per replica (multi-node only)
└── envs/{train,eval}/{env_name}/
├── env_server.log
└── env_worker_*.log
└── envs/{train,eval}/{env_name}.log # one log file per env
```
Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough. Drop into per-node or per-rank logs only when debugging. All logs are loguru with `HH:mm:ss LEVEL message`; levels: `DEBUG`, `INFO`, `SUCCESS`, `WARNING`, `ERROR`.
f"Detected busy event loop. Measured {mean_lag:.1f}s (min={min_lag:.1f}s, med={med_lag:.1f}s, p90={p90_lag:.1f}s, p99={p99_lag:.1f}s, max={max_lag:.1f}s) event loop lag over the last {len(last_lags)} measurement(s)"
File diff suppressed because it is too large
Load Diff
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.