Compare commits

...
Author SHA1 Message Date
halleriteandGitHub 62702bafa7 docs(inference): correct stale serving_tokens.py docstrings for vLLM 0.22 (#2878)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 08:10:26 +02:00
35b452b01c chore: bump verifiers + research-environments to main (#2873)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Bump deps/verifiers (b055799f -> 20abcd91) and deps/research-environments
(dbc58e14 -> 0687a15c) to their latest main, and follow the env
deprecations/ports they shipped.

research-environments removed several v0 envs and ported others to v1:
- drop dead v0 env deps (removed upstream): color-codeword,
  mini-swe-agent-plus, opencode-{cp,deepdive,math,science,swe}
- migrate ported envs v0 -> v1: deepdive, gpqa, livecodebench
- migrate the two multimodal color-codeword configs onto the
  color-codeword-v1 taskset (default harness, subprocess runtime)

Also bump the verifiers floor 0.1.15.dev388 -> dev394 to match the new pin
and relock.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 21:36:03 -07:00
halleriteandGitHub 2e29c66fd7 fix(orchestrator): align gibberish/repetition filters to v1 branch streams (#2872)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 06:02:41 +02:00
halleriteandGitHub d3765e289d chore(deps): bump verifiers to 0.1.15.dev388 (#2870)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-24 22:52:46 +02:00
minh hoangandGitHub 9bf203c678 Fix Docker editable package version resolution (#2866)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-24 11:52:10 -07:00
46bcf628f6 chore: remove outdated math configs (#2865)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: remove outdated config dirs

Prune four stale, unused config directories. None are referenced by
docs, skills, CI, or scripts, and each is a one-off experiment or
feature demo whose last substantive edit predates the recent config
sweeps:

- wordle: legacy v0-bridge demo, last real edit 2025-08-30
- deepscaler: old multi-stage experiment (README points at a
  configs/deepscaler/eval.toml that no longer exists)
- glm5_disagg_inference: one-off disaggregated-inference demo
- elastic: alphabet-sort elastic/DNS-discovery demo

All four still parse against the current schema; removal is about
disuse, not breakage.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: remove outdated acereason_math configs

Prune the stale acereason_math experiment configs (stage1/stage2, last
real edit 2025-12-23). They reference the aime24-v1 eval taskset that is
no longer available, so they fail to load against the current schema.

The live nightly run (configs/ci/nightly/acereason_math.toml) is
unaffected; drop its now-dangling comment reference to the deleted dir.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: keep wordle, elastic and glm5_disagg_inference configs

Narrow this PR to only the deepscaler and acereason_math configs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: remove acereason_math from nightly suite

Drop the nightly acereason-math config and its test. The nightly
workflow auto-discovers tests/nightly/test_*.py, so removing the test
file drops it from the matrix.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 20:45:19 -07:00
a3151e3711 chore: repoint v1 tasksets to research-environments (#2864)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(deps): repoint scaleswe/swebench-verified/terminal-bench-2 v1 tasksets to research-environments

The three container-backed v1 SWE tasksets moved out of verifiers into
research-environments. Repoint their [tool.uv.sources] paths and bump both
submodules to match.

- deps/verifiers: drop the three envs
- deps/research-environments: add the three envs + advance to current main
- uv lock

Taskset ids are unchanged, so run configs that reference them by id need no changes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(deps): bump verifiers + research-environments submodules to current heads

Picks up vf#1851 (swebench-verified ensures uv on PATH before scoring), now ported
into the research-environments copy of swebench_verified_v1.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(deps): repoint 6 more v1 tasksets to research-environments

Following their move out of verifiers, repoint math-env-v1, aime24-v1, r2e-gym-v1,
swelego-v1, wikispeedia-v1, and general-agent-v1 from deps/verifiers to
deps/research-environments, and bump both submodules to the updated heads. The
moved envs now pin verifiers>=0.1.15.dev381 (satisfied by the editable verifiers).

- uv lock

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(deps): bump research-environments (drop moved eval configs + scaleswe fix)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(deps): swap v0 aime for v1 tasksets + reference tau2-bench-v1

Following the aime/wikispeedia v0->v1 replacement in research-environments:
- drop aime2024, aime2025 (v0); reference aime24-v1, aime25-v1, aime26-v1
- add tau2-bench-v1
- bump deps/research-environments + uv lock

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(deps): repin verifiers + research-environments to merged main

verifiers#1853 (remove the moved v1 tasksets) and research-environments#527 (add them)
have merged; repin both submodules to the merged main commits. uv.lock unchanged
(already consistent — `uv lock --check` passes).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(configs): point aime eval envs at the v1 tasksets

The v0 aime2024/aime2025 packages were dropped from the `envs` extra + sources, so
`uv sync --extra envs` no longer registers them and eval sections using the legacy
ids fail at runtime. Switch those eval entries to the v1 tasksets (aime24-v1 /
aime25-v1; default `subprocess` harness), keeping the display names for metric
continuity.

- configs/acereason_math/{stage1,stage2}.toml
- configs/debug/hendrycks_sanity/rl.toml
- configs/math_group/rl.toml

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 20:33:26 -07:00
c33020a3d4 chore: bump activation-offload memory warn threshold to 90% (#2861)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The CPU RAM usage warning in the activation offloader fired at 60%
virtual memory used, which is noisy on healthy runs. Bump the threshold
to 90% so it only warns when memory is genuinely close to exhaustion.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 18:10:19 -07:00
7089ba1e4d feat: vf v1 <> nano bridge (#2742)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-06-23 18:04:57 -07:00
38494ccb41 fix: sync uv.lock to v0.6.0 (#2858)
Tag and Release / auto-tag-on-main (push) Canceled after 0s
Tag and Release / release-from-auto-tag (push) Canceled after 0s
Tag and Release / tag-and-release (push) Canceled after 0s
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
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>
2026-06-22 18:52:13 -07:00
375d8596d8 chore: release v0.6.0 (#2855)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:00:59 -07:00
e035135126 feat: llm-d (EPP+Envoy) router backend (#2697)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-06-22 16:08:07 -07:00
533e992ad2 fix(inference): tolerate KV-transfer finish for already-freed (aborted) reqs (#2843)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-06-22 16:05:22 -07:00
858207d340 add glm 5.2 training support (#2851)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* 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>
2026-06-22 15:33:01 -07:00
minh hoangandGitHub 570463cca2 chore(renderers): bump to submodule to renderers-v0.1.8.dev49 (#2852)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-22 12:28:27 -07:00
JannikStandGitHub 31e81e5b18 feat: support PRIME_RL_REF for runtime source override (#2850)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* 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
2026-06-22 12:15:37 -07:00
samsjaandGitHub 137f8f49c8 [codex] trim orchestrator memory after train steps (#2837)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(orchestrator): trim process memory each train step

* fix(orchestrator): collect garbage before memory trim
2026-06-22 12:13:26 -07:00
Maxwill LinandGitHub f04c8d988c fix(vlm): dispatch Gemma 4 as a VLM and read softcapping from the text config (#2844)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-22 02:23:13 +02:00
4d361adacc fix(orchestrator): drain off-policy rollouts before pausing for weight update (#2841)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
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>
2026-06-19 20:04:08 -07:00
faresobeidandGitHub 7f77713886 update length penalty and add back length weighted baseline (#2702)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-19 02:09:32 +02:00
samsjaandGitHub efeddae6bb add rlm uuid ctf env (#2832)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-18 16:00:38 -07:00
114 changed files with 3712 additions and 5412 deletions
+4 -1
View File
@@ -77,8 +77,11 @@ jobs:
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
from prime_rl.utils.validation import validate_shared_ckpt_config
# `verifiers` (+ its `datasets` dep) is a declared slim dep: the v1 config types
# (EnvConfig, Task, ...) extend verifiers.v1, which is pure-pydantic and pulls no
# GPU/ML deps. We still forbid the actual heavy training deps below.
forbidden = ["torch", "transformers", "vllm", "wandb", "ring_flash_attn",
"verifiers", "prime", "datasets", "liger_kernel", "loguru"]
"prime", "liger_kernel", "loguru"]
leaked = [m for m in forbidden if m in sys.modules]
if leaked:
raise SystemExit(f"slim install leaked heavy deps into sys.modules: {leaked}")
+7
View File
@@ -2,6 +2,13 @@
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.
+18
View File
@@ -77,8 +77,25 @@ COPY deps/ /app/deps/
COPY configs /app/configs
COPY examples /app/examples
COPY benchmarks/scripts /app/benchmarks/scripts
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
# Use submodule git metadata from the build context when present. Docker copies
# only the submodule .git pointer files into /app/deps, so we temporarily link
# /app/.git/modules to the read-only context before resolving versions.
ARG VERIFIERS_PRETEND_VERSION
ARG RENDERERS_PRETEND_VERSION
RUN --mount=type=cache,target=/app/.cache/uv \
--mount=type=bind,source=.,target=/build-context,readonly \
if [ -d /build-context/.git/modules ]; then mkdir -p /app/.git && ln -s /build-context/.git/modules /app/.git/modules; fi \
&& \
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
&& \
if [ -L /app/.git/modules ]; then rm /app/.git/modules && rmdir /app/.git 2>/dev/null || true; fi \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" /app/deps/verifiers/pyproject.toml \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress --group mamba-ssm --locked --no-dev
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
@@ -97,6 +114,7 @@ RUN apt-get update && apt-get install -y \
tmux \
iperf \
openssh-server \
git \
git-lfs \
gpg \
sudo \
+2
View File
@@ -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
@@ -221,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`.
## Docs
-53
View File
@@ -1,53 +0,0 @@
max_steps = 500
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[ckpt]
interval = 100
[wandb]
project = "acereason-math"
name = "stage1"
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 8192
[[orchestrator.train.env]]
id = "math-env"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
id = "math500"
group_size = 1
[[orchestrator.eval.env]]
id = "aime2024"
group_size = 32
[[orchestrator.eval.env]]
id = "aime2025"
group_size = 32
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-54
View File
@@ -1,54 +0,0 @@
max_steps = 1000
seq_len = 16384
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[ckpt]
interval = 100
resume_step = 500
[wandb]
project = "acereason-math"
name = "stage2"
[orchestrator]
batch_size = 2048
group_size = 16
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 16384
[[orchestrator.train.env]]
id = "math-env"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
id = "math500"
group_size = 1
[[orchestrator.eval.env]]
id = "aime2024"
group_size = 32
[[orchestrator.eval.env]]
id = "aime2025"
group_size = 32
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
@@ -19,6 +19,10 @@ training_mode = "sft"
batch_size = 128
group_size = 16
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
-36
View File
@@ -1,36 +0,0 @@
# Run on 8xH200
# Similar to configs/acereason_math/stage1.toml, but
# - 300 instead of 500 steps
# - No checkpointing
# - No evals
max_steps = 300
seq_len = 8192
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 8192
[[orchestrator.train.env]]
id = "math-env"
name = "acereason-math"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
[trainer]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
@@ -21,8 +21,9 @@ group_size = 16
max_completion_tokens = 64
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
name = "color-codeword"
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
harness = { id = "default", runtime = { type = "subprocess" } }
[trainer]
+1 -1
View File
@@ -22,8 +22,8 @@ name = "hendrycks-math"
interval = 50
[[orchestrator.eval.env]]
id = "aime2024"
name = "aime2024"
taskset = { id = "aime24-v1" }
group_size = 16
[trainer.model.ac]
+3 -2
View File
@@ -40,8 +40,9 @@ enforce = false
max_completion_tokens = 64
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
name = "color-codeword"
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
harness = { id = "default", runtime = { type = "subprocess" } }
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
# MODEL_RENDERER_MAP to Qwen3VLRenderer at runtime; no explicit name needed.
-31
View File
@@ -1,31 +0,0 @@
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text"
name = "reverse-text-v1"
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
args = { v1 = true }
[trainer.optim]
lr = 3e-6
[ckpt] # Checkpoint at the end of training
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
+1 -6
View File
@@ -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.
+4
View File
@@ -20,6 +20,10 @@ training_mode = "sft"
batch_size = 128
group_size = 4
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -1,55 +0,0 @@
# SFT from openai/gpt-5-mini via PI inference.
# Requires PRIME_API_KEY + PRIME_TEAM_ID in the environment.
#
# Run with:
# uv run rl @ configs/debug/training_modes/sft_external.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-sft-external"
[orchestrator]
training_mode = "sft"
batch_size = 128
group_size = 4
[orchestrator.train.sampling]
max_completion_tokens = 2048
extra_body = { reasoning_effort = "minimal" }
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "openai/gpt-5-mini"
[orchestrator.teacher.client]
base_url = ["https://api.pinference.ai/api/v1"]
api_key_var = "PRIME_API_KEY"
[orchestrator.teacher.client.headers_from_env]
X-Prime-Team-ID = "PRIME_TEAM_ID"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -20,6 +20,10 @@ training_mode = "sft"
batch_size = 128
group_size = 4
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
+42
View File
@@ -0,0 +1,42 @@
# v1 port of examples/alphabet_sort/rl.toml — identical except the env block, which loads
# the v1 `alphabet-sort-v1` taskset (multi-turn via a colocated vf.User) instead of the v0
# `primeintellect/alphabet-sort` env. Harness runs on the subprocess runtime.
max_steps = 200
seq_len = 2048
[ckpt] # Checkpoint at the end of training
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
project = "alphabet-sort"
name = "alphabet-sort"
[trainer.model]
impl = "auto"
[trainer.model.ac]
freq = 1
[trainer.model.lora]
rank = 32
alpha = 64
[trainer.optim]
lr = 1e-5
[orchestrator]
batch_size = 512
group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 768
[[orchestrator.train.env]]
name = "alphabet-sort"
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, power_per_turn = false }
harness = { id = "default", runtime = { type = "subprocess" } }
[inference] # Default inference config
+55
View File
@@ -0,0 +1,55 @@
# Debug v1 RL run: the v1 `general-agent-v1` taskset (GeneralAgentSolverTaskset) driven by the
# default harness, with the agent and its tool server colocated in a modal sandbox. Copied from
# configs/general_agent/rl_qwen3_4b.toml and rewired for v1 (taskset + harness + renderer; the
# v0 `id = "general-agent-solver-rlm"` env becomes the v1 taskset + a separate harness).
max_steps = 200
seq_len = 32768
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "general-agent-debug"
name = "qwen3-4b-v1"
[ckpt]
interval = 100
keep_last = 1
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[trainer]
[trainer.model]
cp = 2
[trainer.model.ac]
freq = 1
[trainer.model.compile]
[orchestrator]
training_mode = "rl"
batch_size = 256
rollouts_per_example = 8
max_off_policy_steps = 32
[orchestrator.renderer]
name = "qwen3"
[[orchestrator.train.env]]
# v1 general-agent solver taskset; the tool server is colocated in the harness's modal sandbox.
taskset = { id = "general-agent-v1", tools = { colocated = true } }
harness = { id = "default", runtime = { type = "modal" } }
[inference]
gpu_memory_utilization = 0.85
[inference.model]
max_model_len = 32768
[inference.parallel]
dp = 4
+42
View File
@@ -0,0 +1,42 @@
# GSM8K (v1) — the v1 port of configs/gsm8k/rl.toml. Trains Qwen3-0.6B on GSM8K through the
# v1 env server: the orchestrator spawns a v1 EnvServer for the gsm8k-v1 taskset and trains on
# the returned Traces. Runs on 2 GPUs (1 inference, 1 training):
# uv run inference --model.name PrimeIntellect/Qwen3-0.6B # Inference pane (GPU 0)
# uv run rl @ configs/debug/v1/gsm8k.toml --ckpt # Trainer pane (GPU 1)
max_steps = 100
seq_len = 2048
[wandb]
project = "gsm8k-debug"
name = "gsm8k-v1"
[model]
name = "Qwen/Qwen3-0.6B"
[orchestrator]
training_mode = "rl"
batch_size = 512
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 2048
[[orchestrator.train.env]]
taskset = { id = "gsm8k-v1", split = "train" }
harness = { id = "default", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 20
num_examples = 256
[orchestrator.eval.sampling]
max_completion_tokens = 2048
[[orchestrator.eval.env]]
taskset = { id = "gsm8k-v1", split = "test" }
harness = { id = "default", runtime = { type = "subprocess" } }
[trainer] # Default trainer config
[inference] # Default inference config
+55
View File
@@ -0,0 +1,55 @@
# v1 analog of examples/hendrycks_sanity/rl.toml — identical config with only
# the env sections swapped to v1 taskset/harness syntax (math-env taskset,
# default harness, modal runtime). Submits to slurm by default; pass --no-slurm
# to run locally.
output_dir = "/beegfs/mika/hendrycks-sanity-v1"
max_steps = 200
[wandb]
project = "hendrycks-sanity"
name = "v1"
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[slurm]
job_name = "hendrycks-modal"
partition = "all"
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
group_size = 8
seq_len = 8192
max_inflight_rollouts = 256
[[orchestrator.train.env]]
name = "hendrycks-math"
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
harness = { id = "default", runtime = { type = "modal" } }
timeout = { scoring = 300 }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
name = "aime2024"
taskset = { id = "aime24-v1" }
harness = { id = "default", runtime = { type = "modal" } }
timeout = { scoring = 300 }
group_size = 32
[trainer.model]
seq_len = 16384
[inference.model]
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+86
View File
@@ -0,0 +1,86 @@
# v1 port of configs/rlm_swe/qwen35_4b.toml — identical except the env blocks, which load
# the v1 `r2e-gym-v1` taskset through the rlm harness on the prime runtime instead of the
# v0 `rlm_swe` composable env. Same model / trainer / inference / orchestrator knobs.
output_dir = "/beegfs/mika/rlm-swe-qwen35-4b"
max_steps = 400
seq_len = 65536
[slurm]
job_name = "rlm-swe-qwen35-4b"
project_dir = "."
pre_run_command = "prime sandbox delete --label rlm-swe-qwen35-4b -y --plain || true"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
num_infer_replicas = 2
[wandb]
project = "rlm-swe-debug"
name = "qwen35-4b"
[weight_broadcast]
type = "nccl"
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[model]
name = "Qwen/Qwen3.5-4B"
# --- Trainer ---
[trainer]
[trainer.model]
cp = 4
cp_style = "ulysses"
[trainer.model.ac]
freq = 1
[trainer.model.compile]
# --- Orchestrator ---
[orchestrator]
batch_size = 256
group_size = 8
max_inflight_rollouts = 512
max_off_policy_steps = 16
# Thinking enabled for the Qwen3.5 renderer.
[orchestrator.renderer]
name = "qwen3.5"
enable_thinking = true
[orchestrator.train.sampling]
temperature = 1.0
[[orchestrator.train.env]]
name = "rlm-swe-r2e"
taskset = { id = "r2e-gym-v1" }
harness = { id = "rlm", runtime = { type = "prime", labels = ["rlm-swe-qwen35-4b"] } }
[orchestrator.prime_monitor]
# --- Inference ---
[inference]
gpu_memory_utilization = 0.85
enable_prefix_caching = true
[inference.model]
max_model_len = 65536
[inference.parallel]
dp = 8
# Qwen3.5-4B is a VL model; skip the vision tower for text-only SWE.
# `language_model_only` is a vLLM MultiModalConfig arg (no prime-rl field) → pass via vllm_extra.
[inference.vllm_extra]
language_model_only = true
+42
View File
@@ -0,0 +1,42 @@
# Debug RL run on the v1 env server (reverse-text starter).
# The orchestrator spawns a v1 EnvServer per env (it never loads the env
# itself), dispatches rollouts by task index, and trains on the returned Traces
# (renderer-tokenized). Light settings for a quick end-to-end smoke.
max_steps = 20
seq_len = 2048
[wandb]
project = "reverse-text"
name = "v1"
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
training_mode = "rl"
batch_size = 128
group_size = 16
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
taskset = { id = "reverse-text-v1" }
# reverse-text is a pure-text single-turn env: disable the bash tool (the model answers
# directly) and use the subprocess runtime (no docker).
harness = { id = "default", runtime = { type = "subprocess" } }
# No eval block, mirroring examples/reverse_text/rl.toml — this is a train-only
# smoke. Add an [orchestrator.eval] block (with an interval) to exercise eval.
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
+118
View File
@@ -0,0 +1,118 @@
# v1 RL run: Qwen3.6-35B-A3B (MoE) on the v1 `scaleswe-v1` SWE taskset, rlm harness on a prime
# sandbox runtime. Each scaleswe row ships its own Docker image (NEEDS_CONTAINER) which the
# Environment injects into the prime sandbox; the agent edits the repo + runs tests there (no MCP
# toolset). Router replay is enabled: trainer.enable_router_replay replays the routed-expert
# decisions returned by inference (enable_return_routed_experts).
#
# Built from configs/debug/v1/r2e_gym.toml (the v1 SWE structure) + the MoE parallelism from
# configs/general_agent/rl_qwen3_30b_a3b.toml. The deployment/parallelism is a starting point off
# the 30B-A3B reference — confirm/adjust for your cluster and the 35B / 65k-context footprint.
max_steps = 400
seq_len = 65536
[slurm]
job_name = "scaleswe-qwen36-35b-a3b-rlm"
project_dir = "."
partition = "all"
# Clean up this run's orphaned prime sandboxes before launch (label == SLURM job name).
pre_run_command = 'timeout 120 prime sandbox delete --label "$SLURM_JOB_NAME" -y || true'
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 2
[wandb]
project = "scaleswe-debug"
name = "qwen36-35b-a3b-rlm"
[weight_broadcast]
type = "nccl"
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[model]
name = "Qwen/Qwen3.6-35B-A3B"
# --- Trainer ---
[trainer]
# NCCL collective watchdog timeout — raised from default 600s: scaleswe's slow
# multi-node startup (step-0 swebench eval + slow first SWE batch) was tripping the
# 600s _ALLGATHER_BASE watchdog → SIGABRT trainer crash.
dist_timeout_seconds = 3600
# Replay the routed-expert decisions returned by inference (enable_return_routed_experts)
# so the trainer's MoE routing matches the rollout's — cuts trainer/inference mismatch on A3B.
enable_router_replay = true
[trainer.model]
cp = 2
# Qwen3.6 is a hybrid/linear-attention model — ring CP is unsupported; ulysses
# all-to-all on Q/K/V works with the non-softmax kernels.
cp_style = "ulysses"
# Chunk the LM head over tokens to avoid materializing the full [seq, vocab] logits
# (65k seq × large vocab) — big activation-memory saver. 1024 matches the SWE configs.
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
freq = 1
[trainer.model.compile]
# --- Orchestrator ---
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 16
[orchestrator.renderer]
name = "qwen3.6"
enable_thinking = true
[orchestrator.train.sampling]
temperature = 1.0
[[orchestrator.train.env]]
name = "scaleswe"
# v1 scaleswe SWE taskset; rlm harness in a prime sandbox using the row's injected Docker image.
taskset = { id = "scaleswe-v1" }
harness = { id = "rlm", runtime = { type = "prime", labels = ["scaleswe-qwen36-35b-a3b-rlm"] } }
[orchestrator.prime_monitor]
# --- Eval: SWE-Bench Verified (first 100 tasks) every 20 steps, rlm harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
name = "swebench-verified"
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
harness = { id = "rlm", runtime = { type = "prime", labels = ["scaleswe-qwen36-35b-a3b-rlm"] } }
num_examples = 100
group_size = 1
timeout = { rollout = 3600 }
# --- Inference ---
[inference]
gpu_memory_utilization = 0.85
enable_prefix_caching = true
# Return per-token routed-expert decisions to the trainer for router replay
# (pairs with trainer.enable_router_replay).
enable_return_routed_experts = true
[inference.model]
max_model_len = 65536
# Qwen3.6 is not matched by the auto tool-parser resolver; set explicitly so vLLM
# enables auto tool choice (the scaleswe SWE agent sends tool_choice="auto").
tool_call_parser = "qwen3_coder"
[inference.parallel]
dp = 2
tp = 4
-167
View File
@@ -1,167 +0,0 @@
# DeepScaler
This is a reproduction of the [DeepScaleR](https://pretty-radio-b75.notion.site/DeepScaleR-Surpassing-O1-Preview-with-a-1-5B-Model-by-Scaling-RL-19681902c1468005bed8ca303013a4e2) experiments. They use RL to train from `Deepseek-R1-Distill-Qwen-1.5B` to 43.1% on AIME2024, surpassing OpenAI’s o1-preview with just 1.5B parameters.
## Setup
Install the environment using the `prime` CLI.
```bash
prime env install primeintellect/deepscaler
```
Verify that the environment is installed correctly.
```bash
uv run python -c "import deepscaler"
```
## Training
A key insight from the paper is that they train in **stages of increasing context length**. In stages 1, 2 and 3, they train with context lengths of 8192, 16384 and 24576 tokens, respectively. We match their training setup here.
### Stage 1
```bash
bash scripts/tmux.sh -s stage1 -o outputs/stage1
```
```bash
# Run this in the `Trainer` pane
uv run rl @ configs/deepscaler/stage1.toml \
--output-dir outputs/stage1
```
### Stage 2
```bash
bash scripts/tmux.sh -s stage2 -o outputs/stage2
```
```bash
mkdir -p outputs/stage2/checkpoints
ln -s outputs/stage1/checkpoints/step_500 outputs/stage2/checkpoints/step_500
mkdir -p outputs/stage2/weights
ln -s outputs/stage1/weights/step_500 outputs/stage2/weights/step_500
```
```bash
# Run this in the `Trainer` pane
uv run rl @ configs/deepscaler/stage2.toml \
--output-dir outputs/stage2
```
### Stage 3
```bash
bash scripts/tmux.sh -s stage3 -o outputs/stage3
```
```bash
mkdir -p outputs/stage3/checkpoints
ln -s outputs/stage2/checkpoints/step_1000 outputs/stage3/checkpoints/step_1000
mkdir -p outputs/stage3/weights
ln -s outputs/stage2/weights/step_1000 outputs/stage3/weights/step_1000
```
```bash
# Run this in the `Trainer` pane
uv run rl @ configs/deepscaler/stage3.toml \
--output-dir outputs/stage3
```
## Evals
They evaluate on a series of math benchmarks, including Math500, AIME24, AMC23, Minerva Math and Olympiad Math. We will focus on `math500` and `aime2024` for the reproduction, as these are already implemented as evaluation environments on the Environment Hub and also the most prominent benchmarks. We uploaded the weight checkpoints to HF as `DeepSeek-R1-Distill-Qwen-1.5B-DeepScaleR-XXX` and evaluate the base model and each checkpoint.
![Evals](eval.png)
| Model | AIME 2024 | MATH 500 |
|-------|-----------|----------|
| DeepSeek-R1-Distill-Qwen-1.5B | 27.3% (16389±10200) | 81.4% (5450±7327) |
| DeepScaleR-100 | 30.8% (14510±9591) | 83.4% (4694±6311) |
| DeepScaleR-200 | 28.3% (11929±8630) | 83.2% (3610±4774) |
| DeepScaleR-300 | 30.6% (9898±7050) | 84.2% (3270±4027) |
| DeepScaleR-400 | 30.6% (9726±7077) | 83.6% (3283±4024) |
| DeepScaleR-500 | 33.1% (9686±6563) | 84.0% (3081±3438) |
| DeepScaleR-600 | 32.7% (9726±6222) | 86.6% (3205±3167) |
| DeepScaleR-700 | 32.5% (10162±5887) | 87.8% (3569±3953) |
| DeepScaleR-800 | 33.8% (10666±6032) | 85.4% (3835±3727) |
| DeepScaleR-900 | 28.3% (13375±6546) | 80.8% (5480±5887) |
| O1-Preview | 40.0% (N/A) | 81.4% (N/A) |
Start the inference server
```bash
bash scripts/tmux.sh
```
```bash
# Run this in the `Inference` pane
uv run inference --model.name ... --max-model-len 32768
```
*Note: The model checkpoints are uploaded to `mikasenghaas/DeepSeek-R1-Distill-Qwen-1.5B-DeepScaleR-XXX`.*
```bash
uv run eval @ configs/deepscaler/eval.toml --model.name ...
```
<details>
<summary>Raw results</summary>
<pre><code>
Base Model
Evaluated math500 in 1547.25s (Avg@1=0.8140, Pass@1: 0.8140, Completion Length: 5450.29 (±7327.93, ∈[266.00, 32734.00]), Truncated: 3.8%)
Evaluated aime2024 in 1546.06s (Avg@16=0.2729, Pass@8: 0.6130, Completion Length: 16389.57 (±10200.73, ∈[1643.00, 32699.00]), Truncated: 15.2%)
Step 100 (Stage 1)
Evaluated math500 in 1280.38s (Avg@1=0.8340, Pass@1: 0.8340, Completion Length: 4694.13 (±6311.37, ∈[225.00, 32729.00]), Truncated: 2.2%)
Evaluated aime2024 in 1279.09s (Avg@16=0.3083, Pass@8: 0.6363, Completion Length: 14510.24 (±9591.44, ∈[1606.00, 32696.00]), Truncated: 10.4%)
Step 200 (Stage 1)
Evaluated math500 in 942.63s (Avg@1=0.8320, Pass@1: 0.8320, Completion Length: 3610.20 (±4774.83, ∈[404.00, 32649.00]), Truncated: 0.8%)
Evaluated aime2024 in 942.34s (Avg@16=0.2833, Pass@8: 0.6043, Completion Length: 11929.71 (±8630.59, ∈[1770.00, 32701.00]), Truncated: 6.7%)
Step 300 (Stage 1)
Evaluated math500 in 737.77s (Avg@1=0.8420, Pass@1: 0.8420, Completion Length: 3270.25 (±4027.97, ∈[415.00, 32732.00]), Truncated: 0.4%)
Evaluated aime2024 in 736.54s (Avg@16=0.3063, Pass@8: 0.6350, Completion Length: 9898.05 (±7050.03, ∈[1606.00, 32696.00]), Truncated: 3.5%)
Step 400 (Stage 1)
Evaluated math500 in 727.78s (Avg@1=0.8360, Pass@1: 0.8360, Completion Length: 3283.45 (±4024.46, ∈[282.00, 32721.00]), Truncated: 0.4%)
Evaluated aime2024 in 726.83s (Avg@16=0.3063, Pass@8: 0.6567, Completion Length: 9726.12 (±7077.99, ∈[1266.00, 32686.00]), Truncated: 3.3%)
Step 500 (Stage 1)
Evaluated math500 in 660.66s (Avg@1=0.8540, Pass@1: 0.8540, Completion Length: 2961.01 (±3426.75, ∈[543.00, 32695.00]), Truncated: 0.6%)
Evaluated aime2024 in 658.95s (Avg@16=0.3000, Pass@8: 0.6460, Completion Length: 9121.69 (±6423.23, ∈[1323.00, 32687.00]), Truncated: 3.1%)
Step 500 (Stage 2)
Evaluated math500 in 370.32s (Avg@1=0.8400, Pass@1: 0.8400, Completion Length: 3081.88 (±3438.49, ∈[614.00, 32709.00]), Truncated: 0.4%)
Evaluated aime2024 in 368.68s (Avg@16=0.3312, Pass@8: 0.6287, Completion Length: 9686.62 (±6563.93, ∈[1140.00, 32686.00]), Truncated: 2.5%)
Step 600 (Stage 2)
Evaluated math500 in 334.98s (Avg@1=0.8660, Pass@1: 0.8660, Completion Length: 3205.39 (±3167.25, ∈[554.00, 22164.00]), Truncated: 0.0%)
Evaluated aime2024 in 354.83s (Avg@16=0.3271, Pass@8: 0.6353, Completion Length: 9726.84 (±6222.77, ∈[1162.00, 32683.00]), Truncated: 1.9%)
Step 700 (Stage 2)
Evaluated math500 in 377.43s (Avg@1=0.8780, Pass@1: 0.8780, Completion Length: 3569.39 (±3953.57, ∈[618.00, 32611.00]), Truncated: 0.4%)
Evaluated aime2024 in 375.57s (Avg@16=0.3250, Pass@8: 0.6550, Completion Length: 10162.39 (±5887.47, ∈[1428.00, 32672.00]), Truncated: 1.5%)
Step 800 (Stage 2)
Evaluated math500 in 400.01s (Avg@1=0.8540, Pass@1: 0.8540, Completion Length: 3835.00 (±3727.86, ∈[563.00, 23701.00]), Truncated: 0.0%)
Evaluated aime2024 in 398.19s (Avg@16=0.3375, Pass@8: 0.6860, Completion Length: 10666.42 (±6032.30, ∈[1898.00, 32686.00]), Truncated: 1.0%)
Step 850 (Stage 2)
Evaluated math500 in 445.40s (Avg@1=0.8640, Pass@1: 0.8640, Completion Length: 4216.45 (±4022.84, ∈[611.00, 23277.00]), Truncated: 0.0%)
Evaluated aime2024 in 446.29s (Avg@16=0.3250, Pass@8: 0.6350, Completion Length: 11313.77 (±5997.51, ∈[1695.00, 32686.00]), Truncated: 1.9%)
Step 900 (Stage 2)
Evaluated math500 in 564.56s (Avg@1=0.8080, Pass@1: 0.8080, Completion Length: 5480.47 (±5887.06, ∈[662.00, 32729.00]), Truncated: 1.8%)
SUCCESS Evaluated aime2024 in 562.67s (Avg@16=0.2833, Pass@8: 0.6003, Completion Length: 13375.38 (±6546.80, ∈[1706.00, 32687.00]), Truncated: 4.0%)
Step 950 (Stage 3)
Evaluated math500 in 755.59s (Avg@1=0.7200, Pass@1: 0.7200, Completion Length: 8146.41 (±7986.20, ∈[748.00, 32736.00]), Truncated: 4.6%)
Evaluated aime2024 in 751.49s (Avg@16=0.1833, Pass@8: 0.4207, Completion Length: 16031.10 (±6904.70, ∈[2366.00, 32699.00]), Truncated: 4.8%)
</code>
</pre>
</details>
<br/>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

-39
View File
@@ -1,39 +0,0 @@
max_steps = 500
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[wandb]
project = "deepscaler"
name = "stage1"
[ckpt]
interval = 100
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 8192
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-40
View File
@@ -1,40 +0,0 @@
max_steps = 1000
seq_len = 16384
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[wandb]
project = "deepscaler"
name = "stage2"
[ckpt]
interval = 100
resume_step = 500
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 16384
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-40
View File
@@ -1,40 +0,0 @@
max_steps = 1500
seq_len = 24576
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[wandb]
project = "deepscaler"
name = "stage3"
[ckpt]
interval = 100
resume_step = 1000
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 24576
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+1 -1
View File
@@ -27,8 +27,8 @@ ratio = 0.5
interval = 50
[[orchestrator.eval.env]]
id = "aime2024"
name = "aime2024"
taskset = { id = "aime24-v1" }
num_examples = 30
group_size = 4
+1 -3
View File
@@ -60,7 +60,6 @@ temperature = 1.0
[[orchestrator.train.env]]
id = "rlm_swe"
name = "rlm-swe-r2e"
num_workers = 4
[orchestrator.train.env.args]
labels = ["rlm-swe-qwen35-4b"]
@@ -73,8 +72,7 @@ interval = 20
[[orchestrator.eval.env]]
id = "rlm_swe"
name = "rlm-swe-swebench-verified-quick"
num_workers = 4
timeout = 3600
timeout = { rollout = 3600 }
[orchestrator.eval.env.args]
task_type = "swebench"
+41
View File
@@ -0,0 +1,41 @@
# Wordle (classic v0 TextArena env) on 2 GPUs (1 trainer + 1 inference), run via the
# legacy bridge. The Wordle-SFT model plays a full ~6-turn game per rollout; the bridge
# serves each multi-turn rollout to the orchestrator as a vf.Trace.
max_steps = 200
seq_len = 8192
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[wandb]
project = "wordle"
name = "wordle"
[ckpt] # Checkpoint at the end of training
[model]
name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 128
group_size = 8
[[orchestrator.train.env]]
id = "primeintellect/wordle"
name = "wordle"
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer] # Default trainer config
[inference] # single inference GPU (no data parallelism)
# Qwen3 finetune with the standard PI template patch (byte-identical to
# PrimeIntellect/Qwen3-0.6B base); always re-emits prior <think> blocks.
# Match that with the qwen3 renderer's preserve_all_thinking.
[orchestrator.renderer]
name = "qwen3"
preserve_all_thinking = true
+1 -1
+1 -1
+3 -1
View File
@@ -25,7 +25,7 @@ impl = "custom" # or "hf" to force the HF path
| Family | HF config types | EP | CP |
|---|---|---|---|
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | ✅ | ✅ |
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
@@ -38,6 +38,8 @@ impl = "custom" # or "hf" to force the HF path
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:
+13 -3
View File
@@ -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.
```toml
[orchestrator.advantage.length_penalty]
coef = 0.25 # effective penalty is coef * pass_rate * (completion_tokens / seq_len)
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
+17 -4
View File
@@ -30,7 +30,7 @@ We support 3 distinct deployment shapes:
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`, `router_port`, `backend_port`, etc.
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]
@@ -102,7 +102,7 @@ tp = 2
dp = 4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing will be handled by the `vllm-router` instance running on the same node as the 1st replica. We aim to support more advanced routing options, such as `llm-d` or `dynamo` in the future. You can read more about the supported routing options in the [router](#router) section.
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
@@ -167,9 +167,22 @@ This will run 3 inference replicas, each running on 6 nodes. Each replica will r
## Router
We use our own fork of [vllm-router](https://github.com/PrimeIntellect-ai/router) as the request handler. We plan to support more advanced proxy options in the future.
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
Right now, router handles 2 most important things:
```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
+87
View File
@@ -0,0 +1,87 @@
# High-throughput GLM-5 with llm-d
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.
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
```
### Install llm-d
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.
```bash
touch .env
echo "WANDB_API_KEY=your_wandb_api_key" >> .env
echo "HUGGINGFACE_TOKEN=your_huggingface_token" >> .env
```
### sandbox
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.
From your Slurm head node:
```bash
bash scripts/tmux.sh glm5-llmd /shared/outputs/glm5-llmd
```
You can then attach to it by doing `tmux attach -t glm5-llmd`.
## Start the run
Run the following command to start the RL training:
PS: If using the tmux helper, you can run the command in the `Terminal` (window 0) pane and look at the logs in the `Logs` (window 1) pane.
```bash
uv run rl @ examples/glm5_llmd/rl.toml --output-dir /shared/outputs/glm5-llmd
```
Output of the command:
```
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/glm5-llmd/configs [rl.py::515]
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/glm5-llmd/rl.sbatch [rl.py::534]
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/glm5-llmd/rl.sbatch [rl.py::540]
XXX:XX:XX SUCCESS Submitted batch job YYYY
Logs:
Trainer: tail -F /shared/outputs/glm5-llmd/logs/trainer.log
Orchestrator: tail -F /shared/outputs/glm5-llmd/logs/orchestrator.log
Inference: tail -F /shared/outputs/glm5-llmd/logs/inference.log
Envs: tail -F /shared/outputs/glm5-llmd/logs/envs/*/*/*.log
```
+140
View File
@@ -0,0 +1,140 @@
max_steps = 10000000
seq_len = 131072
output_dir = "/shared/outputs/glm5-llmd" # FILL IN: point at your shared filesystem
clean_output_dir = true
[log]
level = "debug"
[wandb]
project = "glm5-llmd"
name = "base"
[weight_broadcast]
type = "nccl"
port = 29502
timeout = 12000
quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
num_train_nodes = 16
num_infer_nodes = 16
gpus_per_node = 8
num_infer_replicas = 1
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 8
num_prefill_replicas = 4
num_decode_nodes = 8
num_decode_replicas = 1
# skip warmup for faster start in cost of some jit overhead early
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_overrides = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
# gives the most KV cache while keeping decent throughput, KV cache increase comes in from lower deep-ep LL static buffers
prefill_vllm_overrides = {"enable_dbo"=true}
decode_vllm_overrides = {"max_num_batched_tokens"=96, "max_num_seqs"=96}
[inference.deployment.router]
type = "llm-d"
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
[orchestrator.model]
name = "zai-org/GLM-5.1-FP8"
[orchestrator.renderer]
name = "glm-5.1"
preserve_all_thinking = true
[orchestrator.train.sampling]
temperature = 1.0
extra_body = {chat_template_kwargs = {clear_thinking = false}}
[[orchestrator.train.env]]
id = "rlm_swe"
name = "r2e"
num_workers = 16
[orchestrator.train.env.args]
max_turns = 300
timeout_seconds = 21600
summarize_at_tokens = [35000, 80000]
poll_interval = 5
rlm_ref = "907115a79b2a50d193863e7ea1f3550acb4386f0"
labels = ["glm5-llmd"]
[orchestrator.advantage]
type = "default"
[inference]
enable_expert_parallel = true
# <0.80 because glm5 layers are too large for 0.85
gpu_memory_utilization = 0.75
enable_eplb = false
use_deep_gemm = true
enable_fp32_lm_head = true
[inference.model]
name = "zai-org/GLM-5.1-FP8"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
# Speed up GLM-5.1 weight load: EP weight filtering + safetensors prefetch.
[inference.vllm_extra]
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
# Mooncake distributed CPU KV store: 1TB/node shared pool across all inference nodes.
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
+1
View File
@@ -10,6 +10,7 @@ dependencies = [
"renderers>=0.1.8.dev28",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.1.15.dev388",
]
[build-system]
@@ -1,25 +1,14 @@
from pathlib import Path
from pydantic import model_validator
from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.shared import LogConfig
from prime_rl.utils.config import BaseConfig
class EnvServerConfig(BaseConfig):
env: EnvConfig = EnvConfig()
env: EnvConfig
log: LogConfig = LogConfig()
env_install_prerelease: bool = False
"""Allow pre-release versions when installing environments. Passes ``--prerelease`` to ``prime env install``."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
@model_validator(mode="after")
def validate_num_workers(self):
if self.env.num_workers == "auto":
self.env.num_workers = 1
return self
@@ -167,8 +167,26 @@ All2AllBackend = Literal[
]
# 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",
}
)
class VllmRouterConfig(BaseConfig):
"""PrimeIntellect vllm-router fronting the per-rank (external-LB) endpoints."""
"""PrimeIntellect vllm-router."""
type: Literal["vllm-router"] = "vllm-router"
@@ -179,9 +197,57 @@ class VllmRouterConfig(BaseConfig):
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
# Discriminated on ``type`` so additional router backends can be added to the
# union (a single member needs no discriminator yet).
RouterConfig: TypeAlias = VllmRouterConfig
class LlmdRouterConfig(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
def prefill_scorers(self) -> dict[str, float]:
"""Effective prefill-profile scorers: ``scorers`` merged with ``prefill_scorer_overrides``."""
return {**self.scorers, **self.prefill_scorer_overrides}
@property
def decode_scorers(self) -> dict[str, float]:
"""Effective decode-profile scorers: ``scorers`` merged with ``decode_scorer_overrides``."""
return {**self.scorers, **self.decode_scorer_overrides}
@model_validator(mode="after")
def validate_scorers(self):
unknown = (
set(self.scorers) | set(self.prefill_scorer_overrides) | set(self.decode_scorer_overrides)
) - KNOWN_SCORERS
if unknown:
raise ValueError(f"Unknown llm-d scorer(s): {sorted(unknown)}. Known scorers: {sorted(KNOWN_SCORERS)}.")
return self
# Discriminated on ``type`` so the launch path can pick the router backend.
RouterConfig: TypeAlias = Annotated[VllmRouterConfig | LlmdRouterConfig, Field(discriminator="type")]
class BaseInferenceDeploymentConfig(BaseConfig):
@@ -240,6 +306,12 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
decode_env_overrides: dict[str, str] = {}
"""Extra environment variables exported only on decode nodes."""
prefill_vllm_overrides: dict[str, Any] = {}
"""Extra vLLM config options merged into --vllm-extra only for prefill ranks (SLURM only)."""
decode_vllm_overrides: dict[str, Any] = {}
"""Extra vLLM config options merged into --vllm-extra only for decode ranks (SLURM only)."""
@property
def num_nodes(self) -> int:
return self.num_prefill_nodes + self.num_decode_nodes
@@ -369,6 +441,18 @@ class InferenceConfig(BaseConfig):
raise ValueError("Must use SLURM for multi-node / disaggregated deployment.")
return self
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
router = getattr(self.deployment, "router", None)
if router is not None and router.type == "llm-d" and self.enable_return_routed_experts:
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(enable_return_routed_experts): it breaks P/D and is unverified for multi-node. "
"Use router type 'vllm-router' for routed-expert runs."
)
return self
@model_validator(mode="after")
def auto_setup_kv_cache_offload(self):
if self.kv_cache_offload is not None:
@@ -1,10 +1,9 @@
import math
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import AliasChoices, Field, model_serializer, model_validator
from pydantic_core.core_schema import SerializerFunctionWrapHandler
import verifiers.v1 as vf
from pydantic import AliasChoices, Field, model_validator
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.shared import (
@@ -143,31 +142,85 @@ class EvalSamplingConfig(BaseConfig):
return data
class TokensLengthPenaltyConfig(BaseConfig):
type: Literal["tokens"] = "tokens"
class EnvConfig(vf.EnvServerConfig):
name: str | None = None
"""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."""
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on model completion tokens. Finite and non-negative."""
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. The ``pool`` sizes the spawned server."""
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
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)."""
max_retries: int = Field(3, ge=0)
"""Times the env server retries a failed rollout before returning an error."""
@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
explicit ``pool`` always wins."""
if isinstance(data, dict) and "num_workers" in data:
num_workers = data.pop("num_workers")
if "pool" not in data and num_workers != "auto":
data["pool"] = {"type": "static", "num_workers": num_workers}
return data
@property
def is_legacy(self) -> bool:
"""A v0/legacy env (run via the bridge): an ``id`` is set and no v1 ``taskset`` is."""
return not self.taskset.id
@property
def env_id(self) -> str:
"""The env identifier — the v1 taskset id (v1) or the legacy env id (v0)."""
return self.taskset.id or self.id or ""
@property
def resolved_name(self) -> str:
return self.name or self.env_id
@model_validator(mode="after")
def validate_env(self):
if not self.taskset.id and not self.id:
raise ValueError('no env configured — set taskset = { id = "<id>" } (v1) or id = "<id>" (v0/legacy)')
if self.resolved_name == "all":
raise ValueError(
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
)
return self
@model_validator(mode="after")
def resolve_legacy_env_kwargs(self):
"""For a v0/legacy env, surface the v1 knobs the legacy bridge applies via
``extra_env_kwargs`` (``env.set_kwargs(...)``): the per-rollout wall-clock timeout and
the multi-turn completion-token budget. (``max_seq_len`` is added per train run in
``OrchestratorConfig.resolve_env_config``, which knows ``seq_len``.)"""
if self.is_legacy:
if self.timeout.rollout is not None:
self.extra_env_kwargs["timeout_seconds"] = self.timeout.rollout
if self.max_output_tokens is not None:
self.extra_env_kwargs["max_total_completion_tokens"] = self.max_output_tokens
return self
class TurnsLengthPenaltyConfig(BaseConfig):
type: Literal["turns"] = "turns"
class LinearLengthPenaltyConfig(BaseConfig):
coef: float = Field(0.25, ge=0, allow_inf_nan=False)
"""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."""
LengthPenaltyConfig: TypeAlias = Annotated[
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
Field(discriminator="type"),
]
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."""
class DefaultAdvantageConfig(BaseConfig):
type: Literal["default"] = "default"
length_penalty: LengthPenaltyConfig | None = None
"""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."""
length_penalty: LinearLengthPenaltyConfig | None = None
"""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."""
class CustomAdvantageConfig(BaseConfig):
@@ -186,69 +239,6 @@ AdvantageConfig: TypeAlias = Annotated[
]
class EnvConfig(BaseConfig):
id: str = "reverse-text"
"""Registered verifiers environment ID (e.g. ``math-env``, ``primeintellect/math-env``). May include an ``@version`` suffix for installation."""
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."""
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."""
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)."""
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``."""
timeout: float | None = Field(None, validation_alias=AliasChoices("timeout", "timeout_seconds"))
"""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."""
@property
def stripped_id(self) -> str:
"""Environment ID without the @version suffix."""
return self.id.split("@")[0]
@property
def resolved_name(self) -> str:
return self.name or self.stripped_id
@model_validator(mode="after")
def validate_env_name(self):
if self.resolved_name == "all":
raise ValueError(
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
)
return self
@model_validator(mode="after")
def resolve_max_total_completion_tokens(self):
self.extra_env_kwargs["max_total_completion_tokens"] = self.max_total_completion_tokens
return self
@model_validator(mode="after")
def resolve_timeout(self):
if self.timeout is not None:
self.extra_env_kwargs["timeout_seconds"] = self.timeout
return self
class TrainEnvConfig(EnvConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
@@ -278,21 +268,19 @@ class EvalEnvConfig(EnvConfig):
class TrainConfig(BaseConfig):
env: list[TrainEnvConfig] = [TrainEnvConfig()]
env: list[TrainEnvConfig] = Field(default_factory=list)
"""Training environments."""
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
num_workers: int | Literal["auto"] = "auto"
"""Default worker processes for env servers. Can be overridden per env."""
max_retries: int = Field(3, ge=0)
"""Default retries for failed rollouts. Can be overridden per env."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_workers, and max_retries."""
"""Resolve per-env overrides: inherit group-level sampling and max_retries (the
worker ``pool`` is configured per env, defaulting to elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.env:
if "sampling" not in env.model_fields_set:
@@ -300,8 +288,6 @@ class TrainConfig(BaseConfig):
else:
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
env.sampling = TrainSamplingConfig(**merged)
if "num_workers" not in env.model_fields_set:
env.num_workers = self.num_workers
if "max_retries" not in env.model_fields_set:
env.max_retries = self.max_retries
return self
@@ -327,7 +313,7 @@ class TrainConfig(BaseConfig):
class EvalConfig(BaseConfig):
env: list[EvalEnvConfig] = [EvalEnvConfig()]
env: list[EvalEnvConfig] = Field(default_factory=list)
"""Evaluation environments."""
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
@@ -339,9 +325,6 @@ class EvalConfig(BaseConfig):
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
"""Default rollouts per example. Can be overridden per env."""
num_workers: int | Literal["auto"] = "auto"
"""Default worker processes for env servers. Can be overridden per env."""
max_retries: int = Field(3, ge=0)
"""Default retries for failed rollouts. Can be overridden per env."""
@@ -354,7 +337,8 @@ class EvalConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_workers, max_retries, num_examples, group_size, and interval. Then resolve auto num_workers."""
"""Resolve per-env overrides: inherit group-level sampling, max_retries, num_examples,
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.env:
if "sampling" not in env.model_fields_set:
@@ -368,17 +352,8 @@ class EvalConfig(BaseConfig):
env.group_size = self.group_size
if "interval" not in env.model_fields_set:
env.interval = self.interval
if "num_workers" not in env.model_fields_set:
env.num_workers = self.num_workers
if "max_retries" not in env.model_fields_set:
env.max_retries = self.max_retries
# Resolve auto num_workers now that num_examples and group_size are set
if env.num_workers == "auto":
if env.num_examples == -1:
env.num_workers = 4
else:
max_concurrent = env.num_examples * env.group_size
env.num_workers = max(1, math.ceil(max_concurrent / 256))
return self
@model_validator(mode="after")
@@ -518,30 +493,16 @@ class OrchestratorConfig(BaseConfig):
tokenizer: TokenizerConfig = TokenizerConfig()
renderer: RendererConfig | None = AutoRendererConfig()
"""Typed renderer config (``renderers.RendererConfig`` discriminated
union). Defaults to ``"auto"``, which resolves from
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. ``None``
opts into MITO (``openai_chat_completions``)."""
renderer: RendererConfig = AutoRendererConfig()
"""Typed renderer config (``renderers.RendererConfig`` discriminated union), required —
training is renderer-only. Defaults to ``"auto"``, which resolves from
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. RL/OPD roll out through the renderer
client; SFT uses it to backfill tokens for its chat-completions teacher."""
pool_size: int | None = Field(None, ge=1)
"""Number of renderer slots shared across concurrent rollouts. Bump
for long multi-turn prompts where client-side jinja tokenization
serializes. Only meaningful when ``renderer`` is not ``None``."""
@model_serializer(mode="wrap")
def _preserve_mito_renderer(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
"""Emit ``renderer = "None"`` (string) when MITO so
``model_dump(exclude_none=True)`` round-trips: dumped TOML has
``renderer = "None"``, and on reload
``BaseConfig._none_str_to_none`` coerces it back to ``None``.
Without this, a MITO orchestrator config saved to
``control/orch.toml`` would lose the renderer key entirely and
reload as the default ``AutoRendererConfig()`` (TITO)."""
result = handler(self)
if self.renderer is None:
result["renderer"] = "None"
return result
serializes."""
optim: OptimizerConfig = OptimizerConfig()
"""Per-run optimizer configuration for multi-run training."""
@@ -630,9 +591,6 @@ class OrchestratorConfig(BaseConfig):
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
env_install_prerelease: bool = False
"""Allow pre-release versions when installing environments (e.g. ``verifiers>=0.1.12.dev5``). Passes ``--prerelease`` to ``prime env install``."""
experimental: OrchestratorExperimentalConfig = OrchestratorExperimentalConfig()
@model_validator(mode="before")
@@ -757,51 +715,14 @@ class OrchestratorConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def _force_no_renderer_for_sft(self):
"""Teacher-backed SFT rolls out via the teacher's plain chat-completions
endpoint; the renderer client doesn't apply. When no teacher is
configured, SFT uses the student rollout path and keeps the renderer."""
if self.training_mode == "sft" and self.teacher is not None:
self.renderer = None
return self
@model_validator(mode="after")
def validate_training_mode(self):
"""Enforce training mode invariants that involve only orchestrator fields."""
has_teacher = self.teacher is not None
if self.training_mode == "rl" and has_teacher:
raise ValueError("orchestrator.teacher must not be set when training_mode = 'rl'.")
if self.training_mode == "opd" and not has_teacher:
raise ValueError("orchestrator.teacher must be configured when training_mode = 'opd'.")
return self
@model_validator(mode="after")
def validate_pool_size(self):
"""``pool_size`` is only meaningful when the renderer is enabled
(``renderer is not None``). Reject otherwise so callers don't
silently pass it and wonder why it's ignored."""
if self.renderer is None and self.pool_size is not None:
raise ValueError(
f"orchestrator.pool_size={self.pool_size!r} is set but "
"orchestrator.renderer is None (MITO mode). Either configure a renderer "
"or remove pool_size."
)
return self
@model_validator(mode="after")
def vlm_requires_renderer(self):
"""VLMs (``[model.vlm]`` block set) must go through the renderer.
The renderer owns the processor per-slot, produces byte-identical
tokens, and ships generic ``mm_kwargs`` keyed by whatever the
model's forward signature expects.
"""
if self.student.model.vlm is not None and self.renderer is None:
raise ValueError(
"orchestrator.renderer must be set when model.vlm is set. "
"VLMs must go through a renderer (e.g. Qwen3VLRenderer) that owns the processor."
)
if self.training_mode in ("opd", "sft") and not has_teacher:
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
return self
@model_validator(mode="after")
@@ -817,7 +738,7 @@ class OrchestratorConfig(BaseConfig):
``DefaultRendererConfig.tool_parser`` is configured. Surface at
config time so ``--dry-run`` reports the error.
"""
if self.renderer is None or self.renderer.name != "auto":
if self.renderer.name != "auto":
return self
from renderers.base import MODEL_RENDERER_MAP
@@ -835,9 +756,7 @@ class OrchestratorConfig(BaseConfig):
f"(b) [orchestrator.renderer] name=<model-specific renderer> — "
f"if {model_id!r} is template-identical to a mapped family "
f"(and ideally also add it upstream to "
f"renderers.base.MODEL_RENDERER_MAP). "
f"(c) orchestrator.renderer='none' — opt out of the renderer "
f"client entirely (MITO)."
f"renderers.base.MODEL_RENDERER_MAP)."
)
@model_validator(mode="after")
@@ -885,12 +804,6 @@ class OrchestratorConfig(BaseConfig):
if "advantage" not in env_cfg.model_fields_set:
env_cfg.advantage = self.advantage
# Resolve train env num_workers from max_inflight_rollouts
for env_cfg in self.train.env:
if env_cfg.num_workers == "auto":
assert self.max_inflight_rollouts is not None
env_cfg.num_workers = max(1, math.ceil(self.max_inflight_rollouts / 256))
return self
@model_validator(mode="after")
@@ -909,12 +822,15 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_config(self):
"""Populate extra_env_kwargs and vLLM sampling defaults from top-level fields."""
is_vllm = self.training_mode != "sft"
"""Set vLLM sampling defaults on each train env from top-level fields."""
if self.training_mode == "sft":
return self
for env in self.train.env:
env.extra_env_kwargs.update(max_seq_len=self.seq_len)
if is_vllm:
env.sampling.extra_body.setdefault("top_k", -1)
env.sampling.extra_body.setdefault("min_p", 0.0)
env.sampling.extra_body.setdefault("return_token_ids", True)
env.sampling.extra_body.setdefault("top_k", -1)
env.sampling.extra_body.setdefault("min_p", 0.0)
env.sampling.extra_body.setdefault("return_token_ids", True)
if env.is_legacy:
# v0 env: cap per-turn response tokens to the training budget (the legacy
# bridge applies extra_env_kwargs via env.set_kwargs).
env.extra_env_kwargs["max_seq_len"] = self.seq_len
return self
@@ -438,6 +438,25 @@ class RLConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node).
Runs after ``auto_setup_router_replay`` so it also catches the
``trainer.enable_router_replay`` path, which sets the inference flag here
(after InferenceConfig's own validators, which therefore miss it).
"""
if self.inference is not None and self.inference.enable_return_routed_experts:
router = getattr(self.inference.deployment, "router", None)
if router is not None and router.type == "llm-d":
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(inference.enable_return_routed_experts / trainer.enable_router_replay): it "
"breaks P/D and is unverified for multi-node. Use router type 'vllm-router' "
"for router-replay runs."
)
return self
@model_validator(mode="after")
def validate_router_replay_without_kv_offload(self):
if (
@@ -100,12 +100,6 @@ class ElasticConfig(BaseConfig):
class ClientConfig(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."""
+60 -31
View File
@@ -1,6 +1,6 @@
[project]
name = "prime-rl"
version = "0.5.0"
version = "0.6.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
@@ -33,13 +33,16 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers",
"verifiers>=0.1.15.dev394",
"renderers",
"dion",
"tilelang>=0.1.8",
"flash-linear-attention",
"nvidia-ml-py>=12.575.51",
"pybase64>=1.4.2",
"orjson>=3.10",
"pandas>=2.0",
"msgspec>=0.18",
]
[project.scripts]
@@ -63,36 +66,49 @@ flash-attn-cute = [
"flash-attn-4",
]
envs = [
"aime2024",
"aime2025",
"alphabet-sort",
"code-env",
"color-codeword",
"deepdive",
"general-agent",
"gpqa",
"hle",
"ifeval",
"livecodebench",
"logic-env",
"math-env",
"math-python",
"math500",
"mini-swe-agent-plus",
"mmlu-pro",
"opencode-cp",
"opencode-deepdive",
"opencode-math",
"opencode-science",
"opencode-swe",
"reverse-text",
"rlm-swe",
"rlm-search",
"uuid-ctf-v1",
"science-env",
"simpleqa-verified",
"tau2-bench",
"wiki-search",
"wordle",
"reverse-text-v1",
"gsm8k-v1",
"math-env-v1",
"aime24-v1",
"aime25-v1",
"aime26-v1",
"alphabet-sort-v1",
"scaleswe-v1",
"color-codeword-v1",
"deepdive-v1",
"gpqa-v1",
"livecodebench-v1",
"r2e-gym-v1",
"terminal-bench-2-v1",
"code-golf-v1",
"deepwiki-v1",
"glossary-v1",
"swelego-v1",
"wiki-search-v1",
"wikispeedia-v1",
"wordle-v1",
"general-agent-v1",
"swebench-verified-v1",
"tau2-bench-v1",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64'",
@@ -152,7 +168,7 @@ override-dependencies = [
"transformers==5.6.2",
"torch>=2.9.0",
"openenv-core",
"verifiers[packages]>=0.1.15.dev150",
"verifiers>=0.1.15.dev394",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -187,8 +203,6 @@ prime-tunnel = false
prime-evals = false
verifiers = false
renderers = false
tasksets = false
harnesses = false
prime-pydantic-config = false
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
vllm-router = false
@@ -199,41 +213,56 @@ nixl-cu12 = false
[tool.uv.sources]
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
# prime-rl depends on the one `verifiers` package (v0 + v1 + the legacy bridge + the built-in v1
# harnesses/tasksets, now bundled in verifiers.v1). v0 envs resolve from
# deps/{verifiers,research-environments}/environments; v1 tasksets (`-v1`) and the `compact`
# example live under deps/{verifiers,research-environments}/environments.
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
aime2024 = { path = "deps/research-environments/environments/aime2024", editable = true }
aime2025 = { path = "deps/research-environments/environments/aime2025", editable = true }
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
code-env = { path = "deps/research-environments/environments/code_env", editable = true }
color-codeword = { path = "deps/research-environments/environments/color_codeword", editable = true }
deepdive = { path = "deps/research-environments/environments/deepdive", editable = true }
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
gpqa = { path = "deps/research-environments/environments/gpqa", editable = true }
harnesses = { path = "deps/verifiers/packages/harnesses", editable = true }
hle = { path = "deps/research-environments/environments/hle", editable = true }
ifeval = { path = "deps/research-environments/environments/ifeval", editable = true }
livecodebench = { path = "deps/research-environments/environments/livecodebench", editable = true }
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
math500 = { path = "deps/research-environments/environments/math500", editable = true }
mini-swe-agent-plus = { path = "deps/research-environments/environments/mini_swe_agent_plus", editable = true }
mmlu-pro = { path = "deps/research-environments/environments/mmlu_pro", editable = true }
opencode-cp = { path = "deps/research-environments/environments/opencode_cp", editable = true }
opencode-deepdive = { path = "deps/research-environments/environments/opencode_deepdive", editable = true }
opencode-math = { path = "deps/research-environments/environments/opencode_math", editable = true }
opencode-science = { path = "deps/research-environments/environments/opencode_science", editable = true }
opencode-swe = { path = "deps/research-environments/environments/opencode_swe", editable = true }
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
uuid-ctf-v1 = { path = "deps/research-environments/environments/uuid_ctf_v1", editable = true }
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
tasksets = { path = "deps/verifiers/packages/tasksets", editable = true }
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
gsm8k-v1 = { path = "deps/verifiers/environments/gsm8k_v1", editable = true }
math-env-v1 = { path = "deps/research-environments/environments/math_env_v1", editable = true }
aime24-v1 = { path = "deps/research-environments/environments/aime24_v1", editable = true }
aime25-v1 = { path = "deps/research-environments/environments/aime25_v1", editable = true }
aime26-v1 = { path = "deps/research-environments/environments/aime26_v1", editable = true }
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
scaleswe-v1 = { path = "deps/research-environments/environments/scaleswe_v1", editable = true }
color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", editable = true }
deepdive-v1 = { path = "deps/research-environments/environments/deepdive_v1", editable = true }
gpqa-v1 = { path = "deps/research-environments/environments/gpqa_v1", editable = true }
livecodebench-v1 = { path = "deps/research-environments/environments/livecodebench_v1", editable = true }
r2e-gym-v1 = { path = "deps/research-environments/environments/r2e_gym_v1", editable = true }
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal_bench_2_v1", editable = true }
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
swelego-v1 = { path = "deps/research-environments/environments/swelego_v1", editable = true }
wiki-search-v1 = { path = "deps/verifiers/environments/wiki_search_v1", editable = true }
wikispeedia-v1 = { path = "deps/research-environments/environments/wikispeedia_v1", editable = true }
wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
general-agent-v1 = { path = "deps/research-environments/environments/general_agent_v1", editable = true }
swebench-verified-v1 = { path = "deps/research-environments/environments/swebench_verified_v1", editable = true }
tau2-bench-v1 = { path = "deps/research-environments/environments/tau2_bench_v1", editable = true }
torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env bash
set -euo pipefail
mode="env"
if [ "${1:-}" = "--shell" ] || [ "${1:-}" = "--github-output" ]; then
mode="${1#--}"
shift
fi
root="${1:-.}"
root="$(cd "$root" && pwd)"
dependency_floor_version() {
local package="$1"
find "$root" \
\( -path "$root/.git" -o -path "$root/.venv" \) -prune -o \
-type f -name pyproject.toml -print |
while IFS= read -r pyproject; do
sed -nE "s/.*[\"']${package}(\\[[^]]+\\])?>=([^\"',; ]+).*/\\2/p" "$pyproject"
done |
sort -V |
tail -n 1
}
next_patch_dev_version() {
local tag="$1"
local distance="$2"
local version="${tag#v}"
local major minor patch
if [ "$distance" = "0" ]; then
printf '%s\n' "$version"
return 0
fi
if [[ "$version" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
major="${BASH_REMATCH[1]}"
minor="${BASH_REMATCH[2]}"
patch="${BASH_REMATCH[3]}"
printf '%s.%s.%s.dev%s\n' "$major" "$minor" "$((patch + 1))" "$distance"
return 0
fi
return 1
}
describe_distance() {
sed -E 's/.*-([0-9]+)-g[0-9a-f]+$/\1/' <<< "$1"
}
describe_tag() {
sed -E 's/-[0-9]+-g[0-9a-f]+$//' <<< "$1"
}
verifiers_git_version() {
local dir="$root/deps/verifiers"
local desc tag distance
[ -d "$dir" ] || return 1
desc="$(git -C "$dir" describe --tags --long --match 'v[0-9]*.[0-9]*.[0-9]*' --exclude '*dev*' 2>/dev/null)" || return 1
tag="$(describe_tag "$desc")"
distance="$(describe_distance "$desc")"
next_patch_dev_version "$tag" "$distance"
}
renderers_git_version() {
local dir="$root/deps/renderers"
local desc tag distance version
[ -d "$dir" ] || return 1
desc="$(git -C "$dir" describe --tags --long --match 'renderers-v*' 2>/dev/null)" || return 1
tag="$(describe_tag "$desc")"
distance="$(describe_distance "$desc")"
version="${tag#renderers-v}"
if [ "$distance" = "0" ]; then
printf '%s\n' "$version"
return 0
fi
next_patch_dev_version "v$version" "$distance"
}
resolve_version() {
local package="$1"
local env_name="$2"
local git_func="$3"
local version
version="${!env_name:-}"
if [ -n "$version" ]; then
printf '%s\n' "$version"
return 0
fi
if version="$("$git_func")" && [ -n "$version" ]; then
printf '%s\n' "$version"
return 0
fi
version="$(dependency_floor_version "$package")"
if [ -n "$version" ]; then
printf '%s\n' "$version"
return 0
fi
printf 'Could not infer a pretend version for %s under %s\n' "$package" "$root" >&2
return 1
}
verifiers_version="$(resolve_version verifiers VERIFIERS_PRETEND_VERSION verifiers_git_version)"
renderers_version="$(resolve_version renderers RENDERERS_PRETEND_VERSION renderers_git_version)"
printf 'Resolved verifiers pretend version: %s\n' "$verifiers_version" >&2
printf 'Resolved renderers pretend version: %s\n' "$renderers_version" >&2
case "$mode" in
shell)
printf "export VERIFIERS_PRETEND_VERSION='%s'\n" "$verifiers_version"
printf "export RENDERERS_PRETEND_VERSION='%s'\n" "$renderers_version"
;;
github-output)
printf 'verifiers=%s\n' "$verifiers_version"
printf 'renderers=%s\n' "$renderers_version"
;;
env)
printf 'VERIFIERS_PRETEND_VERSION=%s\n' "$verifiers_version"
printf 'RENDERERS_PRETEND_VERSION=%s\n' "$renderers_version"
;;
*)
printf 'Unknown output mode: %s\n' "$mode" >&2
exit 2
;;
esac
+67 -1
View File
@@ -4,8 +4,74 @@ set -e
# Set higher ulimit for file descriptors to prevent API timeout issues
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
# Allow runtime override of the prime-rl source itself.
# PRIME_RL_REF can be a git tag, branch, or commit hash. PRIME_RL_REPO
# optionally points at a fork; defaults to the upstream repo.
#
# We clone into a per-ref dir under /tmp, seed the venv from the baked
# /app/.venv so heavy wheels (flash-attn, mamba-ssm, …) survive, then
# `uv sync --inexact` re-installs prime_rl from the override source.
# Workdir + PATH swap so the chart's `uv run trainer/inference/orchestrator`
# resolves the entrypoints from the override venv.
if [ -n "$PRIME_RL_REF" ]; then
PRIME_RL_REPO="${PRIME_RL_REPO:-https://github.com/PrimeIntellect-ai/prime-rl.git}"
# Slug + content hash for the cache dir name. Slug keeps the path
# human-readable; the hash (over repo + ref) prevents collisions
# between distinct refs that slugify the same way (e.g. `feat/foo`
# vs `feat-foo`) and between the same ref on different forks.
REF_SLUG="${PRIME_RL_REF//\//-}"
REF_HASH=$(echo -n "${PRIME_RL_REPO}|${PRIME_RL_REF}" | md5sum | cut -c1-12)
DEST="/tmp/prime-rl-${REF_SLUG}-${REF_HASH}"
# Rewrite ssh://git@github.com URLs to https so submodules listed
# with SSH URLs (deps/verifiers, deps/renderers, deps/research-envs)
# can be cloned from the pod without ssh keys.
git config --global url."https://github.com/".insteadOf "git@github.com:"
if [ ! -d "$DEST/.git" ]; then
echo "[prime-rl] cloning ${PRIME_RL_REPO} for ${PRIME_RL_REF}"
rm -rf "$DEST"
git clone --recurse-submodules "$PRIME_RL_REPO" "$DEST"
fi
# Always fetch + checkout so mutable refs (branches/tags) pick up new
# commits between pod restarts. No-op for immutable SHAs.
echo "[prime-rl] refreshing ${PRIME_RL_REF}"
git -C "$DEST" fetch --quiet --tags --force origin
git -C "$DEST" checkout --quiet --force "$PRIME_RL_REF"
# Fast-forward to upstream tip when PRIME_RL_REF is a branch name.
# Silently no-ops for SHAs/tags (no `origin/<sha>` exists).
git -C "$DEST" reset --hard --quiet "origin/${PRIME_RL_REF}" 2>/dev/null || true
# Refresh submodules to whatever the parent commit pins. `sync`
# picks up URL changes in .gitmodules between checkouts on cache
# hit; `update --init --recursive` applies the pinned SHAs.
git -C "$DEST" submodule sync --recursive
git -C "$DEST" submodule update --init --recursive
if [ ! -d "$DEST/.venv" ]; then
# Seed from the baked venv so the heavy wheels (flash-attn,
# mamba-ssm, …) don't have to be rebuilt. Plain `cp -a` (no
# hardlinks): a subsequent `uv sync` writes into this tree, and
# hardlinks would leak those writes back into /app/.venv when
# /tmp and /app share a filesystem.
cp -a /app/.venv "$DEST/.venv"
fi
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
# Mirror the image's uv sync extras — explicit instead
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
# startup. --inexact keeps the seeded venv's pre-built wheels
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
# override's lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev \
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
--extra envs --extra gpt-oss --extra modelexpress \
--group mamba-ssm )
export VIRTUAL_ENV="$DEST/.venv"
export PATH="$DEST/.venv/bin:$PATH"
cd "$DEST"
fi
# Allow runtime override of the verifiers package version.
# VERIFIERS_VERSION can be a git tag, branch, or commit hash.
# VERIFIERS_VERSION can be a git tag, branch, or commit hash. Runs after the
# PRIME_RL_REF swap so when both are set the install lands in the override
# venv (uv pip install targets $VIRTUAL_ENV when exported).
if [ -n "$VERIFIERS_VERSION" ]; then
echo "Installing verifiers version: $VERIFIERS_VERSION"
uv pip install --reinstall-package verifiers \
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env bash
# Install the llm-d standalone (no-Kubernetes) routing binaries into
# third_party/llmd/bin:
# - epp : llm-d-router Endpoint Picker (the routing brain)
# - pd-sidecar : decode-side proxy for P/D disaggregation
# - envoy : the data-plane proxy that calls the EPP via ext_proc
#
# epp/pd-sidecar are built from a pinned llm-d-router commit. We currently build
# from a small fork that adds P/D disaggregation for vLLM's token-in
# /inference/v1/generate endpoint (prime-rl's renderer / TITO rollout path) —
# upstream's pd-sidecar only disaggregates the OpenAI endpoints, so token-in P/D
# silently runs decode-only. The fork is pending upstream PR
# llm-d/llm-d-router#1458; switch LLMD_ROUTER_REPO back to the upstream repo and
# bump LLMD_ROUTER_REF once it merges. The fork is branched off the upstream
# commit that added the EPP vllmhttp parser (PR #1248), which the renderer path
# also needs.
#
# System Go is not required: a Go toolchain is vendored under third_party/llmd/go
# and used to bootstrap; GOTOOLCHAIN=auto fetches the exact version the module
# pins. Envoy is extracted as a static binary from its release container image
# WITHOUT docker: we build `crane` (pure-Go, talks straight to the OCI registry)
# with the same vendored toolchain and use it to export the image filesystem.
# This is the only step that previously required a docker daemon, which cluster
# compute nodes don't have.
set -euo pipefail
LLMD_ROUTER_REPO="${LLMD_ROUTER_REPO:-https://github.com/S1ro1/llm-d-router.git}"
LLMD_ROUTER_REF="${LLMD_ROUTER_REF:-1ca4243ec84c657b4a5f507a1776d6c15a618d5b}"
GO_BOOTSTRAP_VERSION="${GO_BOOTSTRAP_VERSION:-1.23.4}"
ENVOY_VERSION="${ENVOY_VERSION:-1.36.0}"
ENVOY_IMAGE="${ENVOY_IMAGE:-envoyproxy/envoy:v${ENVOY_VERSION}}"
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
PROJECT_DIR=$(cd "$SCRIPT_DIR/.." && pwd)
LLMD_DIR="$PROJECT_DIR/third_party/llmd"
BIN_DIR="$LLMD_DIR/bin"
GO_ROOT="$LLMD_DIR/go"
SRC_DIR="$LLMD_DIR/src"
GO_TOOLS_BIN="$LLMD_DIR/gotools/bin"
mkdir -p "$BIN_DIR" "$GO_TOOLS_BIN"
# --- Go toolchain (vendored bootstrap; auto-upgrades to the module's version) ---
if [ ! -x "$GO_ROOT/bin/go" ]; then
echo "[install_llmd] downloading bootstrap Go $GO_BOOTSTRAP_VERSION"
rm -rf "$GO_ROOT"
curl -fsSL "https://go.dev/dl/go${GO_BOOTSTRAP_VERSION}.linux-amd64.tar.gz" | tar -xz -C "$LLMD_DIR"
fi
export GOROOT="$GO_ROOT"
export PATH="$GO_ROOT/bin:$PATH"
export GOTOOLCHAIN=auto
echo "[install_llmd] bootstrap $(go version)"
# --- Fetch llm-d-router source at the pinned ref ---
echo "[install_llmd] fetching ${LLMD_ROUTER_REPO}@${LLMD_ROUTER_REF}"
if [ ! -d "$SRC_DIR/.git" ]; then
rm -rf "$SRC_DIR"
git clone --quiet "$LLMD_ROUTER_REPO" "$SRC_DIR"
fi
git -C "$SRC_DIR" remote set-url origin "$LLMD_ROUTER_REPO"
git -C "$SRC_DIR" fetch --quiet origin
git -C "$SRC_DIR" checkout --quiet "$LLMD_ROUTER_REF"
# --- Build epp + pd-sidecar ---
echo "[install_llmd] building epp + pd-sidecar"
( cd "$SRC_DIR" && go build -o "$BIN_DIR/epp" ./cmd/epp && go build -o "$BIN_DIR/pd-sidecar" ./cmd/pd-sidecar )
# --- Envoy static binary (extract from the release image; keep if present) ---
# No docker: build crane with the vendored toolchain and export the image's
# filesystem straight from the registry, then pull out the static envoy binary.
if [ ! -x "$BIN_DIR/envoy" ]; then
if [ ! -x "$GO_TOOLS_BIN/crane" ]; then
echo "[install_llmd] building crane (OCI registry client, no docker needed)"
GOBIN="$GO_TOOLS_BIN" GOFLAGS=-mod=mod \
go install github.com/google/go-containerregistry/cmd/crane@latest
fi
echo "[install_llmd] extracting Envoy ${ENVOY_VERSION} from ${ENVOY_IMAGE}"
"$GO_TOOLS_BIN/crane" export "$ENVOY_IMAGE" - \
| tar -xf - -O usr/local/bin/envoy > "$BIN_DIR/envoy"
chmod +x "$BIN_DIR/envoy"
fi
echo "[install_llmd] installed binaries in $BIN_DIR:"
"$BIN_DIR/epp" --version 2>&1 | head -1 || true
"$BIN_DIR/envoy" --version 2>&1 | head -1 || true
"$BIN_DIR/pd-sidecar" --help >/dev/null 2>&1 && echo " pd-sidecar OK" || true
echo "[install_llmd] done"
+3 -3
View File
@@ -81,7 +81,7 @@ tmux send-keys -t "$SESSION_NAME:Logs.1" \
"tail -F ${LOG_DIR}/orchestrator.log 2>/dev/null" C-m
tmux send-keys -t "$SESSION_NAME:Logs.2" \
"tail -F ${LOG_DIR}/envs/*/*/*.log 2>/dev/null" C-m
"tail -F ${LOG_DIR}/envs/*/*.log 2>/dev/null" C-m
tmux send-keys -t "$SESSION_NAME:Logs.3" \
"tail -F ${LOG_DIR}/inference.log 2>/dev/null" C-m
@@ -95,8 +95,8 @@ tmux send-keys -t "$SESSION_NAME:Claude" \
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
Help the user monitor and debug this run.'" C-m
+11 -1
View File
@@ -27,7 +27,7 @@ uv sync --group dev # + pytest, ruff, pre-commit
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`.
@@ -59,6 +59,16 @@ Flags: `--workspace DIR`, `--deepep-ref REF` (default `73b6ea4`), `--nvshmem-ver
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
+2 -4
View File
@@ -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`.
@@ -82,7 +80,7 @@ Scan for problems:
```bash
grep -E "WARNING|ERROR" {output_dir}/logs/{trainer,orchestrator,inference}.log
grep -E "WARNING|ERROR" {output_dir}/logs/envs/train/*/env_{server,worker_*}.log
grep -E "WARNING|ERROR" {output_dir}/logs/envs/{train,eval}/*.log
```
### Metrics
+19 -5
View File
@@ -1,6 +1,8 @@
import json
import subprocess
import sys
from pathlib import Path
from typing import Any
import tomli_w
@@ -14,6 +16,17 @@ INFERENCE_TOML = "inference.toml"
INFERENCE_SBATCH = "inference.sbatch"
def vllm_overrides_fragment(overrides: dict[str, Any]) -> str:
"""Render per-role vLLM overrides as a JSON fragment for the ROLE_EXTRA bash string.
Returns a leading-comma fragment with quotes escaped for the double-quoted assignment
(e.g. `, \\"max_num_seqs\\": 256`), or an empty string when there are no overrides.
"""
if not overrides:
return ""
return ", " + json.dumps(overrides)[1:-1].replace('"', '\\"')
def write_config(config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None) -> Path:
"""Write resolved config to disk."""
output_dir.mkdir(parents=True, exist_ok=True)
@@ -47,7 +60,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
dp_per_node=dp_per_node,
num_nodes=getattr(config.deployment, "num_nodes", 1),
port=config.server.port,
disaggregated=is_disaggregated,
is_disaggregated=is_disaggregated,
kv_offload=offload is not None,
kv_offload_mooncake=is_mooncake,
kv_offload_cpu_bytes=int(offload.cpu.num_bytes) if is_mooncake else 0,
@@ -65,20 +78,21 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
num_decode_replicas=config.deployment.num_decode_replicas,
prefill_port=config.deployment.prefill_port,
decode_port=config.deployment.decode_port,
router_port=config.deployment.router.port,
router_policy=config.deployment.router.policy,
router=config.deployment.router,
data_parallel_rpc_port=config.data_parallel_rpc_port,
use_deep_gemm=config.use_deep_gemm,
prefill_env_overrides=config.deployment.prefill_env_overrides,
decode_env_overrides=config.deployment.decode_env_overrides,
prefill_vllm_extra_json=vllm_overrides_fragment(config.deployment.prefill_vllm_overrides),
decode_vllm_extra_json=vllm_overrides_fragment(config.deployment.decode_vllm_overrides),
)
elif is_multi_node:
template_vars.update(
router_port=config.deployment.router.port,
router=config.deployment.router,
backend_port=config.deployment.backend_port,
router_policy=config.deployment.router.policy,
data_parallel_rpc_port=config.data_parallel_rpc_port,
enable_expert_parallel=config.enable_expert_parallel,
infer_nodes_per_replica=config.deployment.num_nodes,
)
script = template.render(**template_vars)
+7 -2
View File
@@ -12,7 +12,9 @@ from threading import Event, Thread
import pynvml
import tomli_w
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.inference import vllm_overrides_fragment
from prime_rl.utils.config import cli
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import (
@@ -371,7 +373,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
num_prefill_replicas=infer_deploy.num_prefill_replicas,
num_decode_replicas=infer_deploy.num_decode_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router_port=infer_deploy.router.port,
router=infer_deploy.router,
prefill_port=infer_deploy.prefill_port,
decode_port=infer_deploy.decode_port,
inference_tp=config.inference.parallel.tp,
@@ -379,6 +381,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
use_deep_gemm=config.inference.use_deep_gemm,
prefill_env_overrides=infer_deploy.prefill_env_overrides,
decode_env_overrides=infer_deploy.decode_env_overrides,
prefill_vllm_extra_json=vllm_overrides_fragment(infer_deploy.prefill_vllm_overrides),
decode_vllm_extra_json=vllm_overrides_fragment(infer_deploy.decode_vllm_overrides),
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
**mooncake_vars,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
@@ -397,7 +401,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
nodes_per_infer_replica=config.deployment.num_infer_nodes,
num_infer_replicas=config.deployment.num_infer_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router_port=config.inference.deployment.router.port if config.inference else 8000,
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
infer_nodes_per_replica=config.deployment.num_infer_nodes,
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
inference_tp=config.inference.parallel.tp if config.inference else 1,
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
+62
View File
@@ -21,6 +21,68 @@ def transformers_v5_compat():
monkey_patch_deep_gemm_silu_mul_quant_int64()
monkey_patch_vllm_padded_input_scrub()
monkey_patch_return_routed_experts_with_nixl_connector()
monkey_patch_kv_xfer_finished_tolerate_freed()
def monkey_patch_kv_xfer_finished_tolerate_freed():
"""Tolerate KV-transfer finish notifications for already-freed requests.
In disaggregated P/D (NIXL, optionally + a KV store connector) a request can
be finished — most often ``FINISHED_ABORTED`` from an off-policy cancel, a
client disconnect, or a request timeout — while it still has in-flight KV
transfers. When such a request's ``finished_recving`` and ``finished_sending``
both land in the same ``Scheduler.update_from_output`` step, the stock
``_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`` and kills the EngineCore. On a
DP deployment that one death cascades to every rank via the gloo finish-state
all-reduce, taking down the whole inference pool.
The trigger is the abort itself, not weight-update pause/resume: it reproduces
during normal stepping whenever an aborted request's recv and send complete in
the same step (observed with zero off-policy cancellations, driven only by
incidental client-side aborts). Skip already-freed request ids instead of
asserting — their blocks are freed either way, so dropping the stale
notification is safe.
Upstream issue: https://github.com/vllm-project/vllm/issues/46240
"""
from vllm.logger import init_logger
from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.request import RequestStatus
logger = init_logger("vllm.v1.core.sched.scheduler")
if getattr(Scheduler._update_from_kv_xfer_finished, "_prime_rl_tolerates_freed", False):
return
def _update_from_kv_xfer_finished(self, kv_connector_output):
if self.connector is not None:
self.connector.update_connector_output(kv_connector_output)
for req_id in kv_connector_output.finished_recving or ():
logger.debug("Finished recving KV transfer for request %s", req_id)
# Stale notification for a request freed earlier this step (e.g. an
# aborted request whose send completion freed it). Nothing to do.
if req_id not in self.requests:
continue
req = self.requests[req_id]
if req.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
self.finished_recving_kv_req_ids.add(req_id)
else:
assert RequestStatus.is_finished(req.status)
self._free_blocks(self.requests[req_id])
for req_id in kv_connector_output.finished_sending or ():
logger.debug("Finished sending KV transfer for request %s", req_id)
# See above: the recving branch may have already freed an aborted
# request whose send also completed this step.
if req_id not in self.requests:
continue
self._free_blocks(self.requests[req_id])
_update_from_kv_xfer_finished._prime_rl_tolerates_freed = True
Scheduler._update_from_kv_xfer_finished = _update_from_kv_xfer_finished
logger.warning("Patched Scheduler._update_from_kv_xfer_finished to tolerate freed (aborted) KV-transfer reqs.")
def monkey_patch_nano_v3_reasoning_parser():
+17 -21
View File
@@ -1,28 +1,24 @@
"""Prime-RL extensions to vLLM's `/inference/v1/generate` handler.
vLLM 0.20 ships a generic tokens-in / tokens-out handler at
vLLM 0.22 ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.serve.disagg.serving.ServingTokens`` that already covers
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs and
priority. Three prime-RL features are not in the upstream protocol though, so
we subclass it to add them back:
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
priority, ``data_parallel_rank`` header routing and server-side ``max_tokens``
defaulting. We subclass it for the bits still missing from the upstream handler:
1. ``data_parallel_rank`` routing — read from the ``X-data-parallel-rank``
header and forwarded to ``engine_client.generate``. The DP-replicated
inference servers prime-RL runs need this to target a specific replica.
header and forwarded to ``engine_client.generate``. Upstream ``ServingTokens``
now does this too; we keep the equivalent path for the DP-replicated
inference servers prime-RL runs.
2. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as base64 raw-byte payloads without requiring a vLLM
source fork.
3. Server-side ``max_tokens`` defaulting — ``ServingTokens`` hands the
client-supplied ``SamplingParams`` to the engine verbatim, and
``SamplingParams.max_tokens`` defaults to ``16`` (a dataclass-level
default that predates the OpenAI-compat layer). Every other vLLM
endpoint masks this server-side via
``vllm.entrypoints.utils.get_max_tokens`` (see e.g.
``OpenAIServingChat`` at ``serving.py:284``); the disagg endpoint
skips that path. Mirror it here so callers that omit ``max_tokens``
don't silently truncate at 16. Drop once vLLM patches upstream.
3. Server-side ``max_tokens`` defaulting — upstream ``ServingTokens`` now applies
this itself (via ``GenerateRequest.is_sampling_param_provided`` +
``get_max_tokens``); we keep an equivalent guard so callers that omit
``max_tokens`` don't truncate at vLLM's 16-token ``SamplingParams`` default.
Everything else (request/response schema, sampling params, error handling)
delegates to upstream so we track future vLLM changes for free.
@@ -156,7 +152,7 @@ class PrimeRlServingTokens(ServingTokens):
@cached_property
def _max_tokens_defaults(self) -> tuple[dict, int | None]:
"""Server-side ``max_tokens`` defaulting inputs, mirroring ``OpenAIServingChat``.
"""Server-side ``max_tokens`` defaulting inputs, mirroring upstream ``ServingTokens``.
Computed lazily because ``custom_init_app_state`` swaps in this
subclass via ``object.__new__`` + ``__dict__.update`` (so our
@@ -180,7 +176,7 @@ class PrimeRlServingTokens(ServingTokens):
request: GenerateRequest,
raw_request: Request | None = None,
) -> PrimeRlGenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
# Mirrors upstream ``ServingTokens.serve_tokens`` (vllm 0.20). Diffs:
# Mirrors upstream ``ServingTokens.serve_tokens`` (vllm 0.22). Diffs:
# (a) inject ``data_parallel_rank`` from the inbound header into
# ``engine_client.generate``; (b) default ``sampling_params.max_tokens``
# to ``max_model_len - prompt_len`` when the caller didn't set it; and
@@ -253,10 +249,10 @@ class PrimeRlServingTokens(ServingTokens):
extra["kv_transfer_params"] = request.kv_transfer_params
sampling_params.extra_args = extra
# Server-side ``max_tokens`` defaulting — see module docstring.
# Mirrors ``OpenAIServingChat`` (vllm/entrypoints/openai/chat_completion/
# serving.py:284) so callers that omit ``max_tokens`` don't get capped
# at vLLM's 16-token ``SamplingParams`` default.
# Server-side ``max_tokens`` defaulting — see module docstring. Upstream
# ``ServingTokens`` now does this too; kept here so callers that omit
# ``max_tokens`` don't get capped at vLLM's 16-token ``SamplingParams``
# default.
if not await _client_set_max_tokens(raw_request):
diff_sp, override = self._max_tokens_defaults
sampling_params.max_tokens = get_max_tokens(
+36 -68
View File
@@ -4,21 +4,17 @@ from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable
import torch
import verifiers as vf
from jaxtyping import Float
from torch import Tensor
if TYPE_CHECKING:
from prime_rl.orchestrator.types import TrainRollout
import verifiers.v1 as vf
from prime_rl.orchestrator.types import Rollout
from prime_rl.configs.orchestrator import (
AdvantageConfig,
CustomAdvantageConfig,
LengthPenaltyConfig,
TokensLengthPenaltyConfig,
TurnsLengthPenaltyConfig,
LinearLengthPenaltyConfig,
)
from prime_rl.orchestrator.utils import get_model_completion_len, get_tool_response_len
from prime_rl.utils.utils import import_object
@@ -26,7 +22,7 @@ from prime_rl.utils.utils import import_object
class AdvantageInputs:
"""Inputs for advantage computation of a single group (one example × N rollouts)."""
rollouts: list[vf.RolloutOutput]
rollouts: list[vf.Trace]
@dataclass
@@ -50,68 +46,36 @@ entry per rollout. `assign_advantages` calls it on one already-grouped cohort.
def default_advantage_fn(
inputs: AdvantageInputs,
length_penalty: LengthPenaltyConfig | None = None,
length_penalty: LinearLengthPenaltyConfig | None = None,
max_seq_len: int | None = None,
length_weighted_baseline: bool = False,
) -> AdvantageOutputs:
"""Default GRPO advantage for a single group: reward minus per-group baseline.
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
cost: tokens (weighted completion + tool-response) or trajectory turn count.
``length_penalty`` subtracts ``coef * pass_rate * (completion tokens / max_seq_len)``
from each reward (``pass_rate`` = group mean reward), optionally gated to correct
(``reward == 1``) rollouts. ``length_weighted_baseline`` uses the token-length-weighted
mean reward as the baseline instead of the plain mean.
"""
rewards = torch.tensor([r["reward"] for r in inputs.rollouts], dtype=torch.float32)
rewards = torch.tensor([r.reward for r in inputs.rollouts], dtype=torch.float32)
lengths = torch.tensor([r.completion_len for r in inputs.rollouts], dtype=rewards.dtype)
if isinstance(length_penalty, TokensLengthPenaltyConfig):
w_c = length_penalty.completion_weight
w_t = length_penalty.tool_response_weight
costs = torch.tensor(
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in inputs.rollouts],
dtype=rewards.dtype,
)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
costs = torch.tensor([len(r["trajectory"]) for r in inputs.rollouts], dtype=rewards.dtype)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
if length_penalty is not None:
if max_seq_len is None:
raise ValueError("max_seq_len is required when length_penalty is enabled")
penalty = length_penalty.coef * rewards.mean() * (lengths / max_seq_len)
if length_penalty.gate_by_correctness:
penalty = penalty * rewards
rewards = rewards - penalty
return AdvantageOutputs(advantages=(rewards - rewards.mean()).tolist())
if length_weighted_baseline:
baseline = (lengths * rewards).sum() / lengths.sum()
else:
baseline = rewards.mean()
return AdvantageOutputs(advantages=(rewards - baseline).tolist())
def _efficiency_shaping(
rewards: Float[Tensor, "group_size"],
costs: Float[Tensor, "group_size"],
) -> Float[Tensor, "group_size"]:
"""Correctness-gated efficiency shaping with bounded advantages.
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
preserving zero-mean advantages within the group. `costs` is a per-rollout cost
(e.g., completion length in tokens or number of turns).
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
"""
max_reward = rewards.max()
correct_mask = rewards >= max_reward
num_correct = correct_mask.sum()
# No shaping when max reward is 0 — no correct rollouts to differentiate
if max_reward <= 0:
return rewards - rewards.mean()
# Mean cost of correct rollouts
mean_correct_cost = (costs * correct_mask).sum() / num_correct.clamp(min=1)
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
if mean_correct_cost <= 0:
return rewards - rewards.mean()
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
shaped_rewards = rewards * (1 + bonus * correct_mask)
return shaped_rewards - shaped_rewards.mean()
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
def setup_advantage_fn(config: AdvantageConfig, max_seq_len: int | None = None) -> AdvantageFn:
"""Setup advantage function from config."""
if isinstance(config, CustomAdvantageConfig):
custom_fn = import_object(config.import_path)
@@ -123,25 +87,29 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
return advantage_fn
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
return default_advantage_fn(inputs, length_penalty=config.length_penalty)
return default_advantage_fn(
inputs,
length_penalty=config.length_penalty,
max_seq_len=max_seq_len,
length_weighted_baseline=config.length_weighted_baseline,
)
return advantage_fn
def assign_advantages(
rollouts: list["TrainRollout"], # noqa: F821 (forward ref)
rollouts: list[Rollout],
advantage_fn: AdvantageFn | None,
) -> None:
"""Compute and assign advantages for one finished group of rollouts
(``TrainSink.process_group`` hands in a single group's surviving rollouts).
``advantage_fn=None`` is the trivial case (advantage = reward); a custom
``advantage_fn`` receives the raw ``vf.RolloutOutput``\\ s via
``AdvantageInputs.rollouts``.
``advantage_fn`` receives the ``vf.Trace``\\ s via ``AdvantageInputs.rollouts``.
"""
if advantage_fn is None:
for rollout in rollouts:
rollout.advantage = rollout.reward
return
result = advantage_fn(AdvantageInputs(rollouts=[r.raw for r in rollouts]))
result = advantage_fn(AdvantageInputs(rollouts=[r for r in rollouts]))
for rollout, advantage in zip(rollouts, result.advantages):
rollout.advantage = advantage
+53 -75
View File
@@ -6,13 +6,14 @@
- Emit-everything invariant: every dispatched rollout eventually reaches
``out_q`` exactly once as a ``TrainRollout`` / ``EvalRollout``. Failures
(env error, empty trajectory, task exception, off-policy cancel) carry
``raw["error"]`` set; sinks decide drop / partial-train policy.
``trace.error`` set; sinks decide drop / partial-train policy.
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
schedule next. Transitions are level-triggered (driven by the eval
source's emptiness), so in-flight rollouts of the opposite kind drain
naturally on either side of an eval boundary.
- ``on_new_version`` (called by the watcher) bumps ``off_policy_steps`` on
in-flight train rollouts and drops groups past ``max_off_policy_steps``.
- ``on_version_pending`` (called by the watcher before the engines pause for
the weight update) bumps ``off_policy_steps`` on in-flight train rollouts and
drops groups past ``max_off_policy_steps``.
Eval rollouts are measurements for the policy version they started with,
so they are allowed to finish even if training advances.
Cancellations surface as synthetic ``Cancelled`` markers so the sink's
@@ -28,20 +29,18 @@ from dataclasses import dataclass, field
from enum import Enum, auto
from typing import Literal
import verifiers as vf
import verifiers.v1 as vf
from aiolimiter import AsyncLimiter
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.train_source import TrainSource
from prime_rl.orchestrator.types import (
EvalRollout,
FinishedRollout,
GroupState,
InflightRollout,
Policy,
Rollout,
RolloutKind,
TrainRollout,
)
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
from prime_rl.utils.client import InferencePool, client_identity
@@ -116,7 +115,7 @@ class RolloutDispatcher:
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules
rollouts under shared capacity, and emits ``FinishedRollout``\\ s to
``out_q``. The watcher drives ``on_new_version`` for off-policy
``out_q``. The watcher drives ``on_version_pending`` for off-policy
cancellation; the orchestrator triggers eval epochs."""
def __init__(
@@ -158,7 +157,7 @@ class RolloutDispatcher:
self.groups: dict[uuid.UUID, GroupState] = {}
# Bounded so the dispatcher backpressures on a slow sink
self.out_q: asyncio.Queue[FinishedRollout] = asyncio.Queue(maxsize=max(8, self.max_inflight))
self.out_q: asyncio.Queue[Rollout] = asyncio.Queue(maxsize=max(8, self.max_inflight))
self.mode: DispatcherMode = DispatcherMode.PREFER_TRAIN
# Set by the orchestrator after the final train step; pipeline then
@@ -263,11 +262,16 @@ class RolloutDispatcher:
await safe_cancel(self.task)
self.task = None
async def on_new_version(self, step: int) -> None:
async def on_version_pending(self, step: int) -> None:
"""Bump off-policy counters and drop groups past
``max_off_policy_steps`` (drop_group emits ``Cancelled`` markers so
the sink still finalizes the partial group). Eval rollouts are not
aged because they are tied to their start-time policy version."""
aged because they are tied to their start-time policy version.
Runs *before* the inference engines are paused for the weight update so
the resulting aborts are processed while the engine is still stepping —
otherwise the orphaned KV transfers crash the decode engine on resume
(see ``WeightWatcher.apply_policy_update``)."""
stale_groups: set[uuid.UUID] = set()
cancelled = 0
for meta in self.inflight.values():
@@ -287,6 +291,9 @@ class RolloutDispatcher:
"Consider increasing it to avoid this."
)
async def on_new_version(self, step: int) -> None:
"""No-op: the dispatcher drains in ``on_version_pending`` (pre-pause)."""
async def fill_inflight(self) -> None:
"""Schedule new rollouts up to ``max_inflight``, honoring
``self.mode``. Eval scheduling ignores the orchestrator's dispatch
@@ -373,7 +380,7 @@ class RolloutDispatcher:
return GroupState(
kind=kind,
env_name=env_name,
example=example,
task_idx=example["task_idx"],
rollouts_to_schedule=group_size,
target_rollouts=group_size,
eval_step=eval_step,
@@ -427,7 +434,7 @@ class RolloutDispatcher:
task: asyncio.Task = asyncio.create_task(
env.run_group(
client=client,
example=group.example,
task_idx=group.task_idx,
model_name=model_name,
group_size=permits,
cache_salt=cache_salt,
@@ -440,7 +447,7 @@ class RolloutDispatcher:
task = asyncio.create_task(
env.run_rollout(
client=client,
example=group.example,
task_idx=group.task_idx,
model_name=model_name,
cache_salt=cache_salt,
)
@@ -484,97 +491,60 @@ class RolloutDispatcher:
is_synth_exception = False
try:
result = task.result()
rollouts: list[vf.RolloutOutput] = result if isinstance(result, list) else [result]
rollouts: list[Rollout] = result if isinstance(result, list) else [result]
except asyncio.CancelledError:
return
except Exception as exc:
get_logger().warning(f"Rollout task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
rollouts = [
self.error_rollout_output(error_type=type(exc).__name__, error_repr=repr(exc))
for _ in range(meta.rollout_count)
]
task_idx = group.task_idx if group is not None else -1
rollouts = [Rollout(task=vf.Task(idx=task_idx, prompt=None)) for _ in range(meta.rollout_count)]
for r in rollouts:
r.capture_error(exc)
is_synth_exception = True
for r in rollouts:
if r.get("error") is None and len(r.get("trajectory") or []) == 0:
if not r.has_error and r.num_turns == 0:
# Empty trajectory: promote to an explicit error so the sink
# treats it like any other failure
r["error"] = {
"error": "EmptyTrajectory",
"error_chain_repr": "Rollout returned with no trajectory steps",
"error_chain_str": "",
}
r.errors.append(vf.Error(type="EmptyTrajectory", message="Rollout returned with no trajectory steps"))
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
if r.get("error") is not None:
err_type = r["error"].get("error", "Unknown")
if r.has_error:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if not is_synth_exception:
get_logger().warning(
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — "
f"{r['error'].get('error_chain_repr', err_type)}"
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — {r.error.type}: {r.error.message}"
)
await self.emit_rollout(meta, group, r)
async def emit_rollout(self, meta: InflightRollout, group: GroupState | None, raw: vf.RolloutOutput) -> None:
"""Build a ``TrainRollout`` / ``EvalRollout`` and put it on ``out_q``.
async def emit_rollout(self, meta: InflightRollout, group: GroupState | None, rollout: Rollout) -> None:
"""Stamp prime-rl metadata onto the completed rollout and put it on ``out_q``.
Pops the group from ``self.groups`` once every member has been emitted."""
eval_step = meta.eval_step
policy_version = meta.policy_version
example_id = raw.get("example_id")
if group is not None:
eval_step = group.eval_step
policy_version = group.policy_version_at_start
example_id = group.example["example_id"]
group.emitted += 1
if group.emitted >= group.target_rollouts:
self.groups.pop(meta.group_id, None)
common = dict(
raw=raw,
env_name=meta.env_name,
example_id=example_id if example_id is not None else -1,
group_id=meta.group_id,
policy_version=policy_version,
off_policy_steps=meta.off_policy_steps,
)
rollout: FinishedRollout
if meta.kind == "train":
rollout = TrainRollout(**common)
else:
rollout.kind = meta.kind
rollout.env_name = meta.env_name
rollout.group_id = meta.group_id
rollout.policy_version = policy_version
rollout.off_policy_steps = meta.off_policy_steps
if meta.kind == "eval":
assert eval_step is not None, "eval rollout missing eval_step"
rollout = EvalRollout(**common, eval_step=eval_step)
rollout.eval_step = eval_step
await self.out_q.put(rollout)
@staticmethod
def error_rollout_output(*, error_type: str, error_repr: str) -> vf.RolloutOutput:
"""Minimal ``vf.RolloutOutput`` for rollouts that never produced
real output (task exception, off-policy cancel)."""
out: vf.RolloutOutput = vf.RolloutOutput()
out["error"] = {
"error": error_type,
"error_chain_repr": error_repr,
"error_chain_str": error_repr,
}
out["trajectory"] = []
out["completion"] = None
out["reward"] = 0.0
out["is_truncated"] = False
out["metrics"] = {}
out["stop_condition"] = None
out["token_usage"] = {
"input_tokens": 0.0,
"output_tokens": 0.0,
"final_input_tokens": 0.0,
"final_output_tokens": 0.0,
}
return out
async def drop_group(self, group_id: uuid.UUID) -> int:
"""Cancel remaining in-flight tasks for this group and emit a
``Cancelled`` marker for every rollout it still owes the sink
(both in-flight and not-yet-scheduled). Returns the count for
off-policy metrics."""
group = self.groups.pop(group_id, None)
task_idx = group.task_idx if group is not None else -1
# Sync claim phase: pop matching tasks from ``self.inflight`` and
# release their permits in one non-yielding sweep. After this loop
@@ -594,15 +564,19 @@ class RolloutDispatcher:
last_meta: InflightRollout | None = claimed[-1][1] if claimed else None
for _, meta in claimed:
for _ in range(meta.rollout_count):
raw = self.error_rollout_output(error_type="Cancelled", error_repr="Off-policy cancel")
await self.emit_rollout(meta, group, raw)
trace = Rollout(
task=vf.Task(idx=task_idx, prompt=None),
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
stop_condition="error",
)
await self.emit_rollout(meta, group, trace)
# For non-group-scoring envs, the group may have rollouts that
# were never dispatched (``rollouts_to_schedule > 0``). Emit
# markers for those too so the sink hits ``target_rollouts``
#
# ``last_meta`` can be ``None`` if the only inflight task for this
# group completed naturally between ``on_new_version``'s snapshot
# group completed naturally between ``on_version_pending``'s snapshot
# and us reaching it — synthesize a stand-in from the group state
unscheduled_cancelled = 0
if group is not None and group.rollouts_to_schedule > 0:
@@ -616,8 +590,12 @@ class RolloutDispatcher:
)
unscheduled_cancelled = group.rollouts_to_schedule
for _ in range(unscheduled_cancelled):
raw = self.error_rollout_output(error_type="Cancelled", error_repr="Off-policy cancel")
await self.emit_rollout(fallback_meta, group, raw)
trace = Rollout(
task=vf.Task(idx=task_idx, prompt=None),
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
stop_condition="error",
)
await self.emit_rollout(fallback_meta, group, trace)
cancelled = inflight_cancelled + unscheduled_cancelled
if cancelled > 0:
@@ -1,38 +1,35 @@
import asyncio
from functools import partial
from verifiers.serve import ZMQEnvServer
from verifiers.v1 import pool_serve_kwargs
from verifiers.v1.serve import serve_env
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.orchestrator.utils import setup_env_server_logging
from prime_rl.utils.config import cli
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import get_log_dir
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.utils import clean_exit, get_env_ids_to_install, install_env
from prime_rl.utils.utils import clean_exit
@clean_exit
def run_server(config: EnvServerConfig):
setup_logger(config.log.level, json_logging=config.log.json_logging)
# install environment if not already installed
env_ids_to_install = set()
env_ids_to_install.update(get_env_ids_to_install([config.env]))
for env_id in env_ids_to_install:
install_env(env_id, prerelease=config.env_install_prerelease)
log_dir = (get_log_dir(config.output_dir) / config.env.resolved_name).as_posix()
server = ZMQEnvServer(
env_id=config.env.stripped_id,
env_args=config.env.args,
extra_env_kwargs=config.env.extra_env_kwargs,
log_level=config.log.level,
log_dir=log_dir,
json_logging=config.log.json_logging,
num_workers=config.env.num_workers,
**{"address": config.env.address} if config.env.address is not None else {},
env = config.env
address = env.address or "tcp://127.0.0.1:5000"
# The env's ``pool`` (static or elastic) sizes the server; a v0/legacy env runs through
# the bridge, a v1 env is a native taskset — both serve vf.Trace over the same protocol,
# so the orchestrator is agnostic. serve_env applies the logging setup in this process
# and in every spawned worker.
server_kwargs = (
{"env_id": env.env_id, "env_args": env.args, "extra_env_kwargs": env.extra_env_kwargs}
if env.is_legacy
else {"config": env}
)
serve_env(
**pool_serve_kwargs(env.pool),
legacy=env.is_legacy,
address=address,
log_setup=partial(setup_env_server_logging, config.log.level, config.log.json_logging),
**server_kwargs,
)
asyncio.run(server.run())
def main():
+157 -124
View File
@@ -1,33 +1,90 @@
"""Env wrappers over a v1 env server.
Each ``Env`` owns a v1 ``EnvServer`` (spawned as a child process, or an
external one given by ``config.address``) and an ``EnvClient`` to drive it. The
orchestrator never *runs* an environment: it asks the server for ``info``
(``num_tasks`` + whether group scoring is needed), then runs rollouts purely by
**task index**. The server returns a ``Trace`` (a plain ``model_dump`` — derived values are
properties, not serialized) which we validate into a ``Trace[WireTask]`` — a real ``vf.Trace``
(never a loose dict) whose task keeps the env's
task-specific fields as extras (``WireTask`` allows them). The orchestrator never imports the
env package: the env's *type* and *runtime* both live only in the server, and the orchestrator
drives it purely by task index. (Nothing here reads typed env task fields — only ``task.idx``
and a full ``task.model_dump``, both of which ``WireTask`` preserves.)
"""
from __future__ import annotations
import asyncio
import atexit
import multiprocessing as mp
import os
import queue
import sys
from collections.abc import Iterator, Sequence
from multiprocessing.process import BaseProcess
from pathlib import Path
from typing import Generic, TypeVar
import verifiers as vf
from verifiers.serve import ZMQEnvClient, ZMQEnvServer
from verifiers.utils.serve_utils import get_free_port
import verifiers.v1 as vf
from verifiers.v1.serve import EnvClient
from prime_rl.configs.orchestrator import EnvConfig, EvalEnvConfig, TrainEnvConfig
from prime_rl.orchestrator.advantage import AdvantageFn, setup_advantage_fn
from prime_rl.orchestrator.types import Rollout
from prime_rl.utils.logger import get_logger
REQUIRED_STATE_COLUMNS = ["trajectory"]
# Every wire trace validates into this type. WireTask (extra="allow") keeps the env's task
# fields without importing the env package — the orchestrator never reads them typed (only
# task.idx + task.model_dump).
ROLLOUT_TYPE = Rollout[vf.WireTask]
# Max wait for a spawned env server to bind and report its address. The child
# loads the taskset (possibly downloading a dataset) before reporting, so this
# is generous.
ENV_SERVER_SPAWN_TIMEOUT = 600.0
def _run_env_server(
*,
log_file: str,
log_level: str,
json_logging: bool,
legacy: bool = False,
**kwargs,
) -> None:
"""Spawned-process entry point: redirect this process's output to ``log_file`` (the
server's logging + any subprocess-runtime output), then serve via ``serve_env``. The
worker-pool sizing arrives in ``kwargs`` (``max_workers`` / ``multiplex`` / ``elastic``
from the env's ``pool``). ``serve_env`` applies ``log_setup`` here and in every spawned
worker; a worker inherits this process's redirected stdout/stderr, so its per-rollout
logs reach ``log_file`` too. Top-level so it stays picklable for the ``spawn`` start
method. ``legacy`` picks the v0 bridge."""
from functools import partial
from verifiers.v1.serve import serve_env
from prime_rl.orchestrator.utils import setup_env_server_logging
fh = open(log_file, "w", buffering=1)
os.dup2(fh.fileno(), sys.stdout.fileno())
os.dup2(fh.fileno(), sys.stderr.fileno())
serve_env(
legacy=legacy,
log_setup=partial(setup_env_server_logging, log_level, json_logging),
**kwargs,
)
class Env:
"""Wraps a vf.Environment - only exposes features used in PRIME-RL."""
"""Wraps a v1 env server + client. The orchestrator never loads the env."""
def __init__(self, config: EnvConfig):
self.config = config
self.sampling_args: dict = {}
get_logger().debug(f"Initializing {config.resolved_name} ({config})")
self._env: vf.Environment = vf.load_environment(config.stripped_id, **config.args)
self._env_client: ZMQEnvClient | None = None
self.num_tasks: int = 0
self.requires_group_scoring: bool = False
self._env_client: EnvClient | None = None
self._env_server_process: BaseProcess | None = None
@property
@@ -35,122 +92,105 @@ class Env:
return self.config.resolved_name
@property
def env(self) -> vf.Environment:
return self._env
@property
def env_client(self) -> ZMQEnvClient:
if not self._env_client:
raise RuntimeError(
f"Env {self.name} has no env client connected. Call connect() first to connect to an env server."
)
def env_client(self) -> EnvClient:
if self._env_client is None:
raise RuntimeError(f"Env {self.name} not started — call start() first.")
return self._env_client
@property
def requires_group_scoring(self) -> bool:
return any(self.env.rubric._is_group_func(func) for func in self.env.rubric._get_reward_funcs())
async def start(
self,
log_dir: Path,
log_level: str | None = None,
json_logging: bool = False,
) -> None:
"""Spawn an env server (if needed) and connect to it."""
if self.config.address is None:
address = self._spawn(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
else:
address = self.config.address
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
"""Spawn the env server (if needed), connect, and cache its ``info``."""
external = self.config.address is not None
address = self.config.address or await self._spawn(log_dir, log_level or "INFO", json_logging)
get_logger().debug(f"Connecting {self.name} to env server {address}")
self._env_client = ZMQEnvClient(address=address, name=self.name)
await self.env_client.wait_for_server_startup()
def _spawn(
self,
log_dir: Path,
log_level: str | None = None,
json_logging: bool = False,
) -> str:
assert isinstance(self.config.num_workers, int), (
f"num_workers must be resolved before spawn, got {self.config.num_workers!r}"
self._env_client = EnvClient(address=address)
# A spawned server already reported its address *after* binding + loading,
# so it's up — the untimed ``info`` below is enough. An external server has
# no such handshake, so poll until it answers before we block on ``info``.
if external:
await self.env_client.wait_for_server_startup()
info = await self.env_client.info()
self.num_tasks = info.num_tasks
self.requires_group_scoring = info.requires_group_scoring
get_logger().info(
f"Env {self.name} ready: num_tasks={self.num_tasks} group_scoring={self.requires_group_scoring}"
)
num_workers = self.config.num_workers
address = f"tcp://127.0.0.1:{get_free_port()}"
get_logger().debug(f"Spawning env server {self.name} ({address=}, {num_workers=})")
process = mp.get_context("spawn").Process(
target=ZMQEnvServer.run_server,
args=(
self.config.stripped_id,
self.config.args,
self.config.extra_env_kwargs,
log_level,
(log_dir / self.name).as_posix(),
),
async def _spawn(self, log_dir: Path, log_level: str, json_logging: bool) -> str:
"""Spawn a v1 EnvServer child process (it loads the env; we never do).
The server binds an OS-assigned port (``:0``) and reports the concrete
address back over a queue — no free-port guess, no TOCTOU race. Its output
goes to ``<log_dir>/<name>.log`` (``log_dir`` is already the train/eval-split
``.../logs/envs/{train,eval}`` the orchestrator passes in)."""
ctx = mp.get_context("spawn")
address_queue: mp.Queue = ctx.Queue()
log_file = log_dir / f"{self.name}.log"
log_file.parent.mkdir(parents=True, exist_ok=True)
get_logger().debug(f"Spawning env server {self.name} (id={self.config.env_id}, log={log_file})")
server_kwargs = (
dict(
legacy=True,
env_id=self.config.env_id,
env_args=self.config.args,
extra_env_kwargs=self.config.extra_env_kwargs,
)
if self.config.is_legacy
else dict(legacy=False, config=self.config)
)
process = ctx.Process(
target=_run_env_server,
kwargs=dict(
address=address,
log_file=str(log_file),
log_level=log_level,
json_logging=json_logging,
console_logging=False,
num_workers=num_workers,
**vf.pool_serve_kwargs(self.config.pool),
address="tcp://127.0.0.1:0",
address_queue=address_queue,
**server_kwargs,
),
daemon=False,
)
process.start()
self._env_server_process = process
try:
address = await asyncio.to_thread(address_queue.get, timeout=ENV_SERVER_SPAWN_TIMEOUT)
except queue.Empty:
raise RuntimeError(f"Env server {self.name} did not report its address within {ENV_SERVER_SPAWN_TIMEOUT}s")
finally:
address_queue.close()
address_queue.join_thread()
get_logger().debug(f"Env server {self.name} bound at {address}")
return address
def _sampling_args_with_salt(self, cache_salt: str | None) -> dict:
sampling_args = {**self.sampling_args}
if cache_salt is None:
return sampling_args
extra_body = {**sampling_args.get("extra_body", {}), "cache_salt": cache_salt}
sampling_args["extra_body"] = extra_body
return sampling_args
@property
def state_columns(self) -> list[str]:
"""Required columns plus any extras configured on the env, deduped (required first)."""
merged: list[str] = []
for col in (*REQUIRED_STATE_COLUMNS, *self.config.state_columns):
if col not in merged:
merged.append(col)
return merged
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
sampling = {**self.sampling_args}
if cache_salt is not None:
sampling["extra_body"] = {**sampling.get("extra_body", {}), "cache_salt": cache_salt}
return vf.SamplingConfig(**sampling)
async def run_rollout(
self,
client: vf.ClientConfig,
example: dict,
model_name: str,
cache_salt: str | None,
) -> vf.RolloutOutput:
"""Run a single rollout for an example."""
return await self.env.run_rollout(
vf.RolloutInput(**example),
self, client: vf.ClientConfig, task_idx: int, model_name: str, cache_salt: str | None
) -> Rollout:
"""Run a single rollout for ``task_idx``; return a typed Trace."""
wire = await self.env_client.run_rollout(
task_idx=task_idx,
client=client,
model=model_name,
sampling_args=self._sampling_args_with_salt(cache_salt),
max_retries=self.config.max_retries,
state_columns=self.state_columns,
env_client=self.env_client,
sampling=self._sampling(cache_salt),
)
return ROLLOUT_TYPE.model_construct(**dict(wire))
async def run_group(
self,
client: vf.ClientConfig,
example: dict,
model_name: str,
group_size: int,
cache_salt: str | None,
) -> list[vf.RolloutOutput]:
"""Run a group of rollouts for an example. Required for group-scoring envs."""
return await self.env.run_group(
[vf.RolloutInput(**example) for _ in range(group_size)],
self, client: vf.ClientConfig, task_idx: int, model_name: str, group_size: int, cache_salt: str | None
) -> list[Rollout]:
"""Run a group of rollouts for ``task_idx`` (group-scoring envs); return typed Traces."""
wires = await self.env_client.run_group(
task_idx=task_idx,
n=group_size,
client=client,
model=model_name,
sampling_args=self._sampling_args_with_salt(cache_salt),
max_retries=self.config.max_retries,
state_columns=self.state_columns,
env_client=self.env_client,
sampling=self._sampling(cache_salt),
)
return [ROLLOUT_TYPE.model_construct(**dict(wire)) for wire in wires]
def shutdown(self) -> None:
if self._env_server_process is None:
@@ -162,18 +202,14 @@ class Env:
class TrainEnv(Env):
config: TrainEnvConfig
def __init__(self, config: TrainEnvConfig):
def __init__(self, config: TrainEnvConfig, max_seq_len: int):
super().__init__(config)
self.sampling_args = config.sampling.to_sampling_args()
# Built once — custom advantage funcs do an ``import_object`` we don't
# want to pay per group. ``None`` = reward-only path.
# Built once — custom advantage funcs do an ``import_object`` we don't want to pay per group.
self.advantage_fn: AdvantageFn | None = (
setup_advantage_fn(config.advantage) if config.advantage is not None else None
setup_advantage_fn(config.advantage, max_seq_len=max_seq_len) if config.advantage is not None else None
)
def get_dataset(self, seed: int | None = None):
return self.env.get_dataset(seed=seed)
class EvalEnv(Env):
config: EvalEnvConfig
@@ -181,7 +217,12 @@ class EvalEnv(Env):
def __init__(self, config: EvalEnvConfig):
super().__init__(config)
self.sampling_args = config.sampling.to_sampling_args()
self.examples = self.env.get_eval_dataset(n=config.num_examples).to_list()
self.examples: list[dict] = []
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
await super().start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
self.examples = [{"task_idx": i} for i in range(n)]
EnvT = TypeVar("EnvT", bound=Env)
@@ -209,23 +250,15 @@ class Envs(Generic[EnvT]):
def __len__(self) -> int:
return len(self._envs)
async def start(
self,
log_dir: Path,
log_level: str | None = None,
json_logging: bool = False,
) -> None:
"""Spawn env servers (where needed) and connect env clients one at a time.
Serialized to avoid a TOCTOU port race: get_free_port() only holds the port
until it returns, so parallel spawns can hand the same port to two children.
"""
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
"""Spawn env servers (where needed) and connect, one at a time. Each server
binds an OS-assigned port and reports it back, so there's no port race."""
for env in self:
await env.start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
atexit.register(self.shutdown)
def shutdown(self) -> None:
"""Terminate all spawned env server processes in parallel."""
"""Terminate all spawned env server processes."""
processes = [env._env_server_process for env in self if env._env_server_process is not None]
if not processes:
return
@@ -246,10 +279,10 @@ class Envs(Generic[EnvT]):
class TrainEnvs(Envs[TrainEnv]):
"""Collection of training environments."""
def __init__(self, configs: Sequence[TrainEnvConfig]):
def __init__(self, configs: Sequence[TrainEnvConfig], max_seq_len: int):
self._envs: dict[str, TrainEnv] = {}
for config in configs:
env = TrainEnv(config)
env = TrainEnv(config, max_seq_len=max_seq_len)
self._envs[env.name] = env
+16 -16
View File
@@ -18,7 +18,7 @@ from collections import defaultdict
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.eval_utils import compute_pass_at_k
from prime_rl.orchestrator.types import EvalBatch, EvalBatchMetrics, EvalRollout
from prime_rl.orchestrator.types import EvalBatch, EvalBatchMetrics, Rollout
from prime_rl.utils.logger import get_logger
@@ -27,12 +27,12 @@ class EvalSink:
def __init__(self, *, eval_envs: EvalEnvs) -> None:
self.eval_envs = eval_envs
self.pending_groups: dict[uuid.UUID, list[EvalRollout]] = defaultdict(list)
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
# Bucket size IS the arrival count — ``process_group`` flushes
# everything in without filtering
self.pending_batches: dict[tuple[str, int], list[EvalRollout]] = defaultdict(list)
self.pending_batches: dict[tuple[str, int], list[Rollout]] = defaultdict(list)
def add(self, rollout: EvalRollout) -> EvalBatch | None:
def add(self, rollout: Rollout) -> EvalBatch | None:
"""Process one arrival; finalize the group on the ``group_size``-th
arrival and the per-env epoch on the ``num_examples × group_size``-th."""
env_name = rollout.env_name
@@ -82,7 +82,7 @@ class EvalSink:
# ── level 1: per-rollout (no-op for eval) ─────────────────────────────
def process_rollout(self, rollout: EvalRollout) -> None:
def process_rollout(self, rollout: Rollout) -> None:
"""No-op. Eval rollouts don't need trainer-bound tokenization; the
method exists to keep the three-level structure uniform with
``TrainSink``.
@@ -96,17 +96,17 @@ class EvalSink:
if not group:
return
env_name = group[0].env_name
example_id = group[0].example_id
task_idx = group[0].task.idx
eval_step = group[0].eval_step
bucket = self.pending_batches[(env_name, eval_step)]
bucket.extend(group)
survivors = [r for r in group if r.error is None]
survivors = [r for r in group if not r.has_error]
num_errored = len(group) - len(survivors)
rewards = [r.reward for r in survivors]
avg_reward = sum(rewards) / len(rewards) if rewards else 0.0
get_logger().debug(
f"Finished group | env={env_name} example_id={example_id} eval_step={eval_step} | "
f"Finished group | env={env_name} task_idx={task_idx} eval_step={eval_step} | "
f"rollouts={len(group)} (errored={num_errored}) | reward={avg_reward:.4f}"
)
@@ -120,9 +120,9 @@ class EvalSink:
rollouts = self.pending_batches.pop(key, [])
n_total = len(rollouts)
n_cancelled = sum(1 for r in rollouts if (r.error or {}).get("error") == "Cancelled")
n_errored = sum(1 for r in rollouts if r.error is not None) - n_cancelled
valid = [r for r in rollouts if r.error is None]
n_cancelled = sum(1 for r in rollouts if r.has_error and r.error.type == "Cancelled")
n_errored = sum(1 for r in rollouts if r.has_error) - n_cancelled
valid = [r for r in rollouts if not r.has_error]
metrics = EvalBatchMetrics(
n_rollouts=n_total,
n_cancelled=n_cancelled,
@@ -131,23 +131,23 @@ class EvalSink:
if valid:
rewards = [r.reward for r in valid]
lens = [r.raw["token_usage"]["final_output_tokens"] for r in valid]
lens = [r.completion_len for r in valid]
metrics.group_size = self.group_size_for(env_name)
metrics.reward_mean = float(sum(rewards) / len(rewards))
metrics.completion_len_mean = float(sum(lens) / len(lens))
metrics.completion_len_max = float(max(lens))
metrics.completion_len_min = float(min(lens))
metrics.truncation_rate = float(sum(1 for r in valid if r.is_truncated) / len(valid))
metrics.no_response_rate = float(sum(1 for r in valid if not r.raw.get("completion")) / len(valid))
num_turns = [len(r.raw.get("trajectory") or []) for r in valid]
metrics.no_response_rate = float(sum(1 for r in valid if not r.has_response) / len(valid))
num_turns = [r.num_turns for r in valid]
metrics.num_turns_mean = float(sum(num_turns) / len(num_turns))
metrics.num_turns_min = float(min(num_turns))
metrics.num_turns_max = float(max(num_turns))
# pass@k: errored attempts don't count toward k tries
by_example: dict[int | str, list[float]] = {}
by_example: dict[int, list[float]] = {}
for r in valid:
by_example.setdefault(r.example_id, []).append(r.reward)
by_example.setdefault(r.task.idx, []).append(r.reward)
metrics.n_examples = len(by_example)
unique_rewards = {float(r) for r in rewards}
if unique_rewards.issubset({0.0, 1.0}) and by_example:
+22 -18
View File
@@ -16,7 +16,7 @@ from prime_rl.configs.orchestrator import FilterConfig
from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
from prime_rl.orchestrator.types import TrainRollout
from prime_rl.orchestrator.types import Rollout
@dataclass
@@ -29,7 +29,7 @@ class RolloutFilter(Protocol):
name: str
enforce: bool
def check(self, rollout: "TrainRollout") -> FilterResult: ...
def check(self, rollout: Rollout) -> FilterResult: ...
@dataclass
@@ -49,13 +49,15 @@ class GibberishFilter:
logprob_threshold: float
enforce: bool = False
def check(self, rollout: "TrainRollout") -> FilterResult:
def check(self, rollout: Rollout) -> FilterResult:
global_idx = 0
for step in rollout.raw["trajectory"]:
tokens = step["tokens"]
if tokens is None:
continue
for token_id, logprob in zip(tokens["completion_ids"], tokens["completion_logprobs"]):
for branch in rollout.branches:
# branch.{token_ids,logprobs,sampled_mask} are flat and mutually aligned; the raw
# node arrays are not (node.logprobs covers only the sampled suffix, not the
# generation-prompt scaffold that token_ids/mask also span).
for token_id, logprob, sampled in zip(branch.token_ids, branch.logprobs, branch.sampled_mask):
if not sampled:
continue
if token_id > self.token_id_threshold and logprob < self.logprob_threshold:
return FilterResult(detected=True, detection_index=global_idx)
global_idx += 1
@@ -79,14 +81,16 @@ class RepetitionFilter:
logprob_threshold: float
enforce: bool = False
def check(self, rollout: "TrainRollout") -> FilterResult:
consecutive = 0
def check(self, rollout: Rollout) -> FilterResult:
global_idx = 0
for step in rollout.raw["trajectory"]:
tokens = step["tokens"]
if tokens is None:
continue
for logprob in tokens["completion_logprobs"]:
for branch in rollout.branches:
# Aligned branch streams (see GibberishFilter), and reset the streak per branch:
# flat rollout.nodes interleaves distinct root->leaf paths (compaction/subagents),
# so a per-node walk would run a streak across a branch boundary.
consecutive = 0
for logprob, sampled in zip(branch.logprobs, branch.sampled_mask):
if not sampled:
continue
if logprob > self.logprob_threshold:
consecutive += 1
else:
@@ -105,7 +109,7 @@ class ZeroAdvantageFilter:
name: str
enforce: bool = True
def check(self, rollout: "TrainRollout") -> FilterResult:
def check(self, rollout: Rollout) -> FilterResult:
if rollout.advantage is not None and rollout.advantage == 0.0:
return FilterResult(detected=True)
return FilterResult(detected=False)
@@ -147,8 +151,8 @@ def setup_filters(configs: list[FilterConfig], vocab_size: int, *, kind: str) ->
return filters
def apply_filters(filters: list[RolloutFilter], rollouts: list["TrainRollout"]) -> None: # noqa: F821 (forward ref)
"""Flag ``TrainRollout``\\ s in place with per-filter detection + drop decision.
def apply_filters(filters: list[RolloutFilter], rollouts: list[Rollout]) -> None:
"""Flag ``Rollout``\\ s in place with per-filter detection + drop decision.
Each rollout's ``filter_results`` dict records per-filter detection bools;
``is_filtered`` is True iff an enforcing filter detected it. First matching
+18 -60
View File
@@ -1,9 +1,4 @@
"""MetricsBuilder: assembles the per-step W&B dict.
The only I/O / state is the trainer's token-export metrics, which lag the
orchestrator: ``build`` folds in the oldest unlogged stable step it finds on
disk and tracks the last step logged so it never re-logs one.
"""
"""MetricsBuilder: assembles the per-step W&B dict. No I/O, no side effects."""
from __future__ import annotations
@@ -12,22 +7,18 @@ from typing import Any
import pandas as pd
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.token_export_metrics import collect_next_token_export_metrics
from prime_rl.orchestrator.types import Progress, TrainBatchMetrics, TrainRollout
from prime_rl.orchestrator.types import Progress, Rollout, TrainBatchMetrics
class MetricsBuilder:
def __init__(self, config: OrchestratorConfig, start_step: int = 0) -> None:
def __init__(self, config: OrchestratorConfig) -> None:
self.config = config
# Token exports are read back one step behind the orchestrator; track the
# last run step whose metrics we've folded in so we never re-log a step.
self._last_token_export_step_logged = start_step - 1
def build(
self,
*,
step: int,
rollouts: list[TrainRollout],
rollouts: list[Rollout],
metrics: TrainBatchMetrics,
progress: Progress,
step_time: float,
@@ -41,30 +32,25 @@ class MetricsBuilder:
existing dashboards / alerts keep working."""
num_rollouts = len(rollouts)
num_unique_examples = len({r.group_id for r in rollouts})
num_tokens = sum(
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"] for r in rollouts
)
num_tokens = sum(r.total_tokens for r in rollouts)
results_df = pd.DataFrame(
{
"group_id": [r.group_id for r in rollouts],
"example_id": [r.example_id for r in rollouts],
"task_idx": [r.task.idx for r in rollouts],
"env_name": [r.env_name for r in rollouts],
"reward": [r.reward for r in rollouts],
"is_truncated": [r.is_truncated for r in rollouts],
"is_filtered": [r.is_filtered for r in rollouts],
"stop_condition": [r.raw.get("stop_condition") for r in rollouts],
"seq_len": [
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
for r in rollouts
],
"stop_condition": [r.stop_condition for r in rollouts],
"seq_len": [r.total_tokens for r in rollouts],
"prefill_len": metrics.rollout_prefill_lens,
"decode_len": metrics.rollout_decode_lens,
"samples_per_rollout": metrics.samples_per_rollout,
"num_turns": [len(r.raw["trajectory"]) for r in rollouts],
"num_turns": [r.num_turns for r in rollouts],
}
)
metrics_df = pd.DataFrame([(r.raw.get("metrics") or {}) for r in rollouts])
metrics_df = pd.DataFrame([r.metrics for r in rollouts])
filter_df = pd.DataFrame([r.filter_results for r in rollouts])
timing_df = self.timing_df(rollouts)
@@ -188,42 +174,14 @@ class MetricsBuilder:
for name, count in pre_filter_dropped_by_name.items():
to_log[f"pre_filters/all/{name}/rate"] = count / pre_filter_seen
# Fold in the trainer's token-export metrics for the oldest unlogged stable
# step (exports always lag the orchestrator, so this is a past step).
to_log.update(self.next_token_export_metrics())
return to_log
@property
def last_token_export_step_logged(self) -> int:
return self._last_token_export_step_logged
def next_token_export_metrics(self) -> dict[str, float | int]:
"""Log-ready token-export metrics for the next unlogged stable step (empty if
none), advancing the cursor. They arrive under trainer/, including trainer/step
(the run step they belong to) for plotting against a lag-corrected axis. Shared
by build() and the orchestrator's end-of-run drain."""
token_export = collect_next_token_export_metrics(
self.config.output_dir,
last_logged_step=self._last_token_export_step_logged,
)
if token_export:
self._last_token_export_step_logged = token_export["trainer/step"]
return token_export
@staticmethod
def timing_df(rollouts: list[TrainRollout]) -> pd.DataFrame:
return pd.DataFrame(
[
{
"total": r.raw["timing"]["total"],
"setup": r.raw["timing"]["setup"]["duration"],
"generation": r.raw["timing"]["generation"]["duration"],
"model": r.raw["timing"]["model"]["duration"],
"env": r.raw["timing"]["env"]["duration"],
"scoring": r.raw["timing"]["scoring"]["duration"],
"overhead": r.raw["timing"]["overhead"],
}
for r in rollouts
]
)
def timing_df(rollouts: list[Rollout]) -> pd.DataFrame:
"""Per-rollout timing from the v1 Trace (`generation`/`scoring` spans)."""
rows = []
for r in rollouts:
timing = r.timing
generation, scoring = timing.generation.duration, timing.scoring.duration
rows.append({"total": generation + scoring, "generation": generation, "scoring": scoring})
return pd.DataFrame(rows)
+44 -88
View File
@@ -21,8 +21,6 @@ in ``setup()`` and drives them from ``main_loop()``.
from __future__ import annotations
import asyncio
import ctypes
import logging
import os
import time
from typing import TYPE_CHECKING
@@ -37,8 +35,6 @@ if TYPE_CHECKING:
from prime_rl.transport.base import TrainingBatchSender
from prime_rl.utils.client import InferencePool
from prime_rl.utils.monitor.base import Monitor
from verifiers.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
@@ -58,12 +54,10 @@ from prime_rl.orchestrator.train_sink import TrainSink
from prime_rl.orchestrator.train_source import TrainSource
from prime_rl.orchestrator.types import (
EvalBatch,
EvalRollout,
FinishedRollout,
Policy,
Progress,
Rollout,
TrainBatch,
TrainRollout,
)
from prime_rl.orchestrator.utils import (
compute_teacher_logprobs,
@@ -72,11 +66,12 @@ from prime_rl.orchestrator.utils import (
save_rollouts,
set_default_executor,
setup_student_inference_pool,
trim_process_memory,
)
from prime_rl.orchestrator.watcher import WeightWatcher
from prime_rl.trainer.model import setup_tokenizer
from prime_rl.transport import TrainingBatch, setup_training_batch_sender
from prime_rl.utils.async_utils import safe_cancel
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
from prime_rl.utils.client import init_nccl_broadcast, setup_inference_pool
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
@@ -85,8 +80,6 @@ from prime_rl.utils.pathing import get_log_dir, get_rollout_dir, get_step_path
from prime_rl.utils.usage_reporter import UsageReporter
from prime_rl.utils.utils import (
clean_exit,
get_env_ids_to_install,
install_env,
resolve_latest_ckpt_step,
)
@@ -108,10 +101,12 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
# resumed when the watcher advances ``policy.version``.
TARGET_LAG = 1
# After max_steps, how long to wait for the trainer to finalize the trailing
# token-export steps it hadn't flushed yet, and how often to poll for them.
TOKEN_EXPORT_DRAIN_TIMEOUT_S = 300.0
TOKEN_EXPORT_DRAIN_POLL_S = 2.0
# Drop the per-node training tensors when dumping a Trace to disk (rollout jsonl / wandb
# tables): the multimodal `mm_kwargs` carrier and the router-replay `routed_experts` array are
# training inputs, not part of the rollout record, and would bloat every line. They also can't
# round-trip the json dump — their `__nd__` carriers hold raw bytes. `__all__` applies the
# exclude to every node in the list.
ROLLOUT_DUMP_EXCLUDE = {"nodes": {"__all__": {"multi_modal_data", "routed_experts"}}}
class Orchestrator:
@@ -158,10 +153,9 @@ class Orchestrator:
def __init__(self, config: OrchestratorConfig) -> None:
self.config = config
setup_logger(config.log.level, json_logging=config.log.json_logging)
# Silence in-process ``verifiers.*`` library noise but keep
# ``verifiers.serve`` (env-server lifecycle) through our handler
logging.getLogger("verifiers").setLevel(logging.CRITICAL + 1)
intercept_vf_logging(logger="verifiers.serve", level="WARN")
# Route the in-process v1 library logging through our handler. The
# env server runs in a child process, so its logging is separate.
intercept_vf_logging(logger="verifiers.v1", level="WARN")
get_logger().info(f"Starting orchestrator ({config.training_mode})")
if config.bench:
@@ -211,12 +205,6 @@ class Orchestrator:
with open(config_dir / "orch.toml", "wb") as f:
tomli_w.dump(config.model_dump(exclude_none=True, mode="json"), f)
env_ids_to_install = set(get_env_ids_to_install(config.train.env))
if config.eval is not None:
env_ids_to_install.update(get_env_ids_to_install(config.eval.env))
for env_id in env_ids_to_install:
install_env(env_id, prerelease=config.env_install_prerelease)
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
self.tokenizer = setup_tokenizer(config.tokenizer)
@@ -242,7 +230,11 @@ class Orchestrator:
self.teacher_inference = await setup_inference_pool(
config.teacher.client,
model_name=config.teacher.model.name,
train_client_type="openai_chat_completions",
# SFT rolls the teacher out through the renderer client (token-in/out) so its
# rollouts carry tokens directly — training is renderer-only. (OPD reads teacher
# logprobs via prefill, so its pool client type is moot.)
train_client_type="renderer",
renderer_config=config.renderer,
)
get_logger().info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
@@ -268,7 +260,7 @@ class Orchestrator:
post_filters = setup_filters(config.post_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="post-batch")
get_logger().info("Loading training environments")
self.train_envs = TrainEnvs(config.train.env)
self.train_envs = TrainEnvs(config.train.env, max_seq_len=config.seq_len)
if config.training_mode == "sft":
for env in self.train_envs:
env.sampling_args.pop("logprobs", None)
@@ -387,11 +379,10 @@ class Orchestrator:
training_mode=config.training_mode,
use_cache_salt=use_cache_salt,
)
self.metrics = MetricsBuilder(config, start_step=self.progress.step)
self.metrics = MetricsBuilder(config)
self.train_sink = TrainSink(
config,
tokenizer=self.tokenizer,
renderer=self.renderer,
train_envs=self.train_envs,
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
batch_size=config.batch_size,
@@ -465,7 +456,6 @@ class Orchestrator:
clean_exit = False
try:
await self.main_loop()
await self._drain_token_export_metrics()
clean_exit = True
finally:
elapsed = format_time(time.perf_counter() - start_time)
@@ -482,10 +472,7 @@ class Orchestrator:
get_logger().success("Orchestrator finished.")
else:
get_logger().warning("Orchestrator cleanup complete (forced).")
try:
ctypes.CDLL("libc.so.6").malloc_trim(0)
except Exception as e:
get_logger().debug(f"malloc_trim(0) failed: {e}")
trim_process_memory()
async def main_loop(self) -> None:
"""Consume ``FinishedRollout``\\ s from the dispatcher and route them
@@ -498,53 +485,23 @@ class Orchestrator:
break
try:
rollout: FinishedRollout = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
rollout: Rollout = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
except asyncio.TimeoutError:
continue
if isinstance(rollout, EvalRollout):
if rollout.kind == "eval":
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
eval_batch = self.eval_sink.add(rollout)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
continue
assert isinstance(rollout, TrainRollout)
train_batch = await self.train_sink.add(rollout)
# In drain mode any late-arriving train batch is dropped — we
# don't want to ship past ``max_steps``
if train_batch is not None and not self.draining and not self.stopped.is_set():
await self.finalize_train_batch(train_batch)
async def _drain_token_export_metrics(self) -> None:
"""Token exports lag the orchestrator, so once the loop ends the trainer is
still finalizing the last shipped steps and ``build`` no longer runs to pick
them up. Poll for the remaining stable steps up to ``max_steps - 1`` and log
each under its own ``trainer/step`` (a local W&B step axis, so the final
checkpoint's ``progress.step`` is untouched)."""
if self.config.max_steps is None:
return
if not (self.config.output_dir / "token_exports").exists():
return # token export not enabled for this run — don't block shutdown
target = self.config.max_steps - 1
if self.metrics.last_token_export_step_logged >= target:
return # build() already kept up — nothing trailing to flush
wandb_step = self.progress.step
deadline = time.perf_counter() + TOKEN_EXPORT_DRAIN_TIMEOUT_S
while time.perf_counter() < deadline:
token_export = self.metrics.next_token_export_metrics()
if not token_export:
await asyncio.sleep(TOKEN_EXPORT_DRAIN_POLL_S)
continue
self.monitor.log(token_export, step=wandb_step)
wandb_step += 1
if self.metrics.last_token_export_step_logged >= target:
return
get_logger().warning(
f"Token-export drain timed out before step {target} "
f"(last logged {self.metrics.last_token_export_step_logged})"
)
async def finalize_train_batch(self, batch: TrainBatch) -> None:
"""Ship one ``TrainBatch`` out to the trainer and handle the I/O
side-effects (ckpt, save_rollouts, teacher logprobs, sender.send,
@@ -591,13 +548,11 @@ class Orchestrator:
f"({batch.metrics.n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
)
# Materialize at the I/O boundary so prime-rl metadata travels with
# the raw vf payload on disk + in wandb sample tables
rollout_dicts = [r.to_dict() for r in batch.rollouts]
# Serialize the typed Trace at the I/O boundary (disk + wandb sample tables); drop the
# per-node multimodal tensors — they're for training, not the rollout record, and bloat it.
rollout_dicts = [r.model_dump(mode="json", exclude=ROLLOUT_DUMP_EXCLUDE) for r in batch.rollouts]
step_path = get_step_path(get_rollout_dir(config.output_dir), step)
await asyncio.to_thread(
save_rollouts, rollout_dicts, step_path / "train_rollouts.jsonl", exclude_keys={"trajectory"}
)
await asyncio.to_thread(save_rollouts, rollout_dicts, step_path / "train_rollouts.jsonl")
teacher_logprobs_time = 0.0 # opd only
if config.training_mode == "opd" and self.teacher_inference is not None:
@@ -614,6 +569,7 @@ class Orchestrator:
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
self.update_dispatch_gate()
trim_process_memory()
metrics = self.metrics.build(
step=step,
@@ -628,7 +584,7 @@ class Orchestrator:
pre_filter_dropped_by_name=dict(self.train_sink.pre_filter_dropped_by_name),
)
self.monitor.log(metrics, step=step)
self.monitor.log_samples(rollout_dicts, step=step)
self.monitor.log_samples(batch.rollouts, step=step)
self.monitor.log_distributions(
distributions={
"rewards": [r.reward for r in batch.rollouts],
@@ -650,10 +606,7 @@ class Orchestrator:
num_rollouts = len(batch.rollouts)
num_unique_examples = len({r.group_id for r in batch.rollouts})
num_tokens = sum(
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
for r in batch.rollouts
)
num_tokens = sum(r.total_tokens for r in batch.rollouts)
self.progress.total_tokens += num_tokens
self.progress.total_samples += num_rollouts
self.progress.total_problems += num_unique_examples
@@ -663,6 +616,7 @@ class Orchestrator:
self.train_sink.reset_pre_filter_stats()
self.progress.step += 1
self.maybe_trigger_eval(self.progress.step)
trim_process_memory()
def maybe_trigger_eval(self, step: int) -> None:
"""Fire eligible eval epochs and flip to ``PREFER_EVAL`` if anything
@@ -760,13 +714,14 @@ class Orchestrator:
trainable_rate = (n_trainable / n_survivors) if n_survivors else 0.0
reward_mean = sum(r.reward for r in batch.rollouts) / max(n_survivors, 1)
max_off_policy = max((r.off_policy_steps for r in batch.rollouts), default=0)
turns_mean = sum(len(r.raw.get("trajectory") or []) for r in batch.rollouts) / max(n_survivors, 1)
turns_mean = sum(r.num_turns for r in batch.rollouts) / max(n_survivors, 1)
branches_mean = sum(r.num_branches for r in batch.rollouts) / max(n_survivors, 1)
truncation_rate = sum(1 for r in batch.rollouts if r.is_truncated) / max(n_survivors, 1)
head = (
f"Step {step} | {format_time(step_time):>7} | Reward {reward_mean:.4f} | "
f"Trainable {n_trainable}/{n_survivors} ({trainable_rate:.1%}) | "
f"Turns {turns_mean:.1f} | Max Off-Policy {max_off_policy} | "
f"Turns {turns_mean:.1f} | Branches {branches_mean:.1f} | Max Off-Policy {max_off_policy} | "
f"Error {error_rate:.1%} | Truncation {truncation_rate:.1%}"
)
if len(self.train_envs) <= 1:
@@ -784,15 +739,12 @@ class Orchestrator:
env_error_rate = (n_env_errors / n_env_arrivals) if n_env_arrivals else 0.0
env_reward = (sum(r.reward for r in env_rollouts) / len(env_rollouts)) if env_rollouts else 0.0
env_max_off_policy = max((r.off_policy_steps for r in env_rollouts), default=0)
env_turns = (
sum(len(r.raw.get("trajectory") or []) for r in env_rollouts) / len(env_rollouts)
if env_rollouts
else 0.0
)
env_turns = sum(r.num_turns for r in env_rollouts) / len(env_rollouts) if env_rollouts else 0.0
env_branches = sum(r.num_branches for r in env_rollouts) / len(env_rollouts) if env_rollouts else 0.0
env_truncation = sum(1 for r in env_rollouts if r.is_truncated) / len(env_rollouts) if env_rollouts else 0.0
lines.append(
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_reward:.4f} | "
f"Turns {env_turns:.1f} | Max Off-Policy {env_max_off_policy} | "
f"Turns {env_turns:.1f} | Branches {env_branches:.1f} | Max Off-Policy {env_max_off_policy} | "
f"Error {env_error_rate:.1%} | Truncation {env_truncation:.1%}"
)
get_logger().success("\n\t\t ".join(lines))
@@ -804,15 +756,14 @@ class Orchestrator:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no surviving rollouts, skipping log")
return
rollout_dicts = [r.to_dict() for r in batch.rollouts]
rollout_dicts = [r.model_dump(mode="json", exclude=ROLLOUT_DUMP_EXCLUDE) for r in batch.rollouts]
step_path = get_step_path(get_rollout_dir(self.config.output_dir), batch.step)
await asyncio.to_thread(
save_rollouts,
rollout_dicts,
step_path / f"eval_rollouts_{batch.env_name}.jsonl",
exclude_keys={"trajectory"},
)
self.monitor.log_eval_samples(rollout_dicts, env_name=batch.env_name, step=batch.step)
self.monitor.log_eval_samples(batch.rollouts, env_name=batch.env_name, step=batch.step)
policy_versions = {r.policy_version for r in batch.rollouts}
policy_version = min(policy_versions)
if len(policy_versions) > 1:
@@ -827,11 +778,12 @@ class Orchestrator:
error_rate = ((batch.metrics.n_cancelled + batch.metrics.n_errored) / n_total) if n_total else 0.0
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
branches_mean = sum(r.num_branches for r in batch.rollouts) / len(batch.rollouts)
get_logger().success(
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {batch.metrics.reward_mean:.4f} | "
f"Turns {batch.metrics.num_turns_mean:.1f} | "
f"Turns {batch.metrics.num_turns_mean:.1f} | Branches {branches_mean:.1f} | "
f"Error {error_rate:.1%} | Truncation {batch.metrics.truncation_rate:.1%}"
)
@@ -876,6 +828,10 @@ class Orchestrator:
get_logger().info("Resuming dispatcher")
gate.set()
async def on_version_pending(self, step: int) -> None:
"""No-op: the dispatch gate is re-evaluated in ``on_new_version`` once
the new policy version is live."""
async def on_new_version(self, step: int) -> None:
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
@@ -1,116 +0,0 @@
from __future__ import annotations
import json
import math
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from prime_rl.utils.logger import get_logger
TOKEN_EXPORT_METRIC_FIELDS = ("mismatch_kl", "entropy")
@dataclass
class _Stats:
total: float = 0.0
count: int = 0
maximum: float = -math.inf
def add(self, value: Any) -> None:
if not isinstance(value, int | float):
return
value = float(value)
if not math.isfinite(value):
return
self.total += value
self.count += 1
self.maximum = max(self.maximum, value)
def as_metrics(self, prefix: str) -> dict[str, float]:
if self.count == 0:
return {}
return {
f"{prefix}/mean": self.total / self.count,
f"{prefix}/max": self.maximum,
}
def collect_next_token_export_metrics(output_dir: Path, *, last_logged_step: int) -> dict[str, float | int]:
"""Log-ready metrics for the oldest unlogged stable step, namespaced under
``trainer/`` and stamped with ``trainer/step`` (the run step they belong to).
Empty when there is no new stable step."""
stable_steps = [step for step in _stable_token_export_steps(output_dir) if step > last_logged_step]
if not stable_steps:
return {}
step = min(stable_steps)
metrics: dict[str, float | int] = {
f"trainer/{key}": value for key, value in collect_token_export_metrics(output_dir, step).items()
}
metrics["trainer/step"] = step
return metrics
def collect_token_export_metrics(output_dir: Path, step: int) -> dict[str, float | int]:
step_dir = output_dir / "token_exports" / f"step_{step}"
if not (step_dir / "STABLE").exists():
return {}
stats_by_key: dict[str, _Stats] = {}
sequence_count = 0
skipped_count = 0
for export_file in sorted(step_dir.glob("rank_*.jsonl")):
with export_file.open(encoding="utf-8") as file:
for line in file:
if not line.strip():
continue
# Token exports are best-effort monitoring; a malformed line or a
# length-mismatched record shouldn't abort the orchestrator step.
try:
record = json.loads(line)
values_by_field = {field: _loss_token_values(record, field) for field in TOKEN_EXPORT_METRIC_FIELDS}
except ValueError:
skipped_count += 1
continue
sequence_count += 1
for field, values in values_by_field.items():
for value in values:
stats_by_key.setdefault(field, _Stats()).add(value)
if skipped_count:
get_logger().warning(f"Skipped {skipped_count} malformed token-export record(s) in {step_dir}")
metrics: dict[str, float | int] = {}
if sequence_count == 0:
return metrics
for key, stats in sorted(stats_by_key.items()):
metrics.update(stats.as_metrics(key))
return metrics
def _stable_token_export_steps(output_dir: Path) -> list[int]:
token_exports_dir = output_dir / "token_exports"
if not token_exports_dir.exists():
return []
steps = []
for step_dir in token_exports_dir.glob("step_*"):
if not (step_dir / "STABLE").exists():
continue
try:
steps.append(int(step_dir.name.removeprefix("step_")))
except ValueError:
continue
return sorted(steps)
def _loss_token_values(record: dict[str, Any], field: str) -> list[Any]:
loss_mask = record.get("loss_mask", [])
values = record.get(field, [])
if len(loss_mask) != len(values):
raise ValueError(
f"Token export record has mismatched loss_mask and {field} lengths: {len(loss_mask)} != {len(values)}"
)
return [value for value, keep in zip(values, loss_mask) if keep]
+40 -54
View File
@@ -21,12 +21,8 @@ from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.advantage import assign_advantages
from prime_rl.orchestrator.envs import TrainEnvs
from prime_rl.orchestrator.filters import RolloutFilter, apply_filters
from prime_rl.orchestrator.trajectories import (
backfill_rollout_tokens,
interleave_rollout,
offload_images_to_disk,
)
from prime_rl.orchestrator.types import TrainBatch, TrainBatchMetrics, TrainRollout
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.orchestrator.types import Rollout, TrainBatch, TrainBatchMetrics
from prime_rl.transport import TrainingSample
from prime_rl.utils.logger import get_logger
@@ -39,7 +35,6 @@ class TrainSink:
config: OrchestratorConfig,
*,
tokenizer,
renderer,
train_envs: TrainEnvs,
mm_token_type_ids_mapping: dict[int, int] | None,
batch_size: int | None,
@@ -52,7 +47,6 @@ class TrainSink:
)
self.config = config
self.tokenizer = tokenizer
self.renderer = renderer
self.train_envs = train_envs
self.mm_token_type_ids_mapping = mm_token_type_ids_mapping
self.batch_size = batch_size
@@ -60,11 +54,15 @@ class TrainSink:
self.pre_filters = pre_filters
self.post_filters = post_filters
# Keyed by the dispatcher's group UUID. ``(env_name, example_id)``
# isn't unique — the same example can be re-sampled while an
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
# isn't unique — the same task can be re-sampled while an
# earlier group is still in flight
self.pending_groups: dict[uuid.UUID, list[TrainRollout]] = defaultdict(list)
self.pending_batch: list[TrainRollout] = []
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
self.pending_batch: list[Rollout] = []
# Running token total of ``pending_batch`` (token-batched runs), kept in
# sync on append/pop so the readiness check never re-walks the uncached
# ``Trace.total_tokens`` graph property per arrival.
self.pending_tokens: int = 0
# Reset by the orchestrator after each ship via ``reset_pre_filter_stats``
self.pre_filter_seen = 0
@@ -79,13 +77,13 @@ class TrainSink:
def group_size_for(self, env_name: str) -> int:
return self.train_envs.get(env_name).config.group_size
def in_progress_groups(self) -> list[list[TrainRollout]]:
def in_progress_groups(self) -> list[list[Rollout]]:
"""Per-rollout groups currently accumulating in ``pending_groups`` —
i.e. groups that haven't hit ``group_size`` yet, so the pipeline log
can reflect partial-group progress. Skips group-scoring envs (whose
rollouts only make sense as a unit — the user expects per-group
fill, not per-rollout, for those)."""
out: list[list[TrainRollout]] = []
out: list[list[Rollout]] = []
for rollouts in self.pending_groups.values():
if not rollouts:
continue
@@ -103,11 +101,7 @@ class TrainSink:
if self.batch_size is not None:
return len(self.pending_batch), self.batch_size, "rollouts"
assert self.token_batch_size is not None
tokens = sum(
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
for r in self.pending_batch
)
return tokens, self.token_batch_size, "tokens"
return self.pending_tokens, self.token_batch_size, "tokens"
def buffered_count(self) -> int:
"""Rollouts that have arrived but sit in not-yet-complete groups
@@ -122,13 +116,13 @@ class TrainSink:
counts[r.env_name] += 1
return dict(counts)
async def add(self, rollout: TrainRollout) -> TrainBatch | None:
async def add(self, rollout: Rollout) -> TrainBatch | None:
"""Process one arrival; finalize the group on the ``group_size``-th
arrival; return a ``TrainBatch`` if the batch threshold is met."""
await self.process_rollout(rollout)
env_name = rollout.env_name
self.arrivals_by_env[env_name] += 1
if rollout.error is not None:
if rollout.has_error:
self.errors_by_env[env_name] += 1
self.pending_groups[rollout.group_id].append(rollout)
if len(self.pending_groups[rollout.group_id]) >= self.group_size_for(env_name):
@@ -136,37 +130,26 @@ class TrainSink:
ready = (
len(self.pending_batch) >= self.batch_size
if self.batch_size is not None
else sum(
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
for r in self.pending_batch
)
>= (self.token_batch_size or 0)
else self.pending_tokens >= (self.token_batch_size or 0)
)
if ready:
return self.process_batch()
return None
async def process_rollout(self, rollout: TrainRollout) -> None:
"""Tokenize the rollout eagerly. Backfills tokens if the env didn't
return them (SFT against external teacher APIs); errored rollouts
skip tokenization and get dropped at the group level."""
if rollout.error is not None:
async def process_rollout(self, rollout: Rollout) -> None:
"""Build training samples from the rollout's Trace (one per branch), walking the
message graph. Training is renderer-only across all modes (RL/OPD student, SFT teacher),
so every node already carries its tokens. Errored rollouts are dropped at the group
level, so skip them here."""
if rollout.has_error:
return
raw = rollout.raw
needs_backfill = any(s["tokens"] is None for s in raw.get("trajectory") or [])
if needs_backfill:
await asyncio.to_thread(backfill_rollout_tokens, raw, self.tokenizer, renderer=self.renderer)
samples = await asyncio.to_thread(
interleave_rollout,
raw,
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
trace_to_samples,
rollout,
env_name=rollout.env_name,
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
)
rollout.samples = samples or []
# Offload base64 image bytes to disk as soon as the rollout is
# tokenized, so memory stays flat instead of holding every buffered
# rollout's images until the batch ships (no-op for text-only).
await asyncio.to_thread(offload_images_to_disk, [raw], self.config.output_dir)
def process_group(self, group_id: uuid.UUID) -> None:
"""Finalize one GRPO group: drop errored rollouts (the whole group
@@ -176,8 +159,8 @@ class TrainSink:
if not group:
return
env_name = group[0].env_name
example_id = group[0].example_id
survivors = [r for r in group if r.error is None]
task_idx = group[0].task.idx
survivors = [r for r in group if not r.has_error]
num_errored = len(group) - len(survivors)
# Group-scoring envs: any failure makes survivors' rewards unsafe
@@ -185,23 +168,23 @@ class TrainSink:
env = self.train_envs.get(env_name)
if num_errored > 0 and env.requires_group_scoring:
get_logger().debug(
f"Finished group | env={env_name} example_id={example_id} | "
f"Finished group | env={env_name} task_idx={task_idx} | "
f"rollouts={len(group)} (errored={num_errored}) | dropped: group-scored partial"
)
return
if not survivors:
get_logger().debug(
f"Finished group | env={env_name} example_id={example_id} | "
f"Finished group | env={env_name} task_idx={task_idx} | "
f"rollouts={len(group)} (errored={num_errored}) | dropped: all failed"
)
return
assign_advantages(survivors, self.train_envs.get(env_name).advantage_fn)
assign_advantages(survivors, env.advantage_fn)
# Propagate to the pre-tokenized samples so the orchestrator can
# collect samples at ship time without re-walking rollouts. The env
# has a single sampling temperature; fan it out across each sample's
# completion tokens here (interleave leaves it empty).
# has a single sampling temperature; fan it out per token (context
# tokens are masked out, so their temperature is don't-care).
temperature = env.sampling_args["temperature"]
for r in survivors:
for sample in r.samples:
@@ -209,7 +192,7 @@ class TrainSink:
sample.reward = r.reward
sample.env_name = r.env_name
sample.training_mode = self.config.training_mode
sample.completion_temperatures = [temperature] * len(sample.completion_ids)
sample.temperatures = [temperature] * len(sample.token_ids)
if self.pre_filters:
apply_filters(self.pre_filters, survivors)
@@ -229,6 +212,8 @@ class TrainSink:
r.filter_results = {}
r.is_filtered = False
self.pending_batch.append(r)
if self.token_batch_size is not None:
self.pending_tokens += r.total_tokens
# Per-group summary. One line per finalized group; per-filter
# detection breakdown lives at debug level in ``apply_filters``
@@ -236,7 +221,7 @@ class TrainSink:
avg_reward = sum(rewards) / len(rewards) if rewards else 0.0
filter_str = ", ".join(f"{n}={c}" for n, c in filtered_by_name.items()) if filtered_by_name else "—"
get_logger().debug(
f"Finished group | env={env_name} example_id={example_id} | "
f"Finished group | env={env_name} task_idx={task_idx} | "
f"rollouts={len(group)} (errored={num_errored}, filtered={num_filtered}) | "
f"reward={avg_reward:.4f} | filters: {filter_str}"
)
@@ -255,12 +240,13 @@ class TrainSink:
cut = 0
running = 0
for i, r in enumerate(self.pending_batch):
running += r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
running += r.total_tokens
cut = i + 1
if running >= self.token_batch_size:
break
cohort = self.pending_batch[:cut]
self.pending_batch = self.pending_batch[cut:]
self.pending_tokens -= running
if self.post_filters:
apply_filters(self.post_filters, cohort)
@@ -278,8 +264,8 @@ class TrainSink:
prefill = 0
decode = 0
for sample in r.samples:
sample_decode = sum(sample.completion_mask)
sample_prefill = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode
sample_decode = sum(sample.mask)
sample_prefill = len(sample.token_ids) - sample_decode
decode += sample_decode
prefill += sample_prefill
if not r.is_filtered:
+4 -6
View File
@@ -14,7 +14,7 @@ class TrainSource:
"""``next_example(available_permits)`` picks a weighted-RR env and
returns its next example (or ``None`` when the env's per-call permit
cost doesn't fit — the dispatch loop retries when permits free up).
Returned dicts carry ``env_name`` + ``example_id``."""
Returned dicts carry ``env_name`` + ``task_idx``."""
def __init__(self, train_envs: TrainEnvs, *, seed: int | None) -> None:
self.rng = random.Random(seed)
@@ -28,11 +28,9 @@ class TrainSource:
# per-rollout envs need 1
self.env_costs: dict[str, int] = {}
for env in self.envs:
rows: list[dict] = []
for row in env.get_dataset(seed=seed):
ex = dict(row)
ex["env_name"] = env.name
rows.append(ex)
# The orchestrator never loads the env: sample over the task-index
# range the server reported via info() (num_tasks).
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
self.rng.shuffle(rows)
self.examples[env.name] = rows
self.cursors[env.name] = 0
+97 -634
View File
@@ -1,652 +1,115 @@
import base64
import hashlib
from pathlib import Path
from typing import Any
"""Turn a v1 `Trace` (the env server's native, typed output) into training data.
The orchestrator holds a real `vf.Trace` (validated in `envs.py`), so everything here is
attribute access — no dicts. The trace is a message graph (`trace.nodes`); each `trace.branches`
entry (a root→leaf path) is first-class and carries its own flat token sequence
(`branch.token_ids` / `branch.sampled_mask` / `branch.logprobs`), so a branch yields one
training sample directly. Token-length readers (`completion_len`, `total_tokens`, `num_turns`)
live on `vf.Trace` itself.
Training is renderer-only across every mode (RL/OPD student, SFT teacher), so every node
always carries its tokens — no backfill needed. For multimodal rollouts the branch also carries
the images it introduced (`branch.multi_modal_data`), rebuilt here into the flat `mm_kwargs` /
`mm_token_type_ids` the trainer forwards.
"""
from __future__ import annotations
import numpy as np
import pybase64
import torch
import verifiers as vf
from transformers.tokenization_utils import PreTrainedTokenizer
import verifiers.v1 as vf
from prime_rl.transport import RoutedExperts, TrainingSample
from prime_rl.utils.chat_template import (
common_prefix_len,
deserialize_tool_calls,
normalize_messages,
render_messages,
strip_message_content,
)
from prime_rl.transport import TrainingSample
from prime_rl.transport.types import EncodedTensor, RoutedExperts
from prime_rl.utils.logger import get_logger
# We use list() instead of deepcopy() for flat lists (token IDs, logprobs) - safe because
# primitives are immutable. mm_kwargs payloads are not mutated after creation.
def _to_numpy(val) -> np.ndarray:
"""A renderer mm item value (torch tensor or numpy array) -> a contiguous numpy array."""
if hasattr(val, "detach"): # torch tensor
val = val.detach().cpu().numpy()
return np.ascontiguousarray(val)
def align_routed_experts(
routed_experts: np.ndarray | None,
expected_len: int,
) -> np.ndarray | None:
"""Align routed_experts length with the expected token count.
VLLM's capturer uses `num_tokens - 1` slot mappings because the final
generated token was never fed as input to a forward pass and has no
routing decision. Append zero-filled entries for the missing positions.
"""
if routed_experts is None:
return routed_experts
assert routed_experts.ndim == 3
if routed_experts.shape[0] > expected_len:
return np.ascontiguousarray(routed_experts[:expected_len])
deficit = expected_len - routed_experts.shape[0]
if deficit <= 0:
return routed_experts
padding = np.zeros((deficit, routed_experts.shape[1], routed_experts.shape[2]), dtype=routed_experts.dtype)
return np.concatenate((routed_experts, padding), axis=0)
def _encode_mm_kwargs(mm_items: dict[str, list[dict]]) -> dict[str, EncodedTensor] | None:
"""Concatenate the branch's per-image renderer items into the flat `mm_kwargs` the trainer
forwards — one `EncodedTensor` per kwarg key (e.g. `pixel_values`, `image_grid_thw`), images
cat'd along dim 0 in branch token order. Model-agnostic: the keys are whatever the processor
emits. Returns None when there are no items."""
bins: dict[str, list[np.ndarray]] = {}
for items in mm_items.values(): # per modality
for item in items: # per image
for key, val in item.items():
bins.setdefault(key, []).append(_to_numpy(val))
encoded: dict[str, EncodedTensor] = {}
for key, arrs in bins.items():
arr = np.concatenate(arrs, axis=0)
encoded[key] = EncodedTensor(dtype=str(arr.dtype), shape=list(arr.shape), data=arr.tobytes())
return encoded or None
def _common_prefix_len(a: list[int], b: list[int]) -> int:
return common_prefix_len(a, b)
def _normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
return normalize_messages(messages, default_role)
def _deserialize_tool_calls(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
return deserialize_tool_calls(messages)
def _strip_message_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
return strip_message_content(messages)
def _render_messages(
tokenizer: PreTrainedTokenizer,
messages: list[dict[str, Any]],
add_generation_prompt: bool = False,
tools: list[dict[str, Any]] | None = None,
) -> list[int]:
return render_messages(
tokenizer,
messages,
add_generation_prompt=add_generation_prompt,
tools=tools,
)
def _tokenize_step_from_messages(
step: vf.TrajectoryStep,
tokenizer: PreTrainedTokenizer,
tools: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
prompt = _normalize_messages(step.get("prompt"), default_role="user")
completion = _normalize_messages(step.get("completion"), default_role="assistant")
prompt = _strip_message_content(_deserialize_tool_calls(prompt))
completion = _strip_message_content(_deserialize_tool_calls(completion))
assert all(m.get("role") == "assistant" for m in completion), (
"Expected all completion messages to be assistant role for SFT distillation, "
f"got roles: {[m.get('role') for m in completion]}"
)
all_messages = prompt + completion
prompt_has_assistant_completion = len(completion) > 0 and completion[0].get("role") == "assistant"
prompt_ids = _render_messages(
tokenizer,
prompt,
add_generation_prompt=prompt_has_assistant_completion,
tools=tools,
)
full_ids = _render_messages(
tokenizer,
all_messages,
tools=tools,
)
split_idx = _common_prefix_len(prompt_ids, full_ids)
original_prompt_len = len(prompt_ids)
prompt_ids = full_ids[:split_idx]
completion_ids = full_ids[split_idx:]
completion_mask = [True] * len(completion_ids)
completion_logprobs = [0.0] * len(completion_ids)
return {
"prompt_ids": prompt_ids,
"prompt_mask": [False] * len(prompt_ids),
"completion_ids": completion_ids,
"completion_mask": completion_mask,
"completion_logprobs": completion_logprobs,
"routed_experts": None,
"prompt_prefix_len": split_idx,
"original_prompt_len": original_prompt_len,
}
def _convert_tools_to_oai_format(tool_defs: list) -> list[dict[str, Any]] | None:
"""Convert verifiers Tool objects or dicts to OAI function-calling format."""
if not tool_defs:
def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExperts | None:
"""The branch's router-replay array (`[tokens, layers, top_k]`) -> the transport
`RoutedExperts` the trainer replays. Defensively realigns the token axis to `num_tokens`
(the trainer asserts `routed_experts.shape[0] == len(token_ids)`): truncate if longer,
zero-pad the tail if shorter. `Branch.routed_experts` already guarantees alignment, so this
is a backstop."""
if arr is None:
return None
def _get(tool: Any, key: str) -> Any:
if isinstance(tool, dict):
return tool.get(key)
return getattr(tool, key, None)
return [
{
"type": "function",
"function": {
"name": _get(tool, "name"),
"description": _get(tool, "description"),
"parameters": _get(tool, "parameters"),
**({} if _get(tool, "strict") is None else {"strict": _get(tool, "strict")}),
},
}
for tool in tool_defs
]
arr = np.ascontiguousarray(arr)
if arr.shape[0] > num_tokens:
arr = arr[:num_tokens]
elif arr.shape[0] < num_tokens:
pad = np.zeros((num_tokens - arr.shape[0], *arr.shape[1:]), dtype=arr.dtype)
arr = np.concatenate([arr, pad], axis=0)
return RoutedExperts(data=arr.tobytes(), shape=list(arr.shape), dtype=str(arr.dtype))
def _tokenize_step_with_renderer(
step: vf.TrajectoryStep,
renderer,
tools: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""Tokenize a trajectory step using a Renderer."""
from renderers.base import build_trajectory_step
prompt = _normalize_messages(step.get("prompt"), default_role="user")
completion = _normalize_messages(step.get("completion"), default_role="assistant")
prompt = _strip_message_content(_deserialize_tool_calls(prompt))
completion = _strip_message_content(_deserialize_tool_calls(completion))
return build_trajectory_step(renderer, prompt, completion, tools=tools)
def backfill_rollout_tokens(
output: vf.RolloutOutput,
tokenizer: PreTrainedTokenizer,
renderer=None,
) -> bool:
"""Populate missing step tokens from prompt/completion messages.
When a renderer is provided, uses it for tokenization (faster, deterministic).
Otherwise falls back to the tokenizer + apply_chat_template path.
"""
if all(step["tokens"] is not None for step in output["trajectory"]):
return True
logger = get_logger()
tools = _convert_tools_to_oai_format(output.get("tool_defs", []))
for step_idx, step in enumerate(output["trajectory"]):
if step["tokens"] is not None:
continue
if renderer is not None:
step["tokens"] = _tokenize_step_with_renderer(step, renderer, tools=tools)
else:
reconstructed = _tokenize_step_from_messages(step, tokenizer, tools=tools)
if reconstructed["prompt_prefix_len"] < reconstructed["original_prompt_len"]:
logger.debug(
f"Prompt tokenization was non-prefix for example {output['example_id']} step {step_idx}. "
f"Using longest common prefix length {reconstructed['prompt_prefix_len']} "
f"(original prompt had {reconstructed['original_prompt_len']} tokens)."
)
reconstructed.pop("prompt_prefix_len")
reconstructed.pop("original_prompt_len")
step["tokens"] = reconstructed
return True
def interleave_rollout(
output: vf.RolloutOutput,
mm_token_type_ids_mapping: dict[int, int] | None = None,
def trace_to_samples(
trace: vf.Trace,
*,
env_name: str = "",
) -> list[TrainingSample] | None:
mm_token_type_ids_mapping: dict[int, int] | None = None,
) -> list[TrainingSample]:
"""Convert a v1 `Trace` into `TrainingSample`s — one per branch.
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
`branch.sampled_mask` / `branch.logprobs`), so a sample carries it directly: `mask` marks
the trainable (model-sampled) tokens, the context tokens between completions stay masked
out. On a rollout error the whole completion is masked out. A branch carrying images also
gets `mm_kwargs` (the concatenated pixel tensors) and `mm_token_type_ids` (the renderer's
`mm_token_type_id_map` applied to the branch tokens). Branches with no sampled tokens
(e.g. an openai client carrying none) yield nothing.
"""
Convert vf.RolloutOutput to trainable rollouts by interleaving trajectory steps
where the extension property holds.
When consecutive steps share token prefixes (extension property), they are
merged into a single sample. When extension breaks (e.g., due to context
compaction or a change in control-flow), a new sample is started.
Supports multi-prefix matching to handle interleaved agents. For example,
[agent1-step1, agent1-step2, agent2-step1, agent1-step3] produces two samples:
agent1 steps merged together, agent2 step separate.
Returns a list of samples - could be 1 (extension always held) or up to T
(extension never held).
For VLM models, each renderer-produced trajectory step carries its
per-image processed tensors inline on ``multi_modal_data``; the last
merged step's sidecar covers every image in the sample.
"""
logger = get_logger()
trajectory = output["trajectory"]
if len(trajectory) == 0:
error = output.get("error")
stop = output.get("stop_condition")
logger.warning(
f"No trajectory steps for example {output['example_id']} (error={error}, stop={stop}). Skipping rollout."
)
return None
has_error = output["error"] is not None
def prepare_step_tokens(step: vf.TrajectoryStep, step_idx: int) -> dict[str, Any] | None:
tokens = step["tokens"]
if tokens is not None:
routed_experts_payload = tokens.get("routed_experts")
routed_experts = None
routed_experts_start = None
if routed_experts_payload is not None:
decoded_routed_experts = pybase64.b64decode_as_bytearray(routed_experts_payload["data"])
routed_experts = np.frombuffer(decoded_routed_experts, dtype=np.uint8).reshape(
routed_experts_payload["shape"]
)
routed_experts_start = routed_experts_payload["start"]
return {
"prompt_ids": list(tokens["prompt_ids"]),
"prompt_mask": list(map(bool, tokens["prompt_mask"])),
"completion_ids": list(tokens["completion_ids"]),
"completion_mask": list(map(bool, tokens["completion_mask"])),
"completion_logprobs": list(tokens["completion_logprobs"]),
"routed_experts": routed_experts,
"routed_experts_start": routed_experts_start,
# Renderer-emitted multimodal sidecar (placeholders + per-item
# processed tensors). Populated when the rollout went through
# a multimodal-aware renderer (e.g. Qwen3VLRenderer); absent
# for text-only rollouts.
"multi_modal_data": tokens.get("multi_modal_data"),
}
logger.warning(f"Missing rollout tokens for example {output['example_id']} step {step_idx}.")
return None
prepared_steps: list[dict[str, Any]] = []
for step_idx, step in enumerate(trajectory):
prepared = prepare_step_tokens(step, step_idx)
if prepared is None:
return None
prepared_steps.append(prepared)
# Deferred routed_experts state per sample: O(N) chunk list concatenated
# once at finalize, replacing the prior O(N²) per-extension unpack/repack.
sample_routed_state: dict[int, dict[str, Any]] = {}
routed_prefix_states: dict[int, list[tuple[list[int], list[int], dict[str, Any]]]] = {}
# Track (prefix_tokens, sample, step_indices) per active sample. step_indices
# is the explicit list of prepared_steps positions merged into this sample —
# non-contiguous when other agents' steps interleave.
active_samples: list[tuple[list[int], TrainingSample, list[int]]] = []
def make_sample(tokens: dict[str, Any], step_idx: int) -> TrainingSample:
"""Create a new TrainingSample from a trajectory step."""
if has_error:
completion_mask = [False] * len(tokens["completion_mask"])
else:
completion_mask = list(tokens["completion_mask"])
completion_ids = list(tokens["completion_ids"])
prompt_ids = list(tokens["prompt_ids"])
sample = TrainingSample(
prompt_ids=prompt_ids,
prompt_mask=list(tokens["prompt_mask"]),
completion_ids=completion_ids,
completion_mask=completion_mask,
completion_logprobs=list(tokens["completion_logprobs"]),
completion_temperatures=[],
teacher_logprobs=None,
advantage=None,
env_name=env_name,
mm_token_type_ids=None,
routed_experts=None, # deferred — finalized at end of interleave_rollout
)
# Initialize routed-experts state for this sample. First chunk is the
# raw step routed_experts (no pad, no copy). running_len is the
# cumulative count across chunks; tracked so the boundary fix-up at
# each extension is a no-op append rather than a destructive write.
step_routed = tokens.get("routed_experts")
if step_routed is not None:
routed_start = tokens["routed_experts_start"]
assert routed_start is not None, f"Missing routed_experts_start for step {step_idx}"
chunks: list[np.ndarray] = []
running_len = 0
if routed_start > 0:
source_len = routed_start + 1
assert source_len in routed_prefix_states, (
f"Missing routed prefix state for step {step_idx}: "
f"routed_start={routed_start}, prompt_len={len(tokens['prompt_ids'])}"
)
source_state = None
for prompt_ids, completion_ids, candidate_state in routed_prefix_states[source_len]:
prompt_len = len(prompt_ids)
if (
tokens["prompt_ids"][:prompt_len] == prompt_ids
and tokens["prompt_ids"][prompt_len:source_len] == completion_ids
):
source_state = candidate_state
break
assert source_state is not None, (
f"No matching routed prefix for step {step_idx}: "
f"routed_start={routed_start}, prompt_len={len(tokens['prompt_ids'])}"
)
assert source_state["running_len"] >= routed_start, (
f"Routed prefix too short for step {step_idx}: "
f"running_len={source_state['running_len']}, routed_start={routed_start}"
)
remaining = routed_start
for chunk in source_state["chunks"]:
if remaining == 0:
break
take = min(remaining, int(chunk.shape[0]))
chunks.append(chunk[:take])
remaining -= take
assert remaining == 0, (
f"Could not reconstruct routed prefix for step {step_idx}: "
f"remaining={remaining}, routed_start={routed_start}"
)
running_len = routed_start
chunks.append(step_routed)
running_len += int(step_routed.shape[0])
sample_routed_state[id(sample)] = {
"chunks": chunks,
"running_len": running_len,
}
return sample
def extend_sample(
sample: TrainingSample,
prefix_len: int,
step_idx: int,
) -> None:
"""Extend an existing sample with a new trajectory step (extension property holds)."""
tokens = prepared_steps[step_idx]
# Extend with new prompt tokens (mask=False, no gradient)
new_prompt_ids = tokens["prompt_ids"][prefix_len:]
sample.completion_ids.extend(new_prompt_ids)
sample.completion_mask.extend([False] * len(new_prompt_ids))
sample.completion_logprobs.extend([0.0] * len(new_prompt_ids))
# Extend with new completion tokens
completion_ids = tokens["completion_ids"]
sample.completion_ids.extend(completion_ids)
if has_error:
sample.completion_mask.extend([False] * len(tokens["completion_mask"]))
else:
sample.completion_mask.extend(tokens["completion_mask"])
sample.completion_logprobs.extend(tokens["completion_logprobs"])
step_routed = tokens.get("routed_experts")
state = sample_routed_state.get(id(sample))
if state is not None:
assert step_routed is not None, f"Missing routed experts for routed sample extension at step {step_idx}"
if step_routed is not None:
assert state is not None, f"Unexpected routed experts for unrouted sample at step {step_idx}"
assert tokens["routed_experts_start"] == prefix_len - 1, (
f"Routed experts delta start mismatch at step {step_idx}: "
f"start={tokens['routed_experts_start']}, expected={prefix_len - 1}, prefix_len={prefix_len}"
)
# Delta payloads start at prefix_len - 1. Row 0 fills the boundary
# token missing from the previous request; the rest is the new suffix.
if prefix_len > 0:
boundary_chunk = step_routed[:1]
state["chunks"].append(boundary_chunk)
state["running_len"] += 1
step_routed = step_routed[1:]
new_chunk = step_routed
state["chunks"].append(new_chunk)
state["running_len"] += int(new_chunk.shape[0])
first_tokens = prepared_steps[0]
first_prefix = first_tokens["prompt_ids"] + first_tokens["completion_ids"]
first_sample = make_sample(first_tokens, step_idx=0)
active_samples.append((first_prefix, first_sample, [0]))
first_routed_state = sample_routed_state.get(id(first_sample))
if first_routed_state is not None:
routed_prefix_states.setdefault(len(first_prefix), []).append(
(first_tokens["prompt_ids"], first_tokens["completion_ids"], first_routed_state)
)
for step_idx, _step in enumerate(trajectory[1:], start=1):
tokens = prepared_steps[step_idx]
step_prompt_ids = tokens["prompt_ids"]
# Pick the *longest* matching active prefix. With compaction/rollback,
# one active sample's prefix can be a strict prefix of another (e.g. a
# later sample re-generated tokens that overlap an earlier sample's
# prefix). Both would satisfy the slice check; the shorter would
# silently absorb the longer sample's generated tokens as user input.
matched_idx = None
matched_len = -1
matching_prefix_lens: list[int] = []
for idx, (prefix_tokens, _, _) in enumerate(active_samples):
pl = len(prefix_tokens)
if step_prompt_ids[:pl] == prefix_tokens:
matching_prefix_lens.append(pl)
if pl > matched_len:
matched_idx = idx
matched_len = pl
if len(matching_prefix_lens) > 1:
# Ambiguous extension: rare, but reachable via compaction/rollback
# where a new sample's prefix happens to start with an older
# sample's prefix. Longest-match is the correct choice; surface
# the ambiguity so we can audit if it shows up in real rollouts.
logger.warning(
f"Ambiguous prefix match at step {step_idx} for example {output['example_id']}: "
f"{len(matching_prefix_lens)} of {len(active_samples)} active prefixes match "
f"(lens={sorted(matching_prefix_lens)}, step_prompt_len={len(step_prompt_ids)}). "
f"Extending the longest (len={matched_len})."
)
if matched_idx is not None:
# Extension holds - merge into matched sample
prefix_tokens, sample, step_indices = active_samples[matched_idx]
extend_sample(sample, len(prefix_tokens), step_idx=step_idx)
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
active_samples[matched_idx] = (
new_prefix,
sample,
step_indices + [step_idx],
)
routed_state = sample_routed_state.get(id(sample))
if routed_state is not None:
routed_prefix_states.setdefault(len(new_prefix), []).append(
(tokens["prompt_ids"], tokens["completion_ids"], routed_state)
)
else:
# No prefix matches - start a new sample
logger.debug(
f"Extension property broke at step {step_idx + 1} for example {output['example_id']}. "
f"Starting new sample (active_prefixes={len(active_samples)}, step_prompt_len={len(step_prompt_ids)})."
)
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
sample = make_sample(tokens, step_idx=step_idx)
active_samples.append((new_prefix, sample, [step_idx]))
routed_state = sample_routed_state.get(id(sample))
if routed_state is not None:
routed_prefix_states.setdefault(len(new_prefix), []).append(
(tokens["prompt_ids"], tokens["completion_ids"], routed_state)
)
# Finalize routed_experts for each sample. One concat per sample (O(N) byte
# work) replaces the previous per-step unpack/concat/repack (O(N²)). The
# boundary entries between steps were already inserted as one-entry chunks
# during extend_sample, so a straight concat is correct.
for _, sample, _ in active_samples:
state = sample_routed_state.get(id(sample))
if state is None:
has_error = trace.has_error
samples: list[TrainingSample] = []
for branch in trace.branches:
mask = branch.sampled_mask
if not any(mask):
continue
chunks = state["chunks"]
if not chunks:
continue
combined = np.concatenate(chunks, axis=0) if len(chunks) > 1 else np.ascontiguousarray(chunks[0])
expected_len = len(sample.prompt_ids) + len(sample.completion_ids)
combined = align_routed_experts(combined, expected_len)
combined = np.ascontiguousarray(combined)
sample.routed_experts = RoutedExperts(
data=combined.tobytes(),
shape=list(combined.shape),
dtype=str(combined.dtype),
token_ids = branch.token_ids
mm_kwargs: dict[str, EncodedTensor] | None = None
mm_token_type_ids: list[int] | None = None
mmd = branch.multi_modal_data
if mmd is not None:
mm_kwargs = _encode_mm_kwargs(mmd.mm_items)
mapping = mm_token_type_ids_mapping or {}
mm_token_type_ids = [mapping.get(t, 0) for t in token_ids]
samples.append(
TrainingSample(
token_ids=token_ids,
mask=[m and not has_error for m in mask],
logprobs=branch.logprobs,
temperatures=[], # filled by TrainSink.process_group
teacher_logprobs=None,
advantage=None,
env_name=env_name,
mm_kwargs=mm_kwargs,
mm_token_type_ids=mm_token_type_ids,
routed_experts=_encode_routed_experts(branch.routed_experts, len(token_ids)),
)
)
# Attach images by concatenating mm_items across every step the
# sample covers. verifiers' ``state_to_output`` ships per-step
# *delta* mm_data (each step contains only items not present in the
# prior step's cumulative set, with multiset-aware dedup), so
# reading the last step alone would miss every earlier-turn image.
# Concat in step order recovers the per-sample cumulative set;
# deduping again here would drop legitimate duplicate placeholders.
for _, sample, step_indices in active_samples:
renderer_mm = _union_step_mm_data(prepared_steps, step_indices)
if renderer_mm is not None:
mm_kwargs = _pack_mm_kwargs_from_renderer(renderer_mm)
if mm_kwargs is not None:
sample.mm_kwargs = mm_kwargs
# ``mm_token_type_ids``: 1 for image-placeholder tokens, 2
# for video, 0 otherwise. Renderer-supplied via
# ``mm_token_type_id_map`` (single source of truth).
if mm_token_type_ids_mapping is not None:
sample.mm_token_type_ids = [
mm_token_type_ids_mapping.get(token_id, 0)
for token_id in sample.prompt_ids + sample.completion_ids
]
return [sample for _, sample, _ in active_samples]
def _union_step_mm_data(
prepared_steps: list[dict[str, Any]],
step_indices: list[int],
) -> "dict[str, Any] | None":
"""Concatenate renderer-emitted mm_items across this sample's owned steps.
``step_indices`` lists exactly the ``prepared_steps`` positions merged into
the sample — explicit, not a range, so interleaved-agent trajectories skip
steps owned by other agents.
Verifiers ≥ c7731bbb ships per-step *delta* mm_data instead of
cumulative — see ``verifiers/utils/save_utils.py::_delta_intermediate_mm_data``.
The cross-step dedup is already done there with multiset semantics
(preserving multiplicity for an image that appears in multiple
placeholder runs in the token stream). We just concatenate in step
order to recover the per-sample cumulative; deduping again here
would drop legitimate duplicate placeholders.
"""
union_items: dict[str, list] = {}
union_hashes: dict[str, list] = {}
has_any = False
for i in step_indices:
mm = prepared_steps[i].get("multi_modal_data")
if mm is None:
continue
items = mm.mm_items if hasattr(mm, "mm_items") else (mm or {}).get("mm_items") or {}
hashes = mm.mm_hashes if hasattr(mm, "mm_hashes") else (mm or {}).get("mm_hashes") or {}
for modality, item_lst in items.items():
hash_lst = hashes.get(modality, []) or []
for j, item in enumerate(item_lst or []):
h = hash_lst[j] if j < len(hash_lst) else None
union_items.setdefault(modality, []).append(item)
union_hashes.setdefault(modality, []).append(h)
has_any = True
if not has_any:
return None
return {"mm_items": union_items, "mm_hashes": union_hashes}
def _pack_mm_kwargs_from_renderer(mm_data: Any) -> "dict[str, Any] | None":
"""Batch the renderer's per-image ``mm_items`` into model-agnostic
forward kwargs.
``mm_data`` may arrive as a ``MultiModalData`` instance (in-process
for tests) or as a plain dict (after msgpack round-trip from the
env-worker). Each item is a dict keyed by the names the model's
``forward`` expects (``pixel_values`` + ``image_grid_thw`` for
Qwen3-VL, just ``pixel_values`` for Gemma3-VL, etc.). We batch by
``torch.cat(..., dim=0)`` per key — generic because every HF VLM
processor emits a leading batch/patch dimension, and the renderer
always processes one image per call.
Returns a dict of ``EncodedTensor`` payloads keyed by kwarg name,
or ``None`` when no multimodal data is present.
"""
from verifiers.utils.serve_utils import decode_tensor_payload
from prime_rl.transport.types import EncodedTensor
mm_items = mm_data.mm_items if hasattr(mm_data, "mm_items") else (mm_data or {}).get("mm_items") or {}
# Flatten across modalities into one kwarg dict — the model's
# forward signature is the schema. ``mm_items`` is typically
# ``{"image": [...], "video": [...]}`` but each modality's keys
# don't collide for any HF VLM we ship today.
per_kwarg: dict[str, list] = {}
for _modality, items in mm_items.items():
for item in items or []:
for key, payload in item.items():
per_kwarg.setdefault(key, []).append(decode_tensor_payload(payload))
if not per_kwarg:
return None
out: dict[str, EncodedTensor] = {}
for key, tensors in per_kwarg.items():
cat = torch.cat(tensors, dim=0).contiguous()
arr = cat.detach().cpu().numpy()
out[key] = EncodedTensor(
dtype=str(arr.dtype),
shape=list(arr.shape),
data=arr.tobytes(),
if not samples:
get_logger().warning(
f"No trainable samples (error={has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
)
return out
_FILE_URL_PREFIX = "file://"
def offload_images_to_disk(rollouts: list[vf.RolloutOutput], output_dir: Path) -> int:
"""Replace base64 image data in rollout trajectories with file paths on disk.
Scans all trajectory step prompts for data:image URLs, writes the decoded
image bytes to ``{output_dir}/assets/images/{hash}.png``, and replaces the
URL in-place with ``file://{path}``. Deduplicates by content hash so each
unique image is written only once.
Returns the number of unique images written to disk.
"""
images_dir = output_dir / "assets" / "images"
images_dir.mkdir(parents=True, exist_ok=True)
written: set[str] = set()
for output in rollouts:
for step in output.get("trajectory", []):
prompt = step.get("prompt")
if not prompt or not isinstance(prompt, list):
continue
for msg in prompt:
content = msg.get("content", [])
if not isinstance(content, list):
continue
for item in content:
if item.get("type") != "image_url":
continue
url = item.get("image_url", {}).get("url", "")
if not url.startswith("data:image"):
continue
b64_data = url.split(",", 1)[1]
content_hash = hashlib.sha256(b64_data.encode()).hexdigest()[:16]
path = images_dir / f"{content_hash}.png"
if content_hash not in written:
if not path.exists():
path.write_bytes(base64.b64decode(b64_data))
written.add(content_hash)
item["image_url"]["url"] = f"{_FILE_URL_PREFIX}{path}"
return len(written)
return samples
+32 -60
View File
@@ -3,10 +3,12 @@
from __future__ import annotations
import uuid
from dataclasses import dataclass, field, fields
from typing import Literal, Protocol
from dataclasses import dataclass, field
from typing import Generic, Literal, Protocol
import verifiers as vf
import verifiers.v1 as vf
from pydantic import ConfigDict, Field
from verifiers.v1.task import TaskT
from prime_rl.transport import TrainingSample
@@ -55,7 +57,7 @@ class GroupState:
kind: RolloutKind
env_name: str
example: dict
task_idx: int
rollouts_to_schedule: int
target_rollouts: int
emitted: int = 0
@@ -64,60 +66,25 @@ class GroupState:
policy_version_at_start: int = 0
@dataclass
class FinishedRollout:
"""A completed rollout the sink receives. ``raw`` is the env's untouched
``vf.RolloutOutput``; prime-rl metadata lives on typed fields. Train vs
eval is discriminated via ``isinstance``. ``rollout_id`` is the only
safe key for tracing one rollout — ``(env_name, example_id)`` collides
on re-sampling and ``group_id`` covers a whole group."""
class Rollout(vf.Trace[TaskT], Generic[TaskT]):
"""A completed rollout: the env's typed ``vf.Trace`` *is* the rollout — prime-rl's
orchestration metadata lives on it directly (set by the dispatcher once the rollout
returns), so there's no wrapper. Train vs eval is the ``kind`` discriminator. All metadata
fields are ``exclude=True``, so dumping a Rollout yields a plain trace — the on-disk
``results.jsonl`` is unchanged."""
raw: vf.RolloutOutput
env_name: str
example_id: int | str
group_id: uuid.UUID
policy_version: int
off_policy_steps: int
rollout_id: uuid.UUID = field(default_factory=uuid.uuid4)
model_config = ConfigDict(arbitrary_types_allowed=True) # ``samples`` holds msgspec structs
@property
def error(self) -> dict | None:
return self.raw.get("error")
@property
def reward(self) -> float:
return float(self.raw.get("reward", 0.0))
@property
def is_truncated(self) -> bool:
return bool(self.raw.get("is_truncated", False))
def to_dict(self) -> vf.RolloutOutput:
"""``raw`` + metadata merged for I/O (``save_rollouts``,
``monitor.log_samples``). Shallow copy; never mutates ``self.raw``."""
out: vf.RolloutOutput = dict(self.raw) # type: ignore[assignment]
for f in fields(self):
if f.name in ("raw", "samples"):
continue
val = getattr(self, f.name)
if f.name == "filter_results":
out["filters"] = dict(val)
continue
out[f.name] = str(val) if isinstance(val, uuid.UUID) else val
return out
@dataclass
class TrainRollout(FinishedRollout):
samples: list[TrainingSample] = field(default_factory=list)
advantage: float | None = None
is_filtered: bool = False
filter_results: dict[str, bool] = field(default_factory=dict)
@dataclass
class EvalRollout(FinishedRollout):
eval_step: int = 0
kind: RolloutKind = Field(default="train", exclude=True)
env_name: str = Field(default="", exclude=True)
group_id: uuid.UUID = Field(default_factory=uuid.uuid4, exclude=True)
policy_version: int = Field(default=0, exclude=True)
off_policy_steps: int = Field(default=0, exclude=True)
samples: list[TrainingSample] = Field(default_factory=list, exclude=True)
advantage: float | None = Field(default=None, exclude=True)
is_filtered: bool = Field(default=False, exclude=True)
filter_results: dict[str, bool] = Field(default_factory=dict, exclude=True)
eval_step: int | None = Field(default=None, exclude=True)
@dataclass
@@ -142,7 +109,7 @@ class TrainBatch:
"""``samples`` is the trainer-bound payload (post-filter survivors);
``rollouts`` is the full cohort kept for orchestrator-side I/O."""
rollouts: list[TrainRollout]
rollouts: list[Rollout]
samples: list[TrainingSample]
metrics: TrainBatchMetrics
@@ -197,12 +164,17 @@ class EvalBatch:
env_name: str
step: int
rollouts: list[EvalRollout]
rollouts: list[Rollout]
metrics: EvalBatchMetrics
class VersionObserver(Protocol):
"""Notified after each policy update; walked by the watcher after it
mutates ``Policy``."""
"""Notified around each policy update; walked by the watcher.
``on_version_pending`` fires *before* the inference engines are paused for
the weight update; ``on_new_version`` fires *after* the new weights are live
and ``Policy`` has been mutated."""
async def on_version_pending(self, step: int) -> None: ...
async def on_new_version(self, step: int) -> None: ...
+46 -47
View File
@@ -1,19 +1,20 @@
import asyncio
import ctypes
import gc
import logging
import os
import time
from concurrent.futures import ThreadPoolExecutor
from itertools import cycle
from pathlib import Path
import orjson
import verifiers as vf
from verifiers.utils.client_utils import setup_openai_client
from verifiers.utils.save_utils import make_serializable
import verifiers.v1 as vf
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.transport import TrainingSample
from prime_rl.utils.client import setup_inference_pool
from prime_rl.utils.logger import InterceptHandler, get_logger
from prime_rl.utils.logger import InterceptHandler, get_logger, setup_logger
from prime_rl.utils.utils import (
get_broadcast_dir,
get_ckpt_dir,
@@ -22,63 +23,38 @@ from prime_rl.utils.utils import (
async def setup_student_inference_pool(*, config: OrchestratorConfig, tokenizer):
"""Build the student inference pool + matching renderer. Returns
``(renderer | None, inference_pool)``; ``renderer`` is ``None`` on the
MITO path (``config.renderer is None``)."""
"""Build the student renderer and inference pool, returning ``(renderer, inference_pool)``.
Training is renderer-only: RL/OPD roll out through the env server's renderer client
(token-in/out), and SFT — which rolls out against a chat-completions teacher that returns
no tokens — re-renders the conversation with this renderer to backfill them. The renderer
is built here from the (always-set) ``config.renderer`` and also supplies the multimodal
token-type-id map. The eval client is plain chat-completions (eval traces aren't trained)."""
from renderers.base import create_renderer
client_config = config.student.client
model_name = config.student.model.name
if config.renderer is not None:
renderer = create_renderer(tokenizer, config.renderer)
get_logger().info(f"Initialized {type(renderer).__name__} for {model_name}")
inference_pool = await setup_inference_pool(
client_config,
model_name=model_name,
train_client_type="renderer",
eval_client_type="openai_chat_completions",
renderer_config=config.renderer,
pool_size=config.pool_size,
)
get_logger().info("Using direct renderer rollout client")
return renderer, inference_pool
get_logger().info("Using MITO (openai_chat_completions) for rollouts")
renderer = create_renderer(tokenizer, config.renderer)
get_logger().info("Using renderer rollout client")
inference_pool = await setup_inference_pool(
client_config,
model_name=model_name,
train_client_type="openai_chat_completions",
train_client_type="renderer",
eval_client_type="openai_chat_completions",
renderer_config=config.renderer,
pool_size=config.pool_size,
)
return None, inference_pool
return renderer, inference_pool
def get_model_completion_len(output: vf.RolloutOutput) -> int:
"""Sum of model-generated completion tokens across all turns (excludes
environment-injected tokens between turns)."""
return sum(len(step["tokens"]["completion_ids"]) for step in output["trajectory"] if step.get("tokens"))
def get_tool_response_len(output: vf.RolloutOutput) -> int:
"""Total tool-response tokens consumed across the whole rollout, read from a
harness-emitted metric (e.g. RLM's `rlm_total_tool_response_tokens`, deduped
across turns/branches/sub-RLMs). Returns 0 when no such metric is present."""
metrics = output.get("metrics") or {}
for key, value in metrics.items():
if key.endswith("total_tool_response_tokens") and isinstance(value, (int, float)):
return int(value)
return 0
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path, exclude_keys: set[str] | None = None) -> None:
"""Save rollouts to a JSONL file using verifiers serialization."""
def save_rollouts(rollouts: list[dict], path: Path, exclude_keys: set[str] | None = None) -> None:
"""Save rollouts (Trace dicts, already JSON-serializable) to a JSONL file."""
path.parent.mkdir(parents=True, exist_ok=True)
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
with open(path, "wb") as f:
for rollout in rollouts:
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
f.write(orjson.dumps(row, default=make_serializable, option=opts))
f.write(orjson.dumps(row, default=str, option=opts))
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
@@ -90,12 +66,30 @@ def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix
vf_logger.propagate = False
def setup_env_server_logging(log_level: str, json_logging: bool = False) -> None:
"""Configure logging for an env-server process: prime-rl's logger + routing v1's stdlib
logs through it. Passed to verifiers' ``serve_env`` so it runs in the broker and in every
spawned worker — fresh ``spawn`` processes that otherwise have no handlers and would drop
their per-rollout logs."""
setup_logger(log_level, json_logging=json_logging)
intercept_vf_logging(logger="verifiers.v1", level=log_level)
def set_default_executor(max_workers: int = 64) -> None:
"""Scale the default asyncio thread pool so asyncio.to_thread has enough capacity."""
get_logger().info(f"Setting default executor to ThreadPoolExecutor(max_workers={max_workers})")
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=max_workers))
def trim_process_memory() -> None:
"""Return freed heap pages to the OS on glibc systems."""
gc.collect()
try:
ctypes.CDLL("libc.so.6").malloc_trim(0)
except Exception as exc:
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
async def compute_teacher_logprobs(
clients: list[vf.ClientConfig],
model_name: str,
@@ -103,10 +97,15 @@ async def compute_teacher_logprobs(
) -> list[list[float]]:
"""Compute teacher model logprobs for a batch of training samples via prefill."""
import httpx
from openai import AsyncOpenAI
from vllm.entrypoints.serve.disagg.protocol import GenerateResponse
async def _compute_single(client_config: vf.ClientConfig, sample: TrainingSample) -> list[float]:
client = setup_openai_client(client_config)
client = AsyncOpenAI(
base_url=client_config.base_url,
api_key=os.environ.get(client_config.api_key_var, "EMPTY"),
default_headers=client_config.headers or None,
)
# Two escape hatches from ``AsyncOpenAI.post``:
# 1. URL — ``/inference/v1/generate`` is mounted at server root, not
@@ -125,7 +124,7 @@ async def compute_teacher_logprobs(
cast_to=httpx.Response,
body={
"model": model_name,
"token_ids": list(sample.prompt_ids) + list(sample.completion_ids),
"token_ids": list(sample.token_ids),
"sampling_params": {
"max_tokens": 1,
"temperature": 1.0,
+18
View File
@@ -92,6 +92,24 @@ class WeightWatcher:
f"Orchestrator resumed: checkpoint {next_step} ready (after {format_time(self.last_wait_for_ckpt_time)})"
)
# Drain off-policy rollouts BEFORE pausing the inference engines.
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
# ``_reqs_not_processed``), which is only propagated to the workers
# while the engine is stepping. If we drain after resume instead,
# the aborts race with the flush of KV transfers that completed
# during the pause and trip ``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. Draining first lets the
# aborts settle under normal stepping. ``on_new_version`` (below)
# still runs post-update for observers that need the live version.
for observer in self.observers:
try:
await observer.on_version_pending(next_step)
except Exception as exc:
get_logger().warning(
f"Observer {type(observer).__name__}.on_version_pending({next_step}) raised: {exc!r}"
)
get_logger().debug(f"Updating weights to step {next_step}")
t1 = time.perf_counter()
await self.inference.update_weights(weights_path, lora_name=self.lora_name, step=next_step)
+8 -2
View File
@@ -15,14 +15,20 @@ rank_log() {
# launch_inference_rank <port> <cuda_visible_devices> <dp> <rpc_port> <vllm_extra_json|""> <nixl_side_channel_port|""> <log_file>
launch_inference_rank() {
local port="$1" gpus="$2" dp="$3" rpc="$4" extra="$5" nixl="$6" log="$7"
# Per-rank dir for the mooncake-store lookup ipc socket. It must be unique per process:
# external-LB runs one engine per process, all with data_parallel_rank_local 0, so the
# lookup socket name collides on bind if the dir is shared node-wide. $port is unique per
# rank on the node. Node-local /tmp also avoids inheriting an absent submit-node TMPDIR.
local rpcbase="/tmp/vllm-rpc-$USER-$SLURM_JOB_ID-$port"
mkdir -p "$rpcbase"
local -a cmd=(uv run inference @ "$CONFIG_PATH"
--server.host 0.0.0.0 --server.port "$port"
--parallel.dp "$dp" --data-parallel-size-local 1 --api-server-count 1)
[ -n "$rpc" ] && cmd+=(--data-parallel-rpc-port "$rpc")
[ -n "$extra" ] && cmd+=(--vllm-extra "$extra")
if [ -n "$nixl" ]; then
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" "${cmd[@]}" 2>&1 | tee -a "$log" &
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
else
CUDA_VISIBLE_DEVICES="$gpus" "${cmd[@]}" 2>&1 | tee -a "$log" &
CUDA_VISIBLE_DEVICES="$gpus" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
fi
}
+56 -4
View File
@@ -1,12 +1,63 @@
{# Shared router launch helper, included once per template and called by the
replica-head rank. vllm-router today; an llm-d (EPP+Envoy) branch can slot in
here so the call sites stay router-agnostic. #}
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log_file> [replica_idx]
replica-head rank. The router backend (vllm-router vs llm-d EPP+Envoy) is
chosen here via router.type, so the call sites stay router-agnostic.
node_base/node_count locate this replica's nodes in HOSTNAMES for llm-d
endpoint discovery (disagg uses NUM_PREFILL_NODES/NUM_DECODE_NODES). #}
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log> <replica_idx> <node_base> [node_count]
launch_router() {
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-}"
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-0}" node_base="${7:-0}" node_count="${8:-0}"
{%- if router.type == "llm-d" %}
echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port for replica $replica" | tee "$log"
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
local LLMD_DIR="$OUTPUT_DIR/logs/inference/llmd_${replica}"
mkdir -p "$LLMD_DIR"
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
{%- if is_disaggregated %}
{%- set ep_disaggregated = true %}
{%- set ep_num_prefill = num_prefill_nodes %}
{%- set ep_num_decode = num_decode_nodes %}
{%- set ep_dp = dp_per_node %}
{%- set ep_prefill_port = prefill_port %}
{%- set ep_sidecar_port = router.decode_sidecar_port %}
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
{% include 'llmd/epp_pd.yaml.j2' %}
LLMD_EOF
cat > "$LLMD_DIR/endpoints.yaml" <<LLMD_EOF
{% include 'llmd/endpoints.yaml.j2' %}
LLMD_EOF
local node=0 ip
for ((p=0; p<NUM_PREFILL_NODES; p++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + p))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
for ((d=0; d<NUM_DECODE_NODES; d++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + NUM_PREFILL_NODES + d))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
{%- else %}
{%- set ep_disaggregated = false %}
{%- set ep_num_nodes = infer_nodes_per_replica %}
{%- set ep_dp = dp_per_node %}
{%- set ep_backend_port = backend_port %}
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
{% include 'llmd/epp_estimate.yaml.j2' %}
LLMD_EOF
cat > "$LLMD_DIR/endpoints.yaml" <<LLMD_EOF
{% include 'llmd/endpoints.yaml.j2' %}
LLMD_EOF
local ip
for ((n=0; n<node_count; n++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + n))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${n}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; done
{%- endif %}
cat > "$LLMD_DIR/envoy.yaml" <<LLMD_EOF
{% include 'llmd/envoy.yaml.j2' %}
LLMD_EOF
# grpc-health-port avoids 9003: mooncake_master runs its metrics server on 9003 and
# shares the replica-head node with the EPP, so 9003 would fail to bind and kill the EPP.
epp --pool-name prime-rl --pool-namespace slurm \
--config-file "$LLMD_DIR/epp.yaml" \
--grpc-port 9002 --grpc-health-port 9013 --metrics-port 9090 \
--secure-serving=false --metrics-endpoint-auth=false --tracing=false \
>> "$log" 2>&1 &
envoy -c "$LLMD_DIR/envoy.yaml" >> "$log" 2>&1 &
{%- else %}
local tag="vllm-router"; [ "$mode" = pd ] && tag="vllm-router (PD)"
echo "Starting $tag on $LOCAL_IP:$port${replica:+ for replica $replica}" | tee "$log"
local -a cmd=(vllm-router --policy "$policy" --host 0.0.0.0 --port "$port"
--request-id-headers x-session-id
--worker-startup-timeout-secs 4200 --log-level debug)
if [ "$mode" = pd ]; then
cmd+=(--vllm-pd-disaggregation $worker_args)
@@ -14,4 +65,5 @@ launch_router() {
cmd+=(--worker-urls $worker_args)
fi
"${cmd[@]}" >> "$log" 2>&1 &
{%- endif %}
}
+6 -3
View File
@@ -5,7 +5,8 @@
SLURM templates inside the per-node `bash -c` body, so NO single quotes / apostrophes.
Requires shell vars: LOCAL_IP, INFER_NODE_RANK, OUTPUT_DIR (and SLURM env).
Requires jinja vars: kv_offload_cpu_bytes, kv_offload_disk_path, kv_offload_device_name.
Exports PYTHONHASHSEED + MOONCAKE_CONFIG_PATH for the vLLM process on this node. -#}
Exports PYTHONHASHSEED + MOONCAKE_CONFIG_PATH for the vLLM process. (VLLM_RPC_BASE_PATH,
used by the mooncake-store lookup ipc socket, is set per-rank in _launch_rank.sh.j2.) -#}
# ---- Mooncake distributed store (shared pool across inference nodes) ----
MC_DIR="$OUTPUT_DIR/mooncake/node_${INFER_NODE_RANK}"
mkdir -p "$MC_DIR"
@@ -23,9 +24,11 @@
{%- endif %}
if [ "$SLURMD_NODENAME" = "$MC_HEAD" ]; then
{%- if kv_offload_disk_path %}
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -enable_offload=true -root_fs_dir={{ kv_offload_disk_path }} > "$MC_DIR/master.log" 2>&1 &
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -default_kv_lease_ttl=3600000 -enable_offload=true -root_fs_dir={{ kv_offload_disk_path }} > "$MC_DIR/master.log" 2>&1 &
{%- else %}
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 > "$MC_DIR/master.log" 2>&1 &
# default_kv_lease_ttl raised from 5s: KV blocks were expiring before the decode side
# reused them ("invalid KV blocks ... may have expired"), the real non-NIC config issue.
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -default_kv_lease_ttl=3600000 > "$MC_DIR/master.log" 2>&1 &
{%- endif %}
fi
# Every node waits for the shared master + metadata, then contributes its segment.
+37 -10
View File
@@ -28,7 +28,7 @@ set -e
# Configs
export NUM_NODES={{ num_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
{% if disaggregated -%}
{% if is_disaggregated -%}
export NUM_PREFILL_NODES={{ num_prefill_nodes }}
export NUM_DECODE_NODES={{ num_decode_nodes }}
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
@@ -38,10 +38,13 @@ export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
export PREFILL_PORT={{ prefill_port }}
export DECODE_PORT={{ decode_port }}
export ROUTER_PORT={{ router_port }}
export ROUTER_PORT={{ router.port }}
export RPC_PORT={{ data_parallel_rpc_port }}
{%- if router.type == "llm-d" %}
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
{%- endif %}
{%- elif num_nodes > 1 %}
export ROUTER_PORT={{ router_port }}
export ROUTER_PORT={{ router.port }}
export BACKEND_PORT={{ backend_port }}
export RPC_PORT={{ data_parallel_rpc_port }}
{%- endif %}
@@ -70,7 +73,7 @@ uv sync --all-extras
# Print inference URLs
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
export HOSTNAMES_STR="${HOSTNAMES[*]}"
{% if disaggregated -%}
{% if is_disaggregated -%}
# Build per-replica router URLs
INFER_URLS=""
ALL_ROUTER_ARGS=""
@@ -132,6 +135,10 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[t]orchrun" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
# llm-d router procs (EPP + Envoy + decode pd-sidecar) left over from a prior run.
pkill -9 -f "[e]pp.*pool-name" 2>/dev/null
pkill -9 -f "[e]nvoy.*envoy.yaml" 2>/dev/null
pkill -9 -f "[p]d-sidecar" 2>/dev/null
pkill -9 -f "[v]llm" 2>/dev/null
pkill -9 -f "[p]rime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
@@ -144,7 +151,7 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -x mooncake_client 2>/dev/null
sleep 2
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
CLEANUP_SH
@@ -179,7 +186,7 @@ srun --kill-on-bad-exit=1 bash -c '
{% include "_mooncake_store.sh.j2" %}
{%- endif %}
{% if disaggregated -%}
{% if is_disaggregated -%}
# NVSHMEM libs for DeepEP — ensure the rpath target exists on all nodes
if [ ! -d /tmp/deepep_build/nvshmem/lib ] && [ -d "$OUTPUT_DIR/nvshmem/lib" ]; then
mkdir -p /tmp/deepep_build/nvshmem
@@ -247,7 +254,7 @@ srun --kill-on-bad-exit=1 bash -c '
{% for key, value in prefill_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
else
# ── Decode node ──
export UCX_NET_DEVICES=mlx5_0:1
@@ -262,7 +269,7 @@ srun --kill-on-bad-exit=1 bash -c '
{% for key, value in decode_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
fi
echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT LOCAL_IP=$LOCAL_IP" \
@@ -271,8 +278,28 @@ srun --kill-on-bad-exit=1 bash -c '
# Start the router on the first prefill node of each replica (external LB across per-rank endpoints)
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router_policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
fi
{%- if router.type == "llm-d" %}
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
# + rank) -> vLLM decode (DECODE_PORT + rank) after orchestrating remote prefill.
# Every decode node fronts its own local ranks, so launch on each (not just the
# replica head), or decode nodes beyond the head get advertised but unserved endpoints.
if [ "$ROLE" = "decode" ]; then
SIDECAR_LOG="$OUTPUT_DIR/logs/inference/sidecar_${INFER_NODE_RANK}.log"
echo "Starting pd-sidecar on $LOCAL_IP:$DECODE_SIDECAR_PORT(+rank) -> vLLM $DECODE_PORT(+rank)" | tee $SIDECAR_LOG
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
pd-sidecar \
--port $DECODE_SIDECAR_PORT \
--vllm-port $DECODE_PORT \
--kv-connector nixlv2 \
--secure-proxy=false \
--enable-ssrf-protection=false \
--inference-pool prime-rl \
--data-parallel-size {{ dp_per_node }} \
>> $SIDECAR_LOG 2>&1 &
fi
{%- endif %}
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
@@ -296,7 +323,7 @@ srun --kill-on-bad-exit=1 bash -c '
# Start the router on node 0 (balances across per-rank endpoints — no intra-node DP header)
if [ "$INFER_NODE_RANK" -eq 0 ]; then
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router_policy }}" "$OUTPUT_DIR/logs/inference/router.log"
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log" 0 0 "$NUM_NODES"
fi
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
@@ -0,0 +1,41 @@
{# llm-d file-discovery endpoints: one entry per DP rank. Rendered (via include)
into the sbatch; the per-node address is the __LLMD_ADDR_<node>__ placeholder,
filled with each SLURM host's IPv4 inline in the sbatch (file-discovery rejects
hostnames). Node ordering matches the sbatch's host loop: prefill then decode.
The including sbatch sets ep_* via {% set %}. #}
endpoints:
{%- if ep_disaggregated %}
{%- for node in range(ep_num_prefill) %}
{%- for rank in range(ep_dp) %}
- name: prefill-{{ node }}-rank-{{ rank }}
address: __LLMD_ADDR_{{ node }}__
port: "{{ ep_prefill_port + rank }}"
namespace: default
labels:
llm-d.ai/pool: prime-rl
llm-d.ai/role: prefill
{%- endfor %}
{%- endfor %}
{%- for node in range(ep_num_decode) %}
{%- for rank in range(ep_dp) %}
- name: decode-{{ node }}-rank-{{ rank }}
address: __LLMD_ADDR_{{ ep_num_prefill + node }}__
port: "{{ ep_sidecar_port + rank }}"
namespace: default
labels:
llm-d.ai/pool: prime-rl
llm-d.ai/role: decode
{%- endfor %}
{%- endfor %}
{%- else %}
{%- for node in range(ep_num_nodes) %}
{%- for rank in range(ep_dp) %}
- name: backend-{{ node }}-rank-{{ rank }}
address: __LLMD_ADDR_{{ node }}__
port: "{{ ep_backend_port + rank }}"
namespace: default
labels:
llm-d.ai/pool: prime-rl
{%- endfor %}
{%- endfor %}
{%- endif %}
+97
View File
@@ -0,0 +1,97 @@
{# Envoy data plane: EPP picks the backend (ext_proc) and sets
x-gateway-destination-endpoint; the ORIGINAL_DST cluster routes there. Both
/v1/ (MITO) and /inference/v1/ (TITO) go through the picker. EPP gRPC is on
loopback 9002; the gateway listens on the configured port. #}
admin:
address: { socket_address: { address: 127.0.0.1, port_value: 9901 } }
static_resources:
listeners:
- name: prime_rl
address: { socket_address: { address: 0.0.0.0, port_value: {{ router.port }} } }
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: prime_rl
codec_type: AUTO
stream_idle_timeout: 0s
request_timeout: 0s
route_config:
virtual_hosts:
- name: prime_rl
domains: ["*"]
routes:
- match: { prefix: "/v1/" }
route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s }
- match: { prefix: "/inference/v1/" }
route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s }
http_filters:
- name: envoy.filters.http.ext_proc
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.ext_proc.v3.ExternalProcessor
grpc_service:
envoy_grpc: { cluster_name: epp_cluster }
timeout: 10s
processing_mode:
request_header_mode: SEND
response_header_mode: SEND
request_body_mode: FULL_DUPLEX_STREAMED
response_body_mode: FULL_DUPLEX_STREAMED
request_trailer_mode: SEND
response_trailer_mode: SEND
message_timeout: 1000s
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
suppress_envoy_headers: true
clusters:
- name: backend_cluster
type: ORIGINAL_DST
lb_policy: CLUSTER_PROVIDED
original_dst_lb_config:
use_http_header: true
http_header_name: x-gateway-destination-endpoint
connect_timeout: 5s
# Default circuit breakers (~1024) overflow at high inflight concurrency (>=1536),
# causing "reset reason: overflow" 500s. Raise far above the max concurrent rollouts.
circuit_breakers:
thresholds:
- priority: DEFAULT
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
- priority: HIGH
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
- name: epp_cluster
type: STRICT_DNS
typed_extension_protocol_options:
envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
"@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
explicit_http_config:
http2_protocol_options: {}
load_assignment:
cluster_name: epp_cluster
endpoints:
- lb_endpoints:
- endpoint:
address: { socket_address: { address: 127.0.0.1, port_value: 9002 } }
connect_timeout: 5s
# ext_proc (EPP) connection pool overflows at high concurrency without this — the
# gRPC ext_proc calls are 1:1 with inflight requests, so cap well above max rollouts.
circuit_breakers:
thresholds:
- priority: DEFAULT
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
- priority: HIGH
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
@@ -0,0 +1,34 @@
{# llm-d EPP config: single-pool (non-P/D) routing with approximate prefix-cache
scoring. The vllmhttp parser embeds the OpenAI parser and also handles
/inference/v1/generate (token_ids), so MITO + TITO both get prefix-cache
scoring. Included into the sbatch as a heredoc; $LLMD_DIR is the per-replica
config dir, expanded at launch time. #}
apiVersion: inference.networking.x-k8s.io/v1alpha1
kind: EndpointPickerConfig
plugins:
- name: file-disc
type: file-discovery
parameters:
path: $LLMD_DIR/endpoints.yaml
watchFile: true
- name: vllmhttp-parser
type: vllmhttp-parser
{%- for scorer in router.scorers %}
- type: {{ scorer }}
{%- endfor %}
- type: max-score-picker
- type: single-profile-handler
schedulingProfiles:
- name: default
plugins:
{%- for scorer, weight in router.scorers.items() %}
- pluginRef: {{ scorer }}
weight: {{ weight }}
{%- endfor %}
- pluginRef: max-score-picker
requestHandler:
parser:
pluginRef: vllmhttp-parser
dataLayer:
discovery:
pluginRef: file-disc
@@ -0,0 +1,56 @@
{# llm-d EPP config: prefill/decode disaggregation. disagg-profile-handler runs
the prefill profile when prefix-based-pd-decider sees >= nonCachedTokens
non-cached prompt tokens, else decode-only. Mirrors the upstream llm-d PD
guide: the prefill profile uses prefill_scorers (prefix + queue/kv) and the
decode profile uses scorers (prefix + active-request); prefill-filter /
decode-filter select endpoints by llm-d.ai/role label. Included into the
sbatch as a heredoc; $LLMD_DIR is the per-replica config dir, expanded at
launch time. #}
apiVersion: inference.networking.x-k8s.io/v1alpha1
kind: EndpointPickerConfig
plugins:
- name: file-disc
type: file-discovery
parameters:
path: $LLMD_DIR/endpoints.yaml
watchFile: true
- name: vllmhttp-parser
type: vllmhttp-parser
- name: pd-decider
type: prefix-based-pd-decider
parameters:
nonCachedTokens: {{ router.non_cached_tokens }}
- name: profile-handler
type: disagg-profile-handler
parameters:
deciders:
prefill: pd-decider
- type: prefill-filter
- type: decode-filter
{%- for scorer in ((router.prefill_scorers.keys() | list) + (router.decode_scorers.keys() | list)) | unique %}
- type: {{ scorer }}
{%- endfor %}
- type: max-score-picker
schedulingProfiles:
- name: prefill
plugins:
- pluginRef: prefill-filter
{%- for scorer, weight in router.prefill_scorers.items() %}
- pluginRef: {{ scorer }}
weight: {{ weight }}
{%- endfor %}
- pluginRef: max-score-picker
- name: decode
plugins:
- pluginRef: decode-filter
{%- for scorer, weight in router.decode_scorers.items() %}
- pluginRef: {{ scorer }}
weight: {{ weight }}
{%- endfor %}
- pluginRef: max-score-picker
requestHandler:
parser:
pluginRef: vllmhttp-parser
dataLayer:
discovery:
pluginRef: file-disc
+33 -6
View File
@@ -32,7 +32,7 @@ export NODES_PER_INFER_REPLICA={{ nodes_per_infer_replica }}
export NUM_INFER_REPLICAS={{ num_infer_replicas }}
export GPUS_PER_NODE={{ gpus_per_node }}
{% if num_infer_nodes > 0 -%}
export ROUTER_PORT={{ router_port }}
export ROUTER_PORT={{ router.port }}
export INFERENCE_TP={{ inference_tp }}
export INFERENCE_DP_LOCAL=$((GPUS_PER_NODE / INFERENCE_TP))
export INFERENCE_DATA_PARALLEL_RPC_PORT={{ inference_data_parallel_rpc_port }}
@@ -45,6 +45,9 @@ export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
export PREFILL_PORT={{ prefill_port }}
export DECODE_PORT={{ decode_port }}
{%- if router.type == "llm-d" %}
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
{%- endif %}
{%- else -%}
export BACKEND_PORT={{ backend_port }}
export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parallel else "0" }}
@@ -166,6 +169,10 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[t]orchrun" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
# llm-d router procs (EPP + Envoy + decode pd-sidecar) left over from a prior run.
pkill -9 -f "[e]pp.*pool-name" 2>/dev/null
pkill -9 -f "[e]nvoy.*envoy.yaml" 2>/dev/null
pkill -9 -f "[p]d-sidecar" 2>/dev/null
pkill -9 -f "[v]llm" 2>/dev/null
pkill -9 -f "[p]rime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
@@ -178,7 +185,7 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -x mooncake_client 2>/dev/null
sleep 2
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
CLEANUP_SH
@@ -284,7 +291,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
{% for key, value in prefill_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
else
export UCX_NET_DEVICES=mlx5_0:1
ROLE="decode"
@@ -298,7 +305,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
{% for key, value in decode_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
fi
echo "ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT" \
@@ -307,8 +314,28 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
# Start the router on the first node of each replica (PD mode, external LB across per-rank endpoints)
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
fi
{%- if router.type == "llm-d" %}
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
# + rank) -> vLLM decode (DECODE_PORT + rank) after orchestrating remote prefill.
# Every decode node fronts its own local ranks, so launch on each (not just the
# replica head), or decode nodes beyond the head get advertised but unserved endpoints.
if [ "$ROLE" = "decode" ]; then
SIDECAR_LOG="$OUTPUT_DIR/logs/inference/sidecar_${INFER_NODE_RANK}.log"
echo "Starting pd-sidecar on $LOCAL_IP:$DECODE_SIDECAR_PORT(+rank) -> vLLM $DECODE_PORT(+rank)" | tee $SIDECAR_LOG
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
pd-sidecar \
--port $DECODE_SIDECAR_PORT \
--vllm-port $DECODE_PORT \
--kv-connector nixlv2 \
--secure-proxy=false \
--enable-ssrf-protection=false \
--inference-pool prime-rl \
--data-parallel-size $INFERENCE_DP_LOCAL \
>> $SIDECAR_LOG 2>&1 &
fi
{%- endif %}
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
@@ -325,7 +352,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
# Start the router on the first node of each replica
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
launch_router regular "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
launch_router regular "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$((REPLICA_IDX * NODES_PER_INFER_REPLICA))" "$NODES_PER_INFER_REPLICA"
fi
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + d),
+78 -20
View File
@@ -2,8 +2,10 @@ import copy
from collections.abc import Callable, Sequence
from dataclasses import dataclass
import numpy as np
from prime_rl.trainer.utils import balanced_partition
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
ROUTED_EXPERTS_DTYPE_ITEMSIZE = {
"uint8": 1,
@@ -41,26 +43,77 @@ def _pad_routed_experts(micro_batch: MicroBatch, padding_size: int) -> None:
routed_experts.shape[0] += padding_size
def _slice_encoded(tensor: EncodedTensor, n_rows: int) -> EncodedTensor:
"""First `n_rows` rows of a dim-0-stacked encoded tensor (e.g. pixel_values, image_grid_thw)."""
row = int(np.prod(tensor.shape[1:])) if len(tensor.shape) > 1 else 1
itemsize = np.dtype(tensor.dtype).itemsize
return EncodedTensor(
dtype=tensor.dtype,
shape=[n_rows, *tensor.shape[1:]],
data=tensor.data[: n_rows * row * itemsize],
)
def _truncate_mm(
mm_token_type_ids: list[int], mm_kwargs: dict[str, EncodedTensor], seq_len: int
) -> tuple[int, dict[str, EncodedTensor] | None]:
"""Truncating a sample must not split an image's placeholder block, else the surviving image
token count no longer matches the image embeddings in `mm_kwargs`. Returns the cut point
(<= seq_len, never inside an image block) and `mm_kwargs` sliced to the images whose
placeholders fully survive (None if no image survives)."""
grid = np.frombuffer(bytearray(mm_kwargs["image_grid_thw"].data), dtype=mm_kwargs["image_grid_thw"].dtype).reshape(
mm_kwargs["image_grid_thw"].shape
)
patches_per_image = [int(g.prod()) for g in grid]
total_patches = mm_kwargs["pixel_values"].shape[0]
total_tokens = sum(1 for t in mm_token_type_ids if t)
ppt = total_patches // total_tokens if total_tokens else 1 # patches per token (merge^2)
tokens_per_image = [p // ppt for p in patches_per_image]
surviving = sum(1 for t in mm_token_type_ids[:seq_len] if t)
kept = acc = 0
for n in tokens_per_image:
if acc + n > surviving:
break
acc += n
kept += 1
if acc == surviving:
cut = seq_len # surviving image tokens are exactly `kept` whole images
else:
# `surviving` lands inside image `kept`; cut to its first placeholder, dropping it.
seen, cut = 0, seq_len
for i, t in enumerate(mm_token_type_ids):
if t:
seen += 1
if seen == acc + 1:
cut = i
break
if not kept:
return cut, None
kept_patches = sum(patches_per_image[:kept])
sliced = {k: _slice_encoded(v, kept if k == "image_grid_thw" else kept_patches) for k, v in mm_kwargs.items()}
return cut, sliced
def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch:
"""
Prepare a problem for sequence packing training.
Tokenize and prepare tensors.
"""
input_ids = training_example.prompt_ids + training_example.completion_ids
loss_mask = training_example.prompt_mask + training_example.completion_mask
inference_logprobs = [0.0] * len(training_example.prompt_ids) + training_example.completion_logprobs
input_ids = training_example.token_ids
loss_mask = training_example.mask
inference_logprobs = training_example.logprobs
advantages = [training_example.advantage] * len(input_ids)
reward = training_example.reward if training_example.reward is not None else float("nan")
rewards = [reward] * len(input_ids)
position_ids = list(range(len(input_ids)))
mm_token_type_ids = training_example.mm_token_type_ids
mm_kwargs = training_example.mm_kwargs
assert training_example.env_name != "all", "env_name='all' is reserved for aggregate metric keys"
env_names = [training_example.env_name] * len(input_ids)
# Per-token temperatures: prompt tokens use first completion temp (masked out anyway)
# Default to 1.0 if completion is empty (e.g., model generated only tool calls with no text)
prompt_temp = training_example.completion_temperatures[0] if training_example.completion_temperatures else 1.0
temperatures = [prompt_temp] * len(training_example.prompt_ids) + training_example.completion_temperatures
# Per-token sampling temperatures (context tokens are masked out, so theirs are don't-care).
temperatures = training_example.temperatures
# Teacher logprobs already cover the full sequence (prompt + completion),
# computed via prefill in the orchestrator when a teacher model is configured
@@ -70,20 +123,25 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
)
if len(input_ids) > seq_len:
input_ids = input_ids[:seq_len]
loss_mask = loss_mask[:seq_len]
inference_logprobs = inference_logprobs[:seq_len]
position_ids = position_ids[:seq_len]
advantages = advantages[:seq_len]
rewards = rewards[:seq_len]
temperatures = temperatures[:seq_len]
# Multimodal: never split an image's placeholder block — cut to a whole-image boundary
# and slice mm_kwargs to match, so image-token count == image-embedding count.
cut = seq_len
if mm_token_type_ids is not None and mm_kwargs is not None:
cut, mm_kwargs = _truncate_mm(mm_token_type_ids, mm_kwargs, seq_len)
input_ids = input_ids[:cut]
loss_mask = loss_mask[:cut]
inference_logprobs = inference_logprobs[:cut]
position_ids = position_ids[:cut]
advantages = advantages[:cut]
rewards = rewards[:cut]
temperatures = temperatures[:cut]
if teacher_logprobs is not None:
teacher_logprobs = teacher_logprobs[:seq_len]
teacher_logprobs = teacher_logprobs[:cut]
if routed_experts is not None:
routed_experts = _slice_routed_experts(routed_experts, seq_len)
routed_experts = _slice_routed_experts(routed_experts, cut)
if mm_token_type_ids is not None:
mm_token_type_ids = mm_token_type_ids[:seq_len]
env_names = env_names[:seq_len]
mm_token_type_ids = mm_token_type_ids[:cut]
env_names = env_names[:cut]
assert (
len(input_ids)
@@ -124,7 +182,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
routed_experts=routed_experts,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
mm_kwargs=training_example.mm_kwargs,
mm_kwargs=mm_kwargs,
training_mode=training_example.training_mode,
)
+12
View File
@@ -510,6 +510,18 @@ def get_model(
model_config.use_index_cache = True
model_config.index_topk_freq = config.index_cache.topk_freq
model_config.index_topk_pattern = config.index_cache.topk_pattern
# Explicit override supersedes the model's native IndexShare schedule.
model_config.indexer_types = None
else:
# Auto-enable IndexShare from the model's own indexer schedule (e.g. GLM-5.2). The model
# reads `indexer_types` directly: shared layers reuse cached indices and carry no indexer weights.
indexer_types = getattr(model_config, "indexer_types", None)
if indexer_types and any(t == "shared" for t in indexer_types):
model_config.use_index_cache = True
logger.info(
f"Auto-enabled IndexShare from indexer_types schedule "
f"({sum(t == 'full' for t in indexer_types)}/{len(indexer_types)} full layers)"
)
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
@@ -227,7 +227,11 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
# .contiguous(): the per-layer slice is a strided view of [tokens, layers, topk]
# (dim-1 stride = layers*topk); torch.compile's MoE kernel asserts a contiguous input.
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
@@ -11,6 +11,10 @@ def _index_cache_skip_topk(config, layer_idx: int) -> bool:
if index_topk_pattern is not None:
return layer_idx < len(index_topk_pattern) and index_topk_pattern[layer_idx] == "S"
indexer_types = getattr(config, "indexer_types", None)
if indexer_types is not None:
return layer_idx < len(indexer_types) and indexer_types[layer_idx] == "shared"
return layer_idx % getattr(config, "index_topk_freq", 1) != 0
@@ -162,6 +166,7 @@ class GlmMoeDsaConfig(PretrainedConfig):
use_index_cache=False,
index_topk_freq=1,
index_topk_pattern=None,
indexer_types=None,
scoring_func="sigmoid",
topk_method="noaux_tc",
use_grouped_mm=True,
@@ -218,6 +223,7 @@ class GlmMoeDsaConfig(PretrainedConfig):
self.use_index_cache = use_index_cache
self.index_topk_freq = index_topk_freq
self.index_topk_pattern = index_topk_pattern
self.indexer_types = indexer_types
self.scoring_func = scoring_func
self.topk_method = topk_method
self.use_grouped_mm = use_grouped_mm
@@ -226,6 +232,10 @@ class GlmMoeDsaConfig(PretrainedConfig):
if not self.use_grouped_mm:
warnings.warn("not using grouped mm for moe is very slow, should only be used for debugging")
# head_dim is derived from qk_rope_head_dim (the RoPE slice). Some checkpoints (e.g. GLM-5.2)
# set head_dim=qk_nope_head_dim in config.json; drop it so PretrainedConfig.__init__ can't
# overwrite self.head_dim and break the rotary embedding dimension.
kwargs.pop("head_dim", None)
super().__init__(
pad_token_id=pad_token_id,
tie_word_embeddings=tie_word_embeddings,
@@ -158,7 +158,8 @@ class GlmMoeDsaAttention(nn.Module):
)
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, args.hidden_size, bias=args.attention_bias)
self.indexer = Indexer(args)
# IndexShare (GLM-5.2): layers that reuse cached indices carry no indexer weights.
self.indexer = Indexer(args) if not args.skip_topk else None
self.use_index_cache = args.use_index_cache
self.skip_topk = args.skip_topk
self.scaling = self.qk_head_dim ** (-0.5)
@@ -8,6 +8,7 @@ import torch.nn as nn
from torch import Tensor
from prime_rl.utils.logger import get_logger
from prime_rl.utils.vlm import get_final_logit_softcapping
FUSED_CE_IGNORE_INDEX = -100
@@ -299,8 +300,8 @@ def inject_prime_lm_head(
logger = get_logger()
# Check for Gemma-style softcapping - dispatch to specialized implementation
final_logit_softcapping = getattr(model.config, "final_logit_softcapping", None)
# Check for Gemma-style softcapping - dispatch to specialized implementation.
final_logit_softcapping = get_final_logit_softcapping(model.config)
if final_logit_softcapping:
if fused_cross_entropy == "quack":
raise ValueError(
+16 -26
View File
@@ -160,27 +160,17 @@ class MultiPacker(BasePacker):
def _validate_sample(self, sample: TrainingSample) -> tuple[bool, str | None]:
"""Validate a sample to ensure it won't crash the trainer."""
sample_length = len(sample.prompt_ids) + len(sample.completion_ids)
if len(sample.prompt_mask) != len(sample.prompt_ids):
return (
False,
f"Run wrote a sample with prompt mask length != prompt ids length ({len(sample.prompt_mask)} != {len(sample.prompt_ids)})",
)
if len(sample.completion_mask) != len(sample.completion_ids):
return (
False,
f"Run wrote a sample with completion mask length != completion ids length ({len(sample.completion_mask)} != {len(sample.completion_ids)})",
)
if len(sample.completion_logprobs) != len(sample.completion_ids):
return (
False,
f"Run wrote a sample with completion logprobs length != completion ids length ({len(sample.completion_logprobs)} != {len(sample.completion_ids)})",
)
if len(sample.completion_temperatures) != len(sample.completion_ids):
return (
False,
f"Run wrote a sample with completion temperatures length != completion ids length ({len(sample.completion_temperatures)} != {len(sample.completion_ids)})",
)
sample_length = len(sample.token_ids)
for name, arr in (
("mask", sample.mask),
("logprobs", sample.logprobs),
("temperatures", sample.temperatures),
):
if len(arr) != sample_length:
return (
False,
f"Run wrote a sample with {name} length != token_ids length ({len(arr)} != {sample_length})",
)
if sample_length == 0:
return False, "Run wrote a sample with no tokens"
if sample_length > self.seq_len:
@@ -228,7 +218,7 @@ class MultiPacker(BasePacker):
for sample, step in buffer:
if step > current_step:
break
tokens += len(sample.prompt_ids) + len(sample.completion_ids)
tokens += len(sample.token_ids)
if threshold is not None and tokens >= threshold:
return tokens
return tokens
@@ -265,10 +255,10 @@ class MultiPacker(BasePacker):
if step > current_step:
# Samples from different steps should be consumed later
break
tokens_collected += len(sample.prompt_ids) + len(sample.completion_ids)
tokens_collected += len(sample.token_ids)
if tokens_collected > token_budget:
if tokens_collected == (len(sample.prompt_ids) + len(sample.completion_ids)):
tokens_collected -= len(sample.prompt_ids) + len(sample.completion_ids)
if tokens_collected == (len(sample.token_ids)):
tokens_collected -= len(sample.token_ids)
# This means we have a sample that has more tokens than max seqlen
self.buffers[run_idx].popleft()
continue
@@ -322,7 +312,7 @@ class MultiPacker(BasePacker):
assert steps_by_run[run_idx] == step, "Micro batches for a run must come from a single run step"
samples_by_run[run_idx].append(sample)
num_tokens = len(sample.prompt_ids) + len(sample.completion_ids)
num_tokens = len(sample.token_ids)
if run_idx in per_run_stats:
cur_samples, cur_tokens = per_run_stats[run_idx]
per_run_stats[run_idx] = (cur_samples + 1, cur_tokens + num_tokens)
+11 -8
View File
@@ -24,14 +24,17 @@ class RoutedExperts(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tru
# Orchestrator -> Packer
class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
"""A single training example."""
"""A single training example — one branch of a rollout as a flat token sequence.
prompt_ids: list[int]
prompt_mask: list[bool]
completion_ids: list[int]
completion_mask: list[bool]
completion_logprobs: list[float]
completion_temperatures: list[float] # Per-token temperatures used during generation
There is no prompt/completion split: an agentic, multi-turn branch interleaves context and
model-sampled spans, so ``mask`` marks which tokens are trainable (model-sampled) and
``logprobs`` / ``temperatures`` are aligned per token. All four arrays share the length of
``token_ids``."""
token_ids: list[int]
mask: list[bool]
logprobs: list[float]
temperatures: list[float]
env_name: str
teacher_logprobs: list[float] | None = None
advantage: float | None = None
@@ -74,9 +77,9 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
advantages: list[float]
inference_logprobs: list[float]
position_ids: list[int]
sequence_lengths: list[int]
temperatures: list[float] # Per-token temperatures used during generation
env_names: list[str]
sequence_lengths: list[int]
teacher_logprobs: list[float] | None = None
lora_num_tokens: list[int] | None = None
routed_experts: RoutedExperts | None = None
+1 -1
View File
@@ -72,7 +72,7 @@ class OffloadActivations(saved_tensors_hooks):
# managing cpu memory
self.use_pin_memory: bool = use_pin_memory
self.virtual_memory_safe_pct = 60 # we should not exceed this percentage of memory
self.virtual_memory_safe_pct = 90 # we should not exceed this percentage of memory
# comp stream
if torch.accelerator.is_available():
self.s0 = torch.accelerator.current_stream()
+58
View File
@@ -1,4 +1,11 @@
from __future__ import annotations
import asyncio
from collections import deque
from time import perf_counter
import numpy as np
from pydantic import BaseModel
async def safe_cancel(task: asyncio.Task) -> None:
@@ -13,3 +20,54 @@ async def safe_cancel(task: asyncio.Task) -> None:
async def safe_cancel_all(tasks: list[asyncio.Task]) -> None:
"""Safely cancels and awaits all asyncio.Tasks."""
await asyncio.gather(*[safe_cancel(task) for task in tasks])
class EventLoopLagMonitor:
"""Monitors how busy the main event loop is by timing short sleeps.
Vendored from verifiers.utils.async_utils (the orchestrator now runs on
v1 and no longer depends on v1 verifiers)."""
def __init__(self, measure_interval: float = 0.1, max_measurements: int = 1000):
assert measure_interval > 0 and max_measurements > 0
self.measure_interval = measure_interval
self.max_measurements = max_measurements
self.lags: deque[float] = deque(maxlen=max_measurements)
async def measure_lag(self) -> float:
next_time = perf_counter() + self.measure_interval
await asyncio.sleep(self.measure_interval)
return perf_counter() - next_time
async def run(self) -> None:
"""Loop measuring event-loop lag; run as a background task."""
while True:
self.lags.append(await self.measure_lag())
class EventLoopLagStats(BaseModel):
"""Snapshot of event-loop lag statistics."""
min: float = 0.0
mean: float = 0.0
median: float = 0.0
p90: float = 0.0
p99: float = 0.0
max: float = 0.0
n: int = 0
@classmethod
def from_monitor(cls, monitor: EventLoopLagMonitor) -> EventLoopLagStats:
n = len(monitor.lags)
if n == 0:
return cls(n=0)
arr = np.array(monitor.lags)
return cls(
min=float(arr.min()),
mean=float(arr.mean()),
median=float(np.median(arr)),
p90=float(np.percentile(arr, 90)),
p99=float(np.percentile(arr, 99)),
max=float(arr.max()),
n=n,
)
+15 -25
View File
@@ -8,16 +8,17 @@ from pathlib import Path
from typing import Protocol, runtime_checkable
import httpx
import verifiers as vf
import verifiers.v1 as vf
from httpx import AsyncClient
from openai import NotFoundError
from renderers import RendererConfig
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
from verifiers.v1.clients.config import EvalClientConfig, TrainClientConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.logger import get_logger
# Identity tuple used by ``select_train_client`` to key load counts. ``api_base_url``
# Identity tuple used by ``select_train_client`` to key load counts. ``base_url``
# distinguishes servers; ``X-data-parallel-rank`` distinguishes DP shards within a
# server, since the router uses that header to route to specific GPU ranks.
ClientIdentity = tuple[str, str | None]
@@ -25,7 +26,7 @@ ClientIdentity = tuple[str, str | None]
def client_identity(client: vf.ClientConfig) -> ClientIdentity:
"""Stable identity for load balancing across inference clients."""
return (client.api_base_url, client.extra_headers.get("X-data-parallel-rank"))
return (client.base_url, client.headers.get("X-data-parallel-rank"))
@runtime_checkable
@@ -185,42 +186,31 @@ def setup_clients(
renderer_model_name: str | None = None,
pool_size: int | None = None,
) -> list[vf.ClientConfig]:
clients = []
client_idx = 0
# Only forward the renderer config when the client actually uses a
# renderer — MITO/TITO clients ignore it.
"""Build v1 client configs (one per base_url × DP rank). ``client_type``
``renderer`` → token-in/out (``TrainClientConfig``, with the renderer the env
server should use forwarded as a serialized config so it doesn't fall back to the
default renderer); otherwise plain chat-completions (``EvalClientConfig``)."""
is_renderer = client_type == "renderer"
config_cls = TrainClientConfig if is_renderer else EvalClientConfig
renderer_extra: dict = {}
if client_type == "renderer":
if is_renderer:
renderer_extra = {
"renderer_config": renderer_config,
"renderer": renderer_config,
"pool_size": pool_size or 1,
"renderer_model_name": renderer_model_name,
"renderer_pool_size": pool_size,
}
env_headers = {
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
}
clients: list[vf.ClientConfig] = []
for base_url in client_config.base_url:
for dp_rank in range(client_config.dp_rank_count):
headers = {**client_config.headers, **env_headers}
if client_config.dp_rank_count > 1:
headers["X-data-parallel-rank"] = str(dp_rank)
clients.append(
vf.ClientConfig(
client_idx=client_idx,
client_type=client_type,
api_base_url=base_url,
api_key_var=client_config.api_key_var,
timeout=client_config.timeout,
connect_timeout=client_config.connect_timeout,
max_connections=8192,
max_keepalive_connections=8192,
max_retries=10,
extra_headers=headers,
extra_headers_from_state=client_config.extra_headers_from_state,
**renderer_extra,
)
config_cls(base_url=base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra)
)
client_idx += 1
return clients
+1 -4
View File
@@ -17,7 +17,7 @@ from pathlib import Path
from typing import Literal
import httpx
import verifiers as vf
import verifiers.v1 as vf
from httpx import AsyncClient
from renderers import RendererConfig
@@ -191,8 +191,6 @@ class ElasticInferencePool:
self._eval_index = 0
url_config = ClientConfig(
timeout=self.client_config.timeout,
connect_timeout=self.client_config.connect_timeout,
base_url=urls,
api_key_var=self.client_config.api_key_var,
headers=self.client_config.headers,
@@ -251,7 +249,6 @@ class ElasticInferencePool:
async def _create_admin_client(self, ip: str) -> AsyncClient:
url = self._build_url(ip)
config = ClientConfig(
timeout=self.client_config.timeout,
base_url=[f"{url}/v1"],
api_key_var=self.client_config.api_key_var,
headers=self.client_config.headers,
+9 -6
View File
@@ -1,8 +1,11 @@
from __future__ import annotations
import random
from abc import ABC, abstractmethod
from typing import Any
from typing import TYPE_CHECKING, Any
import verifiers as vf
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
def sample_items_for_logging(items: list[Any], sample_ratio: float | None) -> list[Any]:
@@ -39,11 +42,11 @@ class Monitor(ABC):
pass
@abstractmethod
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
pass
@abstractmethod
def log_eval_samples(self, rollouts: list[vf.RolloutOutput], env_name: str, step: int) -> None:
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
pass
@abstractmethod
@@ -72,10 +75,10 @@ class NoOpMonitor(Monitor):
else:
self.history = [metrics]
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
pass
def log_eval_samples(self, rollouts: list[vf.RolloutOutput], env_name: str, step: int) -> None:
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
pass
def save_final_summary(self, filename: str = "final_summary.json") -> None:
+7 -4
View File
@@ -1,10 +1,13 @@
from typing import Any
from __future__ import annotations
import verifiers as vf
from typing import TYPE_CHECKING, Any
from prime_rl.utils.logger import get_logger
from prime_rl.utils.monitor.base import Monitor
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
class MultiMonitor(Monitor):
"""Monitor that wraps multiple monitors and delegates calls to all of them."""
@@ -26,14 +29,14 @@ class MultiMonitor(Monitor):
except Exception as e:
self.logger.warning(f"Failed to log metrics to {monitor.__class__.__name__}: {e}")
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
for monitor in self.monitors:
try:
monitor.log_samples(rollouts=rollouts, step=step)
except Exception as e:
self.logger.warning(f"Failed to log samples to {monitor.__class__.__name__}: {e}")
def log_eval_samples(self, rollouts: list[vf.RolloutOutput], env_name: str, step: int) -> None:
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
for monitor in self.monitors:
try:
monitor.log_eval_samples(rollouts=rollouts, env_name=env_name, step=step)
+35 -40
View File
@@ -1,3 +1,5 @@
from __future__ import annotations
import asyncio
import io
import json
@@ -7,12 +9,11 @@ import time
from datetime import datetime, timezone
from pathlib import Path
from threading import Thread
from typing import Any
from typing import TYPE_CHECKING, Any
import httpx
import pyarrow as pa
import pyarrow.parquet as pq
import verifiers as vf
from prime_cli.core.config import Config as PrimeConfig
from transformers.tokenization_utils import PreTrainedTokenizer
@@ -21,14 +22,8 @@ from prime_rl.configs.shared import PrimeMonitorConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
def _json(val: Any) -> str:
"""JSON-serialize dicts/lists, pass strings through, default to empty string for None."""
if isinstance(val, str):
return val
if val is None:
return ""
return json.dumps(val)
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
_SAMPLE_SCHEMA = pa.schema(
@@ -286,7 +281,7 @@ class PrimeMonitor(Monitor):
},
)
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
"""Logs rollouts to Prime Intellect API using presigned URLs for direct R2 upload."""
if not self.is_master:
return
@@ -329,35 +324,35 @@ class PrimeMonitor(Monitor):
f"Initiated samples upload at step {step} to Prime Intellect API in {time.perf_counter() - start_time:.2f}s"
)
def _rollouts_to_parquet_bytes(self, rollouts: list[vf.RolloutOutput], step: int) -> bytes | None:
"""Convert rollouts directly to Parquet bytes for upload."""
def _rollouts_to_parquet_bytes(self, rollouts: list[Rollout], step: int) -> bytes | None:
"""Convert rollouts to Parquet bytes for upload. One row per rollout, built from the
message graph: the conversation is the unit (no prompt/completion split — meaningless in
a multi-turn branch), so `completion` carries the main (last) branch's full message list
and `trajectory` carries one message list per branch (`trace.branches`)."""
now = datetime.now(timezone.utc)
rows = []
for sample_id, rollout in enumerate(rollouts):
prompt = rollout.get("prompt")
completion = rollout.get("completion")
trajectory = rollout.get("trajectory") or []
if prompt is None or completion is None or not trajectory:
branches = rollout.branches
if not branches:
continue
main_messages = [m.model_dump(mode="json") for m in branches[-1].messages]
example_id = rollout.get("example_id")
task_idx = rollout.task.idx
try:
problem_id = int(example_id) if example_id is not None else sample_id
problem_id = int(task_idx) if task_idx is not None else sample_id
except (TypeError, ValueError):
problem_id = sample_id
trajectory_data = [
{
"prompt": ts["prompt"],
"completion": ts["completion"],
"reward": ts.get("reward"),
"advantage": ts.get("advantage"),
"extras": ts.get("extras", {}),
"num_input_tokens": len(ts["tokens"]["prompt_ids"]) if ts.get("tokens") else None,
"num_output_tokens": len(ts["tokens"]["completion_ids"]) if ts.get("tokens") else None,
"messages": [m.model_dump(mode="json") for m in branch.messages],
"reward": rollout.reward,
"advantage": rollout.advantage,
"num_input_tokens": branch.prompt_len,
"num_output_tokens": branch.completion_len,
}
for ts in trajectory
for branch in branches
]
rows.append(
@@ -367,19 +362,19 @@ class PrimeMonitor(Monitor):
"tag": "",
"problem_id": problem_id,
"sample_id": sample_id,
"prompt": json.dumps(prompt),
"completion": json.dumps(completion),
"prompt": "",
"completion": json.dumps(main_messages),
"trajectory": json.dumps(trajectory_data),
"answer": rollout.get("answer") or "",
"env_name": rollout.get("env_name") or "",
"task": rollout.get("task") or "",
"info": _json(rollout.get("info")),
"reward": rollout.get("reward"),
"advantage": rollout.get("advantage"),
"metrics": _json(rollout.get("metrics")),
"timing": _json(rollout.get("timing")),
"num_input_tokens": 0,
"num_output_tokens": 0,
"answer": "",
"env_name": rollout.env_name,
"task": rollout.task.model_dump_json(),
"info": json.dumps(rollout.info),
"reward": rollout.reward,
"advantage": rollout.advantage,
"metrics": json.dumps(rollout.metrics),
"timing": rollout.timing.model_dump_json(),
"num_input_tokens": branches[-1].prompt_len,
"num_output_tokens": branches[-1].completion_len,
"created_at": now,
}
)
@@ -492,7 +487,7 @@ class PrimeMonitor(Monitor):
await asyncio.sleep(delay)
return False
def log_eval_samples(self, rollouts: list[vf.RolloutOutput], env_name: str, step: int) -> None:
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
pass
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
+61 -44
View File
@@ -1,22 +1,42 @@
from __future__ import annotations
import json
import os
import sys
import time
from pathlib import Path
from typing import Any
from typing import TYPE_CHECKING, Any
import verifiers as vf
import wandb
from transformers.tokenization_utils import PreTrainedTokenizer
from wandb.errors import CommError
from wandb.sdk.mailbox.mailbox_handle import ServerResponseError
from prime_rl.configs.shared import WandbConfig, WandbWithExtrasConfig
from prime_rl.utils.chat_template import deserialize_tool_calls
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
def _loggable_task(task) -> str:
"""A Table-safe JSON string of the task for sample logging. Image content parts are elided to
a short placeholder — their base64 data bloats the table and breaks wandb Table's nested-type
inference on the variable-length content list (a plain dict would otherwise crash on it)."""
def elide(obj):
if isinstance(obj, dict):
if obj.get("type") == "image_url":
return {"type": "image_url", "image_url": "<image>"}
return {k: elide(v) for k, v in obj.items()}
if isinstance(obj, list):
return [elide(v) for v in obj]
return obj
return json.dumps(elide(task.model_dump(mode="json")))
class WandbMonitor(Monitor):
"""Logs to Weights and Biases."""
@@ -113,13 +133,13 @@ class WandbMonitor(Monitor):
if config is not None and isinstance(config, WandbWithExtrasConfig) and config.log_extras:
if config.log_extras.samples:
self.last_log_samples_step = -1
self.samples_cols = ["step", "env_name", "task", "example_id", "messages", "input_ids", "reward"]
self.samples_cols = ["step", "env_name", "task", "task_idx", "messages", "input_ids", "reward"]
self.samples_table = wandb.Table(
columns=self.samples_cols,
log_mode="INCREMENTAL",
)
self.tokenizer = tokenizer
self.eval_samples_cols = ["step", "env", "task", "example_id", "completion", "reward"]
self.eval_samples_cols = ["step", "env", "task", "task_idx", "completion", "reward"]
self.eval_samples_table = wandb.Table(
columns=self.eval_samples_cols,
log_mode="INCREMENTAL",
@@ -143,7 +163,7 @@ class WandbMonitor(Monitor):
return
wandb.log({**metrics, "step": step})
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
"""Logs rollouts to W&B table."""
if not self.is_master:
return
@@ -172,32 +192,30 @@ class WandbMonitor(Monitor):
start_time = time.perf_counter()
for rollout in rollouts:
trajectory = rollout["trajectory"]
if not trajectory:
continue
last_step = trajectory[-1]
tokens = last_step["tokens"]
full_ids = tokens["prompt_ids"] + tokens["completion_ids"]
messages_text = self.tokenizer.decode(full_ids)
sample = {
"step": step,
"env_name": rollout.get("env_name"),
"task": rollout.get("task"),
"example_id": rollout["example_id"],
"messages": messages_text,
"input_ids": str(full_ids),
"reward": rollout["reward"],
}
assert list(sample.keys()) == self.samples_cols, (
"Order of columns in the table must be the same as order of the keys here"
)
self.samples_table.add_data(*sample.values())
trace = rollout
for branch in trace.branches:
token_ids = branch.token_ids
if not token_ids:
continue
sample = {
"step": step,
"env_name": rollout.env_name,
"task": _loggable_task(trace.task),
"task_idx": trace.task.idx,
"messages": self.tokenizer.decode(token_ids),
"input_ids": str(token_ids),
"reward": trace.reward,
}
assert list(sample.keys()) == self.samples_cols, (
"Order of columns in the table must be the same as order of the keys here"
)
self.samples_table.add_data(*sample.values())
wandb.log({"samples": self.samples_table, "step": step})
self.last_log_samples_step = step
self.logger.debug(f"Logged samples at step {step} to W&B table in {time.perf_counter() - start_time:.2f}s")
def log_eval_samples(self, rollouts: list[vf.RolloutOutput], env_name: str, step: int) -> None:
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
"""Logs eval rollouts to a separate W&B table."""
if not self.is_master:
return
@@ -210,23 +228,22 @@ class WandbMonitor(Monitor):
return
for rollout in rollouts:
completion = rollout.get("completion")
if not completion:
continue
if isinstance(completion, list):
try:
completion = self.tokenizer.apply_chat_template(deserialize_tool_calls(completion), tokenize=False)
except Exception:
completion = str(completion)
sample = {
"step": step,
"env": env_name,
"task": rollout.get("task"),
"example_id": rollout["example_id"],
"completion": completion,
"reward": rollout["reward"],
}
self.eval_samples_table.add_data(*sample.values())
trace = rollout
for branch in trace.branches:
# Eval runs the openai client (no token ids), so show the assistant message
# content rather than decoded tokens.
completion = "".join(m.content or "" for m in branch.messages if m.role == "assistant")
if not completion:
continue
sample = {
"step": step,
"env": env_name,
"task": _loggable_task(trace.task),
"task_idx": trace.task.idx,
"completion": completion,
"reward": trace.reward,
}
self.eval_samples_table.add_data(*sample.values())
wandb.log({"eval/samples": self.eval_samples_table, "step": step})
-30
View File
@@ -2,7 +2,6 @@ import asyncio
import functools
import importlib
import os
import subprocess
import sys
from collections import defaultdict
from contextlib import contextmanager
@@ -13,7 +12,6 @@ import torch
import torch.distributed as dist
import wandb
from prime_rl.configs.orchestrator import EnvConfig, EvalEnvConfig
from prime_rl.utils.logger import get_logger
# TODO: Change all imports to use utils.pathing
@@ -229,31 +227,3 @@ def default_dtype(dtype):
yield
finally:
torch.set_default_dtype(prev)
def install_env(env_id: str, prerelease: bool = False) -> None:
"""Install an environment in subprocess."""
logger = get_logger()
logger.info(f"Installing environment {env_id}")
install_cmd = ["uv", "run", "--no-sync", "prime", "env", "install", env_id]
if prerelease:
install_cmd.insert(-1, "--prerelease")
result = subprocess.run(install_cmd, capture_output=True, text=True)
for line in result.stdout.splitlines():
if line.strip():
logger.info(line)
for line in result.stderr.splitlines():
if line.strip():
logger.warning(line)
if result.returncode != 0:
raise RuntimeError(f"Failed to install environment {env_id} (exit code {result.returncode})")
logger.info(f"Successfully installed environment {env_id}")
def get_env_ids_to_install(env_configs: list[EnvConfig] | list[EvalEnvConfig]) -> set[str]:
"""Get the list of environment IDs to install."""
env_ids_to_install = set()
for env_config in env_configs:
if "/" in env_config.id:
env_ids_to_install.add(env_config.id)
return env_ids_to_install
+11
View File
@@ -29,6 +29,7 @@ VLM_REGISTRY: dict[str, VLMModelInfo] = {
"qwen3_5": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"qwen3_5_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"qwen3_vl_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"gemma4": VLMModelInfo(vision_encoder_attr="model.vision_tower", language_model_attr="model.language_model"),
}
# Text-only default
@@ -86,6 +87,16 @@ def is_vlm_architecture(model_config: PretrainedConfig) -> bool:
return _get_model_info_from_config(model_config) is not None
def get_final_logit_softcapping(model_config: PretrainedConfig) -> float | None:
"""Read ``final_logit_softcapping`` from the text config.
For composite VLM configs (e.g. Gemma) the value lives under ``text_config``;
``get_text_config()`` returns that for VLMs and the config itself for text-only
models, so a plain top-level ``getattr`` would miss it and silently drop softcapping.
"""
return getattr(model_config.get_text_config(), "final_logit_softcapping", None)
def get_layer_prefix(model_config: PretrainedConfig, override: str | None = None) -> str:
"""Return the weight key prefix for language model layers.
-62
View File
@@ -1,62 +0,0 @@
from pathlib import Path
from typing import Callable
import pytest
from tests.conftest import ProcessResult
from tests.utils import check_mismatch_kl_in_range, check_no_error, check_reward_goes_up, strip_escape_codes
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
"""Fixture for W&B name for RL CI integration tests."""
return f"acereason-math-{branch_name}"
@pytest.fixture(scope="module")
def rl_process(
run_process: Callable[..., ProcessResult],
output_dir: Path,
wandb_project: str,
wandb_name: str,
) -> ProcessResult:
cmd = [
"uv",
"run",
"rl",
"@",
"configs/ci/nightly/acereason_math.toml",
"--wandb.project",
wandb_project,
"--wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
]
return run_process(cmd)
MISMATCH_KL_MIN = 0.0
MISMATCH_KL_MAX = 0.0015
@pytest.fixture(scope="module")
def test_no_error(rl_process: ProcessResult, output_dir: Path):
"""Tests that the RL process does not fail."""
check_no_error(rl_process, output_dir)
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
"""Tests that the reward goes up in the RL process"""
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
check_reward_goes_up(orchestrator_stdout)
def test_mismatch_kl_in_band(rl_process: ProcessResult, test_no_error, output_dir: Path):
"""Tests that mismatch KL stays within the expected band."""
with open(output_dir / "logs" / "trainer.log", "r") as f:
trainer_stdout = strip_escape_codes(f.read()).splitlines()
check_mismatch_kl_in_range(trainer_stdout, min_threshold=MISMATCH_KL_MIN, max_threshold=MISMATCH_KL_MAX)

Some files were not shown because too many files have changed in this diff Show More