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>
This commit is contained in:
Mika Senghaas
2026-06-23 18:04:57 -07:00
committed by GitHub
co-authored by Claude Opus 4.8 S1ro1 Matej Sirovatka rasdani Codex
parent 38494ccb41
commit 7089ba1e4d
67 changed files with 2187 additions and 4386 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}")
+6
View File
@@ -2,6 +2,12 @@
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)
@@ -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
-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
+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
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.dev357",
]
[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
@@ -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,6 +142,69 @@ class EvalSamplingConfig(BaseConfig):
return data
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."""
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."""
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 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."""
@@ -177,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."""
@@ -269,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:
@@ -291,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
@@ -318,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)
@@ -330,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."""
@@ -345,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:
@@ -359,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")
@@ -509,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."""
@@ -621,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")
@@ -748,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")
@@ -808,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
@@ -826,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")
@@ -876,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")
@@ -900,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
@@ -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."""
+45 -6
View File
@@ -33,13 +33,16 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers",
"verifiers>=0.1.15.dev357",
"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]
@@ -94,6 +97,24 @@ envs = [
"tau2-bench",
"wiki-search",
"wordle",
"reverse-text-v1",
"gsm8k-v1",
"math-env-v1",
"aime24-v1",
"alphabet-sort-v1",
"scaleswe-v1",
"color-codeword-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",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64'",
@@ -153,7 +174,7 @@ override-dependencies = [
"transformers==5.6.2",
"torch>=2.9.0",
"openenv-core",
"verifiers[packages]>=0.1.15.dev150",
"verifiers>=0.1.15.dev357",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -188,8 +209,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
@@ -200,6 +219,10 @@ 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/environments.
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
@@ -211,7 +234,6 @@ color-codeword = { path = "deps/research-environments/environments/color_codewor
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 }
@@ -233,9 +255,26 @@ rlm-uuid-ctf = { path = "deps/research-environments/environments/rlm_uuid_ctf",
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/verifiers/environments/math_env_v1", editable = true }
aime24-v1 = { path = "deps/verifiers/environments/aime24_v1", editable = true }
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
scaleswe-v1 = { path = "deps/verifiers/environments/scaleswe_v1", editable = true }
color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", editable = true }
r2e-gym-v1 = { path = "deps/verifiers/environments/r2e_gym_v1", editable = true }
terminal-bench-2-v1 = { path = "deps/verifiers/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/verifiers/environments/swelego_v1", editable = true }
wiki-search-v1 = { path = "deps/verifiers/environments/wiki_search_v1", editable = true }
wikispeedia-v1 = { path = "deps/verifiers/environments/wikispeedia_v1", editable = true }
wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
general-agent-v1 = { path = "deps/verifiers/environments/general_agent_v1", editable = true }
swebench-verified-v1 = { path = "deps/verifiers/environments/swebench_verified_v1", editable = true }
torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
+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
+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
+9 -10
View File
@@ -4,17 +4,17 @@ from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable
import torch
import verifiers as vf
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,
LinearLengthPenaltyConfig,
)
from prime_rl.orchestrator.utils import get_model_completion_len
from prime_rl.utils.utils import import_object
@@ -22,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
@@ -57,8 +57,8 @@ def default_advantage_fn(
(``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)
lengths = torch.tensor([get_model_completion_len(r) for r in inputs.rollouts], dtype=rewards.dtype)
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 length_penalty is not None:
if max_seq_len is None:
@@ -98,19 +98,18 @@ def setup_advantage_fn(config: AdvantageConfig, max_seq_len: int | None = None)
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
+38 -69
View File
@@ -6,7 +6,7 @@
- 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
@@ -29,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
@@ -159,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
@@ -382,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,
@@ -436,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,
@@ -449,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,
)
@@ -493,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
@@ -603,8 +564,12 @@ 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
@@ -625,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():
+153 -120
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:
@@ -165,15 +205,11 @@ class TrainEnv(Env):
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, 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
+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:
+19 -17
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,14 @@ 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 node in rollout.nodes:
# token_ids / logprobs / mask are per-token aligned; check only the
# sampled completion tokens, pairing each with its own logprob.
for token_id, logprob, sampled in zip(node.token_ids, node.logprobs, node.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 +80,15 @@ class RepetitionFilter:
logprob_threshold: float
enforce: bool = False
def check(self, rollout: "TrainRollout") -> FilterResult:
def check(self, rollout: Rollout) -> FilterResult:
consecutive = 0
global_idx = 0
for step in rollout.raw["trajectory"]:
tokens = step["tokens"]
if tokens is None:
continue
for logprob in tokens["completion_logprobs"]:
for node in rollout.nodes:
# Streak only over sampled completion tokens — context/prompt tokens
# (mask=False) are not model-generated and must not feed the loop count.
for logprob, sampled in zip(node.logprobs, node.mask):
if not sampled:
continue
if logprob > self.logprob_threshold:
consecutive += 1
else:
@@ -105,7 +107,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 +149,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)
+36 -82
View File
@@ -21,7 +21,6 @@ in ``setup()`` and drives them from ``main_loop()``.
from __future__ import annotations
import asyncio
import logging
import os
import time
from typing import TYPE_CHECKING
@@ -36,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
@@ -57,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,
@@ -76,7 +71,7 @@ from prime_rl.orchestrator.utils import (
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})")
@@ -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)
@@ -495,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,
@@ -588,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:
@@ -626,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],
@@ -648,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
@@ -661,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
@@ -758,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:
@@ -782,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))
@@ -802,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:
@@ -825,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%}"
)
@@ -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
+25 -58
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,7 +164,7 @@ class EvalBatch:
env_name: str
step: int
rollouts: list[EvalRollout]
rollouts: list[Rollout]
metrics: EvalBatchMetrics
+35 -47
View File
@@ -2,20 +2,19 @@ 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,
@@ -24,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):
@@ -92,6 +66,15 @@ 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})")
@@ -114,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
@@ -136,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,
@@ -57,6 +57,7 @@ LLMD_EOF
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)
+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,
)
@@ -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,
+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
+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
+33 -39
View File
@@ -1,6 +1,5 @@
import uuid
import pytest
import verifiers.v1 as vf
from prime_rl.configs.orchestrator import (
CustomAdvantageConfig,
@@ -16,17 +15,22 @@ from prime_rl.orchestrator.advantage import (
setup_advantage_fn,
)
from prime_rl.orchestrator.envs import Env, TrainEnv
from prime_rl.orchestrator.types import TrainRollout
from prime_rl.orchestrator.types import Rollout
def _make_rollout(reward: float, completion_len: int = 0) -> dict:
"""Minimal single-turn rollout dict with ``completion_len`` completion tokens."""
return {
"reward": reward,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(completion_len))}}],
"env_name": "test",
"example_id": 0,
}
def _make_rollout(reward: float, completion_len: int = 0, env_name: str = "test") -> Rollout:
"""Build a ``Rollout`` (message-graph trace): ``reward`` via the reward dict and
``completion_len`` model-sampled completion tokens (a single assistant node)."""
node = vf.MessageNode(
message=vf.AssistantMessage(content="x"),
token_ids=list(range(completion_len)),
mask=[True] * completion_len,
logprobs=[0.0] * completion_len,
sampled=True,
)
rollout = Rollout[vf.Task](task=vf.Task(idx=0, prompt=""), nodes=[node], rewards={"reward": reward})
rollout.env_name = env_name
return rollout
def _make_group(rewards, completion_lengths=None) -> AdvantageInputs:
@@ -38,6 +42,11 @@ def _make_group(rewards, completion_lengths=None) -> AdvantageInputs:
return AdvantageInputs(rollouts=rollouts)
def _train_rollouts(rewards: list[float]) -> list[Rollout]:
"""One group's worth of Rollouts for ``assign_advantages`` (operates on a single group)."""
return [Rollout[vf.Task](task=vf.Task(idx=0, prompt=""), rewards={"reward": r}) for r in rewards]
def test_default_advantage_fn_simple_mean():
inputs = _make_group(rewards=[1.0, 0.5, 0.8], completion_lengths=[10, 12, 8])
result = default_advantage_fn(inputs)
@@ -105,14 +114,18 @@ def test_train_env_threads_max_seq_len_into_advantage_fn(monkeypatch):
def fake_env_init(self, config):
self.config = config
self._env = None
self._env_client = None
self._env_server_process = None
monkeypatch.setattr(Env, "__init__", fake_env_init)
config = OrchestratorConfig(
seq_len=100,
advantage={"type": "default", "length_penalty": {"coef": 1.0}},
train={
"env": [
{
"taskset": {"id": "reverse-text-v1"},
"advantage": {"type": "default", "length_penalty": {"coef": 1.0}},
}
]
},
)
env = TrainEnv(config.train.env[0], max_seq_len=config.seq_len)
@@ -128,12 +141,10 @@ def test_per_env_linear_advantage_uses_runtime_schema():
train={
"env": [
{
"advantage": {
"type": "default",
"length_penalty": {"coef": 1.0},
},
"taskset": {"id": "reverse-text-v1"},
"advantage": {"type": "default", "length_penalty": {"coef": 1.0}},
}
],
]
},
)
@@ -152,6 +163,7 @@ def test_per_env_custom_advantage_uses_runtime_schema():
train={
"env": [
{
"taskset": {"id": "reverse-text-v1"},
"advantage": {
"type": "custom",
"import_path": "tests.unit.orchestrator.test_advantage._dummy_custom_advantage",
@@ -183,24 +195,6 @@ def test_length_weighted_baseline():
assert sum(length * adv for length, adv in zip((10, 30, 60), result.advantages)) == pytest.approx(0.0, abs=1e-5)
def _train_rollouts(rewards: list[float]) -> list[TrainRollout]:
"""Wrap a list of rewards into ``TrainRollout``\\ s sharing a single
``group_id`` — ``assign_advantages`` works on one group at a time
(the sink groups by ``group_id`` upstream)."""
gid = uuid.uuid4()
return [
TrainRollout(
raw={"reward": r, "trajectory": []},
env_name="test",
example_id=0,
group_id=gid,
policy_version=0,
off_policy_steps=0,
)
for r in rewards
]
def test_assign_advantages_writes_field():
rollouts = _train_rollouts([1.0, 0.5, 0.8])
fn = setup_advantage_fn(DefaultAdvantageConfig())
@@ -240,4 +234,4 @@ def test_setup_advantage_fn_with_custom_config():
def _dummy_custom_advantage(inputs: AdvantageInputs, scale: float = 1.0) -> AdvantageOutputs:
"""A simple custom advantage for testing."""
return AdvantageOutputs(advantages=[r["reward"] * scale for r in inputs.rollouts])
return AdvantageOutputs(advantages=[r.reward * scale for r in inputs.rollouts])
+188 -72
View File
@@ -3,13 +3,9 @@ from types import SimpleNamespace
import numpy as np
import pytest
from prime_rl.trainer.batch import (
pad_micro_batch,
prepare_batch,
prepare_sample,
)
from prime_rl.trainer.batch import pad_micro_batch, prepare_batch, prepare_sample
from prime_rl.trainer.utils import build_bin_cost
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
def _routed_experts(data, dtype=np.uint8):
@@ -29,12 +25,10 @@ def make_training_example():
env_name: str = "test-env",
) -> TrainingSample:
return TrainingSample(
prompt_ids=[1, 2],
prompt_mask=[False, False],
completion_ids=[3, 4],
completion_mask=[True, True],
completion_logprobs=[-0.1, -0.2],
completion_temperatures=[temperature, temperature], # Per-token temperatures
token_ids=[1, 2, 3, 4],
mask=[False, False, True, True],
logprobs=[0.0, 0.0, -0.1, -0.2],
temperatures=[temperature, temperature, temperature, temperature],
teacher_logprobs=[0.0, 0.0, 0.0, 0.0],
advantage=1.0,
env_name=env_name,
@@ -48,12 +42,10 @@ def make_sized_training_example(length: int, env_name: str = "test-env") -> Trai
assert length >= 1
prompt_len = length - 1
return TrainingSample(
prompt_ids=[1] * prompt_len,
prompt_mask=[False] * prompt_len,
completion_ids=[2],
completion_mask=[True],
completion_logprobs=[-0.1],
completion_temperatures=[1.0],
token_ids=[1] * prompt_len + [2],
mask=[False] * prompt_len + [True],
logprobs=[0.0] * prompt_len + [-0.1],
temperatures=[1.0] * length,
advantage=1.0,
env_name=env_name,
)
@@ -120,35 +112,8 @@ def test_randomized_packing_invariants():
assert not any(batch.advantages)
def test_prepare_batch_packs_different_temperatures(make_training_example):
"""With per-token temperatures, samples can be packed together regardless of their temperature values."""
example1 = make_training_example(temperature=0.7, env_name="env-a")
example2 = make_training_example(temperature=1.1, env_name="env-b")
batches_per_gpu = prepare_batch(
rollouts=[example1, example2],
seq_len=16,
num_train_workers=1,
idxs=[0, 0],
num_loras=1,
bin_cost=build_bin_cost(None),
)
flat_batches = _flatten_batches(batches_per_gpu)
# With per-token temperatures, samples can now be packed together
assert len(flat_batches) == 1
# Each sample has 4 tokens (2 prompt + 2 completion), so 8 total tokens
assert len(flat_batches[0].temperatures) == 8
# First sample (4 tokens): all get temp 0.7
assert flat_batches[0].temperatures[:4] == [0.7, 0.7, 0.7, 0.7]
# Second sample (4 tokens): all get temp 1.1
assert flat_batches[0].temperatures[4:8] == [1.1, 1.1, 1.1, 1.1]
assert flat_batches[0].env_names == ["env-a"] * 4 + ["env-b"] * 4
assert flat_batches[0].sequence_lengths == [4, 4]
def test_pad_micro_batch_preserves_explicit_sequence_lengths(make_training_example):
micro_batch = prepare_sample(make_training_example(), seq_len=16)
def test_pad_micro_batch_preserves_explicit_sequence_lengths():
micro_batch = prepare_sample(make_sized_training_example(4), seq_len=16)
padded = pad_micro_batch(micro_batch, pad_to_multiple_of=6)
@@ -158,25 +123,6 @@ def test_pad_micro_batch_preserves_explicit_sequence_lengths(make_training_examp
assert padded.loss_mask[-2:] == [False, False]
def test_prepare_batch_does_not_pack_mixed_training_mode(make_training_example):
rl_example = make_training_example(training_mode="rl")
sft_example = make_training_example(training_mode="sft")
batches_per_gpu = prepare_batch(
rollouts=[rl_example, sft_example],
seq_len=16,
num_train_workers=1,
idxs=[0, 0],
num_loras=1,
bin_cost=build_bin_cost(None),
)
flat_batches = _flatten_batches(batches_per_gpu)
assert len(flat_batches) == 2
assert {batch.training_mode for batch in flat_batches} == {"rl", "sft"}
assert [batch.sequence_lengths for batch in flat_batches] == [[4], [4]]
def test_split_to_align_avoids_dummy_micro_batches():
examples = [make_sized_training_example(length) for length in [6, 6, 5, 5, 4, 4]]
@@ -244,18 +190,136 @@ def test_flop_aware_split_to_align_splits_heaviest_flop_bin():
assert sum(len(batch.sequence_lengths) > 1 for batch in real_batches) == 3
def test_training_sample_requires_env_name():
with pytest.raises(TypeError, match="env_name"):
TrainingSample(
token_ids=[1, 2, 3, 4],
mask=[False, False, True, True],
logprobs=[0.0, 0.0, -0.1, -0.2],
temperatures=[1.0, 1.0, 1.0, 1.0],
advantage=1.0,
)
@pytest.mark.parametrize(
("rollout_count", "num_train_workers", "expected_batches_per_worker"), [(4, 2, 2), (5, 2, 3), (7, 1, 7), (11, 4, 3)]
)
def test_prepare_batch_balances_micro_batches_across_workers(
make_training_example, rollout_count, num_train_workers, expected_batches_per_worker
):
examples = [make_training_example() for i in range(rollout_count)]
batches_per_gpu = prepare_batch(
rollouts=examples,
seq_len=4,
num_train_workers=num_train_workers,
idxs=[0] * rollout_count,
num_loras=1,
bin_cost=build_bin_cost(None),
)
assert all(len(worker_batches) == expected_batches_per_worker for worker_batches in batches_per_gpu)
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
assert len(examples) <= len(flat_batches) < len(examples) + num_train_workers
print(flat_batches)
# Real rollouts and dummy padding can be interleaved across workers by the
# FLOP-balanced partition, so classify by content rather than position.
real_batches = [b for b in flat_batches if any(advantage != 0.0 for advantage in b.advantages)]
assert len(real_batches) == len(examples)
for batch in real_batches:
assert sum(1 for advantage in batch.advantages if advantage != 0.0) == 4
assert sum(1 for loss_mask in batch.loss_mask if loss_mask) == 2
# Dummy padding batches have zero advantages and loss mask.
for batch in flat_batches:
if all(advantage == 0.0 for advantage in batch.advantages):
assert sum(1 for loss_mask in batch.loss_mask if loss_mask) == 0
def test_prepare_batch_packs_different_temperatures(make_training_example):
"""With per-token temperatures, samples can be packed together regardless of their temperature values."""
example1 = make_training_example(temperature=0.7, env_name="env-a")
example2 = make_training_example(temperature=1.1, env_name="env-b")
batches_per_gpu = prepare_batch(
rollouts=[example1, example2],
seq_len=16,
num_train_workers=1,
idxs=[0, 0],
num_loras=1,
bin_cost=build_bin_cost(None),
)
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
# With per-token temperatures, samples can now be packed together
assert len(flat_batches) == 1
# Each sample has 4 tokens (2 prompt + 2 completion), so 8 total tokens
assert len(flat_batches[0].temperatures) == 8
# First sample (4 tokens): all get temp 0.7
assert flat_batches[0].temperatures[:4] == [0.7, 0.7, 0.7, 0.7]
# Second sample (4 tokens): all get temp 1.1
assert flat_batches[0].temperatures[4:8] == [1.1, 1.1, 1.1, 1.1]
assert flat_batches[0].env_names == ["env-a"] * 4 + ["env-b"] * 4
def test_prepare_sample_propagates_training_mode(make_training_example):
example = make_training_example(training_mode="sft")
micro_batch = prepare_sample(example, seq_len=16)
assert micro_batch.training_mode == "sft"
def test_prepare_batch_does_not_pack_mixed_training_mode(make_training_example):
rl_example = make_training_example(training_mode="rl")
sft_example = make_training_example(training_mode="sft")
batches_per_gpu = prepare_batch(
rollouts=[rl_example, sft_example],
seq_len=16,
num_train_workers=1,
idxs=[0, 0],
num_loras=1,
bin_cost=build_bin_cost(None),
)
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
assert len(flat_batches) == 2
assert {batch.training_mode for batch in flat_batches} == {"rl", "sft"}
def test_prepare_sample_with_routed_experts():
"""Routed experts are passed through prepare_sample and match input_ids length."""
# 2 prompt + 2 completion = 4 tokens, 2 layers, topk=2
routed_experts = [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[0, 2], [1, 3]], [[1, 0], [3, 2]]]
routed_payload = _routed_experts(routed_experts)
sample = TrainingSample(
token_ids=[1, 2, 3, 4],
mask=[False, False, True, True],
logprobs=[0.0, 0.0, -0.1, -0.2],
temperatures=[1.0, 1.0, 1.0, 1.0],
advantage=1.0,
env_name="test-env",
routed_experts=routed_payload,
)
micro_batch = prepare_sample(sample, seq_len=8)
assert micro_batch.routed_experts is not None
assert micro_batch.routed_experts == routed_payload
def test_prepare_sample_truncates_routed_experts():
"""Routed experts are truncated to seq_len when input exceeds it."""
routed_experts = [[[0, 1]], [[2, 3]], [[4, 5]], [[6, 7]]]
routed_payload = _routed_experts(routed_experts)
expected_payload = _routed_experts(routed_experts[:3])
sample = TrainingSample(
prompt_ids=[1, 2],
prompt_mask=[False, False],
completion_ids=[3, 4],
completion_mask=[True, True],
completion_logprobs=[-0.1, -0.2],
completion_temperatures=[1.0, 1.0],
token_ids=[1, 2, 3, 4],
mask=[False, False, True, True],
logprobs=[0.0, 0.0, -0.1, -0.2],
temperatures=[1.0, 1.0, 1.0, 1.0],
advantage=1.0,
env_name="test-env",
routed_experts=routed_payload,
@@ -265,3 +329,55 @@ def test_prepare_sample_truncates_routed_experts():
assert micro_batch.routed_experts is not None
assert micro_batch.routed_experts == expected_payload
assert micro_batch.env_names == ["test-env"] * 3
def _encoded(arr) -> EncodedTensor:
a = np.asarray(arr)
return EncodedTensor(data=a.tobytes(), shape=list(a.shape), dtype=str(a.dtype))
def test_prepare_sample_truncates_mm_at_image_boundary():
"""Truncation never splits an image's placeholder block: it cuts to a whole-image boundary
and slices mm_kwargs to match, so image-token count stays == image-embedding count."""
# Two 2-token images (patches-per-token = 1): image-pad at indices 1,2 (img0) and 4,5 (img1).
mm_token_type_ids = [0, 1, 1, 0, 1, 1, 0]
pixel_values = np.array([[1.0], [1.0], [2.0], [2.0]], dtype=np.float32) # img0=1.0, img1=2.0
grid = np.array([[1, 2, 1], [1, 2, 1]], dtype=np.int64)
sample = TrainingSample(
token_ids=[10, 11, 12, 13, 14, 15, 16],
mask=[False, False, False, False, False, True, True],
logprobs=[0.0] * 7,
temperatures=[1.0] * 7,
advantage=1.0,
env_name="test-env",
mm_token_type_ids=mm_token_type_ids,
mm_kwargs={"pixel_values": _encoded(pixel_values), "image_grid_thw": _encoded(grid)},
)
# seq_len=5 falls inside img1 (one of its two placeholders survives) -> drop img1 entirely.
mb = prepare_sample(sample, seq_len=5)
assert len(mb.input_ids) == 4 # cut back to img1's first placeholder (index 4)
assert len(mb.mm_token_type_ids) == len(mb.input_ids)
n_placeholders = sum(1 for t in mb.mm_token_type_ids if t)
assert n_placeholders == 2 # only img0's two placeholders remain
# No mismatch: placeholders == image embeddings, and only img0's pixels are kept.
assert mb.mm_kwargs["pixel_values"].shape == [2, 1]
assert mb.mm_kwargs["image_grid_thw"].shape == [1, 3]
kept = np.frombuffer(bytearray(mb.mm_kwargs["pixel_values"].data), dtype=np.float32)
assert kept.tolist() == [1.0, 1.0]
assert n_placeholders == mb.mm_kwargs["pixel_values"].shape[0] # ppt == 1 here
def test_prepare_sample_none_routed_experts():
"""When routed_experts is None, micro_batch.routed_experts is None."""
sample = TrainingSample(
token_ids=[1, 2, 3, 4],
mask=[False, False, True, True],
logprobs=[0.0, 0.0, -0.1, -0.2],
temperatures=[1.0, 1.0, 1.0, 1.0],
advantage=1.0,
env_name="test-env",
)
micro_batch = prepare_sample(sample, seq_len=8)
assert micro_batch.routed_experts is None
+39 -57
View File
@@ -1,6 +1,8 @@
import math
import uuid
import verifiers.v1 as vf
from prime_rl.configs.orchestrator import GibberishFilterConfig, RepetitionFilterConfig
from prime_rl.orchestrator.filters import (
GibberishFilter,
@@ -9,7 +11,18 @@ from prime_rl.orchestrator.filters import (
setup_filter,
setup_filters,
)
from prime_rl.orchestrator.types import TrainRollout
from prime_rl.orchestrator.types import Rollout
def _assistant_node(token_ids: list[int], logprobs: list[float]) -> vf.MessageNode:
"""An assistant node whose tokens are all model-sampled (the filters read each node's
masked-True tokens + logprobs)."""
return vf.MessageNode(
message=vf.AssistantMessage(content="x"),
token_ids=token_ids,
mask=[True] * len(token_ids),
logprobs=logprobs,
)
def _make_rollout(
@@ -18,52 +31,21 @@ def _make_rollout(
*,
reward: float = 1.0,
multi_step: bool = False,
) -> TrainRollout:
"""Build a ``TrainRollout`` with a minimal ``vf.RolloutOutput``-shaped
raw payload — enough for the filters to inspect ``trajectory`` /
``stop_condition`` / etc."""
) -> Rollout:
"""Build a ``Rollout`` (a message-graph trace) carrying the completion tokens — enough for
the filters to inspect each node's sampled tokens / logprobs."""
if multi_step:
mid = len(completion_ids) // 2
trajectory = [
{
"tokens": {
"completion_ids": completion_ids[:mid],
"completion_logprobs": completion_logprobs[:mid],
"completion_mask": [1] * mid,
}
},
{
"tokens": {
"completion_ids": completion_ids[mid:],
"completion_logprobs": completion_logprobs[mid:],
"completion_mask": [1] * (len(completion_ids) - mid),
}
},
nodes = [
_assistant_node(completion_ids[:mid], completion_logprobs[:mid]),
_assistant_node(completion_ids[mid:], completion_logprobs[mid:]),
]
else:
trajectory = [
{
"tokens": {
"completion_ids": completion_ids,
"completion_logprobs": completion_logprobs,
"completion_mask": [1] * len(completion_ids),
}
}
]
raw = {
"trajectory": trajectory,
"reward": reward,
"stop_condition": None,
"metrics": {},
}
return TrainRollout(
raw=raw,
env_name="test",
example_id=0,
group_id=uuid.uuid4(),
policy_version=0,
off_policy_steps=0,
)
nodes = [_assistant_node(completion_ids, completion_logprobs)]
rollout = Rollout[vf.Task](task=vf.Task(idx=0, prompt=""), nodes=nodes, rewards={"reward": reward})
rollout.env_name = "test"
rollout.group_id = uuid.uuid4()
return rollout
def _make_gibberish_filter(vocab_size=128_000, token_id_threshold=100_000, logprob_offset=2.0, enforce=False):
@@ -248,9 +230,9 @@ def test_apply_filters_enforced_flags_rollout():
apply_filters([gibberish_filter], [rollout])
assert rollout.reward == 1.0
assert rollout.raw["trajectory"][0]["tokens"]["completion_ids"] == [120_000]
assert rollout.raw["trajectory"][0]["tokens"]["completion_mask"] == [1]
assert rollout.raw["stop_condition"] is None
assert rollout.nodes[0].token_ids == [120_000]
assert rollout.nodes[0].mask == [True]
assert rollout.stop_condition is None
assert rollout.filter_results == {"gibberish": True}
assert rollout.is_filtered is True
@@ -267,9 +249,9 @@ def test_apply_filters_preserves_clean_rollouts():
apply_filters([gibberish_filter], [rollout])
assert rollout.reward == 1.0
assert rollout.raw["trajectory"][0]["tokens"]["completion_ids"] == [50, 60, 70]
assert all(m == 1 for m in rollout.raw["trajectory"][0]["tokens"]["completion_mask"])
assert rollout.raw["stop_condition"] is None
assert rollout.nodes[0].token_ids == [50, 60, 70]
assert all(rollout.nodes[0].mask)
assert rollout.stop_condition is None
assert rollout.filter_results == {"gibberish": False}
assert rollout.is_filtered is False
@@ -286,7 +268,7 @@ def test_apply_filters_first_filter_wins():
apply_filters([gibberish_filter, repetition_filter], [rollout])
assert rollout.raw["stop_condition"] is None
assert rollout.stop_condition is None
assert rollout.filter_results == {"gibberish": True, "repetition": False}
assert rollout.is_filtered is True
@@ -329,13 +311,13 @@ def test_apply_filters_enforced_preserves_rollout_tokens():
apply_filters([gibberish_filter], [rollout])
assert rollout.raw["trajectory"][0]["tokens"]["completion_ids"] == [10, 120_000, 30]
assert rollout.raw["trajectory"][0]["tokens"]["completion_logprobs"] == [
assert rollout.nodes[0].token_ids == [10, 120_000, 30]
assert rollout.nodes[0].logprobs == [
-1.0,
gibberish_filter.logprob_threshold - 1.0,
-0.5,
]
assert rollout.raw["trajectory"][0]["tokens"]["completion_mask"] == [1, 1, 1]
assert rollout.nodes[0].mask == [True, True, True]
assert rollout.is_filtered is True
@@ -347,11 +329,11 @@ def test_apply_filters_preserves_existing_stop_condition():
completion_logprobs=[gibberish_filter.logprob_threshold - 1.0],
reward=1.0,
)
rollout.raw["stop_condition"] = "generation_truncated"
rollout.stop_condition = "generation_truncated"
apply_filters([gibberish_filter], [rollout])
assert rollout.raw["stop_condition"] == "generation_truncated"
assert rollout.stop_condition == "generation_truncated"
assert rollout.is_filtered is True
@@ -370,8 +352,8 @@ def test_apply_filters_monitor_only_tracks_detection():
apply_filters([gibberish_filter], [rollout])
assert rollout.reward == 1.0
assert all(m == 1 for m in rollout.raw["trajectory"][0]["tokens"]["completion_mask"])
assert rollout.raw["stop_condition"] is None
assert all(rollout.nodes[0].mask)
assert rollout.stop_condition is None
assert rollout.filter_results == {"gibberish": True}
assert rollout.is_filtered is False
@@ -48,44 +48,3 @@ def test_setup_student_inference_pool_uses_renderer_when_enabled():
)
asyncio.run(run())
def test_setup_student_inference_pool_defaults_to_mito():
"""No renderer -> plain MITO chat completions."""
async def run() -> None:
tokenizer = object()
config = SimpleNamespace(
training_mode="rl",
renderer=None,
pool_size=None,
student=SimpleNamespace(
client=SimpleNamespace(base_url=["http://localhost:8000/v1"]),
model=SimpleNamespace(name="student-model"),
),
)
inference_pool = object()
with (
patch("renderers.base.create_renderer") as create_renderer_mock,
patch(
"prime_rl.orchestrator.utils.setup_inference_pool",
new=AsyncMock(return_value=inference_pool),
) as setup_pool_mock,
):
renderer, returned_pool = await setup_student_inference_pool(
config=config,
tokenizer=tokenizer,
)
assert renderer is None
assert returned_pool is inference_pool
create_renderer_mock.assert_not_called()
setup_pool_mock.assert_awaited_once_with(
config.student.client,
model_name="student-model",
train_client_type="openai_chat_completions",
eval_client_type="openai_chat_completions",
)
asyncio.run(run())
@@ -1,141 +0,0 @@
from unittest.mock import MagicMock
import verifiers as vf
from prime_rl.orchestrator.trajectories import backfill_rollout_tokens, interleave_rollout
class SimpleChatTokenizer:
def __init__(self):
self._tok2id: dict[str, int] = {}
self._next_id = 1
def _id(self, token: str) -> int:
if token not in self._tok2id:
self._tok2id[token] = self._next_id
self._next_id += 1
return self._tok2id[token]
def apply_chat_template(self, messages, add_generation_prompt=False, return_dict=False):
del return_dict
ids = []
for message in messages:
role = message.get("role", "unknown")
ids.append(self._id(f"<|{role}|>"))
content = message.get("content", "")
if isinstance(content, str):
if content:
ids.append(self._id(content))
else:
ids.append(self._id(str(content)))
if add_generation_prompt:
ids.append(self._id("<|assistant|>"))
return ids
def test_interleave_rollout_missing_tokens_returns_none():
output = vf.RolloutOutput(
example_id=1,
trajectory=[
vf.TrajectoryStep(
prompt=[{"role": "user", "content": "U1"}],
completion=[{"role": "assistant", "content": "A1"}],
response=MagicMock(),
tokens=None,
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="1",
extras={},
)
],
sampling_args={"temperature": 1.0},
error=None,
)
assert interleave_rollout(output) is None
def test_backfill_rollout_tokens_for_sft():
tokenizer = SimpleChatTokenizer()
output = vf.RolloutOutput(
example_id=42,
env_name="test-env",
trajectory=[
vf.TrajectoryStep(
prompt=[{"role": "user", "content": "U1"}],
completion=[{"role": "assistant", "content": "A1"}],
response=MagicMock(),
tokens=None,
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="1",
extras={},
),
vf.TrajectoryStep(
prompt=[
{"role": "user", "content": "U1"},
{"role": "assistant", "content": "A1"},
{"role": "user", "content": "U2"},
],
completion=[{"role": "assistant", "content": "A2"}],
response=MagicMock(),
tokens=None,
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="1",
extras={},
),
],
sampling_args={"temperature": 1.0},
error=None,
)
backfill_rollout_tokens(output, tokenizer)
rollouts = interleave_rollout(output)
assert rollouts is not None
assert len(rollouts) == 1
rollout = rollouts[0]
step1_prompt_ids = tokenizer.apply_chat_template(
[{"role": "user", "content": "U1"}],
add_generation_prompt=True,
)
step1_full_ids = tokenizer.apply_chat_template(
[{"role": "user", "content": "U1"}, {"role": "assistant", "content": "A1"}],
add_generation_prompt=False,
)
step2_prompt_ids = tokenizer.apply_chat_template(
[
{"role": "user", "content": "U1"},
{"role": "assistant", "content": "A1"},
{"role": "user", "content": "U2"},
],
add_generation_prompt=True,
)
step2_full_ids = tokenizer.apply_chat_template(
[
{"role": "user", "content": "U1"},
{"role": "assistant", "content": "A1"},
{"role": "user", "content": "U2"},
{"role": "assistant", "content": "A2"},
],
add_generation_prompt=False,
)
prefix_len_1 = len(step1_prompt_ids)
prefix_len_2 = len(step2_prompt_ids)
step1_completion_ids = step1_full_ids[prefix_len_1:]
step2_completion_ids = step2_full_ids[prefix_len_2:]
step1_prefix = step1_prompt_ids + step1_completion_ids
step2_new_prompt_ids = step2_prompt_ids[len(step1_prefix) :]
assert rollout.prompt_ids == step1_prompt_ids
assert rollout.completion_ids == step1_completion_ids + step2_new_prompt_ids + step2_completion_ids
assert rollout.completion_mask == (
[True] * len(step1_completion_ids) + [False] * len(step2_new_prompt_ids) + [True] * len(step2_completion_ids)
)
assert rollout.completion_logprobs == [0.0] * len(rollout.completion_ids)
@@ -2,7 +2,8 @@ import asyncio
import json
import httpx
import verifiers as vf
import openai
from verifiers.v1.clients.config import EvalClientConfig
from prime_rl.orchestrator import utils as orchestrator_utils
from prime_rl.transport import TrainingSample
@@ -41,20 +42,19 @@ def test_compute_teacher_logprobs_uses_inference_generate(monkeypatch):
"kv_transfer_params": None,
}
)
monkeypatch.setattr(orchestrator_utils, "setup_openai_client", lambda _: fake_client)
# compute_teacher_logprobs constructs AsyncOpenAI directly; hand back the fake.
monkeypatch.setattr(openai, "AsyncOpenAI", lambda **kwargs: fake_client)
sample = TrainingSample(
prompt_ids=[1],
prompt_mask=[True],
completion_ids=[2, 3],
completion_mask=[True, True],
completion_logprobs=[-0.1, -0.2],
completion_temperatures=[1.0, 1.0],
token_ids=[1, 2, 3],
mask=[False, True, True],
logprobs=[0.0, -0.1, -0.2],
temperatures=[1.0, 1.0, 1.0],
env_name="test-env",
)
result = await orchestrator_utils.compute_teacher_logprobs(
clients=[vf.ClientConfig()],
clients=[EvalClientConfig(base_url="http://fake-host:8000/v1")],
model_name="teacher-model",
samples=[sample],
)
File diff suppressed because it is too large Load Diff
+26 -26
View File
@@ -215,7 +215,7 @@ def test_multi_node_auto_inference_client_dp_rank_count_uses_router_url():
def test_orchestrator_vlm_requires_renderer():
with pytest.raises(ValidationError, match="orchestrator.renderer must be set when model.vlm is set"):
with pytest.raises(ValidationError, match="renderer"):
OrchestratorConfig.model_validate(
{
"student": {
@@ -259,7 +259,7 @@ def test_shared_model_name_propagates_to_subconfigs():
{
"model": {"name": model_name},
"trainer": {},
"orchestrator": {"renderer": None},
"orchestrator": {"renderer": {"name": "default"}},
"inference": {},
}
)
@@ -276,7 +276,7 @@ def test_shared_tokenizer_propagates_when_subconfigs_unset():
"model": {"name": "my-model"},
"tokenizer": {"name": "my-tokenizer"},
"trainer": {},
"orchestrator": {"renderer": None},
"orchestrator": {"renderer": {"name": "default"}},
}
)
assert config.trainer.tokenizer.name == "my-tokenizer"
@@ -293,7 +293,7 @@ def test_shared_and_sub_tokenizer_name_conflict_raises():
"model": {"name": "my-model"},
"tokenizer": {"name": "shared-tok"},
"trainer": {"tokenizer": {"name": "trainer-tok"}},
"orchestrator": {"renderer": None},
"orchestrator": {"renderer": {"name": "default"}},
}
)
@@ -304,7 +304,7 @@ def test_tokenizer_name_falls_back_to_model_name_when_unset():
"model": {"name": "my-model"},
"tokenizer": {"trust_remote_code": True},
"trainer": {},
"orchestrator": {"renderer": None},
"orchestrator": {"renderer": {"name": "default"}},
}
)
assert config.trainer.tokenizer.name == "my-model"
@@ -332,7 +332,7 @@ def test_explicit_subconfig_tokenizer_name_survives_shared_model_propagation():
"model": {"name": "M"},
"trainer": {},
"orchestrator": {
"renderer": None,
"renderer": {"name": "default"},
"tokenizer": {"name": "explicit-orch-tok"},
},
}
@@ -351,7 +351,7 @@ def test_tokenizer_chat_template_mismatch_raises():
RLConfig.model_validate(
{
"trainer": {"tokenizer": {"chat_template": "A"}},
"orchestrator": {"renderer": None, "tokenizer": {"chat_template": "B"}},
"orchestrator": {"renderer": {"name": "default"}, "tokenizer": {"chat_template": "B"}},
}
)
@@ -361,7 +361,7 @@ def test_shared_seq_len_propagates_to_subconfigs():
{
"seq_len": 4096,
"trainer": {},
"orchestrator": {"renderer": None},
"orchestrator": {"renderer": {"name": "default"}},
}
)
assert config.trainer.model.seq_len == 4096
@@ -377,7 +377,7 @@ def test_shared_and_sub_seq_len_conflict_raises():
{
"seq_len": 4096,
"trainer": {"model": {"seq_len": 8192}},
"orchestrator": {"renderer": None},
"orchestrator": {"renderer": {"name": "default"}},
}
)
@@ -389,7 +389,7 @@ def test_shared_and_sub_model_name_conflict_raises():
{
"model": {"name": "X"},
"trainer": {"model": {"name": "Y"}},
"orchestrator": {"renderer": None},
"orchestrator": {"renderer": {"name": "default"}},
}
)
@@ -401,7 +401,7 @@ def test_shared_and_sub_max_steps_conflict_raises():
{
"max_steps": 100,
"trainer": {},
"orchestrator": {"renderer": None, "max_steps": 200},
"orchestrator": {"renderer": {"name": "default"}, "max_steps": 200},
}
)
@@ -416,7 +416,7 @@ def test_trainer_chat_template_cascades_to_inference():
{
"model": {"name": "Qwen/Qwen3-0.6B"},
"trainer": {"tokenizer": {"chat_template": "TPL"}},
"orchestrator": {"renderer": None, "tokenizer": {"chat_template": "TPL"}},
"orchestrator": {"renderer": {"name": "default"}, "tokenizer": {"chat_template": "TPL"}},
"inference": {},
}
)
@@ -442,7 +442,7 @@ def test_shared_wandb_fields_propagate_to_subconfigs():
"offline": False,
},
"trainer": {},
"orchestrator": {"renderer": None},
"orchestrator": {"renderer": {"name": "default"}},
}
)
for component in (config.trainer.wandb, config.orchestrator.wandb):
@@ -462,7 +462,7 @@ def test_empty_shared_ckpt_block_does_not_conflict_with_subconfig_ckpt():
{
"ckpt": {}, # empty block, no field set
"trainer": {"ckpt": {"interval": 50}},
"orchestrator": {"renderer": None, "ckpt": {"interval": 50}},
"orchestrator": {"renderer": {"name": "default"}, "ckpt": {"interval": 50}},
}
)
assert config.trainer.ckpt is not None
@@ -476,7 +476,7 @@ def test_shared_and_subconfig_disjoint_fields_coexist():
{
"model": {"name": "Qwen/Qwen3-0.6B"},
"trainer": {"model": {"impl": "custom"}},
"orchestrator": {"renderer": None},
"orchestrator": {"renderer": {"name": "default"}},
}
)
assert config.trainer.model.name == "Qwen/Qwen3-0.6B"
@@ -528,15 +528,15 @@ def test_orchestrator_explicit_renderer_skips_unmapped_check():
assert config.renderer.name == "qwen3"
def test_orchestrator_renderer_none_skips_unmapped_check():
"""renderer=None (MITO mode) means the renderer client isn't used, so MODEL_RENDERER_MAP doesn't apply."""
config = OrchestratorConfig.model_validate(
{
"model": {"name": "not-a-real-org/not-a-real-model"},
"renderer": None,
}
)
assert config.renderer is None
def test_orchestrator_renderer_none_rejected():
"""A renderer is required (training is renderer-only): the non-optional type rejects None."""
with pytest.raises(ValidationError, match="renderer"):
OrchestratorConfig.model_validate(
{
"model": {"name": "not-a-real-org/not-a-real-model"},
"renderer": None,
}
)
def test_orchestrator_explicit_default_renderer_with_unmapped_model():
@@ -561,7 +561,7 @@ def test_shared_model_name_resolves_inference_parsers():
{
"model": {"name": "Qwen/Qwen3-Coder-30B-A3B-Instruct"},
"trainer": {},
"orchestrator": {"renderer": None},
"orchestrator": {"renderer": {"name": "default"}},
"inference": {},
}
)
@@ -577,7 +577,7 @@ def test_explicit_inference_parser_wins_over_auto():
{
"model": {"name": "Qwen/Qwen3-Coder-30B-A3B-Instruct"},
"trainer": {},
"orchestrator": {"renderer": None},
"orchestrator": {"renderer": {"name": "default"}},
"inference": {"model": {"tool_call_parser": "hermes"}},
}
)
+6 -8
View File
@@ -33,8 +33,8 @@ def create_run_with_config(output_dir: Path, run_name: str) -> Path:
"group_size": 1,
"env": [{"id": "test-env"}],
"sampling": {"temperature": 1.0},
# test-model isn't in MODEL_RENDERER_MAP; bypass the renderer-resolution validator.
"renderer": "None",
# test-model isn't in MODEL_RENDERER_MAP; use the explicit default renderer.
"renderer": {"name": "default"},
}
with open(control_dir / "orch.toml", "wb") as f:
tomli_w.dump(config, f)
@@ -43,12 +43,10 @@ def create_run_with_config(output_dir: Path, run_name: str) -> Path:
def make_training_sample() -> TrainingSample:
return TrainingSample(
prompt_ids=[1],
prompt_mask=[False],
completion_ids=[2],
completion_mask=[True],
completion_logprobs=[-0.1],
completion_temperatures=[1.0],
token_ids=[1, 2],
mask=[False, True],
logprobs=[0.0, -0.1],
temperatures=[1.0, 1.0],
env_name="test-env",
)
+4 -4
View File
@@ -42,8 +42,8 @@ def create_run_with_config(
"batch_size": 32,
"group_size": 4,
"env": [{"id": "test-env"}],
# test-model isn't in MODEL_RENDERER_MAP; bypass the renderer-resolution validator.
"renderer": "None",
# test-model isn't in MODEL_RENDERER_MAP; use the explicit default renderer.
"renderer": {"name": "default"},
}
with open(config_dir / "orch.toml", "wb") as f:
@@ -203,7 +203,7 @@ def test_config_loading(tmp_path: Path) -> None:
"max_steps": 1000,
"group_size": 4,
"env": [{"id": "test-env"}],
"renderer": "None",
"renderer": {"name": "default"},
}
create_run_with_config(tmp_path, "run_test123", config=test_config)
@@ -248,7 +248,7 @@ def test_config_cleanup_on_deletion(tmp_path: Path) -> None:
"batch_size": 16,
"group_size": 4,
"env": [{"id": "test-env"}],
"renderer": "None",
"renderer": {"name": "default"},
}
run_dir = create_run_with_config(tmp_path, "run_delete_me", config=test_config)
+9 -18
View File
@@ -3,7 +3,7 @@ from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
import httpx
import verifiers as vf
from verifiers.v1.clients.config import EvalClientConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.client import _is_retryable_lora_error, load_lora_adapter, setup_clients
@@ -67,13 +67,12 @@ def test_setup_clients_assigns_renderer_and_dp_rank_headers():
renderer_config=renderer_settings,
)
assert [client.client_type for client in clients] == ["renderer", "renderer"]
assert [client.renderer_config for client in clients] == [renderer_settings, renderer_settings]
assert [client.type for client in clients] == ["train", "train"]
assert [client.renderer for client in clients] == [renderer_settings, renderer_settings]
assert [client.renderer_model_name for client in clients] == [None, None]
assert [client.api_base_url for client in clients] == ["http://worker-a:8000/v1"] * 2
assert [client.extra_headers["X-data-parallel-rank"] for client in clients] == ["0", "1"]
assert clients[0].extra_headers["X-Test"] == "test"
assert clients[0].extra_headers_from_state == {"X-Session-ID": "session_id"}
assert [client.base_url for client in clients] == ["http://worker-a:8000/v1"] * 2
assert [client.headers["X-data-parallel-rank"] for client in clients] == ["0", "1"]
assert clients[0].headers["X-Test"] == "test"
def test_setup_clients_assigns_renderer_model_name():
@@ -103,17 +102,9 @@ def test_setup_clients_preserves_chat_client_defaults():
clients = setup_clients(client_config)
assert clients == [
vf.ClientConfig(
client_idx=0,
client_type="openai_chat_completions",
EvalClientConfig(
api_key_var="PRIME_API_KEY",
api_base_url="http://worker-a:8000/v1",
timeout=client_config.timeout,
connect_timeout=client_config.connect_timeout,
max_connections=8192,
max_keepalive_connections=8192,
max_retries=10,
extra_headers={},
extra_headers_from_state={},
base_url="http://worker-a:8000/v1",
headers={},
)
]
+7 -15
View File
@@ -4,7 +4,7 @@ from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import verifiers as vf
from verifiers.v1.clients.config import TrainClientConfig
from prime_rl.utils.elastic import (
AdapterState,
@@ -411,8 +411,6 @@ def test_elastic_clients_preserve_renderer_model_name_when_model_name_updates():
client_config.elastic.port = 8000
client_config.elastic.sync_interval = 5.0
client_config.router_url = None
client_config.timeout = 1200
client_config.connect_timeout = 30.0
client_config.api_key_var = "PRIME_API_KEY"
client_config.headers = {}
client_config.headers_from_env = {}
@@ -435,20 +433,14 @@ def test_elastic_clients_preserve_renderer_model_name_when_model_name_updates():
pool.update_model_name("r8-smoke")
clients = pool.train_clients
# `renderer_model_name` stays pinned to the original base model even after the
# served model name flips to the LoRA adapter (`r8-smoke`).
assert clients == [
vf.ClientConfig(
client_idx=0,
client_type="renderer",
renderer_config=renderer_settings,
TrainClientConfig(
renderer=renderer_settings,
renderer_model_name="Qwen/Qwen3-VL-4B-Instruct",
api_key_var="PRIME_API_KEY",
api_base_url="http://10.0.0.1:8000/v1",
timeout=1200,
connect_timeout=30.0,
max_connections=8192,
max_keepalive_connections=8192,
max_retries=10,
extra_headers={},
extra_headers_from_state={},
base_url="http://10.0.0.1:8000/v1",
headers={},
)
]
+38 -36
View File
@@ -3,7 +3,9 @@ import json
from unittest.mock import Mock
import pyarrow.parquet as pq
import verifiers.v1 as vf
from prime_rl.orchestrator.types import Rollout
from prime_rl.utils.monitor.prime import PrimeMonitor
@@ -13,32 +15,34 @@ def _new_monitor() -> PrimeMonitor:
return monitor
def _build_rollout(*, example_id: int, reward: float, task: str) -> dict:
return {
"example_id": example_id,
"prompt": [{"role": "user", "content": f"prompt-{example_id}"}],
"completion": [{"role": "assistant", "content": f"completion-{example_id}"}],
"trajectory": [
{
"prompt": [{"role": "user", "content": f"prompt-{example_id}"}],
"completion": [{"role": "assistant", "content": f"completion-{example_id}"}],
"reward": reward,
"advantage": reward / 2,
"extras": {"source": "test"},
"tokens": {
"prompt_ids": [1, 2, 3],
"completion_ids": [4, 5],
},
}
],
"answer": f"answer-{example_id}",
"task": task,
"info": {"difficulty": "easy"},
"reward": reward,
"advantage": reward / 2,
"metrics": {"accuracy": reward},
"timing": {"generation": {"start": 0.0, "end": 12.5, "duration": 12.5}},
}
def _build_rollout(*, example_id: int, reward: float, task: str) -> Rollout:
"""Build a v1 ``Rollout`` (message-graph trace). The user node carries the prompt and the
assistant node the completion; ``_rollouts_to_parquet_bytes`` reads the conversation off the
branches (its ``completion`` column is the last branch's messages, ``trajectory`` is one
message list per branch)."""
nodes = [
vf.MessageNode(
message=vf.UserMessage(content=f"prompt-{example_id}"),
token_ids=[1, 2, 3],
mask=[False, False, False],
logprobs=[0.0, 0.0, 0.0],
),
vf.MessageNode(
message=vf.AssistantMessage(content=f"completion-{example_id}"),
token_ids=[4, 5],
mask=[True, True],
logprobs=[-0.1, -0.2],
sampled=True,
),
]
rollout = Rollout[vf.Task](
task=vf.Task(idx=example_id, prompt=f"prompt-{example_id}"),
nodes=nodes,
rewards={"reward": reward},
)
rollout.env_name = task
rollout.advantage = reward / 2
return rollout
def test_rollouts_to_parquet_bytes_preserves_all_rollouts_and_ids():
@@ -63,24 +67,22 @@ def test_rollouts_to_parquet_bytes_preserves_all_rollouts_and_ids():
assert [row["sample_id"] for row in rows] == [0, 1]
assert all(row["run_id"] == "run-123" for row in rows)
assert all(row["step"] == 7 for row in rows)
assert json.loads(rows[0]["prompt"])[0]["content"] == "prompt-101"
# `completion` is the last branch's messages; the prompt user message lives in `trajectory`.
assert json.loads(rows[1]["completion"])[0]["content"] == "completion-202"
trajectory = json.loads(rows[0]["trajectory"])
assert trajectory[0]["messages"][0]["content"] == "prompt-101"
def test_rollouts_to_parquet_bytes_skips_rollouts_without_trajectory():
monitor = _new_monitor()
monitor.run_id = "run-456"
rollout_with_branches = _build_rollout(example_id=1, reward=1.0, task="task-a")
rollout_without_branches = Rollout[vf.Task](task=vf.Task(idx=2, prompt="missing-trajectory"))
assert rollout_without_branches.branches == []
parquet_bytes = monitor._rollouts_to_parquet_bytes(
[
_build_rollout(example_id=1, reward=1.0, task="task-a"),
{
"example_id": 2,
"prompt": [{"role": "user", "content": "missing-trajectory"}],
"completion": [{"role": "assistant", "content": "ignored"}],
"trajectory": [],
},
],
[rollout_with_branches, rollout_without_branches],
step=3,
)
Generated
+369 -723
View File
File diff suppressed because it is too large Load Diff