Compare commits

...
Author SHA1 Message Date
7089ba1e4d feat: vf v1 <> nano bridge (#2742)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: add vf-nano as submodule

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

* chore: bump deps/vf-nano to feat/env-server (EnvServer)

Points the submodule at the vf-nano EnvServer branch so the orchestrator can
build on the env-server abstraction.

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

* feat: run orchestrator on a vf-nano env server (reverse-text)

Switch prime-rl's env path to vf-nano: the orchestrator spawns a vf-nano
EnvServer per env (it never loads an environment), dispatches rollouts by task
index, and trains on the returned Trace dicts (branches + renderer tokens).

- pyproject: dep verifiers -> vf-nano; drop v1/research env packages; only the
  vf-nano reverse-text example; override out the transitive v1 verifiers (pulled
  by the prime CLI) so it can't shadow vf-nano's `verifiers` package; add orjson
  /pandas/msgspec (were transitive via verifiers).
- EnvConfig inherits vf-nano's swappable agent/runtime (+ max_turns).
- envs.py: spawn EnvServer child + EnvClient, info() for num_tasks/group-scoring,
  dispatch by task_idx, adapt Trace -> RolloutOutput-shaped dict.
- trajectories.py: trace_to_samples (one sample per Trace branch) + trace_to_output.
- train_source: index sampling; client pool builds vf-nano ClientConfig; lag
  monitor vendored; env-server entrypoint repointed; ~14 files retyped off
  vf.RolloutOutput / vf.ClientConfig.
- configs/debug/vf_nano_reverse_text.toml.

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

* feat: consume vf-nano Trace natively (branches→samples, shared renderer config)

- trace_to_samples stitches each Trace branch's tokens into one TrainingSample
  (prompt = branch start, then each turn's new context [masked] + generated
  tokens [trained]); drop the RolloutOutput adapter — read the Trace's native
  fields directly (reward, error{type,message}, timing generation/scoring,
  num_turns, branches).
- envs returns the raw Trace; eval_sink / train_sink / dispatcher / metrics /
  orchestrator read native Trace fields (no token_usage/completion/timing.total).
- client pool forwards the shared renderers.RendererConfig to the env server's
  renderer client (so it uses qwen3, not the tool-less default fallback).
- debug config: tool_call_parser=hermes (vLLM accepts the agent's tools),
  max_steps=20.
- bump deps/vf-nano.

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

* refactor: pass typed ClientConfig/SamplingConfig to the env client (no timeout)

- Env.run_rollout/run_group pass the vf-nano ClientConfig object and a
  SamplingConfig (built from the env's sampling args) directly — no model_dump,
  no per-rollout timeout forwarded to the server.
- debug config: max_steps=20.
- bump deps/vf-nano (typed env-server RPC).

* refactor: orchestrator holds a typed vf.Trace[EnvTask] (no dicts)

The env server returns a Trace minus its derived fields; the orchestrator resolves
the env's Task subclass (from config.id) and validates the wire dict into a strict
Trace[EnvTask], so the whole orchestrator works with a real, typed vf.Trace —
typed task fields included (e.g. task.answer), nothing subscriptable.

- envs.py: resolve_task_type(env_id); run_rollout/run_group validate -> Trace[EnvTask].
- trajectories/types/dispatcher/train_sink/eval_sink/metrics/filters/advantage/utils
  /orchestrator: attribute access on the typed Trace (reward, error{type,message},
  branches, timing.<span>.duration, num_turns, ...); derived fields recompute on the
  consumer.
- Task/Trace/TimeSpan stay strict (StrictBaseModel) — no extra=ignore anywhere.
- bump deps/vf-nano.

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

* chore: depend on vf-nano[serve]; bump submodule

The orchestrator spawns the env server, so request the serve extra
(zmq/msgpack) explicitly now that vf-nano keeps them out of core.

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

* chore: bump vf-nano (client docstring cleanup)

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

* chore: drop redundant forward-ref quotes in advantage.py

`from __future__ import annotations` already defers all annotations to strings,
so the quotes + `# noqa: F821` on the TYPE_CHECKING-only `vf.Trace` / `TrainRollout`
annotations are unnecessary (no import cycle — verifiers.nano never imports prime_rl).

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

* refactor: rename FinishedRollout.raw -> trace

The field holds a typed vf.Trace, so `trace` reads truer than `raw` (which
suggested an unparsed dict). Renames the field + every `.raw` access, the
`emit_rollout(trace=...)` param/kwarg, the to_dict field filter, and the
dispatcher cancel-path locals.

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

* refactor: simplify FinishedRollout, read straight off the typed Trace

- Drop the FinishedRollout proxy properties (error/reward/is_truncated and the
  example_id field); consumers now read r.trace.{reward,is_truncated,task.idx,...}
  directly. The trace is the single source of truth.
- Use vf.Trace.has_error for existence checks instead of `.error is not None`.
- Replace the prime-rl trace_* token-length utils with vf.Trace.{completion_len,
  total_tokens,has_response} (now on the trace); keep trace_to_samples.
- Carry task_idx end-to-end (GroupState.task_idx, env.run_rollout/run_group(task_idx),
  source dict key) instead of the example/example_id dict carrier; identity comes
  off trace.task.idx.
- Mark the local-package env arrangement as a temporary/experimental TODO.
- Move the debug config to configs/debug/nano/reverse_text.toml.
- Bump deps/vf-nano (Trace/Turn accessors).

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

* refactor: spawn env server on an OS-assigned port, drop the startup poll

- The env server binds tcp://127.0.0.1:0 and reports its concrete address back
  over a queue; the orchestrator connects to that. Removes _get_free_port and its
  TOCTOU race (the OS assigns the port atomically).
- A spawned server has already bound + loaded by the time it reports its address,
  so the untimed info() is enough — only poll wait_for_server_startup for an
  external (config.address) server, which has no spawn handshake.
- Bump deps/vf-nano (port report + Trace/Branch token-length accessors).

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

* refactor: use vf.task_type instead of a local resolve_task_type

The Task-subclass introspection now lives in vf-nano (vf.task_type); drop the
prime-rl copy and build the typed Trace via vf.Trace[vf.task_type(env_id)]. Bump
deps/vf-nano.

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

* feat: restore backfill_rollout_tokens for SFT (typed Trace)

SFT trains on a teacher served over the chat client, which returns no token ids,
so the trace's turns have tokens=None and trace_to_samples yields nothing. Restore
backfill: for each tokenless turn, render its prompt + assistant response with the
student chat template and split on the longest common prefix to fill TurnTokens
(masks/logprobs come from trace_to_samples). train_sink.process_rollout backfills
when any turn lacks tokens, before building samples.

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

* fix: pass task_idx when building Cancelled traces on off-policy drop

drop_group's error_rollout_output calls omitted the required task_idx, so an
off-policy cancel (on_new_version) raised TypeError. Use the group's task_idx
(or -1 when the group is already gone), mirroring handle_completed_rollout.

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

* refactor: consume typed Trace[WireTask]; inline synthetic error traces

- envs.py: EnvClient now returns Trace[WireTask]; upgrade to this env's real Task
  subclass via self.trace_type.model_validate(wire.to_wire()).
- dispatcher.py: drop the error_rollout_output helper — inline the synthetic error
  Trace at each call site using vf.Error's field names (type/message/traceback); the
  task-exception path carries a real traceback, cancels/empty-trajectory carry none.
- Bump deps/vf-nano.

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

* feat: env-server file logging; align debug config batch/group to canonical

- Spawned env servers now route their output (logging + subprocess-runtime output)
  to <output_dir>/logs/envs/<name>.log via a _run_env_server wrapper that redirects
  stdout/stderr and sets up logging in the child. Previously the orchestrator-spawned
  server logged nowhere.
- Debug config: batch_size 16->128, group_size 8->16, eval num_examples 8->128
  (interval=1), matching configs/debug/training_modes/rl.toml.

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

* fix: don't double the envs/ segment in the env-server log path

The orchestrator already passes a train/eval-split log_dir (.../logs/envs/train,
.../logs/envs/eval), so _spawn must drop the file directly under it
(<log_dir>/<name>.log) rather than re-adding an envs/ subdir — which had buried the
train/eval split under logs/envs/<kind>/envs/<name>.log.

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

* chore: bump vf-nano (Error.traceback str | None)

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

* chore: bump vf-nano (to_wire ordering)

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

* feat: launch env servers as separate processes from the rl entrypoint

Instead of the orchestrator sidecar-spawning each env server as an mp child, the
rl launcher now spawns one `env-server` process per env (train + eval), each on a
free port, with output to logs/envs/{kind}/{name}.log and a crash monitor — same
model as inference/trainer. It sets env.address in the orchestrator config so the
orchestrator attaches (its existing external path) instead of spawning. Envs that
already set address (user-managed external server) are left alone; the orchestrator's
mp sidecar stays as the fallback for running `orchestrator` directly.

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

* refactor: env servers use fixed configurable ports, not get_free_port

Add RLConfig.env_server_base_port (default 5000); the i-th launcher-managed env binds
base_port + i. Drops the get_free_port dependency in the launcher.

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

* refactor: separate train/eval env-server port blocks

Train envs bind base_port + i; eval envs bind base_port + ENV_SERVER_KIND_STRIDE + i
(stride 1000), so each kind has headroom for many envs without the blocks colliding
(was a single running index — train and eval sat adjacent).

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

* fix: env-server logs + sidecar queue cleanup; train-only debug config

- env_server entrypoint: intercept vf-nano stdlib logging so the server's own logs
  (EnvServer up, request failures) land in logs/envs/<kind>/<name>.log — previously
  only loguru output was captured, swallowing them.
- envs.py: close the address-handoff mp.Queue after use (no resource_tracker
  leaked-semaphore warning on the sidecar path).
- configs/debug/nano/reverse_text.toml: drop the eval block, mirroring
  examples/reverse_text/rl.toml (train-only smoke; eval path validated separately).
- bump deps/vf-nano (serve/types docstring trim).

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

* chore: bump vf-nano (BaseRequest marker, no request_type field)

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

* chore: env client uses client= (was client_config=); bump vf-nano

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

* chore: bump vf-nano (drop renderers dep comment)

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

* chore: bump vf-nano (configs/ + cli/ split, serve/ runtime-only)

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

* refactor: drop FinishedRollout.to_dict; serialize the Trace to disk directly

The I/O boundary (save_rollouts + monitor sample tables) now dumps the typed
vf.Trace itself (r.trace.model_dump(mode="json")) instead of a Trace+metadata
merge — the on-disk rollout is just the trace.

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

* refactor: track vf-nano agent->harness rename

vf-nano renamed its rollout-driver abstraction Agent -> Harness. Update the
integration: EnvConfig.agent -> harness (HarnessConfig/DefaultHarnessConfig);
env.run_rollout/run_group spawn forwards harness_config; the env-server entrypoint
passes harness_config/harness_timeout; debug config uses `harness = {...}`. Bump
deps/vf-nano to the renamed branch.

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

* chore: track vf-nano plugin reorg (reverse-text path + bump)

vf-nano reorganized examples into examples/{tasksets,harnesses}/; point the
reverse-text editable source at examples/tasksets/reverse_text and bump deps/vf-nano.
No prime-rl code change — EnvConfig.harness (default) resolves via vf-nano's built-in
harness registry. Verified: 3-step reverse-text smoke trains (0.26 -> 0.42, 0% error).

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

* feat: reuse vf.EnvConfig in the orchestrator (typed taskset/harness, drop args)

prime-rl's EnvConfig now subclasses vf.EnvConfig and resolves taskset + harness to their
specific config types by id (taskset_config_type / harness_config_type), so env-specific
fields are validated against the real config — the untyped `args` dict and the top-level
`id` are gone (id/stripped_id/resolved_name are now properties off taskset.id). Timeouts
come from vf.TimeoutConfig (timeout.rollout / timeout.scoring), superseding prime-rl's flat
timeout. The env server is spawned with the typed taskset_config (no env_id/args).

- pyproject: install the vf-nano plugin packages (default/rlm harnesses, gsm8k taskset)
  as path sources; bump deps/vf-nano to the plugin-packages branch.
- configs/debug/nano/reverse_text.toml: taskset = { id = ... }, harness.id (was harness.type).

Verified: custom taskset (gsm8k.split) + harness (rlm.ref) resolve to typed configs; bad
fields are rejected; the migrated TOML loads through RLConfig.

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

* refactor: inherit vf's shared plugin resolution; trim dead EnvConfig fields

EnvConfig drops its own _resolve_plugins (now inherited from vf.EnvConfig's shared
validator) and the dead v1-forwarding fields: extra_env_kwargs, max_total_completion_tokens,
state_columns (no readers on the vf-nano branch). Also drop stripped_id (no hub installs ->
no @version, so id == it) — callers use .id. Bump deps/vf-nano.

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

* refactor: require a configured taskset per env (no reverse-text default)

EnvConfig no longer auto-defaults its taskset to reverse-text; an env with no taskset id
errors at validation. Env-list defaults are empty (eval's non-empty check still fires only
when an eval block is configured). Bump deps/vf-nano.

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

* chore: bump deps/vf-nano (dashboard taskset.id/harness.id fix)

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

* chore: bump deps/vf-nano (sampling max_tokens fix)

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

* fix(env-server): require a configured env; build EnvServer from the EnvConfig

EnvServerConfig.env was a bare EnvConfig() default, which now raises (no taskset) and
crashed the env-server at import. Make env required — the orchestrator always passes a
real env config. Build the server straight from config.env (vf-nano EnvServer takes the
EnvConfig). Bump deps/vf-nano (is_truncated computed field).

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

* feat(nano): reverse-text uses default harness with enable_bash=false

The model answers directly (no bash tool), so the tool_call_parser is no longer needed.
Bump deps/vf-nano (enable_bash flag).

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

* feat(nano): hendrycks-sanity config on the math-env taskset

Add configs/debug/nano/hendrycks_sanity.toml (vf-nano analog of configs/debug/hendrycks_sanity):
math-env train env on the sanity dataset (R1-distill, default renderer with think parser,
single-turn no-bash), aime24 eval env. Register math-env + aime24 in the envs group + sources.
Bump deps/vf-nano (math/aime tasksets, enable_bash, SerializeAsAny + is_truncated fixes).

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

* chore: bump deps/vf-nano to merged main (math/aime tasksets, fixes)

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

* chore: drop deps/verifiers, bump deps/vf-nano to merged main

vf-nano main (#8) adds the subprocess-runtime env passthrough (inherit host env
minus API_KEY, so UV_CACHE_DIR reaches rollout workers and lands the uv cache on
local disk) and the math-verify scoring fix (wrap gold + prediction in \boxed,
matching v1 math-env — fixes matrix/vector answers scoring 0).

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

* feat(nano): hendrycks-sanity mirrors examples/hendrycks_sanity + slurm overlay

nano config is now a verbatim copy of examples/hendrycks_sanity/rl.toml with only
the env sections swapped to vf-nano taskset/harness syntax (math-env taskset,
default harness, subprocess runtime; aime24 eval). Adds a slurm overlay setting
the output dir, wandb run name, and partition.

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

* chore(nano): fold wandb + slurm into hendrycks_sanity config

Move the [wandb] and [slurm] sections from the slurm overlay into the base config, so it
submits to slurm by default (run locally with --no-slurm). The overlay now only redirects
output_dir. wandb run name is vf-nano-subprocess.

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

* chore(nano): fold output_dir into hendrycks_sanity config, drop slurm overlay

Everything (output_dir, wandb, slurm) now lives in the one config; remove the now-empty
slurm overlay. Run locally with --no-slurm.

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

* feat(vf-v1): run on the unified verifiers package (v0 envs + v1=nano + legacy bridge)

Depend on the single verifiers package (deps/verifiers, nesting vf-nano) instead of standalone
vf-nano. EnvConfig is dual-mode: v0 envs via id+args (legacy bridge), v1 envs via taskset/harness
(native nano). The env-server spawn (standalone + mp) picks LegacyEnvServer for v0 and EnvServer
for v1; both return vf.Trace so the orchestrator is unchanged. Plugin sources repointed under
deps/verifiers; reverse-text is the v0 env, reverse-text-v1 the nano taskset.

Verified: uv run rl @ examples/reverse_text/rl.toml (v0, unchanged) trains via the bridge
(reward 0.14->0.79); vf-eval + vf-eval-v1 reverse-text both reward 1.0.

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

* test(v0): wire alphabet-sort (multi-turn) + bump verifiers (State scrub)

Add the v0 alphabet-sort env as an installable source; bump deps/verifiers to the State-scrub
commit. Verified the bridge on a multi-turn v0 env: alphabet-sort runs (Turns 2.0, 128/128
trainable, 0% error) alongside single-turn reverse-text.

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

* test(v0): wire wordle + add configs/wordle/rl.toml (2-GPU)

Wire the v0 wordle TextArena env (multi-turn game) as an installable source; add a 2-GPU
(1 trainer + 1 inference) wordle config. Verified through the legacy bridge: wordle trains
(Turns ~5.3, reward ~0.81, 128/128 trainable, 0% error).

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

* chore: bump deps/verifiers (v1 hygiene: init.py/tests/docs)

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

* refactor(v1): track de-vendored verifiers, rename nano -> v1

- Bump deps/verifiers to the de-vendored commit: vf-nano is now vendored as the
  verifiers.v1 subpackage (no nested deps/vf-nano submodule).
- Repoint env-plugin sources from deps/verifiers/deps/vf-nano/... to
  deps/verifiers/{examples,packages}/...
- Rename verifiers.nano -> verifiers.v1 across the orchestrator/utils/configs;
  rename configs/debug/nano -> configs/debug/v1. "v1" is the name now (no "nano").

Verification: v0 reverse-text (legacy bridge) and v1 reverse-text-v1 (native)
both train over a 3-step smoke (reward present, 0% error).

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

* chore(v1): bump verifiers (eval/serve, v1 deps in base, bundled plugins)

- Bump deps/verifiers: v1 runtime deps moved to base (no `v1` extra), v1 CLIs
  renamed eval/serve, shipped plugins bundled in the tasksets/harnesses umbrella
  packages, verifiers/v1/harness.py (flattened harnesses subpackage).
- Depend on `verifiers` (was verifiers[v1]) and the `harnesses` umbrella package
  (was standalone default/rlm).

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

* chore(v1): bump verifiers (Task.system_prompt); write full rollout jsonl

- Bump deps/verifiers to the system_prompt commit: Task.system_prompt + harness
  APPENDS_SYSTEM_PROMPT support, reverse_text_v1 byte-identical to the v0 env (separate
  system message), plus this branch's eval/serve, v1-deps-in-base, CI fixes, and the
  retired semgrep policy.
- save_rollouts: drop exclude_keys={"trajectory"} for both train and eval rollouts so the
  jsonl carries the full trajectory.

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

* chore: drop semgrep from uv.lock (verifiers retired the policy group)

Follow-up to the deps/verifiers bump (00c7b77a removed the `policy` dependency
group); regenerates the lock to match.

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

* fix: pin the env-server renderer tokenizer to the base model for LoRA runs

Wire `renderer_model_name` (the base model) into the renderer client config so
the env-server renderer builds its tokenizer from the base model instead of the
per-request LoRA adapter name, which has no published HF tokenizer and 404'd
once LoRA training set the served model name to the adapter. Mirrors the
`renderer_model_name` wiring already in `setup_clients` on main. Bumps
deps/verifiers to the matching fix.

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

* feat(orchestrator): request vLLM token ids for MITO training (#2745)

On the MITO path (no renderer), set return_token_ids in the train env
sampling args so the openai_chat_completions client gets the prompt and
completion token ids back from vLLM and can carry them for training
instead of re-tokenizing the messages downstream. Scoped to
renderer is None so it never reaches the renderer /inference/v1/generate
endpoint (which forwards sampling params to vLLM verbatim).

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

* chore(v1): bump verifiers submodule; restore v0 env catalog + v1 -v1 imports

- bump deps/verifiers to the feat/nano-as-v1 tip (token-parse #1585, bridge meta #1586,
  taskset -v1 rename #1587, native retries #1588, runtime resource cleanup #1590)
- restore the full v0 env catalog in optional-dependencies.envs + [tool.uv.sources]
  (init the research-environments submodule); the taskset -v1 rename freed the v0 names,
  so v0 envs (legacy bridge) and v1 tasksets coexist
- point the v1 taskset sources at their -v1 names / _v1 paths (gsm8k-v1, math-env-v1,
  aime24-v1; reverse-text-v1 already correct)
- update v1 configs to the -v1 taskset ids (hendrycks_sanity) and drop the superseded
  standalone configs/debug/reverse_text_v1.toml
- relock

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

* chore(v1): bump verifiers submodule to feat/nano-as-v1 tip (textarena #1592)

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

* chore(v1): bump verifiers submodule to feat/nano-as-v1 tip

Pulls in runtime resources named after the rollout id (#1596) and the
alphabet-sort-v1 taskset (#1595).

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

* chore(v1): bump verifiers submodule to feat/nano-as-v1 tip

Brings in env-hub ids (#1597), v0 envs on the eval CLI (#1598), modal runtime (#1594).

* chore(v1): add v1 alphabet-sort debug config (port of examples/alphabet_sort)

* fix: forward extra_env_kwargs to v0 legacy envs; drop dead trajectory tests (#2749)

Restores main's escape hatch for v0 (legacy-bridge) envs: a legacy env's extra_env_kwargs
is auto-populated (timeout_seconds <- timeout.rollout, max_total_completion_tokens <-
max_output_tokens, max_seq_len <- seq_len) and forwarded to LegacyEnvServer at spawn, so v0
rollouts again honor the wall-clock timeout, multi-turn completion budget, and seq-len
truncation (all were silently dropped on this branch).

Also removes tests/unit/orchestrator/test_{trajectories,sft_trajectories}.py, which imported
the deleted interleave_rollout and broke test collection.

* fix: install the bundled `tasksets` package (harbor-v1, textarena-v1)

The `envs` extra wired `harnesses` and the individual `*-v1` example tasksets but
never the bundled `tasksets` package, so the integration tasksets it ships
(`harbor-v1`, `textarena-v1`) couldn't be resolved — `import_taskset("harbor-v1")`
raised ModuleNotFoundError ("tried to import 'harbor_v1'").

Add `tasksets` to the `envs` extra + a path source, and bump the verifiers
submodule to the feat/nano-as-v1 tip (#1600), where the bundled tasksets live
under the `tasksets` namespace package (`tasksets.harbor_v1`) and the loader
resolves the namespaced module.

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

* feat: consume the v1 message-graph trace (#2763)

* feat: consume the v1 message-graph trace (graph-walk trace_to_samples)

Walk the new message graph (verifiers feat/trace-message-graph, PR #1606): trace_to_samples
builds one TrainingSample per branch by concatenating each branch path's node token_ids /
sampled_mask / logprobs (graph.branch_token_sequences), splitting prompt|completion at the
first sampled token — identical training tensors to the old per-turn stitching, off a trace
that is now linear (not quadratic) in turns. backfill_rollout_tokens is a no-op (training is
renderer-only; `trajectory` is now a read-only view over the graph). Bumps the verifiers
submodule to the graph-trace branch.

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

* chore: bump verifiers submodule (MessageNode.mask rename)

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

* chore: wire alphabet-sort-v1 taskset

Add alphabet-sort-v1 to the `envs` extra + `[tool.uv.sources]` so
configs/debug/v1/alphabet_sort.toml resolves (it referenced an example taskset that was
never wired into prime-rl). Used to verify graph-based training-sample construction on real
RL runs — v0 (legacy bridge) and v1 (native renderer path) both train cleanly.

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

* refactor: consume nodes/branches directly (drop Turn/trajectory readers)

`trace_to_samples` already walks the graph; the remaining readers move off the removed
Turn/trajectory API: the gibberish/repetition filters iterate per-node completions,
advantage/dispatcher use `trace.num_turns`/`trace.completion_len`, `get_model_completion_len`
is dropped (use `trace.completion_len`), and the renderer-only train_sink drops the backfill
path (also removing `backfill_rollout_tokens`). Bumps the verifiers submodule.

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

* chore: bump verifiers submodule (merge #1605 multiplex interception)

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

* chore: bump verifiers submodule (dead-code cleanup)

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

* chore(v1): bump verifiers (readme highlight + ruff format)

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

* feat: enforce renderer, SFT backfill, branch-first-class logging

Training is renderer-only now. RL/OPD roll out through the renderer client
(exact sampled token ids + logprobs); SFT rolls out against a chat-completions
teacher that returns no tokens and re-renders the conversation to backfill them
(`backfill_trace`). A renderer is required for every mode (`renderer=None`
rejected) — the oai client never produces correct training tokens for the
message graph. Drops the MITO no-renderer training path.

Logging consumes `trace.branches` as the first-class unit (`branch.token_ids` /
`branch.messages`) instead of the removed `trajectory` field; `trace_to_samples`
builds one sample per branch from the same accessors. Sample loggers take the
rollout objects so env_name/advantage are available.

Add configs/v1/training_mode (rl/opd/sft + lora/external) mirroring the v0
debug configs. Fix the v0 SFT debug configs + rlm_swe to validate under the
renderer requirement.

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

* refactor: flat TrainingSample (token_ids + mask), required renderer

Drop the prompt/completion split from TrainingSample — it doesn't fit a
multi-turn/agentic branch, where context and model-sampled spans interleave. A
sample now carries the branch's flat `token_ids` plus per-token `mask` (True =
trainable), `logprobs`, and `temperatures` (all aligned). `prepare_sample`
passes them straight into the MicroBatch (already flat), and the packer
validates against `token_ids` length.

Make `orchestrator.renderer` a non-optional type (drop the `enforce_renderer`
validator) — training is renderer-only, so the type carries the requirement.

Bump the verifiers submodule to feat/nano-as-v1 (merged #1606 + Branch.branches
inlined).

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

* refactor: SFT teacher rolls out through the renderer client (drop backfill)

Training is renderer-only across every mode, so the SFT teacher now rolls out
through the renderer client too — its rollouts carry tokens directly, the same
as RL/OPD. Drops the chat-completions backfill (`backfill_trace` + the SFT path
in TrainSink) and the now-unused TrainSink renderer.

This requires a self-hosted teacher that shares the student's tokenizer (the
student trains on exactly the ids the renderer feeds the teacher); distilling
from an external chat API is no longer supported. Remove the `sft_external`
debug configs.

Validated: SFT on reverse-text-v1 trains cleanly (Trainable 128/128, eval reward
~0.1 -> ~0.82 over 20 steps) with the teacher on the renderer client, no backfill.

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

* chore: drop configs/v1/training_mode README

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

* refactor: consolidate rollout types into Rollout(vf.Trace)

The trace *is* the rollout: replace the FinishedRollout/TrainRollout/EvalRollout
wrappers with a prime-rl Rollout(vf.Trace[TaskT]) subclass that carries the
orchestration metadata (kind, env_name, group_id, policy_version,
off_policy_steps, samples, advantage, is_filtered, filter_results, eval_step) as
exclude=True fields — so dumping a Rollout still yields a plain trace (on-disk
results.jsonl unchanged). envs.py validates the wire trace into Rollout; the
dispatcher stamps the metadata; train vs eval is the `kind` discriminator
(replacing the isinstance check). All consumers read rollout.X directly instead
of rollout.trace.X.

Drop the monitor's SampleRollout duck-type Protocol — the loggers take the real
Rollout (TYPE_CHECKING import) and read branch.token_ids / branch.messages. Also
drop the prime monitor's _split_branch_messages and _json helpers: the
conversation is the unit (no prompt/completion split — meaningless multi-turn).

Fix a latent dispatcher bug surfaced along the way: synthetic error traces used
`error=` / `r.error = ` (a read-only computed field) — now `errors=[...]` /
`r.errors.append(...)`.

Rewrite the (long-stale, dict/`raw`-based) advantage + filters unit tests to
build real Rollouts — they now exercise the current trace-based code (previously
all failing on import/construction).

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

* ci: allow verifiers + datasets in the slim-config dep check

The v1 config types (EnvConfig, Task, ...) extend `verifiers.v1`, which is a
declared, pure-pydantic dependency of prime-rl-configs (it pulls `datasets` for
the taskset/Task types but no GPU/ML deps). Drop `verifiers` and `datasets` from
the slim-install forbidden list — keep the real heavy training deps (torch,
vllm, transformers, ...).

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

---------

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

* chore(v1): bump verifiers submodule to feat/nano-as-v1 tip

Picks up the v1 end-to-end eval test suite (#1609) and the v0 legacy
env-server group-scoring fix (#1612).

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

* chore(v1): bump verifiers submodule to feat/nano-as-v1 tip

Picks up the v0 legacy-bridge fixes: guard against non-renderer training
clients (#1613) and serve the eval split for eval-only v0 envs (#1614).

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

* chore(v1): fix stale sft.toml teacher comments

The SFT teacher rolls out through the renderer client (token-in/out) and
must share the student's tokenizer; drop the leftover oai-client / token
backfill description removed in the renderer-only refactor.

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

* chore(v1): bump verifiers (v0 eval chat-completions client)

Picks up verifiers#1615: the legacy bridge builds a chat-completions client
for v0 eval rollouts (renderer for training), instead of raising on the
non-renderer eval client.

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

* feat(v1): scaleswe configs + taskset registration (#2765)

- register the scaleswe-v1 taskset (pyproject envs list + uv source)
- point the existing rlm-swe config (configs/rlm_swe/qwen35_4b.toml) at the
  scaleswe taskset (task_type="scaleswe", train + eval)
- add configs/debug/v1/scaleswe.toml — a per-env v1 port of that config using
  the scaleswe-v1 taskset via the rlm harness on the prime runtime

Companion to verifiers feat/scaleswe-v1 (scaleswe-v1 taskset + setup/workdir hooks).
Needs the deps/verifiers submodule bumped to that branch once it lands.

* feat(v1): multimodal training through the message graph + color-codeword-v1

Consume the v1 trace's multimodal sidecar. `trace_to_samples` builds, per branch,
`mm_kwargs` (the branch's per-image renderer items concatenated on dim 0 and
EncodedTensor-encoded) and `mm_token_type_ids` (the renderer's
`mm_token_type_id_map` applied to the branch tokens); `TrainSink` threads the
mapping through. The wandb sample logger now renders the task as a Table-safe JSON
string with image data elided — an image-bearing instruction crashed wandb's
Table type inference on the nested content list.

Adds `configs/v1/multimodal_color_codeword.toml` (Qwen3-VL-4B on color-codeword-v1,
2-GPU) and registers the `color-codeword-v1` taskset; bumps the verifiers submodule
for the multimodal message-graph support.

Verified end-to-end: the VLM trains through the mm path (eval 0.69 -> 0.78,
Trainable 256/256 — mm_kwargs reach the Qwen3-VL forward); v0 `color-codeword`
eval 0.625 ~= v1 `color-codeword-v1` eval 0.69 (faithful port).

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

* Revert "feat(v1): multimodal training through the message graph + color-codeword-v1"

This reverts commit 85b27cfc0be12b84f9b36456675b10387d01dc8a.

* feat: multimodal training through the v1 message graph + color-codeword-v1 (#2766)

* feat(v1): multimodal training through the message graph + color-codeword-v1

Consume the v1 trace's multimodal sidecar. `trace_to_samples` builds, per branch,
`mm_kwargs` (the branch's per-image renderer items concatenated on dim 0 and
EncodedTensor-encoded) and `mm_token_type_ids` (the renderer's
`mm_token_type_id_map` applied to the branch tokens); `TrainSink` threads the
mapping through. The wandb sample logger now renders the task as a Table-safe JSON
string with image data elided — an image-bearing instruction crashed wandb's
Table type inference on the nested content list.

Adds `configs/v1/multimodal_color_codeword.toml` (Qwen3-VL-4B on color-codeword-v1,
2-GPU) and registers the `color-codeword-v1` taskset; bumps the verifiers submodule
for the multimodal message-graph support.

Verified end-to-end: the VLM trains through the mm path (eval 0.69 -> 0.78,
Trainable 256/256 — mm_kwargs reach the Qwen3-VL forward); v0 `color-codeword`
eval 0.625 ~= v1 `color-codeword-v1` eval 0.69 (faithful port).

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

* chore(v1): bump verifiers pin — multimodal review-pass cleanups

Picks up the verifiers feat/v1-multimodal head: the multimodal review-pass
(capability-flag docstrings, trimmed mm comments, color-codeword-v1 config
validator + module constants) and the merged malloc_trim worker-RSS fix (#1621).

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

* chore(v1): bump verifiers pin (content-part mm attribution) + config/test sync

- Bump deps/verifiers to the content-part multimodal attribution (drops the unused
  placeholder offset machinery).
- Drop max_turns/seed from the color-codeword-v1 taskset args in the config — the
  taskset hard-codes them as module constants now, and passing them is rejected.
- Update the mm egress unit test to assert mm_items order (the new attribution),
  not placeholder offsets.

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

* fix(trainer): slice mm_kwargs on truncation so tokens match embeddings

When a sample exceeds seq_len, prepare_sample truncated input_ids and
mm_token_type_ids but passed mm_kwargs through whole — leaving more image
embeddings than surviving image placeholders. Now truncation cuts to a
whole-image boundary (never splitting an image's placeholder block) and slices
mm_kwargs (pixel_values + image_grid_thw) to the images that fully survive, so
image-placeholder count == image-embedding count.

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

* chore(v1): bump verifiers pin to ruff-formatted graph.py

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

* chore(v1): remove test_trajectories_mm.py

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

---------

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

* feat: thread num_workers to the env-server worker pool (#2768)

* feat(v1): thread num_workers to the env-server worker pool

Wire the verifiers env-server worker pool into prime-rl: the orchestrator's
spawned env server (envs.py) and the `env-server` CLI now serve via
verifiers' serve_env with num_workers, so requests fan out across N worker
processes instead of one event loop. num_workers was already a config field but
dropped on the floor; it's now passed through and defaults to 4.

Companion to verifiers feat/v1-env-workers; needs deps/verifiers bumped to it.

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

* feat(v1): default num_workers to 4

Make the worker pool the default: num_workers defaults to 4 (was "auto"->1)
across the per-env, train, and eval configs, so training/eval env servers fan
rollouts across 4 worker processes out of the box. "auto" stays a valid value
(scales per concurrency); set num_workers=1 for the old single-process server.

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

* fix(v1): keep num_workers="auto" default on the orchestrator

Revert the orchestrator's per-env / train / eval num_workers defaults back to
"auto" (was 4) so they keep scaling 1 worker per 256 concurrent rollouts out of
the box. The standalone env server can't scale (no concurrency context — it's
driven by external clients), so its resolver collapses "auto" to a fixed 4.

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

---------

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

* chore(v1): bump verifiers to be76cbc3 (env-server worker pool)

Align the pin with #1623 (env-server worker pool: router + N workers),
which the just-merged #2768 (thread num_workers to the pool) requires;
the pin had lagged at the pre-#1623 multimodal tip.

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

* feat(v1): register r2e-gym-v1 taskset

Add r2e-gym-v1 to the base v1 taskset deps + uv sources (editable from
deps/verifiers/examples/tasksets/r2e_gym_v1) so the id resolves through
the v1 loader, matching the other -v1 tasksets.

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

* chore(swe): use r2e-gym for rlm_swe configs (v0 + v1)

- v0 configs/rlm_swe/qwen35_4b.toml: restore the train env to r2e and the
  eval env to swebench-verified-quick (as on main), reverting the scaleswe switch
- v1: rename configs/debug/v1/scaleswe.toml -> r2e_gym.toml, point the train env
  at the r2e-gym-v1 taskset, and drop the eval block

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

* chore(swe): point rlm_swe configs at r2e-gym (content)

Apply the edits the prior rename commit missed:
- v0 rlm_swe/qwen35_4b.toml: train -> r2e, eval -> swebench-verified-quick (as on main)
- v1 debug/v1/r2e_gym.toml: taskset -> r2e-gym-v1, eval block removed

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

* fix(v1): restore env-server worker logs to the env log file (#2770)

Env servers spawn their worker pool as fresh `spawn` processes with no logging
handlers (verifiers#1626), so per-rollout logs (rollout start/done, context-exceed
warnings) were silently dropped. Pass `setup_env_server_logging` to verifiers'
`serve_env` as `log_setup`; it runs in the broker and in every worker. A worker
inherits the broker's redirected stdout/stderr, so its logs land in the same
`envs/{train,eval}/<name>.log` as before — no new files or paths.

Bumps deps/verifiers to the worker-logging fix.

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

* chore(v1): bump verifiers to 955b6cdf (dashboard token usage fallback)

Realign the pin onto origin/feat/nano-as-v1 and pick up #1627: the --rich
dashboard's token counts fall back to provider usage when the endpoint returns
no token ids (no more 0/0). The prior pin 3df34ba5 was a pre-rebase #1626
variant; 955b6cdf already contains the equivalent #1626 (env-server worker
logging) plus #1627.

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

* chore(v1): bump verifiers to 8e4ad735 (clean env-server teardown)

Picks up the serve_env SIGTERM-teardown fix: pool/in-process env servers no
longer print a spurious KeyboardInterrupt traceback into the env logs on
shutdown.

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

* chore(deps): bump verifiers (renderers floor 0.1.8.dev40)

Picks up the verifiers floor bump so the renderers offset-tokenizer fix (dev40,
PRs #72/#75) can't be undercut by a pre-fix PyPI resolution. Re-locks uv.lock to
the dev40 specifier.

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

* chore(v1): bump verifiers to db82b38a (reap subprocess tree on cancel)

Picks up #1628 (reap the whole subprocess tree when a runtime run is cancelled).

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

* feat: elastic env-server pool (inherit static/elastic pool config) (#2774)

* feat(v1): elastic env-server pool (inherit pool config from verifiers)

Companion to verifiers#1629. prime-rl's EnvConfig now extends vf.EnvServerConfig, so
each env inherits the `pool` discriminated union (static{num_workers=4} |
elastic{max_workers=None, multiplex=128}, default elastic) and the orchestrator's env
servers scale workers on demand instead of pre-spawning a fixed `auto` count.

- Drop the per-env / train-group / eval-group `num_workers` fields + the auto-resolution
  (ceil(max_inflight/256)); the elastic pool self-sizes from load.
- envs.py / env_server.py pass `vf.pool_serve_kwargs(env.pool)` to serve_env.
- Bump deps/verifiers to the elastic-pool branch.

Breaking: `num_workers` is replaced by `pool`. Configs set `pool = { type = "elastic",
multiplex = N }` or `{ type = "static", num_workers = N }`; the rlm_swe + r2e debug
configs are migrated.

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

* fix(v1): back-compat shim mapping legacy num_workers -> pool

EnvConfig forbids extra fields, so configs still setting the removed `num_workers`
would hard-fail. Add a `model_validator(mode="before")` that maps it onto `pool`:
an int -> a fixed `static` pool, `"auto"` -> the default `elastic` pool; an explicit
`pool` always wins. Keeps existing (incl. out-of-tree) configs parsing without edits.

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

* chore(v1): drop num_workers from rlm_swe + r2e configs (use default elastic pool)

The default `pool` is already elastic (multiplex 128), so an explicit `pool` here was
redundant — just remove the legacy `num_workers` and inherit the default.

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

---------

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

* chore(v1): bump verifiers to f404e97f (elastic env-server pool)

Realign the pin onto origin/feat/nano-as-v1: the prior pin d0c5bc98 was the
unsquashed #1629 feature branch, now squash-merged as f404e97f
(content-identical). Picks up #1629 (static/elastic env-server pool config).

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

* chore(v1): bump verifiers to 88e9bedd

Picks up #1631 (per-rollout setup timing as a distinct phase) and #1632
(per-call model + runtime retries).

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

* chore(v1): bump verifiers to 40a2e89f (fix trace.timing.*.duration to_wire validation)

Fixes RunRolloutResponse ValidationError 'trace.timing.setup.duration: Extra
inputs are not permitted' that crashed every rollout (#1636 drops computed
durations from to_wire).

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

* chore(v1): bump verifiers to 5dc084f5

Picks up #1638 (add --resume for evals: re-run a previous run's
missing/errored rollouts).

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

* chore(v1): bump verifiers to 472622ba

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

* chore: stop importing env modules in the orchestrator (always Rollout[WireTask]) (#2781)

* chore(v1): stop importing env modules in the orchestrator

The orchestrator built its per-env trace_type as Rollout[vf.task_type(env_id)] for v1 envs, and
vf.task_type imports the env package just to read its Task subclass for typing the wire trace.
Nothing reads typed env task fields - only task.idx and a full task.model_dump - and WireTask
(extra="allow") preserves those fields (incl. on disk). Always use Rollout[vf.WireTask], so the
orchestrator never imports an env package: the env's type and runtime both live only in the
server process.

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

* chore(v1): hoist the constant Rollout[WireTask] to a module-level ROLLOUT_TYPE

It no longer varies per env, so it doesn't belong as a per-instance attribute set in
Env.__init__ - lift it to a module constant used directly in run_rollout/run_group.

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

---------

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

* chore(v1): bump verifiers to 7270e69b

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

* chore(v1): bump verifiers to 66c87d5b

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

* chore(v1): bump verifiers to ef45f720

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

* chore(v1): bump verifiers pin (alphabet-sort host user sim, #1645)

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

* chore(v1): bump verifiers pin (modal creates_per_sec 5 -> 40, #1646)

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

* fix: cap v1 hendrycks-sanity scoring at 10s (#2790)

* fix(v1): cap hendrycks-sanity scoring at 10s

Without a scoring timeout (the default is no limit), a wedged math verify holds its
rollout's permit forever — sympy can spin past the in-script alarm — and at 512
concurrency that starves the pool and stalls long runs. Set timeout.scoring = 10 on the
train and eval envs so the framework cancels and the subprocess runtime kills a runaway
verify, freeing the permit.

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

* chore: drop inline comment on the scoring timeout

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

---------

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

* chore(v1): bump verifiers (eval/train client rename) + adopt config imports (#2792)

Bump deps/verifiers to feat/nano-as-v1 HEAD (8873a740), which includes verifiers#1654 — the v1
interception rework: role-named clients (EvalClient/TrainClient), route-detected wire dialects
(chat/responses/anthropic), 1:1 relay + streaming, reasoning preserved.

Adopt the renamed client config classes in prime_rl/utils/client.py:
OpenAIClientConfig -> EvalClientConfig, RendererClientConfig -> TrainClientConfig.

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

* chore(v1): bump verifiers pin (subprocess cached-interpreter uv-scripts, #1660)

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

* chore(v1): bump verifiers pin (codex built-in harness, #1661)

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

* chore: track terminal-bench-2-v1 as a taskset dependency

It was only a manual editable install, so `uv sync` pruned it. Add it to the env dependency
group + [tool.uv.sources] (mirroring r2e-gym-v1) so it persists across syncs and is available
out of the box.

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

* fix(v1): keep multimodal tensors out of rollout dumps (#2794)

verifiers#1653 (carry mm tensors across the env-server wire) is merged and pinned, so
`MessageNode.multi_modal_data` is no longer `exclude=True` — `model_dump(mode="json")` now
serializes the base64 pixel tensors into `train_rollouts.jsonl` and the wandb sample tables,
bloating every line. They're the training `mm_kwargs` carrier, not part of the rollout
record, so exclude them at the dump boundary (train + eval paths).

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

* chore(v1): install all v1 example tasksets in prime-rl

Declare the remaining 7 verifiers v1 example tasksets (code-golf, deepwiki,
glossary, swelego, wiki-search, wikispeedia, wordle) as editable deps so uv sync
installs every example, matching the verifiers examples set. chromadb/textarena
were already present via the v0 wiki-search/wordle envs.

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

* chore(v1): install the compact example harness in prime-rl

The example harness (examples/harnesses/compact) was missing from prime-rl deps,
so the documented --harness.id compact branching example failed to resolve
(ModuleNotFoundError: harness compact not found). Declare it like the example
tasksets so uv sync installs it.

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

* chore(v1): bump verifiers pin (v1 docs #1662 + Trace.info #1664)

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

* feat(v1): encode router-replay routed_experts into transport (#2808)

* feat(v1): encode router-replay routed_experts into transport

Pack Branch.routed_experts ([tokens, layers, top_k]) into the transport
RoutedExperts the trainer replays, realigning the token axis to len(token_ids)
as a backstop. Bumps the verifiers pin to the companion router-replay commit.

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

* chore(v1): bump verifiers pin (raw-bytes wire) + exclude routed_experts from disk dumps

Bumps deps/verifiers to the raw-bytes router-replay codec (RoutedExperts rename +
msgpack bin wire). routed_experts now rides the env-server wire as raw bytes, so it
can't round-trip the json disk dump — add it to ROLLOUT_DUMP_EXCLUDE alongside
multi_modal_data (both are training inputs, not part of the rollout record).

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

* fix(v1): guard router-replay vs prefix caching + bump verifiers/renderers pins

- Add disable_prefix_caching_for_router_replay validator: prefix-cache hits skip
  recomputing the cached prefix, so the engine returns no routed-expert decisions for
  those tokens. Router replay needs routing for every token, so force
  enable_prefix_caching=False (mirrors the existing kv_cache_offload guard).
- Bump deps/verifiers: tail-pad routed_experts so the final node aligns (the engine
  omits the last position's routing).
- Bump deps/renderers: _get_offset_tokenizer immune to the global fastokens patch race.

Together these make v1 MoE router replay work end-to-end (Qwen3-30B-A3B): verified
mismatch_kl drops vs no-replay (0.0005/0.0002/0.0002 vs 0.0015/0.0015/0.0005 @ steps 0/1/2).

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

* chore: bump deps/renderers pin (ruff format fix)

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

* chore: bump deps/verifiers pin (ruff format)

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

* chore: bump deps/verifiers pin to merged feat/nano-as-v1 (router-replay #1672)

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

* Remove disable_prefix_caching_for_router_replay validator

Drops the guard that force-disabled inference.enable_prefix_caching under router replay.
Validating whether prefix caching is actually compatible with router replay (cache hits
may carry no routed-expert decisions); re-add if the A/B shows it drops routing.

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

---------

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

* fix(orchestrator): keep top-level advantage wiring after merge

The merge auto-resolved train_sink.py and the orchestrator's TrainSink
construction to main's per-env advantage design (#2721), but envs.py and the
configs were kept on the branch's top-level design — so TrainSink read
`train_envs.get(env_name).advantage_fn`, which TrainEnv no longer defines
(AttributeError at rollout time).

Restore the branch's top-level advantage: TrainSink takes `advantage_config`
and builds its own `self.advantage_fn` once. Verified end-to-end with a
reverse-text-v1 RL smoke (reward climbs 0.16 -> 0.40 over 6 steps).

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

* chore(v1): bump verifiers pin to merged main (1b7736a8)

deps/verifiers feat/nano-as-v1 now includes origin/main merged in
(composable tasksets + sandbox/save utils). Pin moves 7a98b566 -> 1b7736a8.

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

* chore: bump pydantic-config submodule to main (single-dash short flags)

deps/pydantic-config 896ade4 -> 99f47c6 (origin/main). Picks up #16
(single-dash short flags for single-character aliases, e.g. `eval -n -m`)
and upstreams the dict[str,str] preservation fix (#14). No uv.lock change
(editable path source).

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

* chore(v1): bump verifiers pin to feat/nano-as-v1 tip (5fc0b295)

Picks up the py3.11 TypedDict CI fix and #1676 (prime-sandbox programs run for
the sandbox lifetime instead of the 15-min background-job default, + retry-log
wording). Pin moves 1b7736a8 -> 5fc0b295.

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

* chore(v1): bump verifiers pin to 3af08c9b

Includes verifiers#1677 - scaleswe-v1 resolves task images via Prime's
Artifact Registry instead of the incomplete public Docker Hub mirror.

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

* fix(orchestrator): trim glibc heap back to the OS each step (#2821)

Factor the existing end-of-run malloc_trim into a `trim_process_memory()`
helper and also call it at the end of `finalize_train_batch`. Each step frees a
step's worth of rollouts / traces / transport buffers, but glibc keeps those
pages in per-arena free lists, so orchestrator RSS climbs over a long run
without ever shrinking. Trimming per step returns them to the OS.

Mirrors the per-step trim in prime-rl #2807 — the trim only; that PR's
`.raw`-based retention helpers don't apply to this branch's typed Rollout/Trace.

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

* chore(v1): bump verifiers pin to 7862985b

Includes verifiers#1678 - scaleswe-v1 Prime Artifact Registry is now opt-in
(`use_prime_registry`, default off), so the default Docker Hub image path works
on local docker runtimes again.

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

* feat: route consistent_hash on X-Session-ID for cross-turn prefix reuse (#2822)

The vllm-router `consistent_hash` policy keys on request-id headers (default
x-request-id / x-correlation-id / x-trace-id / request-id). The v1 inference
clients send none of those per rollout, so a multi-turn rollout's turns hashed
to random DP shards and re-prefilled the growing prompt cold each turn (~40%
prefix cache hit rate on an agentic SWE run, where it should approach the
eviction-limited ceiling).

Launch the router with `--request-id-headers x-session-id` so it keys on the
per-rollout `X-Session-ID` header the v1 clients now emit (companion verifiers
change). Every turn of a rollout pins to one engine, keeping its cross-turn
prefix warm. Harmless for the random / round_robin policies, which ignore
request-id headers.

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

* chore(v1): bump verifiers pin to 211faecb (session-affinity routing)

Picks up verifiers #1680 (session-affinity routing header for cross-turn
prefix reuse) — the counterpart to prime-rl #2822. Pin 7862985b -> 211faecb.

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

* chore(v1): bump verifiers pin to 3f45f73b (scaleswe-v1 image filter)

Picks up verifiers #1679 (filter unavailable scaleswe-v1 images at load).
Pin 211faecb -> 3f45f73b.

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

* chore(v1): bump verifiers pin to 44da378c (r2e-gym-v1 registry opt-in)

Picks up verifiers #1681 (r2e-gym-v1 Prime Artifact Registry opt-in, default
off). Pin 3f45f73b -> 44da378c.

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

* chore(v1): bump verifiers pin to a723977c (scaleswe-v1 image_url filter)

Picks up verifiers #1683 (filter on Docker Hub image_url, not the resolved
image). Pin 44da378c -> a723977c.

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

* chore(v1): bump verifiers pin to 0c8d0aa1 (rootless harness install)

Picks up verifiers #1685 (harnesses install/run without root, pinned
/tmp/vf-{harness}) and #1684 (remove Claude Code harness). Pin a723977c -> 0c8d0aa1.

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

* chore(v1): bump verifiers pin to d4b054e3 (skip region-limited e2e test)

Picks up verifiers #1686 (skip test_multi_turn on prime — colocated user-sim
port exposure is region-limited). Pin 0c8d0aa1 -> d4b054e3.

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

* chore: point verifiers env paths at the flattened environments/ dir (#2824)

* chore: point verifiers env paths at the flattened environments/ dir

Companion to verifiers #1695 (flatten examples/ into a single environments/).
Update the deps/verifiers editable source paths in pyproject.toml + uv.lock:
examples/tasksets/<x> -> environments/<x> and
examples/harnesses/compact -> environments/compact. Bump the verifiers pin to
the flatten branch (7ddc78b2) so the relocated paths resolve.

Re-pin to the merged commit once verifiers #1695 lands.

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

* chore(deps): bump verifiers to 22b02e4b (flatten examples/ into environments/, #1695 merged)

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

---------

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

* chore(v1): advance verifiers pin to feat/nano-as-v1 tip (Trace.state + DNS fix)

#2824 retargeted the env paths but pinned deps/verifiers at 22b02e4b (#1695,
just after the examples/->environments/ flatten), which predates the later
merges. Advance the submodule to the actual feat/nano-as-v1 tip bf30ae5f
(verifiers 0.1.15.dev298): adds Trace.state (#1711), the unconditional MCP
DNS-rebinding relax (#1715, fixes the in-prime tool 421 CI failures), and the
init scaffold (#1713).

bf30ae5f also dropped verifiers' self-referential `packages` extra, so drop
`[packages]` from the verifiers override-dependency (and refresh the stale
sources comment).

Smoke: `eval reverse-text-v1 -n 1` (subprocess, temp=0) runs clean — no errors,
not truncated, reward ~1.0.

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

* chore(v1): bump verifiers pin to feat/nano-as-v1 tip (#1717 + #1719)

Advance deps/verifiers bf30ae5f -> f7fa7482:
- #1717 train-client prefix bridging + token-based message-graph branching
- #1719 default the harness runtime to subprocess

No prime-rl-side changes needed: every prime-rl v1 config already sets
harness.runtime.type explicitly (#1719's default flip is a no-op here), and the
consumed verifiers surface (serve EnvClient/serve_env/pool_serve_kwargs,
clients.config Eval/TrainClientConfig, task.TaskT, the Trace branch/token API) is
untouched by #1717. Imports resolve; reverse-text-v1 eval smoke clean.

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

* chore(v1): bump verifiers pin to feat/nano-as-v1 tip (f7fa7482 -> bbfd5646)

New since the last pin: #1718/#1721 (CI + tests), #1723 (per-harness tool
disabling), #1666 (client consolidation + chat-completion header forwarding),
#1722 (warn on non-default subprocess harnesses). No prime-rl-side changes
needed: clients.config (the consumed surface) is untouched by #1666's client
refactor, #1722 only warns and exempts the default harness (what prime-rl's
subprocess configs use), and the rest is additive/CI-only. Imports resolve;
reverse-text-v1 eval smoke clean (reward 1.0).

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

* chore: verifiers #1732 companion (model_dump traces, Task.prompt rename) (#2831)

* chore(v1): add prime CLI as deps/prime submodule (feat/nano-as-v1)

Tracks the companion PrimeIntellect-ai/prime#751 branch that adds verifiers v1
eval support to the prime CLI (run/view consume the v1 entrypoint + Trace format).

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

* chore(v1): bump verifiers pin to feat/nano-as-v1 tip (bbfd5646 -> 220f21d4)

New: #1727 (per-rollout isolation for shared writable tool servers) and #1702
(trim verifiers runtime deps — modal/notebook/quest/pdf moved to extras). No
prime-rl-side changes needed: the only dropped transitive dep is pymupdf, used
solely by verifiers' experimental quest PDF tool via a lazy import behind the
quest extra (prime-rl never touches it). Imports resolve on dev307;
reverse-text-v1 eval smoke clean (reward 1.0).

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

* chore: validate env-server traces via model_dump (companion to verifiers to_wire removal)

verifiers drops Trace.to_wire/from_wire and the derived computed fields (reward,
is_truncated, error, duration are plain properties now). Swap wire.to_wire() ->
wire.model_dump() when re-typing a returned Trace into ROLLOUT_TYPE; the .reward /
.is_truncated the metrics/eval code reads are the Trace properties, so they still work.

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

* chore: rename vf.Task(instruction=) -> prompt= (verifiers #1732 companion)

verifiers #1732 renames Task.instruction -> Task.prompt; update the dispatcher's
error-rollout Task construction to match. Pin bump to the merged commit comes when #1732
lands.

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

* chore(v1): bump verifiers pin to chore/v1-general-cleanup tip (220f21d4 -> d78d7474)

Pin #1732 (general v1 cleanup) so this companion's model_dump trace handling and the
Task.prompt rename round-trip against a verifiers that actually has them. Re-pin to the
feat/nano-as-v1 tip once #1732 merges.

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

* chore(v1): bump verifiers pin to feat/nano-as-v1 tip (d78d7474 -> caaf0ff3)

#1732 (general v1 cleanup) merged into feat/nano-as-v1; re-pin off the chore branch onto the
integration tip. This companion's model_dump trace handling + Task.prompt rename now run
against merged verifiers.

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

* chore: error-rollout placeholder task uses prompt=None

An error rollout has no prompt; None is the honest value (Task.prompt is str | Messages |
None) rather than an empty string.

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

---------

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

* fix(v1): drop removed enable_bash from harness configs (verifiers #1723) (#2833)

verifiers #1723 (in the current pin) removed the default harness's enable_bash
field — the default harness now exposes only the taskset's MCP tools (use an
agentic harness like mini-swe-agent for a shell). All v1 configs still set
`enable_bash = false`, which now fails config validation (Extra inputs are not
permitted). Drop it (no-bash is the default, so behavior is unchanged); no src/
code referenced it.

Verified: `uv run rl @ configs/debug/v1/reverse_text.toml` (Qwen3-0.6B, 2 steps)
runs end-to-end — orchestrator rollouts Error 0.0% (reward 0.117 -> 0.177),
trainer steps + checkpoint, 'Training finished!'.

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

* chore(v1): bump verifiers pin to feat/nano-as-v1 tip (caaf0ff3 -> cc4afd52)

New: #1733 (robust env-server teardown, no leaked tunnels/sandboxes), #1734
(general-agent solver v1 taskset, additive/opt-in), #1735 (reject unsupported
task system_prompt). No prime-rl-side changes needed: consumed serve/clients
surface unchanged, default harness supports system_prompt, new taskset not
registered. Imports resolve; reverse-text-v1 eval clean (reward ~1.0, no errors).

Note: #1733's worker teardown throws KeyboardInterrupt on SIGTERM but run_server
doesn't swallow it, so a benign KeyboardInterrupt traceback prints at env-server
shutdown (cosmetic; verifiers follow-up).

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

* feat(v1): add debug general-agent-v1 RL config + register the taskset

Add configs/debug/v1/general_agent.toml — the v1 general-agent-v1 taskset
(GeneralAgentSolverTaskset) on the default harness, with the agent and its tool
server colocated in a modal sandbox. Adapted from configs/general_agent/
rl_qwen3_4b.toml (Qwen3-4B, batch 256). Register general-agent-v1 in
[tool.uv.sources] + the envs extra so the id resolves.

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

* feat(v1): add scaleswe-v1 RL config (Qwen3.6-35B-A3B, 65k ctx)

configs/debug/v1/scaleswe.toml — the v1 scaleswe-v1 SWE taskset on the rlm
harness + modal runtime (each row injects its own Docker image into the sandbox;
no MCP toolset). Qwen3.6-35B-A3B, batch 256, 65k context, qwen3.6 renderer with
thinking. Deployment/parallelism (cp=2, infer dp=2 tp=4, 1 train + 1 infer node)
seeded from the 30B-A3B reference — tune on the cluster for the 35B / 65k
footprint. Multi-node slurm; scaleswe-v1 was already registered.

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

* chore(v1): bump verifiers pin (cc4afd52 -> 3c5f6586) + register swebench-verified-v1

New: #1738 (swebench-verified harbor taskset, prime prebuilt images), #1739
(don't retry program exec - fixes forked duplicate trace branches), #1736/#1737
(quest pdf sanitization, dashboard rotation). Register the new swebench-verified-v1
env (source + envs extra); no other prime-rl changes needed.

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

* feat(v1): add SWE-Bench-Verified online eval to the scaleswe run (prime runtime)

Mirror the v0 rlm_swe SWE-bench eval on the v1 scaleswe config: [orchestrator.eval]
interval=20, an eval env on the swebench-verified-v1 taskset via the rlm harness on
the prime runtime (use_prime_registry=true -> prime's prebuilt instance images),
rollout timeout 3600s. Train stays on modal; eval runs on prime.

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

* fix(v1): use public images for the scaleswe SWE-Bench-Verified eval

A debug eval showed use_prime_registry=true fails with IMAGE_PULL_FAILED on the prime
runtime: the SWE-bench Verified sweb.eval.* instance images aren't mirrored into prime's
prod-sandbox Artifact Registry. The same prime sandbox pulls r2e-gym-v1's prime-registry
image and the public swebench/sweb.eval.* image fine, so it's a missing-mirror issue, not
credentials. Drop use_prime_registry (default false -> public Docker Hub images) so the
online eval works on the prime runtime now; flip it back on once the images are mirrored.

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

* chore(v1): bump verifiers pin + re-enable use_prime_registry for the scaleswe SWE eval

Bump deps/verifiers 3c5f6586 -> 952b2a7d, which lands the swebench-verified-v1 prime-image
path fix (PrimeIntellect-ai/verifiers#1740): the mirror keeps the swebench/ org, so
use_prime_registry=true now resolves to prod-sandbox/swebench/sweb.eval.* and pulls. Flip the
scaleswe SWE-Bench-Verified eval back to use_prime_registry=true (verified to pull on a prime
sandbox), for the fast cached mirror instead of public Docker Hub.

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

* chore(v1): cap hendrycks-sanity at 256 in-flight rollouts + 30s scoring timeout

Set orchestrator max_inflight_rollouts=256 (below the 512 batch) and bump the per-env
scoring timeout 10s -> 30s on both the train and eval envs. Guards against the subprocess
env-server stall where unbounded concurrency + a hanging math-verify hold permits until the
run wedges.

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

* chore(v1): bump verifiers pin (general-agent-v1 colocated toolset fix)

Bump deps/verifiers 952b2a7d -> 56a720ca: PrimeIntellect-ai/verifiers#1741 makes the
general-agent-v1 toolset work when colocated in a sandbox (ships the task's tools.py + db.json
over /task). Env-package only - no framework/config surface, no prime-rl changes.

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

* chore(v1): bump hendrycks-sanity scoring timeout to 5min

Raise the per-env scoring timeout 30s -> 300s on both the train and eval envs - 30s was too
tight for the math-verify scoring under load.

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

* feat(orch): show avg branches next to turns in step + eval log lines

Add 'Branches {mean:.1f}' alongside 'Turns' in the per-step train head, the per-env
breakdown, and the eval line - the average trace branch count per rollout (1 = linear, >1 =
compaction/subagents).

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

* chore(v1): update tmux + monitor-run skill for flattened env log paths

Env logs are now one file per env (envs/{train,eval}/{env_name}.log)
instead of nested env_server/env_worker_* files.

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

* chore(v1): bump verifiers pin (retry backoff + relay retries)

Bump deps/verifiers 56a720ca -> 6647fe0a: PrimeIntellect-ai/verifiers#1744 adds exponential
backoff + jitter to the per-call client/runtime retries (so concurrent rollouts don't
re-thunder a shared endpoint) and lets harness clients retry the relay. Internal/additive -
no config schema or API change, no prime-rl edits.

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

* Fix routed SLURM inference DP rank client config (#2830)

Co-authored-by: Codex <codex@primeintellect.ai>
(cherry picked from commit 8dfe8734e3)

* chore(v1): scaleswe Qwen3.6 fixes — ulysses CP + qwen3_coder tool parser

Qwen3.6-35B-A3B is a hybrid/linear-attention MoE: ring CP is unsupported
(use ulysses), and the model id isn't matched by the auto tool-parser
resolver so set tool_call_parser=qwen3_coder explicitly (enables vLLM auto
tool choice for the SWE agent). Complements the cherry-picked #2830 DP-rank
client fix.

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

* chore(v1): bump verifiers pin (usage tracking + Terminus 2 harness)

Bump deps/verifiers 6647fe0a -> a630d3b0:
- PrimeIntellect-ai/verifiers#1704: track cached/reasoning/cost usage in v1 (new Usage type +
  Trace/Branch .usage properties; internal node prompt_tokens -> input_tokens rename).
- PrimeIntellect-ai/verifiers#1747: add the Harbor Terminus 2 harness (additive).

Additive for prime-rl - it consumes only stable Trace properties (completion_len, total_tokens,
num_turns, num_branches) + its own batch metrics, not the raw Usage. Verified: reverse-text RL
smoke (2 steps) trains clean (Error 0.0%, Trainable 128/128, Training finished).

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

* chore(v1): scaleswe — drop eval, prime train runtime, dist_timeout 3600, lm-head chunking

The multi-node trainer kept dying on an NCCL _ALLGATHER_BASE watchdog timeout while
it waited through the slow step-0 swebench eval (eval hogged all rollout slots →
trainer starved on the collective → timeout → SIGABRT). Fixes:
- drop the swebench eval (train-only) — this is what actually cleared the hang
- dist_timeout_seconds 600 -> 3600
- train harness runtime modal -> prime (matches eval; unique label per run)
- fused_lm_head_token_chunk_size = 1024 (activation-memory saver at 65k seq)
cp stays 2 (max for Qwen3.6's 2 KV heads under ulysses; cp=4 fails the divisibility assert).

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

* chore(v1): bump verifiers pin (reuse pool tunnel for colocated state channel)

Bump deps/verifiers a630d3b0 -> 7bb546c2: PrimeIntellect-ai/verifiers#1752 makes colocated
tool/user servers reuse the harness's existing pool tunnel for the state channel instead of
opening a second per-rollout host tunnel (which swamps the tunnel service at high concurrency).
Backward-compatible (new state_base param defaults to None; own-runtime servers still bridge
themselves) - internal rollout/MCP path, no prime-rl edits.

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

* chore(v1): bump verifiers pin (eval progress-bar reward/metric means)

Bump deps/verifiers 7bb546c2 -> b8fad841: PrimeIntellect-ai/verifiers#1753 shows per-reward/
metric running means under the eval progress bar. Eval CLI dashboard + format helper only -
no training/wire surface, no prime-rl edits.

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

* chore(v1): bump verifiers pin (rollout error taxonomy + interception debug logs)

Bump deps/verifiers b8fad841 -> cd205eee:
- PrimeIntellect-ai/verifiers#1751: type v1 rollout errors by boundary (RolloutError +
  Provider/Harness/Toolset/User/Sandbox/Taskset/Interception types, classified via boundary()).
  The trace Error record (type/message/traceback) and stop_condition values are unchanged, so
  prime-rl's consumed surface (vf.Error, errors/stop_condition, 'Cancelled'/'prompt_too_long')
  is intact.
- PrimeIntellect-ai/verifiers#1754: INFO interception up/down + debug-log intercepted routes.

Verified: reverse-text RL smoke (2 steps) trains clean (Error 0.0%, Training finished).

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

* refactor(orch): record caught rollout exceptions via Trace.capture_error

Use the canonical v1 Trace.capture_error(exc) for the dispatcher's caught-exception path
instead of hand-building a vf.Error record + stop_condition - same result (type=exc class
name, message, traceback, stop_condition='error') but routed through the framework's recorder,
so it picks up the #1751 RolloutError boundary types when one escapes. The synthetic Cancelled/
EmptyTrajectory markers stay explicit vf.Error records (not exceptions; the sink/metrics branch
on those exact type strings).

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

* chore(v1): bump verifiers pin (SDK-owned retries; merged worker-SIGTERM fix)

Bump deps/verifiers fedfa570 -> 2474b054, moving off the pre-merge fix/worker-sigterm-teardown
branch commit onto the feat/nano-as-v1 tip:
- PrimeIntellect-ai/verifiers#1755 (merged): swallow SIGTERM KeyboardInterrupt in spawned
  env-server workers.
- PrimeIntellect-ai/verifiers#1756: SDKs own retries; drop framework per-call model/runtime
  retries (removes RetryingClient/RetryingRuntime/CallRetryConfig). RetryConfig + the rollout
  retry (RolloutRetryConfig) are kept.

prime-rl imports none of the removed retry names and never references RetryConfig/.model/.runtime,
so no edits. Verified: config validates + reverse-text RL smoke (2 steps) trains clean
(Error 0.0%, Training finished).

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

* chore(v1): bump verifiers pin (interception env isolation + in-sandbox channel retries)

Bump deps/verifiers 2474b054 -> e002e80d:
- PrimeIntellect-ai/verifiers#1758: keep the interception endpoint out of agent-inheritable env.
- PrimeIntellect-ai/verifiers#1759: retry in-sandbox /state + /task channel fetches; name us in
  the prime expose error.

Internal to harnesses/runtimes/mcp - no prime-rl serve/client/trace surface, no edits. Verified:
reverse-text RL smoke (2 steps, default harness + subprocess runtime) trains clean (Error 0.0%,
Training finished).

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

* chore(v1): bump verifiers pin (ModalRuntime read path fix)

Bump deps/verifiers e002e80d -> 8c9f284b: PrimeIntellect-ai/verifiers#1761 makes
ModalRuntime.read resolve relative paths and stops retrying the tail tool logs. Modal-runtime
internal only - no prime-rl surface, no edits.

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

* chore(v1): bump renderers pin to clean tag renderers-v0.1.8.dev49

057f0087 (renderers-v0.1.8.dev40-2) fails a fresh hatch-vcs editable build
("0.1.8.dev40 can't be bumped"), so only grandfathered venvs built. dev49 is an
exact tag → builds cleanly, unblocking fresh venvs (e.g. running from /shared).

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

* chore(v1): set partition=all + scaleswe prime-sandbox pre_run_command

The SlurmConfig default partition "cluster" doesn't exist on this cluster (only
"all"), so generated sbatches failed to schedule. Set partition=all in the
scaleswe + hendrycks-sanity sources. Add scaleswe's prime-sandbox cleanup as a
pre_run_command (runs on the head node before launch) instead of editing the
sbatch template.

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

* fix(v1): scaleswe deployment 2+2 nodes

Source had num_train_nodes=1/num_infer_nodes=1 (the unconfirmed 30B-A3B starting
point); the run that reached step 36 used 2+2. A single train node OOMs the
35B-A3B trainer. Restore 2 train + 2 infer nodes (32 GPUs).

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

* chore(v1): hendrycks-sanity on modal runtime, 200 steps

Switch the hendrycks-sanity train + eval envs from subprocess to modal (offloads
scoring to modal sandboxes), cap max_steps at 200 (was 5000), rename job to
hendrycks-modal.

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

* chore(v1): bump verifiers pin to 94b7df1 (swebench /testbed workdir, malformed-json tool-args, container-test fix)

Brings in feat/nano-as-v1 #1762 (mark swebench_verified_v1 container-only),
#1763 (feed malformed tool-call JSON back to the model instead of crashing the
rollout), #1765 (pin swebench_verified_v1 task workdir to /testbed).

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

* chore(v1): scaleswe on mini-swe-agent + SWE-Bench-Verified eval (100 tasks)

Switch the scaleswe train harness rlm -> mini-swe-agent (prime sandbox), and re-add a
SWE-Bench-Verified online eval: mini-swe-agent on the prime runtime, use_prime_registry=true,
first 100 tasks (num_examples=100, group_size=1), interval 20, rollout timeout 3600s.

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

* fix(rl): mkdir parent for namespaced env-server config path

A namespaced env id (e.g. "primeintellect/wiki-search") makes the env-server
config filename a nested path; setup_env_servers opened it for writing without
creating the parent dir → FileNotFoundError at launch (slash-free ids were fine).
mkdir(parents=True, exist_ok=True) before the write.

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

* chore(v1): bump verifiers pin (sandbox lifetimes, reasoning state, tau2, harbor CLI)

Bump deps/verifiers 94b7df16 -> 6ac5a3b5:
- PrimeIntellect-ai/verifiers#1749: separate v1 sandbox lifetimes from rollout timeouts (caps
  harness timeouts at the 24h sandbox max). TimeoutConfig fields (setup/rollout/finalize/scoring)
  unchanged.
- PrimeIntellect-ai/verifiers#1748: preserve provider reasoning state across turns (dialects).
- PrimeIntellect-ai/verifiers#1692: migrate the Tau2 benchmark to v1 (new env, additive).
- PrimeIntellect-ai/verifiers#1745: install the pinned Harbor CLI on demand.

prime-rl consumed surface intact (TimeoutConfig, dialects via clients); no edits. Verified:
reverse-text RL smoke (2 steps) trains clean (Error 0.0%, Training finished).

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

* chore(v1): lock the tau2-bench-v1 editable env from the verifiers bump

uv sync picked up the new tau2_bench_v1 workspace member (verifiers#1692, in the last pin bump)
as an editable lock entry. Lockfile-only follow-up.

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

* chore(v1): bump verifiers (final touches #1770, v1 e2e CI green #1771)

#1771 greens the v1 e2e suite and runs it in CI (host+docker only; prime+modal local-only): per-axis matrix marks, assert reward not is_truncated, terminus refuses the host runtime, eval in-process by default. #1770 is the guide/config final touches (0.2.0).

* chore(v1): bump verifiers (ruff-format test_envs)

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

* chore(v1): bump verifiers (drop feat/nano-as-v1 CI trigger)

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

* chore(v1): bump verifiers (test triggers → main only)

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

* chore(v1): bump verifiers (code-golf-v1/aime24-v1 verifiers dep)

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

* chore(v1): add gsm8k v1 config (train + test eval) under configs/debug/v1; drop old configs/v1

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

* chore(v1): bump verifiers to latest feat/nano-as-v1 (276ed743)

30 commits — v1 performance optimizations (zero-copy ZMQ relay, off-event-loop trace persistence, lazy bridged prompts, reduced trace/completion copies) and stateless-JSON MCP servers (#1822). No dependency changes (uv.lock unchanged).

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

* chore(v1): point verifiers submodule to main (post feat/nano-as-v1 merge)

verifiers feat/nano-as-v1 was squash-merged to main; retarget the submodule (8d52bc8e) and .gitmodules branch to main. main's #1826 moved the built-in tasksets/harnesses into the verifiers package, so drop prime-rl's now-defunct standalone harnesses/tasksets deps + editable sources (provided by verifiers.v1 now); compact and the -v1 env pins are unchanged. uv.lock re-resolved (425 pkgs).

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

* fix(tests): migrate unit tests to the bumped verifiers v1 API

The verifiers bump (8d52bc8e) changed several public APIs; these nano unit
tests still used the old surface and failed. Test-only changes:

- OpenAIClientConfig -> EvalClientConfig (test_teacher_logprobs)
- vf.Task(instruction=...) -> prompt=... (test_filters)
- client-config shape: client_type/api_base_url/extra_headers ->
  EvalClientConfig/TrainClientConfig type/base_url/headers/renderer
  (test_client, test_elastic)
- rebuild rollouts as v1 Trace objects with branches, asserting against
  production's actual parquet columns (test_prime_monitor)

(test_advantage's equivalent fix landed in the merge commit.)

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

* feat(trainer): restore main's bin_cost FLOP-balanced packing

The main->nano merge had over-reverted the trainer pipeline to its pre-bin_cost
version. Restore main's packing/distribution so the trainer tracks main; the
only nano-side trainer delta is now the token_ids TrainingSample interface plus
multimodal.

- batch.py: main's bins-based packing (_MicroBatchBin, _materialize_bin,
  _expand_bins_by_splitting, bin_cost-weighted balanced_partition within each
  modality group); keep nano's token_ids prepare_sample + _truncate_mm /
  _slice_encoded image-block-aware truncation.
- transport/types.py: MicroBatch.sequence_lengths (the bin_cost weight input).
- packer.py: thread bin_cost through setup_packer -> prepare_batch; keep nano's
  token_ids sample validation.
- data.py / train.py / token_export.py / utils.py: now identical to main -
  build_bin_cost(model.config) wiring + the precomputed sequence_lengths logprob
  split, dropping nano's redundant get_response_lengths path.
- tests: test_batch / test_packer pass bin_cost=build_bin_cost(None); the
  balance test classifies real vs dummy micro-batches by content (the FLOP
  balanced_partition interleaves dummies rather than appending them).

Verified: 484 unit tests pass (only the 4 GPU-toolkit tilelang model tests fail,
environmental); reverse-text-v1 RL smoke runs 3 clean steps end-to-end.

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

* test(trainer): carry over main's bin_cost packing tests

The bin_cost restore brought the packing code but the fork had patched nano's
test_batch instead of adopting main's, so main's bin_cost-specific tests were
left behind. Port them, token_ids-adapted: randomized packing invariants,
FLOP-aware balancing, FLOP-aware heavy-bin split-to-align, token-cost fallback
distribution, split-to-align avoids dummy micro-batches, and pad_micro_batch
preserves explicit sequence_lengths. 18 test_batch tests pass.

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

* chore: drop deps/prime submodule, revert .gitmodules to main

deps/prime was only referenced from .gitmodules (not pyproject/uv.lock/code);
removing it and resetting .gitmodules to main's version so the PR carries no
submodule-metadata churn. deps/verifiers stays pinned at 8d52bc8e.

* chore: pin verifiers floor to dev357, drop compact env + narrating comments

- verifiers floor -> >=0.1.15.dev357 (latest dev on PyPI = current submodule pin):
  root dependency + override-dependencies, plus prime-rl-configs dependency
- drop the `compact` example env (envs extra + its [tool.uv.sources] entry)
- remove edit-narrating comments (transitive-deps note, envs-list description)

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

* chore: keep renderers/prime-pydantic-config sources below verifiers (match main order)

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

* revert: drop merged gc.collect() in orchestrator trim_process_memory (nano uses malloc_trim only)

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

* chore: unquote forward-ref type annotations + small cleanups

- replace string-literal type annotations with real types via
  `from __future__ import annotations` (+ existing TYPE_CHECKING imports):
  Rollout in orchestrator/filters.py and utils/monitor/{base,multi,prime,wandb}.py,
  EventLoopLagStats in utils/async_utils.py; drop the now-unneeded F821 noqa
- prime monitor: rollout.task/timing.model_dump_json() instead of
  json.dumps(...model_dump(mode="json")) (single Rust-backed serialization)
- drop redundant comments (TrainingSample field comments, renderer passthrough)

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

* chore: drop EnvConfig docstring + redundant id/args fields

id and args are already on vf.EnvServerConfig; prime-rl's bare redefinition of id was shadowing the base's _validate_env_id AfterValidator. Removing both restores inheritance (incl. id validation).

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

* feat(advantage): adopt main's per-env Linear advantage (adapted to vf.Trace)

This PR is only about vf-v1 integration; the RL advantage should match main, not
nano's Tokens/Turns efficiency shaping.

- config: LinearLengthPenaltyConfig (coef, gate_by_correctness) +
  DefaultAdvantageConfig(length_penalty, length_weighted_baseline); per-env
  TrainEnvConfig.advantage + top-level OrchestratorConfig.advantage default
- advantage.py: main's default_advantage_fn / setup_advantage_fn(config, max_seq_len),
  adapted to vf.Trace (r.reward / r.completion_len instead of dict access; Traces
  passed through assign_advantages, advantage written back onto each Trace)
- per-env wiring: TrainEnv.advantage_fn = setup_advantage_fn(config.advantage,
  max_seq_len); TrainEnvs(max_seq_len); train_sink does per-env
  assign_advantages(survivors, env.advantage_fn)
- tests: main's Linear / length-weighted / per-env / max_seq_len-threading
  advantage tests, adapted to nano's vf.Trace _make_rollout
- drop the now-unused get_tool_response_len (only served nano's Tokens advantage)

Verified: 486 unit tests pass; reverse-text-v1 RL smoke 3 clean steps end-to-end
through the per-env advantage path.

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

* chore(v1): relock flash-linear-attention to current HEAD

flash-linear-attention is an unpinned git source (tracks HEAD, as on
main); its HEAD moved e8e791f -> bd67d11, leaving the locked commit stale
so CI's `uv sync --all-extras --locked` re-resolves it and fails. Relock
to the current HEAD.

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

* fix(rl): address e2e review findings

- env-server: forward legacy extra_env_kwargs (rollout timeout / completion
  token budget / max_seq_len) for v0 envs on the rl.py path. The standalone
  env-server CLI dropped them, so legacy envs ran uncapped; the orchestrator
  _spawn path already passed them.
- envs: re-type the wire vf.Trace into Rollout via model_construct instead of
  a model_dump -> model_validate round-trip, avoiding a per-rollout copy of the
  node pixel_values / routed_experts tensors (the server already model_constructs).
- train_sink: keep a running token total for token-batched runs instead of
  re-summing the uncached Trace.total_tokens over the whole pending batch on
  every arrival.
- config: drop dead ClientConfig.timeout / connect_timeout (not wired into the
  v1 rollout clients).
- restore gc.collect() before malloc_trim in trim_process_memory; emit
  Trace.info in the prime-monitor parquet (both match main).

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

* chore(v1): bump verifiers submodule to main (b841e53a)

The v1 work merged into verifiers main; the prior pin 8d52bc8e is an ancestor
of main, so this is a clean fast-forward. verifiers is an editable path dep
with unchanged declared deps, so uv.lock is unchanged. Verified with the
reverse_text v1 debug run (reward 0.11 -> 0.77 over 20 steps, no errors).

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

* fix(rl): correct gibberish/repetition filter logprob alignment

GibberishFilter paired masked completion token_ids with logprobs from the
start of node.logprobs (misaligned on nodes mixing context + sampled tokens);
RepetitionFilter streaked over all logprobs including context. Both now zip
token_ids/logprobs/mask together and process only sampled (mask=True) tokens.

Also document the v1 integration's breaking config changes (env taskset/
harness shape, empty train.env default, num_workers->pool, required renderer,
client timeout removal) in CHANGELOG.md.

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

* fix(rl): require at least one training env at config time

TrainConfig.env defaulted to an empty list with no check (only eval envs were
validated non-empty), so a config with no [[orchestrator.train.env]] parsed
and only failed later in TrainSource during setup. Add a non-empty-env
validator (mirroring EvalConfig) and make OrchestratorConfig.train a required
field (no default), so the failure surfaces at parse / --dry-run.

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

* feat(v1): scaleswe -> rlm harness + router replay

Switch the scaleswe debug config to the rlm harness on prime sandboxes for
both train (scaleswe-v1) and eval (swebench-verified) envs, and enable router
replay (trainer.enable_router_replay + inference.enable_return_routed_experts,
mirroring configs/debug/r3.toml) to cut trainer/inference MoE routing mismatch
on the A3B model. Rename run/job to the -rlm variant and sync the prime
sandbox cleanup labels. Header comment corrected (prime, not modal).

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

* chore(v1): revert config-time train-env-required check (too broad)

The train-required validation (60e824247) broke ~18 config-propagation tests
in test_configs.py that construct OrchestratorConfig/RLConfig without a train
env, plus two checked-in configs that omit one (configs/debug/orch.toml,
examples/glm5_pd_disag/rl.toml). A config-level validator is the wrong place —
the codebase widely constructs train-less OrchestratorConfigs. Reverting to
green CI; a non-empty-train guard belongs at orchestrator setup (fail fast
before TrainSource) instead.

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

* chore(v1): bump verifiers to latest main + drop stale prime-env TODO

- Bump deps/verifiers b841e53a -> 7169d02d (latest verifiers main, clean
  fast-forward, ...#1838). Editable path dep with unchanged declared deps, so
  uv.lock is unchanged. Verified with reverse_text v1 (reward 0.13 -> 0.75 over
  10 steps, no errors).
- Remove the stale "no prime-env hub install" TODO from the orchestrator — it
  never loads environments (the env server imports them in its child process),
  so the note no longer applies.

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

* chore(v1): remove dead prime-env-install path

Namespaced legacy env auto-install was removed (the v1 env server loads envs
directly via serve_env), leaving dead code with no callers/readers: the
`env_install_prerelease` flags (OrchestratorConfig + EnvServerConfig), the
`install_env` helper, and `get_env_ids_to_install`. Drop them and the now-
orphaned `subprocess` / `EnvConfig`,`EvalEnvConfig` imports.

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

* chore(v1): drop in-process env-server spawn, require address

The orchestrator no longer spawns env servers in-process (the mp.Process +
os.dup2 fd-redirect path). It only attaches to a server at EnvConfig.address,
now mandatory at orchestrator runtime - Env.start errors if it's unset. The rl
launcher already spawns one env-server subprocess per env and assigns address,
so launcher-driven runs are unaffected; standalone `uv run orchestrator` must
now be paired with separately-launched env-server(s) and an explicit address
per env.

Removes _run_env_server, Env._spawn, Env/Envs.shutdown, _env_server_process,
and the now-dead mp/os/queue/sys/atexit imports + ENV_SERVER_SPAWN_TIMEOUT.
Updates the standalone-orchestrator docs (training.md, scaling.md --bench) and
the CHANGELOG.

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

* chore(v1): bump verifiers pin (dashboard per-rollout timer includes setup)

51701f4c (#1846).

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

* Revert "chore(v1): drop in-process env-server spawn, require address"

This reverts commit d77546155.

Restore the in-process env-server spawn (orchestrator sidecar-spawns when
address is unset) to mirror main for now. The address-required / attach-only
cleanup is deferred - revisit later.

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

* chore(v1): orchestrator always spawns env servers in-process (mirror main)

Drop the launcher's env-server management: setup_env_servers (which
pre-assigned each env an address + spawned an env-server subprocess), the
per-env subprocess spawn loop in rl_local, the ENV_SERVER_KIND_STRIDE constant,
and the env_server_base_port config field. With no address pre-assigned, the
orchestrator spawns its own v1 EnvServer in-process per env (Env._spawn),
exactly as on main. The env-server CLI and EnvConfig.address are kept for the
optional user-managed external-server path.

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

* fix(trainer): contiguous routed_experts slice for glm4_moe under compile (#2860)

Router replay passes routed_experts[:, :, layer_idx, :] (a strided view of
[tokens, layers, topk], dim-1 stride = layers*topk) into the MoE forward. Under
torch.compile the inductor kernel asserts a contiguous input, so it crashed with
`assert_size_stride ... stride 8==368` on GLM-4.5-Air. Make the slice contiguous.

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

* chore(v1): bump verifiers pin (robust _ENSURE_UV for old base images)

7c347f61 (#1848).

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: rasdani <73563550+rasdani@users.noreply.github.com>
Co-authored-by: Codex <codex@primeintellect.ai>
2026-06-23 18:04:57 -07:00
38494ccb41 fix: sync uv.lock to v0.6.0 (#2858)
Tag and Release / auto-tag-on-main (push) Canceled after 0s
Tag and Release / release-from-auto-tag (push) Canceled after 0s
Tag and Release / tag-and-release (push) Canceled after 0s
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The release bump (#2855) updated pyproject.toml but not uv.lock, so
`uv sync --locked` fails on main (CPU Tests, Docker Push).

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:52:13 -07:00
375d8596d8 chore: release v0.6.0 (#2855)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:00:59 -07:00
e035135126 feat: llm-d (EPP+Envoy) router backend (#2697)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* refactor: drop client-side DP-rank pinning for external-LB

With external-LB data parallelism each DP rank is its own API server on its
own port (the URL is the rank selector), so the client no longer needs the
hybrid-LB `X-data-parallel-rank` header to pin a rollout to an internal DP
shard. Remove the `dp_rank_count` client field + its auto-setup and the
per-rank client expansion: one client per base URL, no rank header. The
router (vllm-router or llm-d EPP) balances across the per-rank endpoints.

This also fixes llm-d routing: the EPP forwards the header to the dp=1
backend, which rejected it ("data_parallel_rank N is out of range").

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

* feat: llm-d (EPP+Envoy) router backend

Add llm-d as a second router backend alongside vllm-router, selected via
`[inference.deployment.router] type = "llm-d"`. Built on the external-LB
launch substrate — the per-rank vLLM engines launch identically; only the
router control plane differs.

- `LlmdRouterConfig`: discriminated-union member with `scorers` (base) +
  per-profile `prefill_scorer_overrides`/`decode_scorer_overrides`,
  `non_cached_tokens`, `decode_sidecar_port`, and a known-scorer validator.
- `launch_router` helper gains an llm-d branch: renders per-replica EPP +
  Envoy + file-discovery endpoints and launches `epp` + `envoy` instead of
  vllm-router. Call sites stay router-agnostic.
- pd-sidecar on each decode node (P/D) for remote-prefill orchestration + NIXL.
- Entrypoints pass the `router` config object to the templates.
- Reject `enable_return_routed_experts` with llm-d (breaks P/D, unverified
  for multi-node).
- SLURM cleanup also clears stale `epp`/`envoy`/`pd-sidecar` processes.
- Presets under `templates/llmd/` + `scripts/install_llmd.sh`; docs + install skill.

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

* fix(inference): mooncake-store + llm-d EPP coexistence on SLURM P/D

- per-rank VLLM_RPC_BASE_PATH: external-LB runs one engine per process (all
  data_parallel_rank_local 0), so the mooncake-store lookup ipc socket collided
  on a node-shared dir; key it by $port. Also avoids an absent submit-node TMPDIR.
- EPP --grpc-health-port 9003 -> 9013: 9003 collided with mooncake_master's
  metrics server on the shared replica-head node, which killed the EPP.
- mooncake_master -default_kv_lease_ttl=3600000: KV blocks were expiring (5s
  default) before the decode side reused them.
- envoy circuit_breakers raised to 100000 on backend + epp clusters: the default
  (~1024) overflowed at high inflight concurrency -> "reset reason: overflow" 500s.
- pd-sidecar launches on every decode node (not just the replica head), else
  decode nodes past the head advertise endpoints nothing serves.

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

* Feat: dockerless llmd install

* chore(configs): add GLM-5.1 llm-d disaggregated RL config

End-to-end RL config used for the GLM-5.1-FP8 llm-d (EPP+Envoy) P/D run:
12 train nodes + 16 inference nodes (8 prefill x2 / 8 decode x2), mooncake KV
store, r2e env. Lives alongside the existing glm5 disaggregated inference preset.

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

* chore(configs): move GLM-5.1 llm-d RL config to dedicated configs/glm5_llmd/

Relocate the end-to-end GLM-5.1-FP8 llm-d (EPP+Envoy) P/D RL config into its own
configs/glm5_llmd/rl.toml (out of glm5_disagg_inference) and refresh it to the
latest tuned version.

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

* feat(inference): per-role prefill/decode vLLM overrides for disaggregated P/D

Add `prefill_vllm_overrides` / `decode_vllm_overrides` to the disaggregated
inference deployment config (mirrors the existing `*_env_overrides`): extra
vLLM config options merged into the per-role `--vllm-extra` JSON for prefill
vs decode ranks on SLURM. Rendered via a small `vllm_overrides_fragment` helper
into the `ROLE_EXTRA` string in the inference / multi-node-RL sbatch templates.

Needed by configs/glm5_llmd/rl.toml (sets `decode_vllm_overrides`), which
otherwise fails `extra="forbid"` validation in test_load_configs.

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

* chore(configs): enable prefill dual-batch-overlap in glm5_llmd config

Set prefill_vllm_overrides = {enable_dbo = true} (the inference-side perf knob
tuned during the GLM-5.1 run). Batch size / num-concurrent / node-scale knobs
left as-is — those are run-specific, not portable config.

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

* chore(configs): tune glm5_llmd prefill/decode replicas (4 prefill / 1 decode)

num_prefill_replicas 2->4, num_decode_replicas 2->1 — the disaggregation split
found to perform best for GLM-5.1 (prefill is the bottleneck; one wide decode
replica maximizes decode KV/batching).

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

* docs: add GLM-5 llm-d example (16-node / 131K trainer) (#2854)

* docs: add GLM-5 llm-d example (16-node / 131K trainer)

Move the glm5_llmd config from configs/ into examples/glm5_llmd/ with a
README, mirroring the other GLM-5 example. Frame llm-d as the faster
router for GLM-5 and document the placeholders users must tweak
(output_dir, slurm partition, mooncake device_name).

Tune the example for a 16-node trainer: seq_len=131072, num_train_nodes=16,
cp=4, and adamw optimizer.

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

* docs: reword GLM-5 llm-d example entry as one-line SLURM deploy

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

* docs: highlight GLM-5 llm-d one-line SLURM deploy in Overview

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

---------

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

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-06-22 16:08:07 -07:00
533e992ad2 fix(inference): tolerate KV-transfer finish for already-freed (aborted) reqs (#2843)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(inference): tolerate KV-transfer finish for already-freed (aborted) reqs

In disaggregated P/D (NIXL, optionally + a KV store), a request can be finished
— most often FINISHED_ABORTED from an off-policy cancel, client disconnect, or
request timeout — while it still has in-flight KV transfers. When such a
request's finished_recving and finished_sending both arrive in the same
Scheduler.update_from_output step, the stock
Scheduler._update_from_kv_xfer_finished frees it in the recving branch
(_free_blocks -> del self.requests[req_id]) and then the sending branch hits
`assert req_id in self.requests`, killing the EngineCore. On a DP deployment
that one death cascades to every rank via the gloo finish-state all-reduce and
takes down the whole decode pool.

Observed on two llm-d P/D runs: the genuine crash is always one rank asserting
in _update_from_kv_xfer_finished, the rest are gloo "Connection closed by peer"
cascade victims. It is abort-triggered, not pause/resume-related: it reproduced
during normal stepping (~19k log lines after the last resume, engine actively
running model batches) and on a run with max_off_policy_steps=80000 / zero
off-policy cancellations — driven purely by incidental client-side aborts.

Monkey-patch _update_from_kv_xfer_finished to skip request ids no longer in
self.requests instead of asserting. Their blocks are already freed, so dropping
the stale notification is safe. Installed via the vllm.general_plugins entry
point so it applies in the EngineCore process where the Scheduler runs.

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

* docs: link upstream vLLM issue #46240 in the KV-xfer patch

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

---------

Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 16:05:22 -07:00
858207d340 add glm 5.2 training support (#2851)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* add glm 5.2 training support

* simplify

* chore: revert accidental research-environments submodule bump

The "add glm 5.2 training support" commit unintentionally moved the
deps/research-environments submodule pointer. Restore it to main's SHA.

---------

Co-authored-by: faresobeid <fares@primeintellect.ai>
2026-06-22 15:33:01 -07:00
minh hoangandGitHub 570463cca2 chore(renderers): bump to submodule to renderers-v0.1.8.dev49 (#2852)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-22 12:28:27 -07:00
JannikStandGitHub 31e81e5b18 feat: support PRIME_RL_REF for runtime source override (#2850)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: support PRIME_RL_REF for runtime source override

Mirrors the existing VERIFIERS_VERSION hook so researchers can dispatch
a run against an arbitrary prime-rl commit/branch/tag without rebuilding
the image. Clones into a per-ref dir under /tmp, seeds the venv from
/app/.venv so heavy wheels (flash-attn, mamba-ssm) survive, then
uv sync --inexact re-installs prime_rl from the override source.

* fix: address bugbot findings on PRIME_RL_REF entrypoint

- Slugify ref for cache dir name so branch names with slashes work.
- Always fetch + checkout on cache hit so mutable refs (branches/tags)
  pick up new commits between pod restarts.
- Move VERIFIERS_VERSION install after the PRIME_RL_REF swap so when
  both are set the install lands in the override venv.

* fix: init submodules and hash-key the override cache dir

- git clone --recurse-submodules so deps/* (verifiers, renderers,
  research-environments, pydantic-config) are populated on cold
  checkout, and refresh on every entrypoint via
  'git submodule update --init --recursive'.
- Rewrite git@github.com SSH URLs to https at runtime so the SSH
  submodule URLs work from pods that have no ssh keys.
- Append md5 hash of the ref to the cache dir name so distinct refs
  that slugify the same way ('feat/foo' vs 'feat-foo') get distinct
  cache dirs.

* fix: drop hardlink seed and key cache on repo+ref

- cp -al hardlinked /app/.venv into the override tree, so the
  subsequent uv sync wrote through to the baked venv on filesystems
  shared with /tmp. Plain cp -a always copies.
- Include PRIME_RL_REPO in the cache-dir hash so the same ref on
  different forks gets distinct cache dirs.

* fix: --all-extras on override sync

uv sync --inexact --no-dev only installed base deps, so env / gpt-oss /
modelexpress changes in the override branch were silently missed. With
--all-extras the override picks them up, and --inexact still keeps
flash-attn-3 / mamba-ssm from the seeded venv.

* fix: mirror image extras explicitly instead of --all-extras

--all-extras pulled in disagg/quack which the baked image does not
ship; their deps (deep-ep, deep-gemm, quack-kernels) would trigger
heavy source builds at pod startup. Mirror Dockerfile.cuda:82's set
exactly so the override venv lines up with the image.

* fix: submodule sync before update to pick up .gitmodules URL changes
2026-06-22 12:15:37 -07:00
samsjaandGitHub 137f8f49c8 [codex] trim orchestrator memory after train steps (#2837)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(orchestrator): trim process memory each train step

* fix(orchestrator): collect garbage before memory trim
2026-06-22 12:13:26 -07:00
Maxwill LinandGitHub f04c8d988c fix(vlm): dispatch Gemma 4 as a VLM and read softcapping from the text config (#2844)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-22 02:23:13 +02:00
4d361adacc fix(orchestrator): drain off-policy rollouts before pausing for weight update (#2841)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The off-policy drain (cancelling rollouts past max_off_policy_steps) ran via
on_new_version *after* the inference engines resumed from the weight-update
pause. In a NIXL P/D deployment this reliably crashed the decode engines.

Aborting a rollout cancels its /generate request; vLLM marks the request
FINISHED_ABORTED and frees it, recording it in the NIXL connector's
_reqs_not_processed set so the worker suppresses its in-flight KV-transfer
completion. That suppression only propagates to the workers while the engine is
stepping. Pausing with mode="keep" (PAUSED_ALL) skips step(), so KV transfers
that complete during the pause are flushed on the first step after resume — at
the same moment the drain fires its aborts. The abort frees the request before
its suppression reaches the worker, so the flushed completion hits
`assert req_id in self.requests` in the decode scheduler's
_update_from_kv_xfer_finished, killing the engine and cascading to every DP
rank via the gloo finish-state all-reduce.

With max_off_policy_steps=8 the first mass drop lands at the 9th weight update,
which is why the run always died at step 8/9.

Move the drain to a new on_version_pending observer hook that the watcher calls
*before* update_weights (before the pause), so the aborts are processed under
normal stepping and the connector's native cleanup completes before the engine
freezes. on_new_version still runs post-update for the orchestrator's dispatch
gate, which needs the live policy version.

Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 20:04:08 -07:00
faresobeidandGitHub 7f77713886 update length penalty and add back length weighted baseline (#2702)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-19 02:09:32 +02:00
samsjaandGitHub efeddae6bb add rlm uuid ctf env (#2832)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-18 16:00:38 -07:00
8dfe8734e3 Fix routed SLURM inference DP rank client config (#2830)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Codex <codex@primeintellect.ai>
2026-06-18 01:29:48 +02:00
faresobeidandGitHub fa21395a68 improve sequence packing (#2723)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* improve sequence packing

* ruff

* clean tests

* add config

* make balancy by flops non-optinal

* fix

* refactor

* merge utils

* remove bin_cost option

* fix

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
2026-06-15 03:00:33 +01:00
samsjaandGitHub b5daec1cbb Clear inference slurm logs on launch (#2814)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-14 14:12:07 -07:00
b452660025 fix(inference): strip routed_experts from chat-completions responses (#2813)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(inference): strip routed_experts from chat-completions responses

routed_experts are consumed only via the serialized /generate (serving_tokens)
path used for router-replay training, which emits them as a {data, shape, start}
object the PD router merges. The stock chat-completions path encodes them as a
base64 np.save string instead, which the PD router rejects ("prefill routed_experts
must be an object with base64 data and shape") — failing every eval rollout, since
evals go through chat completions. enable_return_routed_experts is a server-wide
model-config flag with no per-request toggle, so strip the field on the chat path.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: format routed experts chat patch

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 13:09:08 -07:00
060f25bb3a feat(deployment): optionally run orchestrator on an inference node (#2811)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Adds MultiNodeDeploymentConfig.orchestrator_on_inference (default False). When
False, the orchestrator launches on trainer rank 0 (unchanged behavior). When
True, it launches on the last inference node (a decode node) instead — useful
when trainer nodes are host-RAM-saturated (large CPU-offloaded optimizer state)
and the orchestrator's rollout buffer + env workers would otherwise exhaust
memory there; inference nodes keep weights/KV on GPU with ample free host RAM.

The orchestrator launch is now a single top-level block in multi_node_rl.sbatch.j2
gated on a flag-selected SLURM_PROCID (NUM_INFER_NODES for trainer rank 0, or
NUM_INFER_NODES-1 for the last inference node), so both placements share one code
path. No effect when num_infer_nodes == 0.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 11:51:39 -07:00
faresobeidGitHubfaresobeidcopilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
77af037537 IPO config (#2798)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* IPO config

* fix: apply Ruff formatting in RL loss module

---------

Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-06-14 17:41:42 +01:00
samsjaandGitHub 9281c5589a add nixl to gigitngore (#2805)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-13 16:25:11 -07:00
9dbb523933 fix: raise vLLM DP coordinator startup timeout (hard-coded 30s) (#2804)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The coordinator child spawns on the DP-rank-0 API server while every
engine-core rank on the node is importing and loading weights, so its
spawn-time re-import can exceed 30s under that CPU/IO contention (seen
on multi-node disaggregated GLM-5.1 launches). Patch _wait_for_zmq_addrs
with a configurable timeout via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT
(default 300s).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-13 16:23:08 -07:00
5789850d4d fix(trainer): freeze DSA sparse indexer so checkpoint resume doesn't crash-loop (#2800)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The DSA sparse-attention indexer runs its forward under torch.no_grad(), so its
params (wq_b, wk, k_norm, weights_proj) never receive a gradient. They were left
with requires_grad=True and handed to AdamW, which lazily creates per-param state
only on the first step where a grad exists -- so the indexer params stayed
stateless.

This breaks strict checkpoint resume. At save time DCP's _init_optim_state
returns early (optim.state already non-empty), so the stateless indexer params
are omitted from the saved optimizer state. At load time the optimizer is fresh,
so _init_optim_state runs a zero-grad step over every requires_grad param and
materializes exp_avg/exp_avg_sq/step for the indexer too. DCP then demands those
keys, the checkpoint doesn't have them, and load dies with:

    RuntimeError: Missing key in checkpoint state_dict:
        app.optimizers.state.model.layers.0.self_attn.indexer.wq_b.weight.step

With resume_step=-1 every restart re-picks the same checkpoint and crashes
identically -> crash-loop.

Fix:
- freeze_sparse_indexer(): set requires_grad=False on all Indexer params, called
  unconditionally in setup_model (no-op for non-DSA models). The indexer is never
  trainable anyway, so this only makes save/load state symmetric.
- _create_optimizer(): hand only trainable params to AdamW/SGD/SignSGD (Muon
  already filtered internally), so frozen params carry no optimizer state.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-13 23:46:59 +02:00
JannikStandGitHub 146fcd0136 fix(inference): restore usage block on /inference/v1/generate (#2784)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(inference): restore usage block on /inference/v1/generate response

* fix(inference): apply ruff formatting

* fix(inference): drive _FinalOutputCapture through async-for, not __anext__

* fix(inference): always emit cached_tokens, drop enable_prompt_tokens_details gate

* chore: bump verifiers to fix/hatch-vcs-fallback-version

Pin to the fallback-version fix (PrimeIntellect-ai/verifiers#1650) so the
prime-rl Docker build resolves a version without VCS metadata. Temporary
pin to the PR branch; should move to verifiers main once #1650 lands.

* fix(inference): annotate _FinalOutputCapture source as AsyncIterable
2026-06-12 19:07:09 +02:00
samsjaandGitHub b0612a0e1f add rlm search (#2783)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* add rlm search

* bump dep
2026-06-11 21:25:18 -07:00
DominikandGitHub c0a026c0d4 Send Prime monitor display config to platform (#2709)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-12 02:27:05 +02:00
Jackmin801andGitHub 7c9c1308dc Register Nano V3 reasoning parser (#2767)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: register nano v3 reasoning parser

* chore: apply ruff formatting
2026-06-11 16:38:51 -07:00
941019f2e3 [feat] multiplex trainer token export and agg to prime monitor on orch side (#2641)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* multiplex trainer output

* update skill

* test: cover multi-run token exports

* feat: export token metrics from orchestrator

* refactor: store token export run fields on microbatch

* refactor: send microbatches without payload wrapper

* test: cover orchestrator token-export metric collection

Adds an integration test asserting the orchestrator's per-step read path
(collect_token_export_metrics) surfaces finite mismatch_kl/entropy mean/max
from real multi-run exports. Complements the file-writing coverage in
test_token_exports_are_run_local; reuses the existing fixture.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: defer token-export STABLE until run step fully consumed

A single orchestrator run_step can span multiple trainer steps when the
packer splits its samples across packs (token budget). mark_stable() ran
every trainer step and marked any dir touched that step, so the orchestrator
could read a run step's exports as complete from only the first pack's
sequences and advance its cursor, never aggregating the remainder.

Mark a run's export dir STABLE only once that run step is fully consumed —
gated on the same ready_to_update signal that drives its optimizer step.
Dirs for runs not yet ready carry over to a later trainer step. run_id=None
(single-run export) never spans trainer steps, so it is marked immediately.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat: stamp token-export metrics with their trainer step

Token exports lag the orchestrator step they're logged under (the trainer
runs behind), so on the default W&B step axis mismatch_kl/entropy appear
shifted right. Log the run step the exports actually belong to as
`trainer/step` so the metrics can be plotted against a lag-corrected axis.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor: fold token-export metrics into MetricsBuilder under trainer/

Move the token-export collection from the orchestrator mainline into
MetricsBuilder.build, which now owns the last-logged-step cursor (seeded from
the resumed step via start_step). Namespace the metrics under trainer/
(trainer/mismatch_kl/*, trainer/entropy/*) alongside trainer/step so they
group in W&B and can be plotted against a lag-corrected axis.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor: drop redundant max_step from token-export reader

Exports always lag the orchestrator (the current step's batch is shipped just
before metrics are built and trained afterward), so no stable export at or
beyond the current step can exist on disk. The `step <= max_step` filter was
always satisfied; the last_logged_step cursor alone drives correctness.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor: return log-ready dict from token-export reader

Drop the TokenExportMetricsResult dataclass that was unpacked into a dict one
line later. collect_next_token_export_metrics now returns the trainer/-prefixed
metrics (including trainer/step) directly, so the builder just updates the log
dict and reads trainer/step back to advance its cursor.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor: guard token-export log update under the truthiness check

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor: drop redundant run_idx guard in SinglePacker

The receiver always stamps batch.run_idx from used_idxs (a key of idx_2_id),
so the is-not-None/in-idx_2_id check was always true. Index directly, matching
MultiPacker.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor: mark token-export STABLE with a barrier instead of all_gather

The all_gather_object did barrier + dir-union + rank-0 write. Replace it with a
plain dist.barrier() (so STABLE only lands after every rank flushed its
rank_*.jsonl), then each rank touches STABLE for the dirs it wrote. touch is
idempotent, so ranks sharing a (run, step) dir converge harmlessly, and the
union is covered without shipping dir lists.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor: barrier at the call site, drop participate_in_stable_marking

The barrier lived inside the exporter, so the disabled variant needed a
participate_in_stable_marking flag to opt into it. Move the barrier to the
single train-loop call site, gated on token export being enabled (uniform
across ranks): every rank barriers together, then writers touch STABLE and
disabled ranks no-op. DisabledTokenExporter is a pure no-op again and the
exporter does no collectives.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor: drop dist.is_initialized guard before token-export barrier

train() always calls setup_torch_distributed before the training loop, so dist
is initialized by the time the barrier runs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore: drop redundant comments around token-export barrier

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor: derive token-export root from output_dir.parent

root_output_dir was just output_dir.parent of self.output_dir and used in one
place; drop the redundant attribute.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: skip malformed token-export records instead of aborting the step

Token-export metrics are best-effort monitoring read inside MetricsBuilder.build
every step. A malformed JSONL line or a loss_mask/value length mismatch raised
ValueError, which would abort the orchestrator step. Guard each record, skip and
count failures, and warn once per step dir; good records still aggregate.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat: drain trailing token-export metrics after max_steps

Token exports lag the orchestrator, so the last shipped steps are finalized by
the trainer after the main loop ends — and build() no longer runs to log them,
dropping the tail. Add an end-of-run drain that polls for the remaining stable
steps up to max_steps-1 and logs each under its own trainer/step (a local W&B
step axis, leaving progress.step for the final checkpoint untouched). Gated on
token export being on for the run; early-returns when build() already kept up;
bounded by a timeout. Shared collection extracted to
MetricsBuilder.next_token_export_metrics.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* make token export a top-level trainer flag

* chore: fold token export into multi-run integration config

* chore: revert multi-run trainer config override

* chore: remove token export unit tests

* docs: document token export config migration

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 15:05:10 -07:00
9e1f0521e3 fix(scripts): verify IB support in UCX build for NIXL (#2761)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
UCX's --with-verbs silently disables IB when the rdma-core dev headers
are missing, producing a TCP-only build that only fails much later at
runtime with NIXL_ERR_BACKEND. On hosts with RDMA devices, require the
headers before building and verify the rc_verbs transport made it into
the built UCX. Also pass --with-rdmacm so the rdmacm connection manager
is built when available.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 14:32:58 -07:00
e466d233e9 fix(slurm): portable GLOO/UCX NIC selection in sbatch templates (#2760)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
GLOO_SOCKET_IFNAME was hardcoded to bond0 and UCX_NET_DEVICES to all,
both of which break on clusters with different NIC naming or with RDMA
devices UCX cannot open (e.g. a non-functional Ethernet bond, which
fails NIXL backend creation with NIXL_ERR_BACKEND). Derive the gloo
interface from LOCAL_IP and enumerate RDMA ports from sysfs (ibv_devices
is not on the job PATH), preferring InfiniBand, falling back to RoCE,
and keeping "all" on hosts without RDMA devices.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 14:32:09 -07:00
9ea9fb193e fix(client): retry all admin ops with bounded timeouts (#2759)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
/resume and /update_weights previously had no retry and no per-attempt
timeout, so a transient failure or stuck server during a weight update
could leave engines paused indefinitely (the admin AsyncClient uses
timeout=None). Factor the /pause retry into a shared _admin_post helper
with a single default timeout, overridable per call; /update_weights
gets a longer one since the collective NCCL receive can take a while.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 14:29:47 -07:00
alelpoanandGitHub 91c86b7383 fix(docs): fix broken links (404) in overview and advanced pages (#2744)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-10 12:15:09 -07:00
alelpoanandGitHub d4b30bf3ae fix(docs): escape invalid MDX character in inference.md (#2740)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>
2026-06-10 12:14:33 -07:00
samsjaandGitHub d5ce4ce84d Update README.md (#2750)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* Update README.md

Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>

* Update README.md

Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>

---------

Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
2026-06-09 21:20:07 -07:00
samsjaandGitHub 04d067145f update deps (#2736)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* update deps

* update deps

* update deps
2026-06-09 19:31:19 -07:00
samsjaandGitHub 632ef2b318 chore: remove private configs submodule (#2741)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Remove the configs/private submodule (research-configs) and all
references to it throughout the codebase:

- Remove submodule from .gitmodules and git tracking
- Simplify install.sh: use plain git submodule update --init --recursive
  now that no private submodule can fail for users without access
- Update skills/install/SKILL.md to reflect simplified submodule init
- Remove configs/private/ entry from skills/configs/SKILL.md key files
- Simplify test_configs.py: no longer need to filter out private/ path
2026-06-09 19:31:08 -07:00
faresobeidandGitHub c8759c370a add router replay to latentMoE models (#2738)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-10 00:01:11 +01:00
Tim KostolanskyandGitHub 0695f9caa5 fix: allow sft without teacher (#2720)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-09 12:34:20 -07:00
halleriteandGitHub e0f8a35c78 feat(orchestrator): per-env advantage strategy (#2721)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-09 05:05:13 +02:00
faresobeidandGitHub 54012df504 orch improvements (#2725)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* orch improvements

* fixes
2026-06-09 01:48:12 +01:00
samsjaandGitHub 53b22b55c8 fix: add prime-pydantic-config as direct dep so uv uses editable path source (#2733)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The [tool.uv.sources] override for prime-pydantic-config was being ignored
because it was only a transitive dependency (via prime-rl-configs). uv only
applies source overrides for packages that appear in project.dependencies.
Adding it as a direct dependency makes uv resolve from the local editable
path (deps/pydantic-config) instead of PyPI.
2026-06-08 16:34:24 -07:00
minh hoangandGitHub c2a5fa466c chore(renderers): bump to submodule to renderers-v0.1.8.dev41 (#2732)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-08 15:16:58 -07:00
Matej SirovatkaandGitHub 90b074492e Feat: fix weight reload to cpu optim (#2729)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-08 17:58:23 +02:00
766e36f000 Feat/fp8 fused transpose cast (#2724)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(fp8): fuse transpose into the dX block-fp8 weight cast

The dX backward built `weight.transpose(0, 1).contiguous()` and re-cast it to
fp8 every step, materializing a full bf16 transpose buffer plus an extra
read/write pass. Add `per_block_cast_to_fp8_tp_triton`, which produces the
block-fp8 of `weight.T` directly by reusing the existing per-block kernel with
swapped output/scale strides — no intermediate buffer.

128x128 block quantization is transpose-symmetric, so the result is
bit-identical to casting the materialized transpose; DeepGEMM receives an
identical B tensor. Verified byte-for-byte across shapes; ~14x faster on a
4096x4096 weight (373 -> 27 us).

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

* deslopified

* also add fused implementation for per-token

* Fix: skip tests on <Hopper

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
2026-06-07 17:51:36 +02:00
209f76eb52 fix(install): support aarch64 hosts with any compute capability (#2587)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The aarch64 host install path was broken: `uv sync` installs flash-attn
from PyPI source but pyproject sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE,
so the compiled extension never builds. `scripts/docker-arm64-post-install.sh`
fixed it for Docker GB200 builds but hardcoded sm_100 and /app/.venv,
leaving Hopper hosts (H100/H200/GH200) without a recipe.

Changes:
- `scripts/docker-arm64-post-install.sh`: auto-detect compute capability
  via nvidia-smi when available; parameterize venv path. Preserves the
  sm_100 default when no GPU is visible (Docker buildx).
- `scripts/install.sh`: call the post-install for aarch64 hosts after
  `uv sync --all-extras`. Previously the script ran uv sync and exited,
  leaving aarch64 users with a broken venv.
- `README.md`: document the aarch64 post-install step (mirrors the
  existing 3.1 Flash Attention 3 pattern).

Validated on GH200 (sm_90, aarch64):
- forward + backward parity vs torch SDPA (max diff < 0.05 / 0.25)
- 383/384 unit tests pass (the 1 failure is unrelated TileLang/MoE)
- SFT trainer smoke test (5 steps, Qwen3-0.6B) runs with flash_attention_2

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-05 20:21:11 -07:00
127 changed files with 5125 additions and 4415 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}")
+3 -2
View File
@@ -23,7 +23,8 @@ configs/endpoints.py
final_summary.json
.pydantic_config
.chroma_db
deps/nixl_*
nixl_workspace/*
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
@@ -202,4 +203,4 @@ debug_I2_zero_band
outputs/
third_party/
third_party/
-3
View File
@@ -7,9 +7,6 @@
[submodule "research-environments"]
path = deps/research-environments
url = git@github.com:PrimeIntellect-ai/research-environments.git
[submodule "configs/private"]
path = configs/private
url = git@github.com:PrimeIntellect-ai/research-configs.git
[submodule "pydantic-config"]
path = deps/pydantic-config
url = https://github.com/PrimeIntellect-ai/pydantic-config
+8
View File
@@ -2,6 +2,14 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **verifiers v1 training integration** (collection of removals/renames). The orchestrator now trains against a v1 env server returning `vf.Trace` rollouts, renderer-only, with a unified token schema.
- **`[[orchestrator.train.env]]` is now a v1 `vf.EnvServerConfig`**: a v1 env is `taskset = { id = "<id>" }` + `harness = { id = "default", runtime = { type = "subprocess" } }`. A bare `id = "<id>"` (optionally with `args`) runs the v0 env through the verifiers legacy bridge — old flat `id`/`args`-only configs keep working as legacy envs; v1 envs must use the `taskset`/`harness` shape.
- **`orchestrator.train.env` no longer defaults to a `reverse-text` env**: the default is now empty (`[]`), so configs must declare `[[orchestrator.train.env]]` explicitly.
- **`...env[].num_workers` → `pool`**: per-env worker sizing moves to a `pool` config (`static`/`elastic`). Back-compat: `num_workers = N` maps to `pool = { type = "static", num_workers = N }` and `"auto"` to the default elastic pool; the group-level `orchestrator.train.num_workers` / `orchestrator.eval.num_workers` are removed.
- **`orchestrator.renderer` is now required (MITO removed)**: it was `RendererConfig | None`, where `renderer = None` selected the MITO path; training is now renderer-only, so `renderer` is non-optional. Drop `renderer = None` / `renderer = "None"`.
- **`...client.timeout` / `...client.connect_timeout` removed**: the v1 rollout client manages its own timeouts. Drop these from `[orchestrator.student.client]` and `[orchestrator.teacher.client]`. (2026-06-23)
- **`orchestrator.advantage` length-penalty overhaul + length-weighted baseline**: `length_penalty` is now a single shape — a linear penalty that subtracts `coef * pass_rate * (model completion tokens / orchestrator.seq_len)` from each reward before the baseline subtraction (`pass_rate` = group mean reward, so solved-often problems get the strongest concision pressure and never-solved groups get none), with an optional `gate_by_correctness` flag (default `false`) that restricts the penalty to correct rollouts (`reward == 1`). The previous discriminated `type = "tokens" | "turns"` efficiency-shaping variants and the per-penalty `max_length` field have been removed — configure `[orchestrator.advantage.length_penalty]` with `coef` (and optionally `gate_by_correctness`) instead; the denominator is always `orchestrator.seq_len`. Also adds `orchestrator.advantage.length_weighted_baseline` (default `false`): when enabled, the GRPO baseline is the token-length-weighted mean reward (`sum(len_i * reward_i) / sum(len_i)`) instead of the plain mean. (2026-06-03)
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
+1
View File
@@ -97,6 +97,7 @@ RUN apt-get update && apt-get install -y \
tmux \
iperf \
openssh-server \
git \
git-lfs \
gpg \
sudo \
+13 -2
View File
@@ -38,6 +38,7 @@ PRIME-RL is a framework for large-scale reinforcement learning. It is designed t
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
7. Hackable, modular, and extensible by design.
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/glm5_llmd/README.md).
## Models support
@@ -55,10 +56,10 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#vision-language-models) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ❌ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
| GLM-4 · GLM-4.5 MoE · INTELLECT-3 (`glm4_moe`) | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5-Air`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | yes | ✅ | ✅ |
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ❌ | ✅ |
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ✅ | ✅ |
| Other HF causal LMs | Qwen3 dense, Mistral, … (`impl = "hf"`) | varies | ❌ | ✅ |
@@ -110,6 +111,15 @@ source $HOME/.local/bin/env
uv sync --all-extras
```
4.1. On aarch64 hosts: build flash-attn from source for your GPU
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`.
```bash
bash scripts/docker-arm64-post-install.sh
```
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
@@ -212,6 +222,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
3. [**Intellect-3.1**](examples/Intellect-3.1/README.md): Reproduce our `INTELLECT-3.1` training run.
4. [**MiniMax-M2.5 SWE**](examples/minimax_m2.5_swe/README.md): Train `MiniMax-M2.5` on agentic SWE tasks.
5. [**High-throughput GLM-5**](examples/glm5_pd_disag/README.md): Train `GLM-5` with PD disaggregation and FP8 inference on SWE.
6. [**High-throughput GLM-5 (llm-d)**](examples/glm5_llmd/README.md): One-line SLURM deployment for `GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload — the faster way to run `GLM-5`.
## Docs
@@ -1,5 +1,6 @@
# Trainer config for multi-run RL integration test
max_concurrent_runs = 2
enable_token_export = true
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -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
Submodule configs/private deleted from 70c3503e1d
+1 -3
View File
@@ -60,7 +60,6 @@ temperature = 1.0
[[orchestrator.train.env]]
id = "rlm_swe"
name = "rlm-swe-r2e"
num_workers = 4
[orchestrator.train.env.args]
labels = ["rlm-swe-qwen35-4b"]
@@ -73,8 +72,7 @@ interval = 20
[[orchestrator.eval.env]]
id = "rlm_swe"
name = "rlm-swe-swebench-verified-quick"
num_workers = 4
timeout = 3600
timeout = { rollout = 3600 }
[orchestrator.eval.env.args]
task_type = "swebench"
+41
View File
@@ -0,0 +1,41 @@
# Wordle (classic v0 TextArena env) on 2 GPUs (1 trainer + 1 inference), run via the
# legacy bridge. The Wordle-SFT model plays a full ~6-turn game per rollout; the bridge
# serves each multi-turn rollout to the orchestrator as a vf.Trace.
max_steps = 200
seq_len = 8192
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[wandb]
project = "wordle"
name = "wordle"
[ckpt] # Checkpoint at the end of training
[model]
name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 128
group_size = 8
[[orchestrator.train.env]]
id = "primeintellect/wordle"
name = "wordle"
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer] # Default trainer config
[inference] # single inference GPU (no data parallelism)
# Qwen3 finetune with the standard PI template patch (byte-identical to
# PrimeIntellect/Qwen3-0.6B base); always re-emits prior <think> blocks.
# Match that with the qwen3 renderer's preserve_all_thinking.
[orchestrator.renderer]
name = "qwen3"
preserve_all_thinking = true
+1 -1
+1 -1
+4 -2
View File
@@ -25,7 +25,7 @@ impl = "custom" # or "hf" to force the HF path
| Family | HF config types | EP | CP |
|---|---|---|---|
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | ✅ | ✅ |
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
@@ -38,6 +38,8 @@ impl = "custom" # or "hf" to force the HF path
The custom path enables you to set EP, CP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
### Expert Parallelism Backends
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
@@ -115,7 +117,7 @@ LoRA pairs naturally with [multi-tenant training](#multi-tenant-training) — ea
## Multi-Tenant Training
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/src/prime_rl/trainer/runs).
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/src/prime_rl/trainer/runs.py).
## Disaggregated Prefill/Decode Inference
+29 -3
View File
@@ -136,10 +136,20 @@ The default advantage is per-group reward minus per-group baseline (DR-GRPO with
This is intentionally simple — it does the right thing for most envs. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
Two built-in **length penalties** can be layered on top of any advantage to discourage rambling:
A **length penalty** can be layered on top of the default advantage to discourage rambling. Configured under `[orchestrator.advantage.length_penalty]`, it subtracts a `coef * pass_rate * (completion tokens / orchestrator.seq_len)` term from every reward before the baseline subtraction, where `pass_rate` is the problem's mean reward across the group. The pass-rate factor means problems the model already solves reliably get the strongest push toward concise outputs, while rarely-solved problems are barely penalized (a never-solved group, mean reward 0, gets none). Set `gate_by_correctness = true` to apply the penalty only to correct rollouts (`reward == 1`), leaving incorrect ones untouched:
- `[orchestrator.length_penalty] type = "tokens"` — penalizes long completions in tokens, with configurable target and slope.
- `[orchestrator.length_penalty] type = "turns"` — penalizes long multi-turn rollouts by turn count.
```toml
[orchestrator.advantage.length_penalty]
coef = 0.25 # effective penalty is coef * pass_rate * (completion_tokens / seq_len)
gate_by_correctness = false # when true, only penalize rollouts with reward == 1
```
By default the baseline is the plain group mean reward. Set `length_weighted_baseline = true` to instead use the token-length-weighted mean — `sum(len_i * reward_i) / sum(len_i)` — which centers advantages by per-token expected reward when rollouts vary a lot in length:
```toml
[orchestrator.advantage]
length_weighted_baseline = true
```
### Custom Advantage
@@ -167,6 +177,22 @@ kwargs = { eps = 1e-8 }
`AdvantageInputs.rollouts` is a list of `verifiers.RolloutOutput`, so you have access to the full rollout (turns, tool calls, custom metadata) — not just the reward. Use this for anything reward-shaping-like that needs trajectory context.
### Per-Env Advantage
`advantage` can be set per training environment. Each env inherits the top-level `[orchestrator.advantage]` when it doesn't set its own, so mixed-env runs can give each env its own advantage computation:
```toml
[orchestrator.advantage]
type = "default" # the default every env inherits unless it overrides
[[orchestrator.train.env]]
id = "math-env" # inherits the default above
[[orchestrator.train.env]]
id = "agent-env"
advantage = { type = "custom", import_path = "my_module.normalized_advantage" }
```
## Filters
Filters drop rollouts between scoring and training. Built-ins (composable):
+1 -1
View File
@@ -2,7 +2,7 @@
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `token_export` flag) that aren't surfaced here.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
## Table of Contents
+18 -5
View File
@@ -30,7 +30,7 @@ We support 3 distinct deployment shapes:
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `router_port`, `backend_port`, etc.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `backend_port`, and a `[...deployment.router]` block, etc.
```toml
[inference.deployment]
@@ -102,7 +102,7 @@ tp = 2
dp = 4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing will be handled by the `vllm-router` instance running on the same node as the 1st replica. We aim to support more advanced routing options, such as `llm-d` or `dynamo` in the future. You can read more about the supported routing options in the [router](#router) section.
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a router instance running on the same node as the 1st replica — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[...deployment.router]` block. You can read more about the supported routing options in the [router](#router) section.
### Wide-EP
@@ -167,9 +167,22 @@ This will run 3 inference replicas, each running on 6 nodes. Each replica will r
## Router
We use our own fork of [vllm-router](https://github.com/PrimeIntellect-ai/router) as the request handler. We plan to support more advanced proxy options in the future.
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
Right now, router handles 2 most important things:
```toml
[inference.deployment.router] # or [deployment.router] for the standalone inference entrypoint
type = "llm-d" # "vllm-router" (default) or "llm-d"
# llm-d-only knobs (all optional):
scorers = { "prefix-cache-scorer" = 3.0, "active-request-scorer" = 2.0 } # base, applied to every profile
prefill_scorer_overrides = { "queue-scorer" = 2.0, "kv-cache-utilization-scorer" = 2.0 } # merged onto the P/D prefill profile
decode_scorer_overrides = {} # merged onto the P/D decode profile
non_cached_tokens = 16 # below this many non-cached prompt tokens, skip remote prefill (P/D)
```
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy. Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
Both backends support the 2 most important things:
- Request routing - KV cache re-use and balanced routing
- P/D disaggregation - handling the prefill and decode stages separately
@@ -252,7 +265,7 @@ headless = true
### Router Replay
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer<->inference mismatch by an order of magnitude, resulting in more stable training.
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.enable_return_routed_experts = true`.
+1 -1
View File
@@ -10,7 +10,7 @@ A `prime-rl` RL run is three cooperating processes:
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). We are trying to stay up-to-date with the latest vLLM features, you can read more about the supported features and deployment options in the dedicated [inference documentation](inference.md).
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [trainer documentation](trainer.md).
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses the filesystem (or NCCL for synchronous setups). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
+87
View File
@@ -0,0 +1,87 @@
# High-throughput GLM-5 with llm-d
This example trains `GLM-5.1` with RL on agentic SWE tasks using P/D disaggregation, FP8 inference, and a Mooncake distributed CPU KV store — fronted by the upstream [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy).
**llm-d is the faster way to run GLM-5.** It is the recommended router backend for large GLM-5 runs: its `active-request-scorer` is an in-flight load balancer that spreads requests across ranks immediately, instead of relying on metrics that are scraped on a delay (as the default `vllm-router` does). Combined with prefix-cache affinity for grouped rollouts, this keeps prefill and decode ranks evenly loaded under the bursty request pattern of RL. If you want the simpler default router instead, see the [GLM-5 PD disaggregation example](../glm5_pd_disag/README.md).
## Requirements
You need access to a Slurm cluster with at least **32 nodes** (16 trainer + 16 inference, 8 GPUs each) and a shared filesystem. In this guide we assume the NFS is mounted at `/shared`; you can change it to your own path.
You also need prime-rl cloned on your cluster into the shared filesystem.
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
```
### Install llm-d
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
```bash
bash scripts/install_llmd.sh
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
```bash
touch .env
echo "WANDB_API_KEY=your_wandb_api_key" >> .env
echo "HUGGINGFACE_TOKEN=your_huggingface_token" >> .env
```
### sandbox
The SWE environment is configured to use Prime Intellect Sandboxes. You can find more information about the sandboxes [here](https://docs.primeintellect.ai/sandboxes/overview). You will need to create a sandbox account and add the credentials to the `.env` file. Alternatively, you can adapt the code of the environment to use your own sandbox implementation.
## Tweak before launching
This config is tuned for our cluster — a few values **must** be adapted to yours before you run. Search the config for these markers:
- **`output_dir`** (`# FILL IN`) — point it at your shared filesystem.
- **`[slurm] partition`** (`# FILL IN`) — set it to your cluster's Slurm partition.
- **`[inference.kv_cache_offload] device_name`** (`# do it yourself`) — the list of RDMA NICs for Mooncake. Auto-detection is unreliable, so set it by hand from `nvidia-smi topo -m` on your nodes.
A few more knobs you may want to tune for your hardware:
- **Trainer parallelism** — this config assumes **16 trainer nodes** at **131K** sequence length with `cp = 4` (context parallel) and the `adamw` optimizer. If you have fewer trainer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` accordingly.
- **Scorer weights** (`[inference.deployment.router]`) — the `scorers` / `prefill_scorer_overrides` / `decode_scorer_overrides` weights follow the upstream llm-d P/D guide and are a good starting point; tune them if your prefill/decode balance drifts.
- **Mooncake CPU pool** (`[inference.kv_cache_offload.cpu] num_bytes`) — defaults to 1TB/node; lower it if your nodes have less RAM.
## Tmux session
We recommend using the tmux helper to start the run and look at the logs.
From your Slurm head node:
```bash
bash scripts/tmux.sh glm5-llmd /shared/outputs/glm5-llmd
```
You can then attach to it by doing `tmux attach -t glm5-llmd`.
## Start the run
Run the following command to start the RL training:
PS: If using the tmux helper, you can run the command in the `Terminal` (window 0) pane and look at the logs in the `Logs` (window 1) pane.
```bash
uv run rl @ examples/glm5_llmd/rl.toml --output-dir /shared/outputs/glm5-llmd
```
Output of the command:
```
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/glm5-llmd/configs [rl.py::515]
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/glm5-llmd/rl.sbatch [rl.py::534]
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/glm5-llmd/rl.sbatch [rl.py::540]
XXX:XX:XX SUCCESS Submitted batch job YYYY
Logs:
Trainer: tail -F /shared/outputs/glm5-llmd/logs/trainer.log
Orchestrator: tail -F /shared/outputs/glm5-llmd/logs/orchestrator.log
Inference: tail -F /shared/outputs/glm5-llmd/logs/inference.log
Envs: tail -F /shared/outputs/glm5-llmd/logs/envs/*/*/*.log
```
+140
View File
@@ -0,0 +1,140 @@
max_steps = 10000000
seq_len = 131072
output_dir = "/shared/outputs/glm5-llmd" # FILL IN: point at your shared filesystem
clean_output_dir = true
[log]
level = "debug"
[wandb]
project = "glm5-llmd"
name = "base"
[weight_broadcast]
type = "nccl"
port = 29502
timeout = 12000
quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
num_train_nodes = 16
num_infer_nodes = 16
gpus_per_node = 8
num_infer_replicas = 1
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 8
num_prefill_replicas = 4
num_decode_nodes = 8
num_decode_replicas = 1
# skip warmup for faster start in cost of some jit overhead early
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_overrides = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
# gives the most KV cache while keeping decent throughput, KV cache increase comes in from lower deep-ep LL static buffers
prefill_vllm_overrides = {"enable_dbo"=true}
decode_vllm_overrides = {"max_num_batched_tokens"=96, "max_num_seqs"=96}
[inference.deployment.router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 } # need some prefix-cache routing, however due to shared mooncake pool do low prio
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 } # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 } # decode doesn't really create queue, it fills in KV cache fast, give 4.0
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[slurm]
job_name = "glm5-llmd"
partition = "all" # FILL IN: set to your cluster's partition
[trainer]
dist_timeout_seconds = 1800
enable_token_export = true
[trainer.model]
name = "zai-org/GLM-5.1"
impl = "custom"
attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
ep = 8
optim_cpu_offload = true
fp8 = true
[trainer.model.ac]
freq = 1
[trainer.model.compile]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.optim]
type = "adamw"
lr = 1e-6
weight_decay = 0.0
[orchestrator]
batch_size = 256
rollouts_per_example = 16
max_inflight_rollouts = 2048
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
[orchestrator.model]
name = "zai-org/GLM-5.1-FP8"
[orchestrator.renderer]
name = "glm-5.1"
preserve_all_thinking = true
[orchestrator.train.sampling]
temperature = 1.0
extra_body = {chat_template_kwargs = {clear_thinking = false}}
[[orchestrator.train.env]]
id = "rlm_swe"
name = "r2e"
num_workers = 16
[orchestrator.train.env.args]
max_turns = 300
timeout_seconds = 21600
summarize_at_tokens = [35000, 80000]
poll_interval = 5
rlm_ref = "907115a79b2a50d193863e7ea1f3550acb4386f0"
labels = ["glm5-llmd"]
[orchestrator.advantage]
type = "default"
[inference]
enable_expert_parallel = true
# <0.80 because glm5 layers are too large for 0.85
gpu_memory_utilization = 0.75
enable_eplb = false
use_deep_gemm = true
enable_fp32_lm_head = true
[inference.model]
name = "zai-org/GLM-5.1-FP8"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
# Speed up GLM-5.1 weight load: EP weight filtering + safetensors prefetch.
[inference.vllm_extra]
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
# Mooncake distributed CPU KV store: 1TB/node shared pool across all inference nodes.
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
+1
View File
@@ -10,6 +10,7 @@ dependencies = [
"renderers>=0.1.8.dev28",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.1.15.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
@@ -167,8 +167,26 @@ All2AllBackend = Literal[
]
# Known llm-d EPP scorer plugins (used to guard the ``scorers`` map against typos).
KNOWN_SCORERS = frozenset(
{
"prefix-cache-scorer",
"precise-prefix-cache-scorer",
"queue-scorer",
"kv-cache-utilization-scorer",
"active-request-scorer",
"load-aware-scorer",
"running-requests-size-scorer",
"token-load-scorer",
"latency-scorer",
"session-affinity-scorer",
"lora-affinity-scorer",
}
)
class VllmRouterConfig(BaseConfig):
"""PrimeIntellect vllm-router fronting the per-rank (external-LB) endpoints."""
"""PrimeIntellect vllm-router."""
type: Literal["vllm-router"] = "vllm-router"
@@ -179,9 +197,57 @@ class VllmRouterConfig(BaseConfig):
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
# Discriminated on ``type`` so additional router backends can be added to the
# union (a single member needs no discriminator yet).
RouterConfig: TypeAlias = VllmRouterConfig
class LlmdRouterConfig(BaseConfig):
"""llm-d router backend (EPP + Envoy)."""
type: Literal["llm-d"] = "llm-d"
port: int = 8000
"""Port the Envoy gateway listens on — becomes the client-facing router URL."""
scorers: dict[str, float] = {
"prefix-cache-scorer": 3.0,
"active-request-scorer": 2.0,
}
"""EPP scorer name → weight, applied to every routing profile (before the per-profile P/D overrides). Defaults to prefix-cache affinity plus in-flight (active-request) load balancing. Unknown scorer names are rejected."""
prefill_scorer_overrides: dict[str, float] = {
"queue-scorer": 2.0,
"kv-cache-utilization-scorer": 2.0,
}
"""P/D only: scorer → weight merged onto ``scorers`` for the prefill profile (a per-profile weight overrides the base)."""
decode_scorer_overrides: dict[str, float] = {}
"""P/D only: scorer → weight merged onto ``scorers`` for the decode profile (a per-profile weight overrides the base); empty by default."""
non_cached_tokens: int = 16
"""P/D only: requests with fewer than this many non-cached prompt tokens skip remote prefill and run decode-only."""
decode_sidecar_port: int = 8300
"""P/D only: port the decode-side llm-d sidecar listens on."""
@property
def prefill_scorers(self) -> dict[str, float]:
"""Effective prefill-profile scorers: ``scorers`` merged with ``prefill_scorer_overrides``."""
return {**self.scorers, **self.prefill_scorer_overrides}
@property
def decode_scorers(self) -> dict[str, float]:
"""Effective decode-profile scorers: ``scorers`` merged with ``decode_scorer_overrides``."""
return {**self.scorers, **self.decode_scorer_overrides}
@model_validator(mode="after")
def validate_scorers(self):
unknown = (
set(self.scorers) | set(self.prefill_scorer_overrides) | set(self.decode_scorer_overrides)
) - KNOWN_SCORERS
if unknown:
raise ValueError(f"Unknown llm-d scorer(s): {sorted(unknown)}. Known scorers: {sorted(KNOWN_SCORERS)}.")
return self
# Discriminated on ``type`` so the launch path can pick the router backend.
RouterConfig: TypeAlias = Annotated[VllmRouterConfig | LlmdRouterConfig, Field(discriminator="type")]
class BaseInferenceDeploymentConfig(BaseConfig):
@@ -240,6 +306,12 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
decode_env_overrides: dict[str, str] = {}
"""Extra environment variables exported only on decode nodes."""
prefill_vllm_overrides: dict[str, Any] = {}
"""Extra vLLM config options merged into --vllm-extra only for prefill ranks (SLURM only)."""
decode_vllm_overrides: dict[str, Any] = {}
"""Extra vLLM config options merged into --vllm-extra only for decode ranks (SLURM only)."""
@property
def num_nodes(self) -> int:
return self.num_prefill_nodes + self.num_decode_nodes
@@ -369,6 +441,18 @@ class InferenceConfig(BaseConfig):
raise ValueError("Must use SLURM for multi-node / disaggregated deployment.")
return self
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
router = getattr(self.deployment, "router", None)
if router is not None and router.type == "llm-d" and self.enable_return_routed_experts:
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(enable_return_routed_experts): it breaks P/D and is unverified for multi-node. "
"Use router type 'vllm-router' for routed-expert runs."
)
return self
@model_validator(mode="after")
def auto_setup_kv_cache_offload(self):
if self.kv_cache_offload is not None:
@@ -1,10 +1,9 @@
import math
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import AliasChoices, Field, model_serializer, model_validator
from pydantic_core.core_schema import SerializerFunctionWrapHandler
import verifiers.v1 as vf
from pydantic import AliasChoices, Field, model_validator
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.shared import (
@@ -143,24 +142,12 @@ class EvalSamplingConfig(BaseConfig):
return data
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."""
class EnvConfig(vf.EnvServerConfig):
name: str | None = None
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the ``id`` without ``@version``. Must be unique across all envs in the same group."""
args: dict = {}
"""Keyword arguments forwarded to ``vf.load_environment``. See the environment's docstring for accepted args."""
extra_env_kwargs: dict[str, Any] = {}
"""Extra kwargs passed to the env (e.g. ``seq_len``, ``max_total_completion_tokens``). Auto-populated by the orchestrator; user overrides are generally discouraged. The main use case is matching ``extra_env_kwargs`` when running an env in an isolated environment server."""
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
address: str | None = None
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically."""
num_workers: int | Literal["auto"] = "auto"
"""Worker processes for the spawned env server. ``auto`` scales to 1 worker per 256 concurrent rollouts. Ignored when ``address`` is set."""
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically. The ``pool`` sizes the spawned server."""
ratio: float | None = Field(None, gt=0)
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
@@ -168,26 +155,36 @@ class EnvConfig(BaseConfig):
max_retries: int = Field(3, ge=0)
"""Times the env server retries a failed rollout before returning an error."""
max_total_completion_tokens: int = -1
"""Maximum total completion tokens across all turns in a multi-turn rollout. ``-1`` disables. Auto-populated into ``extra_env_kwargs``."""
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."""
@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 stripped_id(self) -> str:
"""Environment ID without the @version suffix."""
return self.id.split("@")[0]
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.stripped_id
return self.name or self.env_id
@model_validator(mode="after")
def validate_env_name(self):
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.'
@@ -195,15 +192,51 @@ class EnvConfig(BaseConfig):
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
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
@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 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."""
gate_by_correctness: bool = False
"""When True, scale each rollout's penalty by its reward (``penalty * reward``), so correct rollouts (``reward == 1``) are penalized and incorrect ones (``reward == 0``) are not. When False, every rollout is penalized equally."""
class DefaultAdvantageConfig(BaseConfig):
type: Literal["default"] = "default"
length_penalty: LinearLengthPenaltyConfig | None = None
"""Length penalty applied during advantage computation. Subtracts a ``coef * pass_rate * (completion tokens / orchestrator.seq_len)`` term from each reward (``pass_rate`` = group mean reward) before the baseline subtraction, so solved-often problems get the strongest concision pressure and never-solved groups get none. None disables the penalty."""
length_weighted_baseline: bool = False
"""When True, the GRPO baseline is the token-length-weighted mean reward (``sum(len_i * reward_i) / sum(len_i)``) instead of the plain group mean, centering advantages by per-token expected reward."""
class CustomAdvantageConfig(BaseConfig):
type: Literal["custom"] = "custom"
import_path: str
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
kwargs: dict[str, Any] = Field(default_factory=dict)
"""Kwargs forwarded to the advantage function."""
AdvantageConfig: TypeAlias = Annotated[
DefaultAdvantageConfig | CustomAdvantageConfig,
Field(discriminator="type"),
]
class TrainEnvConfig(EnvConfig):
@@ -214,6 +247,11 @@ class TrainEnvConfig(EnvConfig):
"""Rollouts generated per example for GRPO group-relative advantages.
Inherits from ``orchestrator.group_size`` when unset."""
advantage: AdvantageConfig | None = None
"""Advantage strategy for this env's GRPO groups. Inherits from the top-level
``orchestrator.advantage`` when unset; set a different ``default``/``custom``
config to give this env its own advantage computation."""
class EvalEnvConfig(EnvConfig):
sampling: EvalSamplingConfig = EvalSamplingConfig()
@@ -230,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:
@@ -252,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
@@ -279,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)
@@ -291,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."""
@@ -306,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:
@@ -320,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")
@@ -374,49 +397,6 @@ class CheckpointConfig(BaseConfig):
"""Skip loading the progress from checkpoint."""
class TokensLengthPenaltyConfig(BaseConfig):
type: Literal["tokens"] = "tokens"
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on model completion tokens. Finite and non-negative."""
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
class TurnsLengthPenaltyConfig(BaseConfig):
type: Literal["turns"] = "turns"
LengthPenaltyConfig: TypeAlias = Annotated[
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
Field(discriminator="type"),
]
class DefaultAdvantageConfig(BaseConfig):
type: Literal["default"] = "default"
length_penalty: LengthPenaltyConfig | None = None
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
class CustomAdvantageConfig(BaseConfig):
type: Literal["custom"] = "custom"
import_path: str
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
kwargs: dict[str, Any] = Field(default_factory=dict)
"""Kwargs forwarded to the advantage function."""
AdvantageConfig: TypeAlias = Annotated[
DefaultAdvantageConfig | CustomAdvantageConfig,
Field(discriminator="type"),
]
# Flags rare tokens generated at high entropy (Section 5.2, https://arxiv.org/abs/2510.02387).
class GibberishFilterConfig(BaseConfig):
type: Literal["gibberish"] = "gibberish"
@@ -513,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``); SFT mode forces this."""
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."""
@@ -625,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")
@@ -752,16 +715,6 @@ class OrchestratorConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def _force_no_renderer_for_sft(self):
"""SFT rolls out via the teacher's plain chat-completions endpoint; the
renderer client doesn't apply. Force ``renderer=None`` so the user
doesn't have to remember to set it. Declared before the renderer
validators below so they see the corrected value."""
if self.training_mode == "sft":
self.renderer = None
return self
@model_validator(mode="after")
def validate_training_mode(self):
"""Enforce training mode invariants that involve only orchestrator fields."""
@@ -772,34 +725,6 @@ class OrchestratorConfig(BaseConfig):
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
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."
)
return self
@model_validator(mode="after")
def validate_renderer_auto_resolves(self):
"""Reject the silent DefaultRenderer fallback at config time.
@@ -813,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
@@ -831,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,11 +799,10 @@ class OrchestratorConfig(BaseConfig):
if "group_size" not in env_cfg.model_fields_set:
env_cfg.group_size = self.group_size
# Resolve train env num_workers from max_inflight_rollouts
# Propagate the top-level ``advantage`` into each train env that didn't set its own.
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))
if "advantage" not in env_cfg.model_fields_set:
env_cfg.advantage = self.advantage
return self
@@ -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
@@ -167,6 +167,9 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
nodes_per_fsdp_group: int | None = None
"""Training nodes per FSDP island. Auto-sets ``trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
orchestrator_on_inference: bool = False
"""Run the orchestrator on the last inference node instead of trainer rank 0 (frees host RAM on the trainer node)."""
@property
def total_infer_nodes(self) -> int:
return self.num_infer_nodes * self.num_infer_replicas
@@ -435,6 +438,25 @@ class RLConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node).
Runs after ``auto_setup_router_replay`` so it also catches the
``trainer.enable_router_replay`` path, which sets the inference flag here
(after InferenceConfig's own validators, which therefore miss it).
"""
if self.inference is not None and self.inference.enable_return_routed_experts:
router = getattr(self.inference.deployment, "router", None)
if router is not None and router.type == "llm-d":
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(inference.enable_return_routed_experts / trainer.enable_router_replay): it "
"breaks P/D and is unverified for multi-node. Use router type 'vllm-router' "
"for router-replay runs."
)
return self
@model_validator(mode="after")
def validate_router_replay_without_kv_offload(self):
if (
@@ -603,16 +625,20 @@ class RLConfig(BaseConfig):
def auto_setup_inference_client(self):
"""Auto-configure orchestrator student client from the inference server config.
For all modes, sets dp_rank_count from inference DP size. For SFT mode,
also sets base_url - rl/opd rely on the ClientConfig default
(``["http://localhost:8000/v1"]``) which already matches the auto-launched
student vLLM at inference.server.port = 8000.
Direct single-node runs expose all local DP ranks behind one base URL,
so pin logical clients with ``X-data-parallel-rank``. Multi-node SLURM
runs expose a vllm-router URL instead; the router balances across
per-rank backend URLs and forwards request headers, so the orchestrator
must not inject a DP-rank header there.
"""
if self.inference is None:
return self
client = self.orchestrator.student.client
if "dp_rank_count" not in client.model_fields_set:
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
if self.deployment.type == "multi_node":
client.dp_rank_count = 1
else:
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
if self.orchestrator.training_mode == "sft" and "base_url" not in client.model_fields_set:
host = self.inference.server.host or "localhost"
port = self.inference.server.port
@@ -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."""
@@ -425,6 +425,18 @@ class DefaultLossConfig(BaseConfig):
"""Temperature for the KL term."""
class IPOLossConfig(BaseConfig):
type: Literal["ipo"] = "ipo"
ipo_threshold: float = Field(0.1, ge=0)
"""Upper DPPO masking threshold."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
kl_tau: float = Field(1e-3, ge=0)
"""Temperature for the KL term."""
class CustomLossConfig(BaseConfig):
type: Literal["custom"] = "custom"
@@ -435,7 +447,7 @@ class CustomLossConfig(BaseConfig):
"""Kwargs forwarded to the loss function."""
LossConfig: TypeAlias = Annotated[DefaultLossConfig | CustomLossConfig, Field(discriminator="type")]
LossConfig: TypeAlias = Annotated[DefaultLossConfig | IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
class FakeDataLoaderConfig(BaseConfig):
@@ -490,15 +502,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
]
class TokenExportConfig(BaseConfig):
"""Configures per-token rollout exports from the RL trainer."""
class TrainerExperimentalConfig(BaseConfig):
token_export: TokenExportConfig | None = None
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
class TrainerConfig(BaseConfig):
model: ModelConfig = ModelConfig()
@@ -562,7 +565,8 @@ class TrainerConfig(BaseConfig):
max_concurrent_runs: int = Field(1, ge=1)
"""Maximum number of concurrent runs to allow. If 1, only one run may run at a time."""
experimental: TrainerExperimentalConfig = TrainerExperimentalConfig()
enable_token_export: bool = False
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
@model_validator(mode="after")
def deepep_disables_grad_clipping(self):
@@ -22,6 +22,8 @@ REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"^zai-org/GLM-"), "glm45"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
# Only Qwen3 Thinking models reason — Instruct/base models do not.
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
+52 -6
View File
@@ -1,11 +1,12 @@
[project]
name = "prime-rl"
version = "0.5.0"
version = "0.6.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
dependencies = [
"prime-rl-configs",
"prime-pydantic-config",
"beartype>=0.21.0",
"datasets>=4.0.0",
"jaxtyping>=0.3.2",
@@ -27,17 +28,21 @@ dependencies = [
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
"openai>=1.106.1",
"orjson>=3.11.0",
"rich>=14.0.0",
"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]
@@ -77,7 +82,6 @@ envs = [
"math-python",
"math500",
"mini-swe-agent-plus",
"mini-swe-agent-plus-rlm",
"mmlu-pro",
"opencode-cp",
"opencode-deepdive",
@@ -86,11 +90,31 @@ envs = [
"opencode-swe",
"reverse-text",
"rlm-swe",
"rlm-search",
"rlm-uuid-ctf",
"science-env",
"simpleqa-verified",
"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'",
@@ -150,6 +174,7 @@ override-dependencies = [
"transformers==5.6.2",
"torch>=2.9.0",
"openenv-core",
"verifiers>=0.1.15.dev357",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -184,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
@@ -196,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 }
@@ -215,7 +242,6 @@ math-env = { path = "deps/research-environments/environments/math_env", editable
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
math500 = { path = "deps/research-environments/environments/math500", editable = true }
mini-swe-agent-plus = { path = "deps/research-environments/environments/mini_swe_agent_plus", editable = true }
mini-swe-agent-plus-rlm = { path = "deps/research-environments/environments/mini_swe_agent_plus_rlm", editable = true }
mmlu-pro = { path = "deps/research-environments/environments/mmlu_pro", editable = true }
opencode-cp = { path = "deps/research-environments/environments/opencode_cp", editable = true }
opencode-deepdive = { path = "deps/research-environments/environments/opencode_deepdive", editable = true }
@@ -224,11 +250,31 @@ opencode-science = { path = "deps/research-environments/environments/opencode_sc
opencode-swe = { path = "deps/research-environments/environments/opencode_swe", editable = true }
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
rlm-uuid-ctf = { path = "deps/research-environments/environments/rlm_uuid_ctf", editable = true }
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
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" }
+37 -10
View File
@@ -1,17 +1,44 @@
#!/bin/bash
# arm64 post-install fixups for Docker builds.
set -e
# arm64 post-install fixups: rebuild flash-attn from source for the target GPU.
#
# Why this exists: pyproject.toml sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE to keep
# `uv sync` fast; on x86_64 it pins a prebuilt wheel to fill in the binary, but no
# such wheel exists for aarch64. Without this script, `import flash_attn` fails on
# aarch64 with `ModuleNotFoundError: No module named 'flash_attn_2_cuda'`.
#
# Defaults preserve the existing Docker behavior (sm_100 / GB200). On a host with
# `nvidia-smi` available, the compute capability is auto-detected from the local
# GPU. Override via env vars if needed:
# TORCH_CUDA_ARCH_LIST e.g. 9.0 (Hopper), 10.0 (Blackwell)
# VENV_PATH path to the venv (default: $(pwd)/.venv)
# MAX_JOBS parallel nvcc jobs (default: 4)
set -euo pipefail
echo "=== building flash-attn from source (sm_100 / GB200) ==="
# Run from /tmp so uv doesn't read pyproject.toml's [tool.uv.extra-build-variables]
# which sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and prevents CUDA kernel compilation.
export TORCH_CUDA_ARCH_LIST="10.0"
export MAX_JOBS=4
if [ -z "${TORCH_CUDA_ARCH_LIST:-}" ]; then
# Try to detect from the local GPU. Tolerate any failure mode (binary missing,
# driver not loaded, Docker buildx without --gpus) and fall back to GB200.
TORCH_CUDA_ARCH_LIST="$(nvidia-smi --query-gpu=compute_cap --format=csv,noheader 2>/dev/null | head -1 | tr -d ' ' || true)"
: "${TORCH_CUDA_ARCH_LIST:=10.0}"
fi
export TORCH_CUDA_ARCH_LIST
VENV_PATH="${VENV_PATH:-$(pwd)/.venv}"
if [ ! -x "$VENV_PATH/bin/python" ]; then
echo "ERROR: no python at $VENV_PATH/bin/python. Run from the project root or set VENV_PATH." >&2
exit 1
fi
export MAX_JOBS="${MAX_JOBS:-4}"
export FLASH_ATTENTION_FORCE_BUILD=TRUE
export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
(cd /tmp && uv pip install --python /app/.venv/bin/python \
"flash-attn==2.8.3" --no-build-isolation --no-binary flash-attn --no-cache)
echo "=== building flash-attn from source (TORCH_CUDA_ARCH_LIST=$TORCH_CUDA_ARCH_LIST, MAX_JOBS=$MAX_JOBS) ==="
echo " target venv: $VENV_PATH"
# Run from /tmp so uv ignores the project's [tool.uv.extra-build-variables],
# which sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and would prevent kernel compilation.
(cd /tmp && uv pip install --python "$VENV_PATH/bin/python" \
"flash-attn==2.8.3" --no-build-isolation --no-binary flash-attn --no-cache --reinstall-package flash-attn)
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
uv pip install --reinstall --no-deps \
uv pip install --python "$VENV_PATH/bin/python" --reinstall --no-deps \
"flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
+67 -1
View File
@@ -4,8 +4,74 @@ set -e
# Set higher ulimit for file descriptors to prevent API timeout issues
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
# Allow runtime override of the prime-rl source itself.
# PRIME_RL_REF can be a git tag, branch, or commit hash. PRIME_RL_REPO
# optionally points at a fork; defaults to the upstream repo.
#
# We clone into a per-ref dir under /tmp, seed the venv from the baked
# /app/.venv so heavy wheels (flash-attn, mamba-ssm, …) survive, then
# `uv sync --inexact` re-installs prime_rl from the override source.
# Workdir + PATH swap so the chart's `uv run trainer/inference/orchestrator`
# resolves the entrypoints from the override venv.
if [ -n "$PRIME_RL_REF" ]; then
PRIME_RL_REPO="${PRIME_RL_REPO:-https://github.com/PrimeIntellect-ai/prime-rl.git}"
# Slug + content hash for the cache dir name. Slug keeps the path
# human-readable; the hash (over repo + ref) prevents collisions
# between distinct refs that slugify the same way (e.g. `feat/foo`
# vs `feat-foo`) and between the same ref on different forks.
REF_SLUG="${PRIME_RL_REF//\//-}"
REF_HASH=$(echo -n "${PRIME_RL_REPO}|${PRIME_RL_REF}" | md5sum | cut -c1-12)
DEST="/tmp/prime-rl-${REF_SLUG}-${REF_HASH}"
# Rewrite ssh://git@github.com URLs to https so submodules listed
# with SSH URLs (deps/verifiers, deps/renderers, deps/research-envs)
# can be cloned from the pod without ssh keys.
git config --global url."https://github.com/".insteadOf "git@github.com:"
if [ ! -d "$DEST/.git" ]; then
echo "[prime-rl] cloning ${PRIME_RL_REPO} for ${PRIME_RL_REF}"
rm -rf "$DEST"
git clone --recurse-submodules "$PRIME_RL_REPO" "$DEST"
fi
# Always fetch + checkout so mutable refs (branches/tags) pick up new
# commits between pod restarts. No-op for immutable SHAs.
echo "[prime-rl] refreshing ${PRIME_RL_REF}"
git -C "$DEST" fetch --quiet --tags --force origin
git -C "$DEST" checkout --quiet --force "$PRIME_RL_REF"
# Fast-forward to upstream tip when PRIME_RL_REF is a branch name.
# Silently no-ops for SHAs/tags (no `origin/<sha>` exists).
git -C "$DEST" reset --hard --quiet "origin/${PRIME_RL_REF}" 2>/dev/null || true
# Refresh submodules to whatever the parent commit pins. `sync`
# picks up URL changes in .gitmodules between checkouts on cache
# hit; `update --init --recursive` applies the pinned SHAs.
git -C "$DEST" submodule sync --recursive
git -C "$DEST" submodule update --init --recursive
if [ ! -d "$DEST/.venv" ]; then
# Seed from the baked venv so the heavy wheels (flash-attn,
# mamba-ssm, …) don't have to be rebuilt. Plain `cp -a` (no
# hardlinks): a subsequent `uv sync` writes into this tree, and
# hardlinks would leak those writes back into /app/.venv when
# /tmp and /app share a filesystem.
cp -a /app/.venv "$DEST/.venv"
fi
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
# Mirror the image's extras (Dockerfile.cuda:82) — explicit instead
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
# startup. --inexact keeps the seeded venv's pre-built wheels
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
# override's lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev \
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
--extra envs --extra gpt-oss --extra modelexpress \
--group mamba-ssm )
export VIRTUAL_ENV="$DEST/.venv"
export PATH="$DEST/.venv/bin:$PATH"
cd "$DEST"
fi
# Allow runtime override of the verifiers package version.
# VERIFIERS_VERSION can be a git tag, branch, or commit hash.
# VERIFIERS_VERSION can be a git tag, branch, or commit hash. Runs after the
# PRIME_RL_REF swap so when both are set the install lands in the override
# venv (uv pip install targets $VIRTUAL_ENV when exported).
if [ -n "$VERIFIERS_VERSION" ]; then
echo "Installing verifiers version: $VERIFIERS_VERSION"
uv pip install --reinstall-package verifiers \
+11 -17
View File
@@ -74,27 +74,11 @@ ensure_known_hosts() {
fi
}
# Initialize each submodule independently so that a missing private repo
# (e.g. configs/private when the user lacks access) does not abort the install.
init_submodules() {
if [ ! -f .gitmodules ]; then
return 0
fi
local paths failures
paths=$(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | awk '{print $2}')
failures=()
for path in $paths; do
log_info "Initializing submodule: ${path}"
if git submodule update --init --recursive -- "$path"; then
:
else
log_warn "Could not initialize submodule '${path}' (likely no access). Continuing without it."
failures+=("$path")
fi
done
if [ "${#failures[@]}" -gt 0 ]; then
log_warn "Skipped submodules: ${failures[*]}"
fi
git submodule update --init --recursive
}
main() {
@@ -159,6 +143,16 @@ main() {
log_info "Installing pre-commit hooks..."
uv run pre-commit install
# aarch64 has no prebuilt flash-attn wheel; build it from source for the local GPU.
# Without this, `import flash_attn` fails with `ModuleNotFoundError: flash_attn_2_cuda`.
# Run last so no subsequent uv operation (which implicitly syncs against the lockfile)
# rebuilds flash-attn from PyPI with FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and undoes this.
if [ "$(uname -m)" = "aarch64" ]; then
log_info "aarch64 detected: building flash-attn from source (this takes 20-30 minutes)..."
log_warn "Future 'uv sync --all-extras' or 'uv run' will remove this build. Use 'uv sync --inexact' or 'uv run --no-sync' to keep it."
bash scripts/docker-arm64-post-install.sh
fi
log_info "Installation completed!"
}
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env bash
# Install the llm-d standalone (no-Kubernetes) routing binaries into
# third_party/llmd/bin:
# - epp : llm-d-router Endpoint Picker (the routing brain)
# - pd-sidecar : decode-side proxy for P/D disaggregation
# - envoy : the data-plane proxy that calls the EPP via ext_proc
#
# epp/pd-sidecar are built from a pinned llm-d-router commit. We currently build
# from a small fork that adds P/D disaggregation for vLLM's token-in
# /inference/v1/generate endpoint (prime-rl's renderer / TITO rollout path) —
# upstream's pd-sidecar only disaggregates the OpenAI endpoints, so token-in P/D
# silently runs decode-only. The fork is pending upstream PR
# llm-d/llm-d-router#1458; switch LLMD_ROUTER_REPO back to the upstream repo and
# bump LLMD_ROUTER_REF once it merges. The fork is branched off the upstream
# commit that added the EPP vllmhttp parser (PR #1248), which the renderer path
# also needs.
#
# System Go is not required: a Go toolchain is vendored under third_party/llmd/go
# and used to bootstrap; GOTOOLCHAIN=auto fetches the exact version the module
# pins. Envoy is extracted as a static binary from its release container image
# WITHOUT docker: we build `crane` (pure-Go, talks straight to the OCI registry)
# with the same vendored toolchain and use it to export the image filesystem.
# This is the only step that previously required a docker daemon, which cluster
# compute nodes don't have.
set -euo pipefail
LLMD_ROUTER_REPO="${LLMD_ROUTER_REPO:-https://github.com/S1ro1/llm-d-router.git}"
LLMD_ROUTER_REF="${LLMD_ROUTER_REF:-1ca4243ec84c657b4a5f507a1776d6c15a618d5b}"
GO_BOOTSTRAP_VERSION="${GO_BOOTSTRAP_VERSION:-1.23.4}"
ENVOY_VERSION="${ENVOY_VERSION:-1.36.0}"
ENVOY_IMAGE="${ENVOY_IMAGE:-envoyproxy/envoy:v${ENVOY_VERSION}}"
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
PROJECT_DIR=$(cd "$SCRIPT_DIR/.." && pwd)
LLMD_DIR="$PROJECT_DIR/third_party/llmd"
BIN_DIR="$LLMD_DIR/bin"
GO_ROOT="$LLMD_DIR/go"
SRC_DIR="$LLMD_DIR/src"
GO_TOOLS_BIN="$LLMD_DIR/gotools/bin"
mkdir -p "$BIN_DIR" "$GO_TOOLS_BIN"
# --- Go toolchain (vendored bootstrap; auto-upgrades to the module's version) ---
if [ ! -x "$GO_ROOT/bin/go" ]; then
echo "[install_llmd] downloading bootstrap Go $GO_BOOTSTRAP_VERSION"
rm -rf "$GO_ROOT"
curl -fsSL "https://go.dev/dl/go${GO_BOOTSTRAP_VERSION}.linux-amd64.tar.gz" | tar -xz -C "$LLMD_DIR"
fi
export GOROOT="$GO_ROOT"
export PATH="$GO_ROOT/bin:$PATH"
export GOTOOLCHAIN=auto
echo "[install_llmd] bootstrap $(go version)"
# --- Fetch llm-d-router source at the pinned ref ---
echo "[install_llmd] fetching ${LLMD_ROUTER_REPO}@${LLMD_ROUTER_REF}"
if [ ! -d "$SRC_DIR/.git" ]; then
rm -rf "$SRC_DIR"
git clone --quiet "$LLMD_ROUTER_REPO" "$SRC_DIR"
fi
git -C "$SRC_DIR" remote set-url origin "$LLMD_ROUTER_REPO"
git -C "$SRC_DIR" fetch --quiet origin
git -C "$SRC_DIR" checkout --quiet "$LLMD_ROUTER_REF"
# --- Build epp + pd-sidecar ---
echo "[install_llmd] building epp + pd-sidecar"
( cd "$SRC_DIR" && go build -o "$BIN_DIR/epp" ./cmd/epp && go build -o "$BIN_DIR/pd-sidecar" ./cmd/pd-sidecar )
# --- Envoy static binary (extract from the release image; keep if present) ---
# No docker: build crane with the vendored toolchain and export the image's
# filesystem straight from the registry, then pull out the static envoy binary.
if [ ! -x "$BIN_DIR/envoy" ]; then
if [ ! -x "$GO_TOOLS_BIN/crane" ]; then
echo "[install_llmd] building crane (OCI registry client, no docker needed)"
GOBIN="$GO_TOOLS_BIN" GOFLAGS=-mod=mod \
go install github.com/google/go-containerregistry/cmd/crane@latest
fi
echo "[install_llmd] extracting Envoy ${ENVOY_VERSION} from ${ENVOY_IMAGE}"
"$GO_TOOLS_BIN/crane" export "$ENVOY_IMAGE" - \
| tar -xf - -O usr/local/bin/envoy > "$BIN_DIR/envoy"
chmod +x "$BIN_DIR/envoy"
fi
echo "[install_llmd] installed binaries in $BIN_DIR:"
"$BIN_DIR/epp" --version 2>&1 | head -1 || true
"$BIN_DIR/envoy" --version 2>&1 | head -1 || true
"$BIN_DIR/pd-sidecar" --help >/dev/null 2>&1 && echo " pd-sidecar OK" || true
echo "[install_llmd] done"
+25
View File
@@ -10,6 +10,19 @@ PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
VENV_BIN="$PROJECT_DIR/.venv/bin"
PYTHON="$VENV_BIN/python"
# UCX's --with-verbs silently disables IB/RoCE support when the rdma-core *dev*
# headers (verbs.h / rdma_cma.h) are missing, yielding a TCP-only build. On hosts
# with RDMA devices, require the headers up front instead of failing at runtime.
HAVE_RDMA=0
if compgen -G "/sys/class/infiniband/*" > /dev/null; then
HAVE_RDMA=1
if [ ! -f /usr/include/infiniband/verbs.h ] || [ ! -f /usr/include/rdma/rdma_cma.h ]; then
echo "ERROR: host has RDMA devices but the rdma-core dev headers are missing." >&2
echo "Install them first, e.g.: apt-get install -y libibverbs-dev librdmacm-dev" >&2
exit 1
fi
fi
WORKSPACE="$PROJECT_DIR/nixl_workspace"
mkdir -p "$WORKSPACE"
UCX_SRC="$WORKSPACE/ucx_source"
@@ -40,11 +53,23 @@ if [ ! -f "$UCX_INSTALL/lib/libucs.so" ]; then
--enable-devel-headers \
--enable-mt \
--with-verbs \
--with-rdmacm \
--with-cuda="$CUDA_PATH" \
--with-ze=no
make -j"$NPROC"
make install
echo "=== UCX installed to $UCX_INSTALL ==="
# Fail loudly if the IB transports didn't make it into the build.
if [ "$HAVE_RDMA" = 1 ]; then
ucx_transports=$(LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}" \
"$UCX_INSTALL/bin/ucx_info" -d)
if ! grep -q "Transport: rc_verbs" <<< "$ucx_transports"; then
echo "ERROR: UCX built without IB (rc_verbs) transport despite RDMA devices being present." >&2
echo "Check that libibverbs-dev / librdmacm-dev were present at configure time." >&2
exit 1
fi
fi
else
echo "=== UCX already built, skipping ==="
fi
+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 -3
View File
@@ -62,10 +62,10 @@ In TOML, an empty section header (`[ckpt]`) does the same.
## RL trainer token exports
For rollout debugging, enable trainer-side token export under `trainer.experimental.token_export` (or `experimental.token_export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
```toml
[trainer.experimental.token_export]
enable_token_export = true
```
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
@@ -74,5 +74,4 @@ Leave it unset for normal training. When enabled, it exports every sequence from
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
- `configs/debug/` — minimal debug configs
- `configs/private/` — private configs submodule (internal)
- `examples/` — full example configs
+12 -4
View File
@@ -16,11 +16,9 @@ bash scripts/install.sh # clones, inits submodules, installs uv, runs `uv sync
For an existing clone, init submodules explicitly:
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive
```
Do **not** run `git submodule update --init --recursive` without paths — it tries to clone the private `configs/private` submodule and aborts for users without access. `scripts/install.sh` walks submodules one at a time and skips failures, so it works for everyone.
## Sync
```bash
@@ -29,7 +27,7 @@ uv sync --group dev # + pytest, ruff, pre-commit
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
```
The `envs` extra installs every env workspace listed in `[tool.uv.workspace]`. Adding a new env means adding it to `members`, the `envs` extra, and `[tool.uv.sources]`.
The `envs` extra installs environments listed under `[project.optional-dependencies].envs`, resolved through `[tool.uv.sources]`. Adding a new env means adding its package name to `envs` and its editable source path to `[tool.uv.sources]`.
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
@@ -61,6 +59,16 @@ Flags: `--workspace DIR`, `--deepep-ref REF` (default `73b6ea4`), `--nvshmem-ver
Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
### llm-d router backend
Multi-node / disaggregated deployments can route through the upstream llm-d Endpoint Picker instead of `vllm-router` (set `[...deployment.router] type = "llm-d"`). It needs three native binaries — install once:
```bash
bash scripts/install_llmd.sh # builds epp + pd-sidecar from a pinned llm-d-router commit (vendored Go), fetches envoy
```
Binaries land in `third_party/llmd/bin/{epp,envoy,pd-sidecar}` (a shared path, so SLURM nodes see them). `epp` is pinned to the commit that includes the `vllmhttp-parser` (PR #1248) so prime-rl's renderer/TITO `/inference/v1/generate` path routes correctly. Override the pin with `LLMD_ROUTER_REF=<sha>`. The EPP + Envoy + endpoints configs are rendered from `templates/llmd/*.yaml.j2` (included into the SLURM script); only the per-node IPv4 addresses are filled in inline at launch time.
## Key files
- `pyproject.toml` — dependencies, extras, dependency groups
+2 -4
View File
@@ -71,9 +71,7 @@ After a restart, verify all processes are back up and progress resumed before th
├── inference/
│ ├── node_*.log # per-node (multi-node only)
│ └── router_0.log # vllm-router per replica (multi-node only)
└── envs/{train,eval}/{env_name}/
├── env_server.log
└── env_worker_*.log
└── envs/{train,eval}/{env_name}.log # one log file per env
```
Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough. Drop into per-node or per-rank logs only when debugging. All logs are loguru with `HH:mm:ss LEVEL message`; levels: `DEBUG`, `INFO`, `SUCCESS`, `WARNING`, `ERROR`.
@@ -82,7 +80,7 @@ Scan for problems:
```bash
grep -E "WARNING|ERROR" {output_dir}/logs/{trainer,orchestrator,inference}.log
grep -E "WARNING|ERROR" {output_dir}/logs/envs/train/*/env_{server,worker_*}.log
grep -E "WARNING|ERROR" {output_dir}/logs/envs/{train,eval}/*.log
```
### Metrics
+19 -5
View File
@@ -1,6 +1,8 @@
import json
import subprocess
import sys
from pathlib import Path
from typing import Any
import tomli_w
@@ -14,6 +16,17 @@ INFERENCE_TOML = "inference.toml"
INFERENCE_SBATCH = "inference.sbatch"
def vllm_overrides_fragment(overrides: dict[str, Any]) -> str:
"""Render per-role vLLM overrides as a JSON fragment for the ROLE_EXTRA bash string.
Returns a leading-comma fragment with quotes escaped for the double-quoted assignment
(e.g. `, \\"max_num_seqs\\": 256`), or an empty string when there are no overrides.
"""
if not overrides:
return ""
return ", " + json.dumps(overrides)[1:-1].replace('"', '\\"')
def write_config(config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None) -> Path:
"""Write resolved config to disk."""
output_dir.mkdir(parents=True, exist_ok=True)
@@ -47,7 +60,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
dp_per_node=dp_per_node,
num_nodes=getattr(config.deployment, "num_nodes", 1),
port=config.server.port,
disaggregated=is_disaggregated,
is_disaggregated=is_disaggregated,
kv_offload=offload is not None,
kv_offload_mooncake=is_mooncake,
kv_offload_cpu_bytes=int(offload.cpu.num_bytes) if is_mooncake else 0,
@@ -65,20 +78,21 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
num_decode_replicas=config.deployment.num_decode_replicas,
prefill_port=config.deployment.prefill_port,
decode_port=config.deployment.decode_port,
router_port=config.deployment.router.port,
router_policy=config.deployment.router.policy,
router=config.deployment.router,
data_parallel_rpc_port=config.data_parallel_rpc_port,
use_deep_gemm=config.use_deep_gemm,
prefill_env_overrides=config.deployment.prefill_env_overrides,
decode_env_overrides=config.deployment.decode_env_overrides,
prefill_vllm_extra_json=vllm_overrides_fragment(config.deployment.prefill_vllm_overrides),
decode_vllm_extra_json=vllm_overrides_fragment(config.deployment.decode_vllm_overrides),
)
elif is_multi_node:
template_vars.update(
router_port=config.deployment.router.port,
router=config.deployment.router,
backend_port=config.deployment.backend_port,
router_policy=config.deployment.router.policy,
data_parallel_rpc_port=config.data_parallel_rpc_port,
enable_expert_parallel=config.enable_expert_parallel,
infer_nodes_per_replica=config.deployment.num_nodes,
)
script = template.render(**template_vars)
+9 -2
View File
@@ -12,7 +12,9 @@ from threading import Event, Thread
import pynvml
import tomli_w
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.inference import vllm_overrides_fragment
from prime_rl.utils.config import cli
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import (
@@ -371,7 +373,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
num_prefill_replicas=infer_deploy.num_prefill_replicas,
num_decode_replicas=infer_deploy.num_decode_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router_port=infer_deploy.router.port,
router=infer_deploy.router,
prefill_port=infer_deploy.prefill_port,
decode_port=infer_deploy.decode_port,
inference_tp=config.inference.parallel.tp,
@@ -379,10 +381,13 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
use_deep_gemm=config.inference.use_deep_gemm,
prefill_env_overrides=infer_deploy.prefill_env_overrides,
decode_env_overrides=infer_deploy.decode_env_overrides,
prefill_vllm_extra_json=vllm_overrides_fragment(infer_deploy.prefill_vllm_overrides),
decode_vllm_extra_json=vllm_overrides_fragment(infer_deploy.decode_vllm_overrides),
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
**mooncake_vars,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
)
else:
script = template.render(
@@ -396,7 +401,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
nodes_per_infer_replica=config.deployment.num_infer_nodes,
num_infer_replicas=config.deployment.num_infer_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router_port=config.inference.deployment.router.port if config.inference else 8000,
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
infer_nodes_per_replica=config.deployment.num_infer_nodes,
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
inference_tp=config.inference.parallel.tp if config.inference else 1,
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
@@ -405,6 +411,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
**mooncake_vars,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
+151
View File
@@ -17,9 +17,89 @@ def transformers_v5_compat():
_patch_qwen35_lora()
_patch_lora_key_prefix()
monkey_patch_nano_v3_reasoning_parser()
monkey_patch_deep_gemm_silu_mul_quant_int64()
monkey_patch_vllm_padded_input_scrub()
monkey_patch_return_routed_experts_with_nixl_connector()
monkey_patch_kv_xfer_finished_tolerate_freed()
def monkey_patch_kv_xfer_finished_tolerate_freed():
"""Tolerate KV-transfer finish notifications for already-freed requests.
In disaggregated P/D (NIXL, optionally + a KV store connector) a request can
be finished — most often ``FINISHED_ABORTED`` from an off-policy cancel, a
client disconnect, or a request timeout — while it still has in-flight KV
transfers. When such a request's ``finished_recving`` and ``finished_sending``
both land in the same ``Scheduler.update_from_output`` step, the stock
``_update_from_kv_xfer_finished`` frees it in the recving branch
(``_free_blocks`` -> ``del self.requests[req_id]``) and then the sending
branch hits ``assert req_id in self.requests`` and kills the EngineCore. On a
DP deployment that one death cascades to every rank via the gloo finish-state
all-reduce, taking down the whole inference pool.
The trigger is the abort itself, not weight-update pause/resume: it reproduces
during normal stepping whenever an aborted request's recv and send complete in
the same step (observed with zero off-policy cancellations, driven only by
incidental client-side aborts). Skip already-freed request ids instead of
asserting — their blocks are freed either way, so dropping the stale
notification is safe.
Upstream issue: https://github.com/vllm-project/vllm/issues/46240
"""
from vllm.logger import init_logger
from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.request import RequestStatus
logger = init_logger("vllm.v1.core.sched.scheduler")
if getattr(Scheduler._update_from_kv_xfer_finished, "_prime_rl_tolerates_freed", False):
return
def _update_from_kv_xfer_finished(self, kv_connector_output):
if self.connector is not None:
self.connector.update_connector_output(kv_connector_output)
for req_id in kv_connector_output.finished_recving or ():
logger.debug("Finished recving KV transfer for request %s", req_id)
# Stale notification for a request freed earlier this step (e.g. an
# aborted request whose send completion freed it). Nothing to do.
if req_id not in self.requests:
continue
req = self.requests[req_id]
if req.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
self.finished_recving_kv_req_ids.add(req_id)
else:
assert RequestStatus.is_finished(req.status)
self._free_blocks(self.requests[req_id])
for req_id in kv_connector_output.finished_sending or ():
logger.debug("Finished sending KV transfer for request %s", req_id)
# See above: the recving branch may have already freed an aborted
# request whose send also completed this step.
if req_id not in self.requests:
continue
self._free_blocks(self.requests[req_id])
_update_from_kv_xfer_finished._prime_rl_tolerates_freed = True
Scheduler._update_from_kv_xfer_finished = _update_from_kv_xfer_finished
logger.warning("Patched Scheduler._update_from_kv_xfer_finished to tolerate freed (aborted) KV-transfer reqs.")
def monkey_patch_nano_v3_reasoning_parser():
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
class NanoV3ReasoningParser(DeepSeekR1ReasoningParser):
def extract_reasoning(self, model_output, request):
reasoning_content, final_content = super().extract_reasoning(model_output, request)
chat_template_kwargs = getattr(request, "chat_template_kwargs", None)
if chat_template_kwargs and chat_template_kwargs.get("enable_thinking") is False and final_content is None:
reasoning_content, final_content = final_content, reasoning_content
return reasoning_content, final_content
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
def monkey_patch_return_routed_experts_with_nixl_connector():
@@ -66,6 +146,44 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
def monkey_patch_strip_routed_experts_from_chat():
"""Drop routed_experts from chat-completions responses.
routed_experts are only consumed via the serialized ``/generate``
(serving_tokens) path used for router-replay training, which encodes them as a
``{data, shape, start}`` object the PD router can merge. The stock
chat-completions path instead encodes them as a base64 ``np.save`` *string*,
which the PD router rejects ("prefill routed_experts must be an object with
base64 data and shape") and fails every eval rollout (evals go through chat
completions). ``enable_return_routed_experts`` is a server-wide model-config
flag with no per-request toggle, so strip the field on the chat path here.
"""
from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat
from vllm.logger import init_logger
logger = init_logger(__name__)
if getattr(OpenAIServingChat.chat_completion_full_generator, "_prime_rl_strips_routed_experts", False):
return
_original = OpenAIServingChat.chat_completion_full_generator
async def _strip(result_generator):
async for res in result_generator:
for output in res.outputs:
output.routed_experts = None
yield res
async def _patched(self, request, result_generator, *args, **kwargs):
return await _original(self, request, _strip(result_generator), *args, **kwargs)
_patched._prime_rl_strips_routed_experts = True
OpenAIServingChat.chat_completion_full_generator = _patched
logger.info(
"Stripped routed_experts from chat-completions responses (PD router merges only the /generate object form)."
)
@triton.jit
def _silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel(
y_ptr,
@@ -836,3 +954,36 @@ def monkey_patch_fp32_lm_head():
LogitsProcessor.__init__ = _patched_init
LogitsProcessor._get_logits = _patched_get_logits
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
def monkey_patch_dp_coordinator_startup_timeout():
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 30s.
The coordinator child process is spawned on the DP-rank-0 API server while
every engine-core rank on the node is importing and loading weights, so its
own spawn-time re-import can take well over 30s under that CPU/IO
contention (seen on multi-node disaggregated GLM-5.1 launches). Configurable
via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT (seconds, default 300).
"""
import multiprocessing.connection
import os
from vllm.v1.engine.coordinator import DPCoordinator
timeout = float(os.environ.get("PRIME_DP_COORDINATOR_STARTUP_TIMEOUT", "300"))
def _patched_wait_for_zmq_addrs(self, zmq_addr_pipe):
try:
ready = multiprocessing.connection.wait([zmq_addr_pipe, self.proc.sentinel], timeout=timeout)
if not ready:
raise RuntimeError(
f"DP Coordinator process failed to report ZMQ addresses within {timeout}s during startup."
)
try:
return zmq_addr_pipe.recv()
except EOFError:
raise RuntimeError("DP Coordinator process failed during startup.") from None
finally:
zmq_addr_pipe.close()
DPCoordinator._wait_for_zmq_addrs = _patched_wait_for_zmq_addrs
+16
View File
@@ -20,8 +20,11 @@ from prime_rl.utils.logger import get_logger
logger = get_logger()
from prime_rl.inference.patches import (
monkey_patch_dp_coordinator_startup_timeout,
monkey_patch_harmony_stop_token_propagation,
monkey_patch_load_lora_adapter,
monkey_patch_nano_v3_reasoning_parser,
monkey_patch_strip_routed_experts_from_chat,
monkey_patch_tokenize_params_validation,
monkey_patch_vllm_padded_input_scrub,
)
@@ -35,9 +38,22 @@ monkey_patch_load_lora_adapter()
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
monkey_patch_tokenize_params_validation()
# NOTE: Register Nano V3 reasoning parser so configs can use
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
monkey_patch_nano_v3_reasoning_parser()
# NOTE: Optional mitigation for vLLM padded decode inputs until the native fix
# is available in our pinned runtime.
monkey_patch_vllm_padded_input_scrub()
# NOTE: routed_experts are consumed only via the serialized /generate path (router
# replay). The chat-completions path encodes them as a base64 np.save string the PD
# router cannot merge, which fails eval rollouts (they use chat completions). Strip
# routed_experts from chat responses since the server-wide enable flag has no
# per-request toggle.
monkey_patch_strip_routed_experts_from_chat()
# NOTE: vLLM hard-codes a 30s DP coordinator startup timeout, which the rank-0
# API server blows through when all engine-core ranks on the node are loading
# weights concurrently (multi-node disaggregated deployments).
monkey_patch_dp_coordinator_startup_timeout()
logger = init_logger("vllm.entrypoints.openai.api_server")
+79 -3
View File
@@ -30,12 +30,17 @@ delegates to upstream so we track future vLLM changes for free.
from __future__ import annotations
from collections.abc import AsyncGenerator
from collections.abc import AsyncGenerator, AsyncIterable
from functools import cached_property
from typing import Any
from fastapi import Request
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
from vllm.entrypoints.openai.engine.protocol import (
ErrorResponse,
PromptTokenUsageInfo,
RequestResponseMetadata,
UsageInfo,
)
from vllm.entrypoints.serve.disagg.protocol import (
GenerateRequest,
GenerateResponse,
@@ -55,6 +60,12 @@ class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
class PrimeRlGenerateResponse(GenerateResponse):
choices: list[PrimeRlGenerateResponseChoice]
# Upstream ``GenerateResponse`` doesn't declare a ``usage`` field, so the
# parent ``ServingTokens.serve_tokens_full_generator`` constructs it and
# Pydantic silently drops it on serialization. Declare it here so the
# router can extract per-run token counts (and cached-prefix tokens) for
# platform billing — see https://github.com/PrimeIntellect-ai/router/pull/43.
usage: UsageInfo | None = None
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
@@ -74,6 +85,49 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
)
class _FinalOutputCapture:
"""Wraps a ``RequestOutput`` async generator to record the last yielded item.
Needed so the response builder can construct a ``usage`` block from
``final_res.prompt_token_ids`` / ``output.token_ids`` / ``num_cached_tokens``
after delegating iteration to upstream.
"""
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
# ``source`` may be any async-iterable — including
# ``_GenerateRoutedExpertsCapture``, which exposes the protocol via
# ``async def __aiter__`` (an async generator function) and has no
# ``__anext__`` method. Drive it through ``async for`` rather than
# poking ``__anext__`` directly so both shapes work.
self._source = source
self.final_res: RequestOutput | None = None
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
async for item in self._source:
self.final_res = item
yield item
def _build_usage(final_res: RequestOutput) -> UsageInfo:
assert final_res.prompt_token_ids is not None
num_prompt_tokens = len(final_res.prompt_token_ids)
if final_res.encoder_prompt_token_ids is not None:
num_prompt_tokens += len(final_res.encoder_prompt_token_ids)
num_generated_tokens = sum(len(output.token_ids) for output in final_res.outputs)
usage = UsageInfo(
prompt_tokens=num_prompt_tokens,
completion_tokens=num_generated_tokens,
total_tokens=num_prompt_tokens + num_generated_tokens,
)
# Always emit cached tokens when vLLM reports any. Upstream gates this on
# ``enable_prompt_tokens_details`` (default False) for OpenAI-API compat,
# but ``/inference/v1/generate`` is prime-rl internal — the cache-discount
# billing pipeline always wants the cached subset surfaced.
if final_res.num_cached_tokens:
usage.prompt_tokens_details = PromptTokenUsageInfo(cached_tokens=final_res.num_cached_tokens)
return usage
async def _client_set_max_tokens(raw_request: Request | None) -> bool:
"""Whether the inbound JSON body carried ``sampling_params.max_tokens``.
@@ -273,11 +327,33 @@ class PrimeRlServingTokens(ServingTokens):
)
result_generator = capture
# Always capture the final ``RequestOutput`` so we can attach a
# ``usage`` block to the response. The router parses ``usage`` for
# per-run billing metrics; without it the cache-discount counter
# (``vllm_router_run_cached_prompt_tokens_total``) stays at zero.
final_capture = _FinalOutputCapture(result_generator)
result_generator = final_capture
response = await super().serve_tokens_full_generator(
request, result_generator, request_id, model_name, request_metadata
)
if capture is not None and isinstance(response, GenerateResponse):
if not isinstance(response, GenerateResponse):
return response
if capture is not None:
response = capture.post_process(response)
elif not isinstance(response, PrimeRlGenerateResponse):
# Upgrade to the prime-rl subclass so the declared ``usage`` field
# actually surfaces in JSON (the parent class would drop it).
response = PrimeRlGenerateResponse(
request_id=response.request_id,
choices=[PrimeRlGenerateResponseChoice(**choice.model_dump()) for choice in response.choices],
prompt_logprobs=response.prompt_logprobs,
kv_transfer_params=response.kv_transfer_params,
)
if final_capture.final_res is not None:
response.usage = _build_usage(final_capture.final_res)
return response
+36 -68
View File
@@ -4,21 +4,17 @@ from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable
import torch
import verifiers as vf
from jaxtyping import Float
from torch import Tensor
if TYPE_CHECKING:
from prime_rl.orchestrator.types import TrainRollout
import verifiers.v1 as vf
from prime_rl.orchestrator.types import Rollout
from prime_rl.configs.orchestrator import (
AdvantageConfig,
CustomAdvantageConfig,
LengthPenaltyConfig,
TokensLengthPenaltyConfig,
TurnsLengthPenaltyConfig,
LinearLengthPenaltyConfig,
)
from prime_rl.orchestrator.utils import get_model_completion_len, get_tool_response_len
from prime_rl.utils.utils import import_object
@@ -26,7 +22,7 @@ from prime_rl.utils.utils import import_object
class AdvantageInputs:
"""Inputs for advantage computation of a single group (one example × N rollouts)."""
rollouts: list[vf.RolloutOutput]
rollouts: list[vf.Trace]
@dataclass
@@ -50,68 +46,36 @@ entry per rollout. `assign_advantages` calls it on one already-grouped cohort.
def default_advantage_fn(
inputs: AdvantageInputs,
length_penalty: LengthPenaltyConfig | None = None,
length_penalty: LinearLengthPenaltyConfig | None = None,
max_seq_len: int | None = None,
length_weighted_baseline: bool = False,
) -> AdvantageOutputs:
"""Default GRPO advantage for a single group: reward minus per-group baseline.
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
cost: tokens (weighted completion + tool-response) or trajectory turn count.
``length_penalty`` subtracts ``coef * pass_rate * (completion tokens / max_seq_len)``
from each reward (``pass_rate`` = group mean reward), optionally gated to correct
(``reward == 1``) rollouts. ``length_weighted_baseline`` uses the token-length-weighted
mean reward as the baseline instead of the plain mean.
"""
rewards = torch.tensor([r["reward"] for r in inputs.rollouts], dtype=torch.float32)
rewards = torch.tensor([r.reward for r in inputs.rollouts], dtype=torch.float32)
lengths = torch.tensor([r.completion_len for r in inputs.rollouts], dtype=rewards.dtype)
if isinstance(length_penalty, TokensLengthPenaltyConfig):
w_c = length_penalty.completion_weight
w_t = length_penalty.tool_response_weight
costs = torch.tensor(
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in inputs.rollouts],
dtype=rewards.dtype,
)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
costs = torch.tensor([len(r["trajectory"]) for r in inputs.rollouts], dtype=rewards.dtype)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
if length_penalty is not None:
if max_seq_len is None:
raise ValueError("max_seq_len is required when length_penalty is enabled")
penalty = length_penalty.coef * rewards.mean() * (lengths / max_seq_len)
if length_penalty.gate_by_correctness:
penalty = penalty * rewards
rewards = rewards - penalty
return AdvantageOutputs(advantages=(rewards - rewards.mean()).tolist())
if length_weighted_baseline:
baseline = (lengths * rewards).sum() / lengths.sum()
else:
baseline = rewards.mean()
return AdvantageOutputs(advantages=(rewards - baseline).tolist())
def _efficiency_shaping(
rewards: Float[Tensor, "group_size"],
costs: Float[Tensor, "group_size"],
) -> Float[Tensor, "group_size"]:
"""Correctness-gated efficiency shaping with bounded advantages.
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
preserving zero-mean advantages within the group. `costs` is a per-rollout cost
(e.g., completion length in tokens or number of turns).
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
"""
max_reward = rewards.max()
correct_mask = rewards >= max_reward
num_correct = correct_mask.sum()
# No shaping when max reward is 0 — no correct rollouts to differentiate
if max_reward <= 0:
return rewards - rewards.mean()
# Mean cost of correct rollouts
mean_correct_cost = (costs * correct_mask).sum() / num_correct.clamp(min=1)
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
if mean_correct_cost <= 0:
return rewards - rewards.mean()
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
shaped_rewards = rewards * (1 + bonus * correct_mask)
return shaped_rewards - shaped_rewards.mean()
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
def setup_advantage_fn(config: AdvantageConfig, max_seq_len: int | None = None) -> AdvantageFn:
"""Setup advantage function from config."""
if isinstance(config, CustomAdvantageConfig):
custom_fn = import_object(config.import_path)
@@ -123,25 +87,29 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
return advantage_fn
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
return default_advantage_fn(inputs, length_penalty=config.length_penalty)
return default_advantage_fn(
inputs,
length_penalty=config.length_penalty,
max_seq_len=max_seq_len,
length_weighted_baseline=config.length_weighted_baseline,
)
return advantage_fn
def assign_advantages(
rollouts: list["TrainRollout"], # noqa: F821 (forward ref)
rollouts: list[Rollout],
advantage_fn: AdvantageFn | None,
) -> None:
"""Compute and assign advantages for one finished group of rollouts
(``TrainSink.process_group`` hands in a single group's surviving rollouts).
``advantage_fn=None`` is the trivial case (advantage = reward); a custom
``advantage_fn`` receives the raw ``vf.RolloutOutput``\\ s via
``AdvantageInputs.rollouts``.
``advantage_fn`` receives the ``vf.Trace``\\ s via ``AdvantageInputs.rollouts``.
"""
if advantage_fn is None:
for rollout in rollouts:
rollout.advantage = rollout.reward
return
result = advantage_fn(AdvantageInputs(rollouts=[r.raw for r in rollouts]))
result = advantage_fn(AdvantageInputs(rollouts=[r for r in rollouts]))
for rollout, advantage in zip(rollouts, result.advantages):
rollout.advantage = advantage
+80 -98
View File
@@ -6,13 +6,16 @@
- Emit-everything invariant: every dispatched rollout eventually reaches
``out_q`` exactly once as a ``TrainRollout`` / ``EvalRollout``. Failures
(env error, empty trajectory, task exception, off-policy cancel) carry
``raw["error"]`` set; sinks decide drop / partial-train policy.
``trace.error`` set; sinks decide drop / partial-train policy.
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
schedule next. Transitions are level-triggered (driven by the eval
source's emptiness), so in-flight rollouts of the opposite kind drain
naturally on either side of an eval boundary.
- ``on_new_version`` (called by the watcher) bumps ``off_policy_steps`` on
every in-flight rollout and drops groups past ``max_off_policy_steps``.
- ``on_version_pending`` (called by the watcher before the engines pause for
the weight update) bumps ``off_policy_steps`` on in-flight train rollouts and
drops groups past ``max_off_policy_steps``.
Eval rollouts are measurements for the policy version they started with,
so they are allowed to finish even if training advances.
Cancellations surface as synthetic ``Cancelled`` markers so the sink's
count-to-``group_size`` finalization still fires.
"""
@@ -26,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
@@ -114,7 +115,7 @@ class RolloutDispatcher:
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules
rollouts under shared capacity, and emits ``FinishedRollout``\\ s to
``out_q``. The watcher drives ``on_new_version`` for off-policy
``out_q``. The watcher drives ``on_version_pending`` for off-policy
cancellation; the orchestrator triggers eval epochs."""
def __init__(
@@ -131,6 +132,7 @@ class RolloutDispatcher:
tasks_per_minute: float | None,
max_off_policy_steps: int,
training_mode: Literal["rl", "opd", "sft"],
use_cache_salt: bool = True,
) -> None:
self.policy = policy
self.train_envs = train_envs
@@ -142,6 +144,7 @@ class RolloutDispatcher:
self.train_source = train_source
self.eval_source = eval_source
self.training_mode = training_mode
self.use_cache_salt = use_cache_salt
self.max_off_policy_steps = max_off_policy_steps
self.max_inflight = max_inflight_rollouts
@@ -154,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
@@ -259,35 +262,44 @@ class RolloutDispatcher:
await safe_cancel(self.task)
self.task = None
async def on_new_version(self, step: int) -> None:
async def on_version_pending(self, step: int) -> None:
"""Bump off-policy counters and drop groups past
``max_off_policy_steps`` (drop_group emits ``Cancelled`` markers so
the sink still finalizes the partial group)."""
stale_groups: dict[uuid.UUID, RolloutKind] = {}
cancelled_by_kind: dict[RolloutKind, int] = {"train": 0, "eval": 0}
the sink still finalizes the partial group). Eval rollouts are not
aged because they are tied to their start-time policy version.
Runs *before* the inference engines are paused for the weight update so
the resulting aborts are processed while the engine is still stepping —
otherwise the orphaned KV transfers crash the decode engine on resume
(see ``WeightWatcher.apply_policy_update``)."""
stale_groups: set[uuid.UUID] = set()
cancelled = 0
for meta in self.inflight.values():
if meta.kind != "train":
continue
meta.off_policy_steps += 1
if meta.off_policy_steps > self.max_off_policy_steps:
stale_groups[meta.group_id] = meta.kind
stale_groups.add(meta.group_id)
for gid, kind in stale_groups.items():
for gid in stale_groups:
removed = await self.drop_group(gid)
cancelled_by_kind[kind] += removed
cancelled += removed
for kind in ("train", "eval"):
n = cancelled_by_kind[kind]
if n:
get_logger().warning(
f"Cancelled {n} {kind} rollouts past max_off_policy_steps={self.max_off_policy_steps}. "
"Consider increasing it to avoid this."
)
if cancelled:
get_logger().warning(
f"Cancelled {cancelled} train rollouts past max_off_policy_steps={self.max_off_policy_steps}. "
"Consider increasing it to avoid this."
)
async def on_new_version(self, step: int) -> None:
"""No-op: the dispatcher drains in ``on_version_pending`` (pre-pause)."""
async def fill_inflight(self) -> None:
"""Schedule new rollouts up to ``max_inflight``, honoring
``self.mode``. When ``PREFER_EVAL``'s source exhausts we flip back
to ``PREFER_TRAIN`` so the eval tail drains alongside fresh train."""
if not self.dispatch_allowed.is_set():
return
``self.mode``. Eval scheduling ignores the orchestrator's dispatch
gate (evals are version-pinned measurements); only train scheduling
respects it. When ``PREFER_EVAL``'s source exhausts we flip back to
``PREFER_TRAIN`` so the eval tail drains alongside fresh train."""
while True:
if self.available_permits <= 0:
return
@@ -308,7 +320,9 @@ class RolloutDispatcher:
scheduled = await self.try_schedule("eval")
if not scheduled:
return
else: # PREFER_TRAIN
else: # PREFER_TRAIN — respects the orchestrator's dispatch gate
if not self.dispatch_allowed.is_set():
return
scheduled = await self.try_schedule("train")
if not scheduled:
return
@@ -366,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,
@@ -408,13 +422,10 @@ class RolloutDispatcher:
if env_collection is None:
return False
env = env_collection.get(group.env_name)
# SFT-mode train rollouts hit the frozen teacher pool; salting per
# policy version would invalidate the teacher's prefix cache every
# weight update for no reason.
if self.training_mode == "sft" and group.kind == "train":
cache_salt = None
else:
if group.kind == "eval" or self.use_cache_salt:
cache_salt = str(group.policy_version_at_start)
else:
cache_salt = None
if env.requires_group_scoring:
permits = group.rollouts_to_schedule
@@ -423,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,
@@ -436,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,
)
@@ -480,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
@@ -590,15 +564,19 @@ class RolloutDispatcher:
last_meta: InflightRollout | None = claimed[-1][1] if claimed else None
for _, meta in claimed:
for _ in range(meta.rollout_count):
raw = self.error_rollout_output(error_type="Cancelled", error_repr="Off-policy cancel")
await self.emit_rollout(meta, group, raw)
trace = Rollout(
task=vf.Task(idx=task_idx, prompt=None),
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
stop_condition="error",
)
await self.emit_rollout(meta, group, trace)
# For non-group-scoring envs, the group may have rollouts that
# were never dispatched (``rollouts_to_schedule > 0``). Emit
# markers for those too so the sink hits ``target_rollouts``
#
# ``last_meta`` can be ``None`` if the only inflight task for this
# group completed naturally between ``on_new_version``'s snapshot
# group completed naturally between ``on_version_pending``'s snapshot
# and us reaching it — synthesize a stand-in from the group state
unscheduled_cancelled = 0
if group is not None and group.rollouts_to_schedule > 0:
@@ -612,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():
+160 -268
View File
@@ -1,38 +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 time
from collections.abc import Awaitable, Callable, Iterator, Sequence
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 pandas as pd
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.eval_utils import compute_pass_at_k
from prime_rl.utils.logger import ProgressTracker, get_logger
from prime_rl.utils.monitor import get_monitor
from prime_rl.utils.utils import capitalize
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
@@ -40,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:
@@ -167,12 +202,13 @@ class Env:
class TrainEnv(Env):
config: TrainEnvConfig
def __init__(self, config: TrainEnvConfig):
def __init__(self, config: TrainEnvConfig, max_seq_len: int):
super().__init__(config)
self.sampling_args = config.sampling.to_sampling_args()
def get_dataset(self, seed: int | None = None):
return self.env.get_dataset(seed=seed)
# 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
)
class EvalEnv(Env):
@@ -181,148 +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 evaluate(
self,
model_name: str,
get_client: Callable[[], Awaitable[vf.ClientConfig]],
step: int,
cache_salt: str,
) -> list[vf.RolloutOutput]:
num_examples = len(self.examples)
group_size = self.config.group_size
get_logger().info(f"Evaluating {self.name} ({num_examples=}, {group_size=})")
total_rollouts = num_examples * group_size
pbar = ProgressTracker(total=total_rollouts, desc=f"Evaluating {self.name}")
eval_start = time.perf_counter()
if self.requires_group_scoring:
async def run_with_progress(example: dict) -> list[vf.RolloutOutput] | None:
"""Run group_size rollouts as a scored group for one example."""
try:
client = await get_client()
outputs = await self.run_group(
client=client,
example=example,
model_name=model_name,
group_size=group_size,
cache_salt=cache_salt,
)
pbar.update(group_size)
return outputs
except Exception as e:
get_logger().warning(f"Group failed: {e}")
pbar.update(group_size)
return None
coros = [run_with_progress(example) for example in self.examples]
else:
async def run_with_progress(example: dict) -> list[vf.RolloutOutput] | None:
"""Run a single rollout for one example."""
try:
client = await get_client()
output = await self.run_rollout(
client=client, example=example, model_name=model_name, cache_salt=cache_salt
)
pbar.update(1)
return [output]
except Exception as e:
get_logger().warning(f"Rollout failed: {e}")
pbar.update(1)
return None
coros = [run_with_progress(example) for example in self.examples for _ in range(group_size)]
try:
results = await asyncio.gather(*coros)
finally:
pbar.close()
successful_outputs = [o for group in results if group is not None for o in group]
failed_count = total_rollouts - len(successful_outputs)
eval_time = time.perf_counter() - eval_start
if failed_count:
get_logger().warning(
f"{failed_count}/{total_rollouts} ({failed_count / total_rollouts * 100:.1f}%) rollouts failed"
)
if not successful_outputs:
get_logger().warning(f"All rollouts failed for {self.name}, skipping logging metrics")
get_monitor().log(
{
f"eval/{self.name}/failed_rollouts": failed_count / total_rollouts,
"step": step,
},
step=step,
)
return []
# Log metrics
monitor = get_monitor()
rows = [
{
"example_id": o["example_id"],
"reward": o["reward"],
"completion_len": o["token_usage"]["final_output_tokens"],
"is_truncated": o["is_truncated"],
"has_error": o.get("error") is not None,
"no_response": not o.get("completion"),
}
for o in successful_outputs
]
results_df = pd.DataFrame(rows)
unique_rewards = results_df.reward.dropna().unique()
could_be_binary = set(unique_rewards).issubset({0.0, 1.0})
if could_be_binary:
pass_at_k = (
results_df.groupby("example_id")
.apply(lambda x: compute_pass_at_k(x.reward.dropna()), include_groups=False)
.apply(pd.Series)
)
else:
pass_at_k = None
get_logger().warning("Skipping computing pass@k rates because the task rewards appear to be non-binary")
message = f"Evaluated {self.name} in {eval_time:.2f}s (Avg@{group_size}={results_df.reward.mean():.4f}"
if could_be_binary:
assert pass_at_k is not None
for pass_rate, pass_rate_score in pd.Series(pass_at_k.mean()).items():
message += f", {capitalize(str(pass_rate))}: {pass_rate_score:.4f}"
message += (
f", No-response: {results_df.no_response.mean() * 100:.1f}%"
f", Completion Length: {results_df.completion_len.mean():.2f} (±{results_df.completion_len.std():.2f}, ∈[{results_df.completion_len.min():.2f}, {results_df.completion_len.max():.2f}])"
f", Truncated: {results_df.is_truncated.mean() * 100:.1f}%)"
)
get_logger().success(message)
eval_metrics = {
f"avg@{group_size}": float(results_df.reward.mean()),
"no_response/mean": float(results_df.no_response.mean()),
"no_response/count": int(results_df.no_response.sum()),
"completion_len/mean": results_df.completion_len.mean().item(),
"completion_len/max": results_df.completion_len.max().item(),
"completion_len/min": results_df.completion_len.min().item(),
"is_truncated/mean": results_df.is_truncated.mean().item(),
"failed_rollouts": failed_count / total_rollouts,
"time": eval_time,
}
if could_be_binary:
assert pass_at_k is not None
eval_metrics.update(pd.Series(pass_at_k.mean()).to_dict())
eval_metrics = {f"eval/{self.name}/{key}": v for key, v in eval_metrics.items()}
eval_metrics["step"] = step
monitor.log(eval_metrics, step=step)
monitor.log_eval_samples(successful_outputs, env_name=self.name, step=step)
return successful_outputs
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)
@@ -350,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
@@ -387,10 +279,10 @@ class Envs(Generic[EnvT]):
class TrainEnvs(Envs[TrainEnv]):
"""Collection of training environments."""
def __init__(self, configs: Sequence[TrainEnvConfig]):
def __init__(self, configs: Sequence[TrainEnvConfig], max_seq_len: int):
self._envs: dict[str, TrainEnv] = {}
for config in configs:
env = TrainEnv(config)
env = TrainEnv(config, max_seq_len=max_seq_len)
self._envs[env.name] = env
+16 -16
View File
@@ -18,7 +18,7 @@ from collections import defaultdict
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.eval_utils import compute_pass_at_k
from prime_rl.orchestrator.types import EvalBatch, EvalBatchMetrics, EvalRollout
from prime_rl.orchestrator.types import EvalBatch, EvalBatchMetrics, Rollout
from prime_rl.utils.logger import get_logger
@@ -27,12 +27,12 @@ class EvalSink:
def __init__(self, *, eval_envs: EvalEnvs) -> None:
self.eval_envs = eval_envs
self.pending_groups: dict[uuid.UUID, list[EvalRollout]] = defaultdict(list)
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
# Bucket size IS the arrival count — ``process_group`` flushes
# everything in without filtering
self.pending_batches: dict[tuple[str, int], list[EvalRollout]] = defaultdict(list)
self.pending_batches: dict[tuple[str, int], list[Rollout]] = defaultdict(list)
def add(self, rollout: EvalRollout) -> EvalBatch | None:
def add(self, rollout: Rollout) -> EvalBatch | None:
"""Process one arrival; finalize the group on the ``group_size``-th
arrival and the per-env epoch on the ``num_examples × group_size``-th."""
env_name = rollout.env_name
@@ -82,7 +82,7 @@ class EvalSink:
# ── level 1: per-rollout (no-op for eval) ─────────────────────────────
def process_rollout(self, rollout: EvalRollout) -> None:
def process_rollout(self, rollout: Rollout) -> None:
"""No-op. Eval rollouts don't need trainer-bound tokenization; the
method exists to keep the three-level structure uniform with
``TrainSink``.
@@ -96,17 +96,17 @@ class EvalSink:
if not group:
return
env_name = group[0].env_name
example_id = group[0].example_id
task_idx = group[0].task.idx
eval_step = group[0].eval_step
bucket = self.pending_batches[(env_name, eval_step)]
bucket.extend(group)
survivors = [r for r in group if r.error is None]
survivors = [r for r in group if not r.has_error]
num_errored = len(group) - len(survivors)
rewards = [r.reward for r in survivors]
avg_reward = sum(rewards) / len(rewards) if rewards else 0.0
get_logger().debug(
f"Finished group | env={env_name} example_id={example_id} eval_step={eval_step} | "
f"Finished group | env={env_name} task_idx={task_idx} eval_step={eval_step} | "
f"rollouts={len(group)} (errored={num_errored}) | reward={avg_reward:.4f}"
)
@@ -120,9 +120,9 @@ class EvalSink:
rollouts = self.pending_batches.pop(key, [])
n_total = len(rollouts)
n_cancelled = sum(1 for r in rollouts if (r.error or {}).get("error") == "Cancelled")
n_errored = sum(1 for r in rollouts if r.error is not None) - n_cancelled
valid = [r for r in rollouts if r.error is None]
n_cancelled = sum(1 for r in rollouts if r.has_error and r.error.type == "Cancelled")
n_errored = sum(1 for r in rollouts if r.has_error) - n_cancelled
valid = [r for r in rollouts if not r.has_error]
metrics = EvalBatchMetrics(
n_rollouts=n_total,
n_cancelled=n_cancelled,
@@ -131,23 +131,23 @@ class EvalSink:
if valid:
rewards = [r.reward for r in valid]
lens = [r.raw["token_usage"]["final_output_tokens"] for r in valid]
lens = [r.completion_len for r in valid]
metrics.group_size = self.group_size_for(env_name)
metrics.reward_mean = float(sum(rewards) / len(rewards))
metrics.completion_len_mean = float(sum(lens) / len(lens))
metrics.completion_len_max = float(max(lens))
metrics.completion_len_min = float(min(lens))
metrics.truncation_rate = float(sum(1 for r in valid if r.is_truncated) / len(valid))
metrics.no_response_rate = float(sum(1 for r in valid if not r.raw.get("completion")) / len(valid))
num_turns = [len(r.raw.get("trajectory") or []) for r in valid]
metrics.no_response_rate = float(sum(1 for r in valid if not r.has_response) / len(valid))
num_turns = [r.num_turns for r in valid]
metrics.num_turns_mean = float(sum(num_turns) / len(num_turns))
metrics.num_turns_min = float(min(num_turns))
metrics.num_turns_max = float(max(num_turns))
# pass@k: errored attempts don't count toward k tries
by_example: dict[int | str, list[float]] = {}
by_example: dict[int, list[float]] = {}
for r in valid:
by_example.setdefault(r.example_id, []).append(r.reward)
by_example.setdefault(r.task.idx, []).append(r.reward)
metrics.n_examples = len(by_example)
unique_rewards = {float(r) for r in rewards}
if unique_rewards.issubset({0.0, 1.0}) and by_example:
+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
+16 -28
View File
@@ -7,7 +7,7 @@ from typing import Any
import pandas as pd
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.types import Progress, TrainBatchMetrics, TrainRollout
from prime_rl.orchestrator.types import Progress, Rollout, TrainBatchMetrics
class MetricsBuilder:
@@ -18,7 +18,7 @@ class MetricsBuilder:
self,
*,
step: int,
rollouts: list[TrainRollout],
rollouts: list[Rollout],
metrics: TrainBatchMetrics,
progress: Progress,
step_time: float,
@@ -32,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)
@@ -182,18 +177,11 @@ class MetricsBuilder:
return to_log
@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)
+64 -64
View File
@@ -21,8 +21,6 @@ in ``setup()`` and drives them from ``main_loop()``.
from __future__ import annotations
import asyncio
import ctypes
import logging
import os
import time
from typing import TYPE_CHECKING
@@ -37,8 +35,6 @@ if TYPE_CHECKING:
from prime_rl.transport.base import TrainingBatchSender
from prime_rl.utils.client import InferencePool
from prime_rl.utils.monitor.base import Monitor
from verifiers.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
@@ -58,12 +54,10 @@ from prime_rl.orchestrator.train_sink import TrainSink
from prime_rl.orchestrator.train_source import TrainSource
from prime_rl.orchestrator.types import (
EvalBatch,
EvalRollout,
FinishedRollout,
Policy,
Progress,
Rollout,
TrainBatch,
TrainRollout,
)
from prime_rl.orchestrator.utils import (
compute_teacher_logprobs,
@@ -72,11 +66,12 @@ from prime_rl.orchestrator.utils import (
save_rollouts,
set_default_executor,
setup_student_inference_pool,
trim_process_memory,
)
from prime_rl.orchestrator.watcher import WeightWatcher
from prime_rl.trainer.model import setup_tokenizer
from prime_rl.transport import TrainingBatch, setup_training_batch_sender
from prime_rl.utils.async_utils import safe_cancel
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
from prime_rl.utils.client import init_nccl_broadcast, setup_inference_pool
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
@@ -85,8 +80,6 @@ from prime_rl.utils.pathing import get_log_dir, get_rollout_dir, get_step_path
from prime_rl.utils.usage_reporter import UsageReporter
from prime_rl.utils.utils import (
clean_exit,
get_env_ids_to_install,
install_env,
resolve_latest_ckpt_step,
)
@@ -108,6 +101,13 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
# resumed when the watcher advances ``policy.version``.
TARGET_LAG = 1
# 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:
# Set in ``__init__``
@@ -153,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:
@@ -206,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)
@@ -237,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})")
@@ -263,7 +260,7 @@ class Orchestrator:
post_filters = setup_filters(config.post_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="post-batch")
get_logger().info("Loading training environments")
self.train_envs = TrainEnvs(config.train.env)
self.train_envs = TrainEnvs(config.train.env, max_seq_len=config.seq_len)
if config.training_mode == "sft":
for env in self.train_envs:
env.sampling_args.pop("logprobs", None)
@@ -345,13 +342,14 @@ class Orchestrator:
else:
get_logger().info("Training from scratch")
# SFT generates rollouts via the teacher (the student is trained on
# the teacher's outputs); RL / OPD generate via the student
if config.training_mode == "sft":
assert self.teacher_inference is not None, "sft mode requires teacher inference"
# SFT train rollouts come from the teacher when configured; otherwise
# they use the existing student rollout pool.
if config.training_mode == "sft" and self.teacher_inference is not None:
rollout_inference = self.teacher_inference
use_cache_salt = False
else:
rollout_inference = self.student_inference
use_cache_salt = True
self.train_source = TrainSource(self.train_envs, seed=42)
self.eval_source: EvalSource | None = (
@@ -379,17 +377,16 @@ class Orchestrator:
tasks_per_minute=config.tasks_per_minute,
max_off_policy_steps=config.max_off_policy_steps,
training_mode=config.training_mode,
use_cache_salt=use_cache_salt,
)
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,
token_batch_size=config.token_batch_size,
advantage_config=config.advantage,
pre_filters=pre_filters,
post_filters=post_filters,
)
@@ -475,10 +472,7 @@ class Orchestrator:
get_logger().success("Orchestrator finished.")
else:
get_logger().warning("Orchestrator cleanup complete (forced).")
try:
ctypes.CDLL("libc.so.6").malloc_trim(0)
except Exception as e:
get_logger().debug(f"malloc_trim(0) failed: {e}")
trim_process_memory()
async def main_loop(self) -> None:
"""Consume ``FinishedRollout``\\ s from the dispatcher and route them
@@ -491,18 +485,17 @@ 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:
self.finalize_eval_batch(eval_batch)
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``
@@ -555,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:
@@ -578,6 +569,7 @@ class Orchestrator:
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
self.update_dispatch_gate()
trim_process_memory()
metrics = self.metrics.build(
step=step,
@@ -592,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],
@@ -614,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
@@ -627,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
@@ -724,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:
@@ -748,46 +739,51 @@ 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))
def finalize_eval_batch(self, batch: EvalBatch) -> None:
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch (save_rollouts,
monitor.log_eval_samples, monitor.log)."""
if not batch.rollouts:
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)
save_rollouts(
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(batch.metrics.to_wandb_dict(env_name=batch.env_name, step=batch.step), 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:
get_logger().warning(
f"Eval {batch.env_name} step {batch.step} had mixed policy versions: {sorted(policy_versions)}"
)
metrics = batch.metrics.to_wandb_dict(env_name=batch.env_name, step=batch.step)
metrics[f"eval/{batch.env_name}/policy_version"] = float(policy_version)
self.monitor.log(metrics, step=batch.step)
n_total = batch.metrics.n_rollouts
error_rate = ((batch.metrics.n_cancelled + batch.metrics.n_errored) / n_total) if n_total else 0.0
max_off_policy = max((r.off_policy_steps for r in batch.rollouts), default=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"{format_time(elapsed):>7} | Reward {batch.metrics.reward_mean:.4f} | "
f"Turns {batch.metrics.num_turns_mean:.1f} | Max Off-Policy {max_off_policy} | "
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {batch.metrics.reward_mean:.4f} | "
f"Turns {batch.metrics.num_turns_mean:.1f} | Branches {branches_mean:.1f} | "
f"Error {error_rate:.1%} | Truncation {batch.metrics.truncation_rate:.1%}"
)
@@ -832,6 +828,10 @@ class Orchestrator:
get_logger().info("Resuming dispatcher")
gate.set()
async def on_version_pending(self, step: int) -> None:
"""No-op: the dispatch gate is re-evaluated in ``on_new_version`` once
the new policy version is live."""
async def on_new_version(self, step: int) -> None:
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
+42 -60
View File
@@ -17,16 +17,12 @@ import asyncio
import uuid
from collections import defaultdict
from prime_rl.configs.orchestrator import AdvantageConfig, OrchestratorConfig
from prime_rl.orchestrator.advantage import assign_advantages, setup_advantage_fn
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,12 +35,10 @@ class TrainSink:
config: OrchestratorConfig,
*,
tokenizer,
renderer,
train_envs: TrainEnvs,
mm_token_type_ids_mapping: dict[int, int] | None,
batch_size: int | None,
token_batch_size: int | None,
advantage_config: AdvantageConfig | None,
pre_filters: list[RolloutFilter],
post_filters: list[RolloutFilter],
) -> None:
@@ -53,22 +47,22 @@ 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
self.token_batch_size = token_batch_size
# Built once — custom advantage funcs do an ``import_object`` and
# we don't want to pay that per group. ``None`` = reward-only path
self.advantage_fn = setup_advantage_fn(advantage_config) if advantage_config is not None else None
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
@@ -83,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
@@ -107,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
@@ -126,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):
@@ -140,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
@@ -180,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
@@ -189,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.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:
@@ -213,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)
@@ -233,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``
@@ -240,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}"
)
@@ -259,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)
@@ -282,8 +264,8 @@ class TrainSink:
prefill = 0
decode = 0
for sample in r.samples:
sample_decode = sum(sample.completion_mask)
sample_prefill = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode
sample_decode = sum(sample.mask)
sample_prefill = len(sample.token_ids) - sample_decode
decode += sample_decode
prefill += sample_prefill
if not r.is_filtered:
+4 -6
View File
@@ -14,7 +14,7 @@ class TrainSource:
"""``next_example(available_permits)`` picks a weighted-RR env and
returns its next example (or ``None`` when the env's per-call permit
cost doesn't fit — the dispatch loop retries when permits free up).
Returned dicts carry ``env_name`` + ``example_id``."""
Returned dicts carry ``env_name`` + ``task_idx``."""
def __init__(self, train_envs: TrainEnvs, *, seed: int | None) -> None:
self.rng = random.Random(seed)
@@ -28,11 +28,9 @@ class TrainSource:
# per-rollout envs need 1
self.env_costs: dict[str, int] = {}
for env in self.envs:
rows: list[dict] = []
for row in env.get_dataset(seed=seed):
ex = dict(row)
ex["env_name"] = env.name
rows.append(ex)
# The orchestrator never loads the env: sample over the task-index
# range the server reported via info() (num_tasks).
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
self.rng.shuffle(rows)
self.examples[env.name] = rows
self.cursors[env.name] = 0
+97 -634
View File
@@ -1,652 +1,115 @@
import base64
import hashlib
from pathlib import Path
from typing import Any
"""Turn a v1 `Trace` (the env server's native, typed output) into training data.
The orchestrator holds a real `vf.Trace` (validated in `envs.py`), so everything here is
attribute access — no dicts. The trace is a message graph (`trace.nodes`); each `trace.branches`
entry (a root→leaf path) is first-class and carries its own flat token sequence
(`branch.token_ids` / `branch.sampled_mask` / `branch.logprobs`), so a branch yields one
training sample directly. Token-length readers (`completion_len`, `total_tokens`, `num_turns`)
live on `vf.Trace` itself.
Training is renderer-only across every mode (RL/OPD student, SFT teacher), so every node
always carries its tokens — no backfill needed. For multimodal rollouts the branch also carries
the images it introduced (`branch.multi_modal_data`), rebuilt here into the flat `mm_kwargs` /
`mm_token_type_ids` the trainer forwards.
"""
from __future__ import annotations
import numpy as np
import pybase64
import torch
import verifiers as vf
from transformers.tokenization_utils import PreTrainedTokenizer
import verifiers.v1 as vf
from prime_rl.transport import RoutedExperts, TrainingSample
from prime_rl.utils.chat_template import (
common_prefix_len,
deserialize_tool_calls,
normalize_messages,
render_messages,
strip_message_content,
)
from prime_rl.transport import TrainingSample
from prime_rl.transport.types import EncodedTensor, RoutedExperts
from prime_rl.utils.logger import get_logger
# We use list() instead of deepcopy() for flat lists (token IDs, logprobs) - safe because
# primitives are immutable. mm_kwargs payloads are not mutated after creation.
def _to_numpy(val) -> np.ndarray:
"""A renderer mm item value (torch tensor or numpy array) -> a contiguous numpy array."""
if hasattr(val, "detach"): # torch tensor
val = val.detach().cpu().numpy()
return np.ascontiguousarray(val)
def align_routed_experts(
routed_experts: np.ndarray | None,
expected_len: int,
) -> np.ndarray | None:
"""Align routed_experts length with the expected token count.
VLLM's capturer uses `num_tokens - 1` slot mappings because the final
generated token was never fed as input to a forward pass and has no
routing decision. Append zero-filled entries for the missing positions.
"""
if routed_experts is None:
return routed_experts
assert routed_experts.ndim == 3
if routed_experts.shape[0] > expected_len:
return np.ascontiguousarray(routed_experts[:expected_len])
deficit = expected_len - routed_experts.shape[0]
if deficit <= 0:
return routed_experts
padding = np.zeros((deficit, routed_experts.shape[1], routed_experts.shape[2]), dtype=routed_experts.dtype)
return np.concatenate((routed_experts, padding), axis=0)
def _encode_mm_kwargs(mm_items: dict[str, list[dict]]) -> dict[str, EncodedTensor] | None:
"""Concatenate the branch's per-image renderer items into the flat `mm_kwargs` the trainer
forwards — one `EncodedTensor` per kwarg key (e.g. `pixel_values`, `image_grid_thw`), images
cat'd along dim 0 in branch token order. Model-agnostic: the keys are whatever the processor
emits. Returns None when there are no items."""
bins: dict[str, list[np.ndarray]] = {}
for items in mm_items.values(): # per modality
for item in items: # per image
for key, val in item.items():
bins.setdefault(key, []).append(_to_numpy(val))
encoded: dict[str, EncodedTensor] = {}
for key, arrs in bins.items():
arr = np.concatenate(arrs, axis=0)
encoded[key] = EncodedTensor(dtype=str(arr.dtype), shape=list(arr.shape), data=arr.tobytes())
return encoded or None
def _common_prefix_len(a: list[int], b: list[int]) -> int:
return common_prefix_len(a, b)
def _normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
return normalize_messages(messages, default_role)
def _deserialize_tool_calls(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
return deserialize_tool_calls(messages)
def _strip_message_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
return strip_message_content(messages)
def _render_messages(
tokenizer: PreTrainedTokenizer,
messages: list[dict[str, Any]],
add_generation_prompt: bool = False,
tools: list[dict[str, Any]] | None = None,
) -> list[int]:
return render_messages(
tokenizer,
messages,
add_generation_prompt=add_generation_prompt,
tools=tools,
)
def _tokenize_step_from_messages(
step: vf.TrajectoryStep,
tokenizer: PreTrainedTokenizer,
tools: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
prompt = _normalize_messages(step.get("prompt"), default_role="user")
completion = _normalize_messages(step.get("completion"), default_role="assistant")
prompt = _strip_message_content(_deserialize_tool_calls(prompt))
completion = _strip_message_content(_deserialize_tool_calls(completion))
assert all(m.get("role") == "assistant" for m in completion), (
"Expected all completion messages to be assistant role for SFT distillation, "
f"got roles: {[m.get('role') for m in completion]}"
)
all_messages = prompt + completion
prompt_has_assistant_completion = len(completion) > 0 and completion[0].get("role") == "assistant"
prompt_ids = _render_messages(
tokenizer,
prompt,
add_generation_prompt=prompt_has_assistant_completion,
tools=tools,
)
full_ids = _render_messages(
tokenizer,
all_messages,
tools=tools,
)
split_idx = _common_prefix_len(prompt_ids, full_ids)
original_prompt_len = len(prompt_ids)
prompt_ids = full_ids[:split_idx]
completion_ids = full_ids[split_idx:]
completion_mask = [True] * len(completion_ids)
completion_logprobs = [0.0] * len(completion_ids)
return {
"prompt_ids": prompt_ids,
"prompt_mask": [False] * len(prompt_ids),
"completion_ids": completion_ids,
"completion_mask": completion_mask,
"completion_logprobs": completion_logprobs,
"routed_experts": None,
"prompt_prefix_len": split_idx,
"original_prompt_len": original_prompt_len,
}
def _convert_tools_to_oai_format(tool_defs: list) -> list[dict[str, Any]] | None:
"""Convert verifiers Tool objects or dicts to OAI function-calling format."""
if not tool_defs:
def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExperts | None:
"""The branch's router-replay array (`[tokens, layers, top_k]`) -> the transport
`RoutedExperts` the trainer replays. Defensively realigns the token axis to `num_tokens`
(the trainer asserts `routed_experts.shape[0] == len(token_ids)`): truncate if longer,
zero-pad the tail if shorter. `Branch.routed_experts` already guarantees alignment, so this
is a backstop."""
if arr is None:
return None
def _get(tool: Any, key: str) -> Any:
if isinstance(tool, dict):
return tool.get(key)
return getattr(tool, key, None)
return [
{
"type": "function",
"function": {
"name": _get(tool, "name"),
"description": _get(tool, "description"),
"parameters": _get(tool, "parameters"),
**({} if _get(tool, "strict") is None else {"strict": _get(tool, "strict")}),
},
}
for tool in tool_defs
]
arr = np.ascontiguousarray(arr)
if arr.shape[0] > num_tokens:
arr = arr[:num_tokens]
elif arr.shape[0] < num_tokens:
pad = np.zeros((num_tokens - arr.shape[0], *arr.shape[1:]), dtype=arr.dtype)
arr = np.concatenate([arr, pad], axis=0)
return RoutedExperts(data=arr.tobytes(), shape=list(arr.shape), dtype=str(arr.dtype))
def _tokenize_step_with_renderer(
step: vf.TrajectoryStep,
renderer,
tools: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""Tokenize a trajectory step using a Renderer."""
from renderers.base import build_trajectory_step
prompt = _normalize_messages(step.get("prompt"), default_role="user")
completion = _normalize_messages(step.get("completion"), default_role="assistant")
prompt = _strip_message_content(_deserialize_tool_calls(prompt))
completion = _strip_message_content(_deserialize_tool_calls(completion))
return build_trajectory_step(renderer, prompt, completion, tools=tools)
def backfill_rollout_tokens(
output: vf.RolloutOutput,
tokenizer: PreTrainedTokenizer,
renderer=None,
) -> bool:
"""Populate missing step tokens from prompt/completion messages.
When a renderer is provided, uses it for tokenization (faster, deterministic).
Otherwise falls back to the tokenizer + apply_chat_template path.
"""
if all(step["tokens"] is not None for step in output["trajectory"]):
return True
logger = get_logger()
tools = _convert_tools_to_oai_format(output.get("tool_defs", []))
for step_idx, step in enumerate(output["trajectory"]):
if step["tokens"] is not None:
continue
if renderer is not None:
step["tokens"] = _tokenize_step_with_renderer(step, renderer, tools=tools)
else:
reconstructed = _tokenize_step_from_messages(step, tokenizer, tools=tools)
if reconstructed["prompt_prefix_len"] < reconstructed["original_prompt_len"]:
logger.debug(
f"Prompt tokenization was non-prefix for example {output['example_id']} step {step_idx}. "
f"Using longest common prefix length {reconstructed['prompt_prefix_len']} "
f"(original prompt had {reconstructed['original_prompt_len']} tokens)."
)
reconstructed.pop("prompt_prefix_len")
reconstructed.pop("original_prompt_len")
step["tokens"] = reconstructed
return True
def interleave_rollout(
output: vf.RolloutOutput,
mm_token_type_ids_mapping: dict[int, int] | None = None,
def trace_to_samples(
trace: vf.Trace,
*,
env_name: str = "",
) -> list[TrainingSample] | None:
mm_token_type_ids_mapping: dict[int, int] | None = None,
) -> list[TrainingSample]:
"""Convert a v1 `Trace` into `TrainingSample`s — one per branch.
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
`branch.sampled_mask` / `branch.logprobs`), so a sample carries it directly: `mask` marks
the trainable (model-sampled) tokens, the context tokens between completions stay masked
out. On a rollout error the whole completion is masked out. A branch carrying images also
gets `mm_kwargs` (the concatenated pixel tensors) and `mm_token_type_ids` (the renderer's
`mm_token_type_id_map` applied to the branch tokens). Branches with no sampled tokens
(e.g. an openai client carrying none) yield nothing.
"""
Convert vf.RolloutOutput to trainable rollouts by interleaving trajectory steps
where the extension property holds.
When consecutive steps share token prefixes (extension property), they are
merged into a single sample. When extension breaks (e.g., due to context
compaction or a change in control-flow), a new sample is started.
Supports multi-prefix matching to handle interleaved agents. For example,
[agent1-step1, agent1-step2, agent2-step1, agent1-step3] produces two samples:
agent1 steps merged together, agent2 step separate.
Returns a list of samples - could be 1 (extension always held) or up to T
(extension never held).
For VLM models, each renderer-produced trajectory step carries its
per-image processed tensors inline on ``multi_modal_data``; the last
merged step's sidecar covers every image in the sample.
"""
logger = get_logger()
trajectory = output["trajectory"]
if len(trajectory) == 0:
error = output.get("error")
stop = output.get("stop_condition")
logger.warning(
f"No trajectory steps for example {output['example_id']} (error={error}, stop={stop}). Skipping rollout."
)
return None
has_error = output["error"] is not None
def prepare_step_tokens(step: vf.TrajectoryStep, step_idx: int) -> dict[str, Any] | None:
tokens = step["tokens"]
if tokens is not None:
routed_experts_payload = tokens.get("routed_experts")
routed_experts = None
routed_experts_start = None
if routed_experts_payload is not None:
decoded_routed_experts = pybase64.b64decode_as_bytearray(routed_experts_payload["data"])
routed_experts = np.frombuffer(decoded_routed_experts, dtype=np.uint8).reshape(
routed_experts_payload["shape"]
)
routed_experts_start = routed_experts_payload["start"]
return {
"prompt_ids": list(tokens["prompt_ids"]),
"prompt_mask": list(map(bool, tokens["prompt_mask"])),
"completion_ids": list(tokens["completion_ids"]),
"completion_mask": list(map(bool, tokens["completion_mask"])),
"completion_logprobs": list(tokens["completion_logprobs"]),
"routed_experts": routed_experts,
"routed_experts_start": routed_experts_start,
# Renderer-emitted multimodal sidecar (placeholders + per-item
# processed tensors). Populated when the rollout went through
# a multimodal-aware renderer (e.g. Qwen3VLRenderer); absent
# for text-only rollouts.
"multi_modal_data": tokens.get("multi_modal_data"),
}
logger.warning(f"Missing rollout tokens for example {output['example_id']} step {step_idx}.")
return None
prepared_steps: list[dict[str, Any]] = []
for step_idx, step in enumerate(trajectory):
prepared = prepare_step_tokens(step, step_idx)
if prepared is None:
return None
prepared_steps.append(prepared)
# Deferred routed_experts state per sample: O(N) chunk list concatenated
# once at finalize, replacing the prior O(N²) per-extension unpack/repack.
sample_routed_state: dict[int, dict[str, Any]] = {}
routed_prefix_states: dict[int, list[tuple[list[int], list[int], dict[str, Any]]]] = {}
# Track (prefix_tokens, sample, step_indices) per active sample. step_indices
# is the explicit list of prepared_steps positions merged into this sample —
# non-contiguous when other agents' steps interleave.
active_samples: list[tuple[list[int], TrainingSample, list[int]]] = []
def make_sample(tokens: dict[str, Any], step_idx: int) -> TrainingSample:
"""Create a new TrainingSample from a trajectory step."""
if has_error:
completion_mask = [False] * len(tokens["completion_mask"])
else:
completion_mask = list(tokens["completion_mask"])
completion_ids = list(tokens["completion_ids"])
prompt_ids = list(tokens["prompt_ids"])
sample = TrainingSample(
prompt_ids=prompt_ids,
prompt_mask=list(tokens["prompt_mask"]),
completion_ids=completion_ids,
completion_mask=completion_mask,
completion_logprobs=list(tokens["completion_logprobs"]),
completion_temperatures=[],
teacher_logprobs=None,
advantage=None,
env_name=env_name,
mm_token_type_ids=None,
routed_experts=None, # deferred — finalized at end of interleave_rollout
)
# Initialize routed-experts state for this sample. First chunk is the
# raw step routed_experts (no pad, no copy). running_len is the
# cumulative count across chunks; tracked so the boundary fix-up at
# each extension is a no-op append rather than a destructive write.
step_routed = tokens.get("routed_experts")
if step_routed is not None:
routed_start = tokens["routed_experts_start"]
assert routed_start is not None, f"Missing routed_experts_start for step {step_idx}"
chunks: list[np.ndarray] = []
running_len = 0
if routed_start > 0:
source_len = routed_start + 1
assert source_len in routed_prefix_states, (
f"Missing routed prefix state for step {step_idx}: "
f"routed_start={routed_start}, prompt_len={len(tokens['prompt_ids'])}"
)
source_state = None
for prompt_ids, completion_ids, candidate_state in routed_prefix_states[source_len]:
prompt_len = len(prompt_ids)
if (
tokens["prompt_ids"][:prompt_len] == prompt_ids
and tokens["prompt_ids"][prompt_len:source_len] == completion_ids
):
source_state = candidate_state
break
assert source_state is not None, (
f"No matching routed prefix for step {step_idx}: "
f"routed_start={routed_start}, prompt_len={len(tokens['prompt_ids'])}"
)
assert source_state["running_len"] >= routed_start, (
f"Routed prefix too short for step {step_idx}: "
f"running_len={source_state['running_len']}, routed_start={routed_start}"
)
remaining = routed_start
for chunk in source_state["chunks"]:
if remaining == 0:
break
take = min(remaining, int(chunk.shape[0]))
chunks.append(chunk[:take])
remaining -= take
assert remaining == 0, (
f"Could not reconstruct routed prefix for step {step_idx}: "
f"remaining={remaining}, routed_start={routed_start}"
)
running_len = routed_start
chunks.append(step_routed)
running_len += int(step_routed.shape[0])
sample_routed_state[id(sample)] = {
"chunks": chunks,
"running_len": running_len,
}
return sample
def extend_sample(
sample: TrainingSample,
prefix_len: int,
step_idx: int,
) -> None:
"""Extend an existing sample with a new trajectory step (extension property holds)."""
tokens = prepared_steps[step_idx]
# Extend with new prompt tokens (mask=False, no gradient)
new_prompt_ids = tokens["prompt_ids"][prefix_len:]
sample.completion_ids.extend(new_prompt_ids)
sample.completion_mask.extend([False] * len(new_prompt_ids))
sample.completion_logprobs.extend([0.0] * len(new_prompt_ids))
# Extend with new completion tokens
completion_ids = tokens["completion_ids"]
sample.completion_ids.extend(completion_ids)
if has_error:
sample.completion_mask.extend([False] * len(tokens["completion_mask"]))
else:
sample.completion_mask.extend(tokens["completion_mask"])
sample.completion_logprobs.extend(tokens["completion_logprobs"])
step_routed = tokens.get("routed_experts")
state = sample_routed_state.get(id(sample))
if state is not None:
assert step_routed is not None, f"Missing routed experts for routed sample extension at step {step_idx}"
if step_routed is not None:
assert state is not None, f"Unexpected routed experts for unrouted sample at step {step_idx}"
assert tokens["routed_experts_start"] == prefix_len - 1, (
f"Routed experts delta start mismatch at step {step_idx}: "
f"start={tokens['routed_experts_start']}, expected={prefix_len - 1}, prefix_len={prefix_len}"
)
# Delta payloads start at prefix_len - 1. Row 0 fills the boundary
# token missing from the previous request; the rest is the new suffix.
if prefix_len > 0:
boundary_chunk = step_routed[:1]
state["chunks"].append(boundary_chunk)
state["running_len"] += 1
step_routed = step_routed[1:]
new_chunk = step_routed
state["chunks"].append(new_chunk)
state["running_len"] += int(new_chunk.shape[0])
first_tokens = prepared_steps[0]
first_prefix = first_tokens["prompt_ids"] + first_tokens["completion_ids"]
first_sample = make_sample(first_tokens, step_idx=0)
active_samples.append((first_prefix, first_sample, [0]))
first_routed_state = sample_routed_state.get(id(first_sample))
if first_routed_state is not None:
routed_prefix_states.setdefault(len(first_prefix), []).append(
(first_tokens["prompt_ids"], first_tokens["completion_ids"], first_routed_state)
)
for step_idx, _step in enumerate(trajectory[1:], start=1):
tokens = prepared_steps[step_idx]
step_prompt_ids = tokens["prompt_ids"]
# Pick the *longest* matching active prefix. With compaction/rollback,
# one active sample's prefix can be a strict prefix of another (e.g. a
# later sample re-generated tokens that overlap an earlier sample's
# prefix). Both would satisfy the slice check; the shorter would
# silently absorb the longer sample's generated tokens as user input.
matched_idx = None
matched_len = -1
matching_prefix_lens: list[int] = []
for idx, (prefix_tokens, _, _) in enumerate(active_samples):
pl = len(prefix_tokens)
if step_prompt_ids[:pl] == prefix_tokens:
matching_prefix_lens.append(pl)
if pl > matched_len:
matched_idx = idx
matched_len = pl
if len(matching_prefix_lens) > 1:
# Ambiguous extension: rare, but reachable via compaction/rollback
# where a new sample's prefix happens to start with an older
# sample's prefix. Longest-match is the correct choice; surface
# the ambiguity so we can audit if it shows up in real rollouts.
logger.warning(
f"Ambiguous prefix match at step {step_idx} for example {output['example_id']}: "
f"{len(matching_prefix_lens)} of {len(active_samples)} active prefixes match "
f"(lens={sorted(matching_prefix_lens)}, step_prompt_len={len(step_prompt_ids)}). "
f"Extending the longest (len={matched_len})."
)
if matched_idx is not None:
# Extension holds - merge into matched sample
prefix_tokens, sample, step_indices = active_samples[matched_idx]
extend_sample(sample, len(prefix_tokens), step_idx=step_idx)
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
active_samples[matched_idx] = (
new_prefix,
sample,
step_indices + [step_idx],
)
routed_state = sample_routed_state.get(id(sample))
if routed_state is not None:
routed_prefix_states.setdefault(len(new_prefix), []).append(
(tokens["prompt_ids"], tokens["completion_ids"], routed_state)
)
else:
# No prefix matches - start a new sample
logger.debug(
f"Extension property broke at step {step_idx + 1} for example {output['example_id']}. "
f"Starting new sample (active_prefixes={len(active_samples)}, step_prompt_len={len(step_prompt_ids)})."
)
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
sample = make_sample(tokens, step_idx=step_idx)
active_samples.append((new_prefix, sample, [step_idx]))
routed_state = sample_routed_state.get(id(sample))
if routed_state is not None:
routed_prefix_states.setdefault(len(new_prefix), []).append(
(tokens["prompt_ids"], tokens["completion_ids"], routed_state)
)
# Finalize routed_experts for each sample. One concat per sample (O(N) byte
# work) replaces the previous per-step unpack/concat/repack (O(N²)). The
# boundary entries between steps were already inserted as one-entry chunks
# during extend_sample, so a straight concat is correct.
for _, sample, _ in active_samples:
state = sample_routed_state.get(id(sample))
if state is None:
has_error = trace.has_error
samples: list[TrainingSample] = []
for branch in trace.branches:
mask = branch.sampled_mask
if not any(mask):
continue
chunks = state["chunks"]
if not chunks:
continue
combined = np.concatenate(chunks, axis=0) if len(chunks) > 1 else np.ascontiguousarray(chunks[0])
expected_len = len(sample.prompt_ids) + len(sample.completion_ids)
combined = align_routed_experts(combined, expected_len)
combined = np.ascontiguousarray(combined)
sample.routed_experts = RoutedExperts(
data=combined.tobytes(),
shape=list(combined.shape),
dtype=str(combined.dtype),
token_ids = branch.token_ids
mm_kwargs: dict[str, EncodedTensor] | None = None
mm_token_type_ids: list[int] | None = None
mmd = branch.multi_modal_data
if mmd is not None:
mm_kwargs = _encode_mm_kwargs(mmd.mm_items)
mapping = mm_token_type_ids_mapping or {}
mm_token_type_ids = [mapping.get(t, 0) for t in token_ids]
samples.append(
TrainingSample(
token_ids=token_ids,
mask=[m and not has_error for m in mask],
logprobs=branch.logprobs,
temperatures=[], # filled by TrainSink.process_group
teacher_logprobs=None,
advantage=None,
env_name=env_name,
mm_kwargs=mm_kwargs,
mm_token_type_ids=mm_token_type_ids,
routed_experts=_encode_routed_experts(branch.routed_experts, len(token_ids)),
)
)
# Attach images by concatenating mm_items across every step the
# sample covers. verifiers' ``state_to_output`` ships per-step
# *delta* mm_data (each step contains only items not present in the
# prior step's cumulative set, with multiset-aware dedup), so
# reading the last step alone would miss every earlier-turn image.
# Concat in step order recovers the per-sample cumulative set;
# deduping again here would drop legitimate duplicate placeholders.
for _, sample, step_indices in active_samples:
renderer_mm = _union_step_mm_data(prepared_steps, step_indices)
if renderer_mm is not None:
mm_kwargs = _pack_mm_kwargs_from_renderer(renderer_mm)
if mm_kwargs is not None:
sample.mm_kwargs = mm_kwargs
# ``mm_token_type_ids``: 1 for image-placeholder tokens, 2
# for video, 0 otherwise. Renderer-supplied via
# ``mm_token_type_id_map`` (single source of truth).
if mm_token_type_ids_mapping is not None:
sample.mm_token_type_ids = [
mm_token_type_ids_mapping.get(token_id, 0)
for token_id in sample.prompt_ids + sample.completion_ids
]
return [sample for _, sample, _ in active_samples]
def _union_step_mm_data(
prepared_steps: list[dict[str, Any]],
step_indices: list[int],
) -> "dict[str, Any] | None":
"""Concatenate renderer-emitted mm_items across this sample's owned steps.
``step_indices`` lists exactly the ``prepared_steps`` positions merged into
the sample — explicit, not a range, so interleaved-agent trajectories skip
steps owned by other agents.
Verifiers ≥ c7731bbb ships per-step *delta* mm_data instead of
cumulative — see ``verifiers/utils/save_utils.py::_delta_intermediate_mm_data``.
The cross-step dedup is already done there with multiset semantics
(preserving multiplicity for an image that appears in multiple
placeholder runs in the token stream). We just concatenate in step
order to recover the per-sample cumulative; deduping again here
would drop legitimate duplicate placeholders.
"""
union_items: dict[str, list] = {}
union_hashes: dict[str, list] = {}
has_any = False
for i in step_indices:
mm = prepared_steps[i].get("multi_modal_data")
if mm is None:
continue
items = mm.mm_items if hasattr(mm, "mm_items") else (mm or {}).get("mm_items") or {}
hashes = mm.mm_hashes if hasattr(mm, "mm_hashes") else (mm or {}).get("mm_hashes") or {}
for modality, item_lst in items.items():
hash_lst = hashes.get(modality, []) or []
for j, item in enumerate(item_lst or []):
h = hash_lst[j] if j < len(hash_lst) else None
union_items.setdefault(modality, []).append(item)
union_hashes.setdefault(modality, []).append(h)
has_any = True
if not has_any:
return None
return {"mm_items": union_items, "mm_hashes": union_hashes}
def _pack_mm_kwargs_from_renderer(mm_data: Any) -> "dict[str, Any] | None":
"""Batch the renderer's per-image ``mm_items`` into model-agnostic
forward kwargs.
``mm_data`` may arrive as a ``MultiModalData`` instance (in-process
for tests) or as a plain dict (after msgpack round-trip from the
env-worker). Each item is a dict keyed by the names the model's
``forward`` expects (``pixel_values`` + ``image_grid_thw`` for
Qwen3-VL, just ``pixel_values`` for Gemma3-VL, etc.). We batch by
``torch.cat(..., dim=0)`` per key — generic because every HF VLM
processor emits a leading batch/patch dimension, and the renderer
always processes one image per call.
Returns a dict of ``EncodedTensor`` payloads keyed by kwarg name,
or ``None`` when no multimodal data is present.
"""
from verifiers.utils.serve_utils import decode_tensor_payload
from prime_rl.transport.types import EncodedTensor
mm_items = mm_data.mm_items if hasattr(mm_data, "mm_items") else (mm_data or {}).get("mm_items") or {}
# Flatten across modalities into one kwarg dict — the model's
# forward signature is the schema. ``mm_items`` is typically
# ``{"image": [...], "video": [...]}`` but each modality's keys
# don't collide for any HF VLM we ship today.
per_kwarg: dict[str, list] = {}
for _modality, items in mm_items.items():
for item in items or []:
for key, payload in item.items():
per_kwarg.setdefault(key, []).append(decode_tensor_payload(payload))
if not per_kwarg:
return None
out: dict[str, EncodedTensor] = {}
for key, tensors in per_kwarg.items():
cat = torch.cat(tensors, dim=0).contiguous()
arr = cat.detach().cpu().numpy()
out[key] = EncodedTensor(
dtype=str(arr.dtype),
shape=list(arr.shape),
data=arr.tobytes(),
if not samples:
get_logger().warning(
f"No trainable samples (error={has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
)
return out
_FILE_URL_PREFIX = "file://"
def offload_images_to_disk(rollouts: list[vf.RolloutOutput], output_dir: Path) -> int:
"""Replace base64 image data in rollout trajectories with file paths on disk.
Scans all trajectory step prompts for data:image URLs, writes the decoded
image bytes to ``{output_dir}/assets/images/{hash}.png``, and replaces the
URL in-place with ``file://{path}``. Deduplicates by content hash so each
unique image is written only once.
Returns the number of unique images written to disk.
"""
images_dir = output_dir / "assets" / "images"
images_dir.mkdir(parents=True, exist_ok=True)
written: set[str] = set()
for output in rollouts:
for step in output.get("trajectory", []):
prompt = step.get("prompt")
if not prompt or not isinstance(prompt, list):
continue
for msg in prompt:
content = msg.get("content", [])
if not isinstance(content, list):
continue
for item in content:
if item.get("type") != "image_url":
continue
url = item.get("image_url", {}).get("url", "")
if not url.startswith("data:image"):
continue
b64_data = url.split(",", 1)[1]
content_hash = hashlib.sha256(b64_data.encode()).hexdigest()[:16]
path = images_dir / f"{content_hash}.png"
if content_hash not in written:
if not path.exists():
path.write_bytes(base64.b64decode(b64_data))
written.add(content_hash)
item["image_url"]["url"] = f"{_FILE_URL_PREFIX}{path}"
return len(written)
return samples
+32 -60
View File
@@ -3,10 +3,12 @@
from __future__ import annotations
import uuid
from dataclasses import dataclass, field, fields
from typing import Literal, Protocol
from dataclasses import dataclass, field
from typing import Generic, Literal, Protocol
import verifiers as vf
import verifiers.v1 as vf
from pydantic import ConfigDict, Field
from verifiers.v1.task import TaskT
from prime_rl.transport import TrainingSample
@@ -55,7 +57,7 @@ class GroupState:
kind: RolloutKind
env_name: str
example: dict
task_idx: int
rollouts_to_schedule: int
target_rollouts: int
emitted: int = 0
@@ -64,60 +66,25 @@ class GroupState:
policy_version_at_start: int = 0
@dataclass
class FinishedRollout:
"""A completed rollout the sink receives. ``raw`` is the env's untouched
``vf.RolloutOutput``; prime-rl metadata lives on typed fields. Train vs
eval is discriminated via ``isinstance``. ``rollout_id`` is the only
safe key for tracing one rollout — ``(env_name, example_id)`` collides
on re-sampling and ``group_id`` covers a whole group."""
class Rollout(vf.Trace[TaskT], Generic[TaskT]):
"""A completed rollout: the env's typed ``vf.Trace`` *is* the rollout — prime-rl's
orchestration metadata lives on it directly (set by the dispatcher once the rollout
returns), so there's no wrapper. Train vs eval is the ``kind`` discriminator. All metadata
fields are ``exclude=True``, so dumping a Rollout yields a plain trace — the on-disk
``results.jsonl`` is unchanged."""
raw: vf.RolloutOutput
env_name: str
example_id: int | str
group_id: uuid.UUID
policy_version: int
off_policy_steps: int
rollout_id: uuid.UUID = field(default_factory=uuid.uuid4)
model_config = ConfigDict(arbitrary_types_allowed=True) # ``samples`` holds msgspec structs
@property
def error(self) -> dict | None:
return self.raw.get("error")
@property
def reward(self) -> float:
return float(self.raw.get("reward", 0.0))
@property
def is_truncated(self) -> bool:
return bool(self.raw.get("is_truncated", False))
def to_dict(self) -> vf.RolloutOutput:
"""``raw`` + metadata merged for I/O (``save_rollouts``,
``monitor.log_samples``). Shallow copy; never mutates ``self.raw``."""
out: vf.RolloutOutput = dict(self.raw) # type: ignore[assignment]
for f in fields(self):
if f.name in ("raw", "samples"):
continue
val = getattr(self, f.name)
if f.name == "filter_results":
out["filters"] = dict(val)
continue
out[f.name] = str(val) if isinstance(val, uuid.UUID) else val
return out
@dataclass
class TrainRollout(FinishedRollout):
samples: list[TrainingSample] = field(default_factory=list)
advantage: float | None = None
is_filtered: bool = False
filter_results: dict[str, bool] = field(default_factory=dict)
@dataclass
class EvalRollout(FinishedRollout):
eval_step: int = 0
kind: RolloutKind = Field(default="train", exclude=True)
env_name: str = Field(default="", exclude=True)
group_id: uuid.UUID = Field(default_factory=uuid.uuid4, exclude=True)
policy_version: int = Field(default=0, exclude=True)
off_policy_steps: int = Field(default=0, exclude=True)
samples: list[TrainingSample] = Field(default_factory=list, exclude=True)
advantage: float | None = Field(default=None, exclude=True)
is_filtered: bool = Field(default=False, exclude=True)
filter_results: dict[str, bool] = Field(default_factory=dict, exclude=True)
eval_step: int | None = Field(default=None, exclude=True)
@dataclass
@@ -142,7 +109,7 @@ class TrainBatch:
"""``samples`` is the trainer-bound payload (post-filter survivors);
``rollouts`` is the full cohort kept for orchestrator-side I/O."""
rollouts: list[TrainRollout]
rollouts: list[Rollout]
samples: list[TrainingSample]
metrics: TrainBatchMetrics
@@ -197,12 +164,17 @@ class EvalBatch:
env_name: str
step: int
rollouts: list[EvalRollout]
rollouts: list[Rollout]
metrics: EvalBatchMetrics
class VersionObserver(Protocol):
"""Notified after each policy update; walked by the watcher after it
mutates ``Policy``."""
"""Notified around each policy update; walked by the watcher.
``on_version_pending`` fires *before* the inference engines are paused for
the weight update; ``on_new_version`` fires *after* the new weights are live
and ``Policy`` has been mutated."""
async def on_version_pending(self, step: int) -> None: ...
async def on_new_version(self, step: int) -> None: ...
+46 -47
View File
@@ -1,19 +1,20 @@
import asyncio
import ctypes
import gc
import logging
import os
import time
from concurrent.futures import ThreadPoolExecutor
from itertools import cycle
from pathlib import Path
import orjson
import verifiers as vf
from verifiers.utils.client_utils import setup_openai_client
from verifiers.utils.save_utils import make_serializable
import verifiers.v1 as vf
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.transport import TrainingSample
from prime_rl.utils.client import setup_inference_pool
from prime_rl.utils.logger import InterceptHandler, get_logger
from prime_rl.utils.logger import InterceptHandler, get_logger, setup_logger
from prime_rl.utils.utils import (
get_broadcast_dir,
get_ckpt_dir,
@@ -22,63 +23,38 @@ from prime_rl.utils.utils import (
async def setup_student_inference_pool(*, config: OrchestratorConfig, tokenizer):
"""Build the student inference pool + matching renderer. Returns
``(renderer | None, inference_pool)``; ``renderer`` is ``None`` on the
MITO path (``config.renderer is None``)."""
"""Build the student renderer and inference pool, returning ``(renderer, inference_pool)``.
Training is renderer-only: RL/OPD roll out through the env server's renderer client
(token-in/out), and SFT — which rolls out against a chat-completions teacher that returns
no tokens — re-renders the conversation with this renderer to backfill them. The renderer
is built here from the (always-set) ``config.renderer`` and also supplies the multimodal
token-type-id map. The eval client is plain chat-completions (eval traces aren't trained)."""
from renderers.base import create_renderer
client_config = config.student.client
model_name = config.student.model.name
if config.renderer is not None:
renderer = create_renderer(tokenizer, config.renderer)
get_logger().info(f"Initialized {type(renderer).__name__} for {model_name}")
inference_pool = await setup_inference_pool(
client_config,
model_name=model_name,
train_client_type="renderer",
eval_client_type="openai_chat_completions",
renderer_config=config.renderer,
pool_size=config.pool_size,
)
get_logger().info("Using direct renderer rollout client")
return renderer, inference_pool
get_logger().info("Using MITO (openai_chat_completions) for rollouts")
renderer = create_renderer(tokenizer, config.renderer)
get_logger().info("Using renderer rollout client")
inference_pool = await setup_inference_pool(
client_config,
model_name=model_name,
train_client_type="openai_chat_completions",
train_client_type="renderer",
eval_client_type="openai_chat_completions",
renderer_config=config.renderer,
pool_size=config.pool_size,
)
return None, inference_pool
return renderer, inference_pool
def get_model_completion_len(output: vf.RolloutOutput) -> int:
"""Sum of model-generated completion tokens across all turns (excludes
environment-injected tokens between turns)."""
return sum(len(step["tokens"]["completion_ids"]) for step in output["trajectory"] if step.get("tokens"))
def get_tool_response_len(output: vf.RolloutOutput) -> int:
"""Total tool-response tokens consumed across the whole rollout, read from a
harness-emitted metric (e.g. RLM's `rlm_total_tool_response_tokens`, deduped
across turns/branches/sub-RLMs). Returns 0 when no such metric is present."""
metrics = output.get("metrics") or {}
for key, value in metrics.items():
if key.endswith("total_tool_response_tokens") and isinstance(value, (int, float)):
return int(value)
return 0
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path, exclude_keys: set[str] | None = None) -> None:
"""Save rollouts to a JSONL file using verifiers serialization."""
def save_rollouts(rollouts: list[dict], path: Path, exclude_keys: set[str] | None = None) -> None:
"""Save rollouts (Trace dicts, already JSON-serializable) to a JSONL file."""
path.parent.mkdir(parents=True, exist_ok=True)
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
with open(path, "wb") as f:
for rollout in rollouts:
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
f.write(orjson.dumps(row, default=make_serializable, option=opts))
f.write(orjson.dumps(row, default=str, option=opts))
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
@@ -90,12 +66,30 @@ def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix
vf_logger.propagate = False
def setup_env_server_logging(log_level: str, json_logging: bool = False) -> None:
"""Configure logging for an env-server process: prime-rl's logger + routing v1's stdlib
logs through it. Passed to verifiers' ``serve_env`` so it runs in the broker and in every
spawned worker — fresh ``spawn`` processes that otherwise have no handlers and would drop
their per-rollout logs."""
setup_logger(log_level, json_logging=json_logging)
intercept_vf_logging(logger="verifiers.v1", level=log_level)
def set_default_executor(max_workers: int = 64) -> None:
"""Scale the default asyncio thread pool so asyncio.to_thread has enough capacity."""
get_logger().info(f"Setting default executor to ThreadPoolExecutor(max_workers={max_workers})")
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=max_workers))
def trim_process_memory() -> None:
"""Return freed heap pages to the OS on glibc systems."""
gc.collect()
try:
ctypes.CDLL("libc.so.6").malloc_trim(0)
except Exception as exc:
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
async def compute_teacher_logprobs(
clients: list[vf.ClientConfig],
model_name: str,
@@ -103,10 +97,15 @@ async def compute_teacher_logprobs(
) -> list[list[float]]:
"""Compute teacher model logprobs for a batch of training samples via prefill."""
import httpx
from openai import AsyncOpenAI
from vllm.entrypoints.serve.disagg.protocol import GenerateResponse
async def _compute_single(client_config: vf.ClientConfig, sample: TrainingSample) -> list[float]:
client = setup_openai_client(client_config)
client = AsyncOpenAI(
base_url=client_config.base_url,
api_key=os.environ.get(client_config.api_key_var, "EMPTY"),
default_headers=client_config.headers or None,
)
# Two escape hatches from ``AsyncOpenAI.post``:
# 1. URL — ``/inference/v1/generate`` is mounted at server root, not
@@ -125,7 +124,7 @@ async def compute_teacher_logprobs(
cast_to=httpx.Response,
body={
"model": model_name,
"token_ids": list(sample.prompt_ids) + list(sample.completion_ids),
"token_ids": list(sample.token_ids),
"sampling_params": {
"max_tokens": 1,
"temperature": 1.0,
+18
View File
@@ -92,6 +92,24 @@ class WeightWatcher:
f"Orchestrator resumed: checkpoint {next_step} ready (after {format_time(self.last_wait_for_ckpt_time)})"
)
# Drain off-policy rollouts BEFORE pausing the inference engines.
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
# ``_reqs_not_processed``), which is only propagated to the workers
# while the engine is stepping. If we drain after resume instead,
# the aborts race with the flush of KV transfers that completed
# during the pause and trip ``assert req_id in self.requests`` in
# the decode scheduler's ``_update_from_kv_xfer_finished`` — killing
# the engine and cascading to every DP rank. Draining first lets the
# aborts settle under normal stepping. ``on_new_version`` (below)
# still runs post-update for observers that need the live version.
for observer in self.observers:
try:
await observer.on_version_pending(next_step)
except Exception as exc:
get_logger().warning(
f"Observer {type(observer).__name__}.on_version_pending({next_step}) raised: {exc!r}"
)
get_logger().debug(f"Updating weights to step {next_step}")
t1 = time.perf_counter()
await self.inference.update_weights(weights_path, lora_name=self.lora_name, step=next_step)
+8 -2
View File
@@ -15,14 +15,20 @@ rank_log() {
# launch_inference_rank <port> <cuda_visible_devices> <dp> <rpc_port> <vllm_extra_json|""> <nixl_side_channel_port|""> <log_file>
launch_inference_rank() {
local port="$1" gpus="$2" dp="$3" rpc="$4" extra="$5" nixl="$6" log="$7"
# Per-rank dir for the mooncake-store lookup ipc socket. It must be unique per process:
# external-LB runs one engine per process, all with data_parallel_rank_local 0, so the
# lookup socket name collides on bind if the dir is shared node-wide. $port is unique per
# rank on the node. Node-local /tmp also avoids inheriting an absent submit-node TMPDIR.
local rpcbase="/tmp/vllm-rpc-$USER-$SLURM_JOB_ID-$port"
mkdir -p "$rpcbase"
local -a cmd=(uv run inference @ "$CONFIG_PATH"
--server.host 0.0.0.0 --server.port "$port"
--parallel.dp "$dp" --data-parallel-size-local 1 --api-server-count 1)
[ -n "$rpc" ] && cmd+=(--data-parallel-rpc-port "$rpc")
[ -n "$extra" ] && cmd+=(--vllm-extra "$extra")
if [ -n "$nixl" ]; then
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" "${cmd[@]}" 2>&1 | tee -a "$log" &
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
else
CUDA_VISIBLE_DEVICES="$gpus" "${cmd[@]}" 2>&1 | tee -a "$log" &
CUDA_VISIBLE_DEVICES="$gpus" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
fi
}
+56 -4
View File
@@ -1,12 +1,63 @@
{# Shared router launch helper, included once per template and called by the
replica-head rank. vllm-router today; an llm-d (EPP+Envoy) branch can slot in
here so the call sites stay router-agnostic. #}
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log_file> [replica_idx]
replica-head rank. The router backend (vllm-router vs llm-d EPP+Envoy) is
chosen here via router.type, so the call sites stay router-agnostic.
node_base/node_count locate this replica's nodes in HOSTNAMES for llm-d
endpoint discovery (disagg uses NUM_PREFILL_NODES/NUM_DECODE_NODES). #}
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log> <replica_idx> <node_base> [node_count]
launch_router() {
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-}"
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-0}" node_base="${7:-0}" node_count="${8:-0}"
{%- if router.type == "llm-d" %}
echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port for replica $replica" | tee "$log"
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
local LLMD_DIR="$OUTPUT_DIR/logs/inference/llmd_${replica}"
mkdir -p "$LLMD_DIR"
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
{%- if is_disaggregated %}
{%- set ep_disaggregated = true %}
{%- set ep_num_prefill = num_prefill_nodes %}
{%- set ep_num_decode = num_decode_nodes %}
{%- set ep_dp = dp_per_node %}
{%- set ep_prefill_port = prefill_port %}
{%- set ep_sidecar_port = router.decode_sidecar_port %}
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
{% include 'llmd/epp_pd.yaml.j2' %}
LLMD_EOF
cat > "$LLMD_DIR/endpoints.yaml" <<LLMD_EOF
{% include 'llmd/endpoints.yaml.j2' %}
LLMD_EOF
local node=0 ip
for ((p=0; p<NUM_PREFILL_NODES; p++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + p))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
for ((d=0; d<NUM_DECODE_NODES; d++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + NUM_PREFILL_NODES + d))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
{%- else %}
{%- set ep_disaggregated = false %}
{%- set ep_num_nodes = infer_nodes_per_replica %}
{%- set ep_dp = dp_per_node %}
{%- set ep_backend_port = backend_port %}
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
{% include 'llmd/epp_estimate.yaml.j2' %}
LLMD_EOF
cat > "$LLMD_DIR/endpoints.yaml" <<LLMD_EOF
{% include 'llmd/endpoints.yaml.j2' %}
LLMD_EOF
local ip
for ((n=0; n<node_count; n++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + n))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${n}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; done
{%- endif %}
cat > "$LLMD_DIR/envoy.yaml" <<LLMD_EOF
{% include 'llmd/envoy.yaml.j2' %}
LLMD_EOF
# grpc-health-port avoids 9003: mooncake_master runs its metrics server on 9003 and
# shares the replica-head node with the EPP, so 9003 would fail to bind and kill the EPP.
epp --pool-name prime-rl --pool-namespace slurm \
--config-file "$LLMD_DIR/epp.yaml" \
--grpc-port 9002 --grpc-health-port 9013 --metrics-port 9090 \
--secure-serving=false --metrics-endpoint-auth=false --tracing=false \
>> "$log" 2>&1 &
envoy -c "$LLMD_DIR/envoy.yaml" >> "$log" 2>&1 &
{%- else %}
local tag="vllm-router"; [ "$mode" = pd ] && tag="vllm-router (PD)"
echo "Starting $tag on $LOCAL_IP:$port${replica:+ for replica $replica}" | tee "$log"
local -a cmd=(vllm-router --policy "$policy" --host 0.0.0.0 --port "$port"
--request-id-headers x-session-id
--worker-startup-timeout-secs 4200 --log-level debug)
if [ "$mode" = pd ]; then
cmd+=(--vllm-pd-disaggregation $worker_args)
@@ -14,4 +65,5 @@ launch_router() {
cmd+=(--worker-urls $worker_args)
fi
"${cmd[@]}" >> "$log" 2>&1 &
{%- endif %}
}
+6 -3
View File
@@ -5,7 +5,8 @@
SLURM templates inside the per-node `bash -c` body, so NO single quotes / apostrophes.
Requires shell vars: LOCAL_IP, INFER_NODE_RANK, OUTPUT_DIR (and SLURM env).
Requires jinja vars: kv_offload_cpu_bytes, kv_offload_disk_path, kv_offload_device_name.
Exports PYTHONHASHSEED + MOONCAKE_CONFIG_PATH for the vLLM process on this node. -#}
Exports PYTHONHASHSEED + MOONCAKE_CONFIG_PATH for the vLLM process. (VLLM_RPC_BASE_PATH,
used by the mooncake-store lookup ipc socket, is set per-rank in _launch_rank.sh.j2.) -#}
# ---- Mooncake distributed store (shared pool across inference nodes) ----
MC_DIR="$OUTPUT_DIR/mooncake/node_${INFER_NODE_RANK}"
mkdir -p "$MC_DIR"
@@ -23,9 +24,11 @@
{%- endif %}
if [ "$SLURMD_NODENAME" = "$MC_HEAD" ]; then
{%- if kv_offload_disk_path %}
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -enable_offload=true -root_fs_dir={{ kv_offload_disk_path }} > "$MC_DIR/master.log" 2>&1 &
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -default_kv_lease_ttl=3600000 -enable_offload=true -root_fs_dir={{ kv_offload_disk_path }} > "$MC_DIR/master.log" 2>&1 &
{%- else %}
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 > "$MC_DIR/master.log" 2>&1 &
# default_kv_lease_ttl raised from 5s: KV blocks were expiring before the decode side
# reused them ("invalid KV blocks ... may have expired"), the real non-NIC config issue.
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -default_kv_lease_ttl=3600000 > "$MC_DIR/master.log" 2>&1 &
{%- endif %}
fi
# Every node waits for the shared master + metadata, then contributes its segment.
+58 -12
View File
@@ -28,7 +28,7 @@ set -e
# Configs
export NUM_NODES={{ num_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
{% if disaggregated -%}
{% if is_disaggregated -%}
export NUM_PREFILL_NODES={{ num_prefill_nodes }}
export NUM_DECODE_NODES={{ num_decode_nodes }}
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
@@ -38,10 +38,13 @@ export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
export PREFILL_PORT={{ prefill_port }}
export DECODE_PORT={{ decode_port }}
export ROUTER_PORT={{ router_port }}
export ROUTER_PORT={{ router.port }}
export RPC_PORT={{ data_parallel_rpc_port }}
{%- if router.type == "llm-d" %}
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
{%- endif %}
{%- elif num_nodes > 1 %}
export ROUTER_PORT={{ router_port }}
export ROUTER_PORT={{ router.port }}
export BACKEND_PORT={{ backend_port }}
export RPC_PORT={{ data_parallel_rpc_port }}
{%- endif %}
@@ -51,6 +54,7 @@ export PROJECT_DIR={{ project_dir }}
export CONFIG_PATH={{ config_path }}
export OUTPUT_DIR={{ output_dir }}
mkdir -p $OUTPUT_DIR/logs/inference
rm -f $OUTPUT_DIR/logs/inference/*.log
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
# General
@@ -69,7 +73,7 @@ uv sync --all-extras
# Print inference URLs
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
export HOSTNAMES_STR="${HOSTNAMES[*]}"
{% if disaggregated -%}
{% if is_disaggregated -%}
# Build per-replica router URLs
INFER_URLS=""
ALL_ROUTER_ARGS=""
@@ -131,6 +135,10 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[t]orchrun" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
# llm-d router procs (EPP + Envoy + decode pd-sidecar) left over from a prior run.
pkill -9 -f "[e]pp.*pool-name" 2>/dev/null
pkill -9 -f "[e]nvoy.*envoy.yaml" 2>/dev/null
pkill -9 -f "[p]d-sidecar" 2>/dev/null
pkill -9 -f "[v]llm" 2>/dev/null
pkill -9 -f "[p]rime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
@@ -143,7 +151,7 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -x mooncake_client 2>/dev/null
sleep 2
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
CLEANUP_SH
@@ -178,7 +186,7 @@ srun --kill-on-bad-exit=1 bash -c '
{% include "_mooncake_store.sh.j2" %}
{%- endif %}
{% if disaggregated -%}
{% if is_disaggregated -%}
# NVSHMEM libs for DeepEP — ensure the rpath target exists on all nodes
if [ ! -d /tmp/deepep_build/nvshmem/lib ] && [ -d "$OUTPUT_DIR/nvshmem/lib" ]; then
mkdir -p /tmp/deepep_build/nvshmem
@@ -194,10 +202,28 @@ srun --kill-on-bad-exit=1 bash -c '
export VLLM_MOE_USE_DEEP_GEMM=1
{%- endif %}
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
export GLOO_SOCKET_IFNAME=bond0
# Bind gloo to the interface that owns LOCAL_IP (the rendezvous IP) — NIC
# names vary across clusters (bond0, eth0, ...). If the lookup fails, leave
# GLOO_SOCKET_IFNAME unset so gloo falls back to its own detection.
GLOO_IFNAME=$(ip -o -4 addr show to "$LOCAL_IP" 2>/dev/null | awk "{print \$2; exit}")
if [ -n "$GLOO_IFNAME" ]; then export GLOO_SOCKET_IFNAME=$GLOO_IFNAME; fi
export VLLM_ENGINE_READY_TIMEOUT_S=4200
export UCX_TLS=all
export UCX_NET_DEVICES=all
# Enumerate RDMA NICs for UCX/NIXL from sysfs (ibv_devices is not on the job
# PATH). Prefer InfiniBand ports and fall back to RoCE: "all" would also pick
# up non-functional devices (e.g. an Ethernet bond UCX cannot open), which
# fails NIXL backend creation. Hosts without RDMA devices keep "all" (TCP).
rdma_ports() {
for port in /sys/class/infiniband/*/ports/*; do
[ "$(cat "$port/link_layer" 2>/dev/null)" = "$1" ] || continue
grep -q ACTIVE "$port/state" 2>/dev/null || continue
dev=${port%/ports/*}
echo "$(basename "$dev"):$(basename "$port")"
done | paste -sd,
}
UCX_NET_DEVICES=$(rdma_ports InfiniBand)
[ -n "$UCX_NET_DEVICES" ] || UCX_NET_DEVICES=$(rdma_ports Ethernet)
export UCX_NET_DEVICES=${UCX_NET_DEVICES:-all}
export LD_LIBRARY_PATH="$PROJECT_DIR/third_party/ucx/lib:$PROJECT_DIR/third_party/ucx/lib/ucx:${LD_LIBRARY_PATH:-}"
export VLLM_NIXL_SIDE_CHANNEL_HOST=$LOCAL_IP
@@ -228,7 +254,7 @@ srun --kill-on-bad-exit=1 bash -c '
{% for key, value in prefill_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
else
# ── Decode node ──
export UCX_NET_DEVICES=mlx5_0:1
@@ -243,7 +269,7 @@ srun --kill-on-bad-exit=1 bash -c '
{% for key, value in decode_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
fi
echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT LOCAL_IP=$LOCAL_IP" \
@@ -252,8 +278,28 @@ srun --kill-on-bad-exit=1 bash -c '
# Start the router on the first prefill node of each replica (external LB across per-rank endpoints)
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router_policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
fi
{%- if router.type == "llm-d" %}
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
# + rank) -> vLLM decode (DECODE_PORT + rank) after orchestrating remote prefill.
# Every decode node fronts its own local ranks, so launch on each (not just the
# replica head), or decode nodes beyond the head get advertised but unserved endpoints.
if [ "$ROLE" = "decode" ]; then
SIDECAR_LOG="$OUTPUT_DIR/logs/inference/sidecar_${INFER_NODE_RANK}.log"
echo "Starting pd-sidecar on $LOCAL_IP:$DECODE_SIDECAR_PORT(+rank) -> vLLM $DECODE_PORT(+rank)" | tee $SIDECAR_LOG
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
pd-sidecar \
--port $DECODE_SIDECAR_PORT \
--vllm-port $DECODE_PORT \
--kv-connector nixlv2 \
--secure-proxy=false \
--enable-ssrf-protection=false \
--inference-pool prime-rl \
--data-parallel-size {{ dp_per_node }} \
>> $SIDECAR_LOG 2>&1 &
fi
{%- endif %}
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
@@ -277,7 +323,7 @@ srun --kill-on-bad-exit=1 bash -c '
# Start the router on node 0 (balances across per-rank endpoints — no intra-node DP header)
if [ "$INFER_NODE_RANK" -eq 0 ]; then
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router_policy }}" "$OUTPUT_DIR/logs/inference/router.log"
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log" 0 0 "$NUM_NODES"
fi
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
@@ -0,0 +1,41 @@
{# llm-d file-discovery endpoints: one entry per DP rank. Rendered (via include)
into the sbatch; the per-node address is the __LLMD_ADDR_<node>__ placeholder,
filled with each SLURM host's IPv4 inline in the sbatch (file-discovery rejects
hostnames). Node ordering matches the sbatch's host loop: prefill then decode.
The including sbatch sets ep_* via {% set %}. #}
endpoints:
{%- if ep_disaggregated %}
{%- for node in range(ep_num_prefill) %}
{%- for rank in range(ep_dp) %}
- name: prefill-{{ node }}-rank-{{ rank }}
address: __LLMD_ADDR_{{ node }}__
port: "{{ ep_prefill_port + rank }}"
namespace: default
labels:
llm-d.ai/pool: prime-rl
llm-d.ai/role: prefill
{%- endfor %}
{%- endfor %}
{%- for node in range(ep_num_decode) %}
{%- for rank in range(ep_dp) %}
- name: decode-{{ node }}-rank-{{ rank }}
address: __LLMD_ADDR_{{ ep_num_prefill + node }}__
port: "{{ ep_sidecar_port + rank }}"
namespace: default
labels:
llm-d.ai/pool: prime-rl
llm-d.ai/role: decode
{%- endfor %}
{%- endfor %}
{%- else %}
{%- for node in range(ep_num_nodes) %}
{%- for rank in range(ep_dp) %}
- name: backend-{{ node }}-rank-{{ rank }}
address: __LLMD_ADDR_{{ node }}__
port: "{{ ep_backend_port + rank }}"
namespace: default
labels:
llm-d.ai/pool: prime-rl
{%- endfor %}
{%- endfor %}
{%- endif %}
+97
View File
@@ -0,0 +1,97 @@
{# Envoy data plane: EPP picks the backend (ext_proc) and sets
x-gateway-destination-endpoint; the ORIGINAL_DST cluster routes there. Both
/v1/ (MITO) and /inference/v1/ (TITO) go through the picker. EPP gRPC is on
loopback 9002; the gateway listens on the configured port. #}
admin:
address: { socket_address: { address: 127.0.0.1, port_value: 9901 } }
static_resources:
listeners:
- name: prime_rl
address: { socket_address: { address: 0.0.0.0, port_value: {{ router.port }} } }
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: prime_rl
codec_type: AUTO
stream_idle_timeout: 0s
request_timeout: 0s
route_config:
virtual_hosts:
- name: prime_rl
domains: ["*"]
routes:
- match: { prefix: "/v1/" }
route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s }
- match: { prefix: "/inference/v1/" }
route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s }
http_filters:
- name: envoy.filters.http.ext_proc
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.ext_proc.v3.ExternalProcessor
grpc_service:
envoy_grpc: { cluster_name: epp_cluster }
timeout: 10s
processing_mode:
request_header_mode: SEND
response_header_mode: SEND
request_body_mode: FULL_DUPLEX_STREAMED
response_body_mode: FULL_DUPLEX_STREAMED
request_trailer_mode: SEND
response_trailer_mode: SEND
message_timeout: 1000s
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
suppress_envoy_headers: true
clusters:
- name: backend_cluster
type: ORIGINAL_DST
lb_policy: CLUSTER_PROVIDED
original_dst_lb_config:
use_http_header: true
http_header_name: x-gateway-destination-endpoint
connect_timeout: 5s
# Default circuit breakers (~1024) overflow at high inflight concurrency (>=1536),
# causing "reset reason: overflow" 500s. Raise far above the max concurrent rollouts.
circuit_breakers:
thresholds:
- priority: DEFAULT
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
- priority: HIGH
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
- name: epp_cluster
type: STRICT_DNS
typed_extension_protocol_options:
envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
"@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
explicit_http_config:
http2_protocol_options: {}
load_assignment:
cluster_name: epp_cluster
endpoints:
- lb_endpoints:
- endpoint:
address: { socket_address: { address: 127.0.0.1, port_value: 9002 } }
connect_timeout: 5s
# ext_proc (EPP) connection pool overflows at high concurrency without this — the
# gRPC ext_proc calls are 1:1 with inflight requests, so cap well above max rollouts.
circuit_breakers:
thresholds:
- priority: DEFAULT
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
- priority: HIGH
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
@@ -0,0 +1,34 @@
{# llm-d EPP config: single-pool (non-P/D) routing with approximate prefix-cache
scoring. The vllmhttp parser embeds the OpenAI parser and also handles
/inference/v1/generate (token_ids), so MITO + TITO both get prefix-cache
scoring. Included into the sbatch as a heredoc; $LLMD_DIR is the per-replica
config dir, expanded at launch time. #}
apiVersion: inference.networking.x-k8s.io/v1alpha1
kind: EndpointPickerConfig
plugins:
- name: file-disc
type: file-discovery
parameters:
path: $LLMD_DIR/endpoints.yaml
watchFile: true
- name: vllmhttp-parser
type: vllmhttp-parser
{%- for scorer in router.scorers %}
- type: {{ scorer }}
{%- endfor %}
- type: max-score-picker
- type: single-profile-handler
schedulingProfiles:
- name: default
plugins:
{%- for scorer, weight in router.scorers.items() %}
- pluginRef: {{ scorer }}
weight: {{ weight }}
{%- endfor %}
- pluginRef: max-score-picker
requestHandler:
parser:
pluginRef: vllmhttp-parser
dataLayer:
discovery:
pluginRef: file-disc
@@ -0,0 +1,56 @@
{# llm-d EPP config: prefill/decode disaggregation. disagg-profile-handler runs
the prefill profile when prefix-based-pd-decider sees >= nonCachedTokens
non-cached prompt tokens, else decode-only. Mirrors the upstream llm-d PD
guide: the prefill profile uses prefill_scorers (prefix + queue/kv) and the
decode profile uses scorers (prefix + active-request); prefill-filter /
decode-filter select endpoints by llm-d.ai/role label. Included into the
sbatch as a heredoc; $LLMD_DIR is the per-replica config dir, expanded at
launch time. #}
apiVersion: inference.networking.x-k8s.io/v1alpha1
kind: EndpointPickerConfig
plugins:
- name: file-disc
type: file-discovery
parameters:
path: $LLMD_DIR/endpoints.yaml
watchFile: true
- name: vllmhttp-parser
type: vllmhttp-parser
- name: pd-decider
type: prefix-based-pd-decider
parameters:
nonCachedTokens: {{ router.non_cached_tokens }}
- name: profile-handler
type: disagg-profile-handler
parameters:
deciders:
prefill: pd-decider
- type: prefill-filter
- type: decode-filter
{%- for scorer in ((router.prefill_scorers.keys() | list) + (router.decode_scorers.keys() | list)) | unique %}
- type: {{ scorer }}
{%- endfor %}
- type: max-score-picker
schedulingProfiles:
- name: prefill
plugins:
- pluginRef: prefill-filter
{%- for scorer, weight in router.prefill_scorers.items() %}
- pluginRef: {{ scorer }}
weight: {{ weight }}
{%- endfor %}
- pluginRef: max-score-picker
- name: decode
plugins:
- pluginRef: decode-filter
{%- for scorer, weight in router.decode_scorers.items() %}
- pluginRef: {{ scorer }}
weight: {{ weight }}
{%- endfor %}
- pluginRef: max-score-picker
requestHandler:
parser:
pluginRef: vllmhttp-parser
dataLayer:
discovery:
pluginRef: file-disc
+69 -17
View File
@@ -32,7 +32,7 @@ export NODES_PER_INFER_REPLICA={{ nodes_per_infer_replica }}
export NUM_INFER_REPLICAS={{ num_infer_replicas }}
export GPUS_PER_NODE={{ gpus_per_node }}
{% if num_infer_nodes > 0 -%}
export ROUTER_PORT={{ router_port }}
export ROUTER_PORT={{ router.port }}
export INFERENCE_TP={{ inference_tp }}
export INFERENCE_DP_LOCAL=$((GPUS_PER_NODE / INFERENCE_TP))
export INFERENCE_DATA_PARALLEL_RPC_PORT={{ inference_data_parallel_rpc_port }}
@@ -45,6 +45,9 @@ export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
export PREFILL_PORT={{ prefill_port }}
export DECODE_PORT={{ decode_port }}
{%- if router.type == "llm-d" %}
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
{%- endif %}
{%- else -%}
export BACKEND_PORT={{ backend_port }}
export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parallel else "0" }}
@@ -57,6 +60,7 @@ export CONFIG_DIR={{ config_dir }}
export OUTPUT_DIR={{ output_dir }}
export ORCHESTRATOR_OUTPUT_DIR={{ orchestrator_output_dir }}
mkdir -p $OUTPUT_DIR/logs/trainer $OUTPUT_DIR/logs/inference
rm -f $OUTPUT_DIR/logs/inference/*.log
ln -sfn trainer/node_0.log $OUTPUT_DIR/logs/trainer.log
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
@@ -165,6 +169,10 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[t]orchrun" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
# llm-d router procs (EPP + Envoy + decode pd-sidecar) left over from a prior run.
pkill -9 -f "[e]pp.*pool-name" 2>/dev/null
pkill -9 -f "[e]nvoy.*envoy.yaml" 2>/dev/null
pkill -9 -f "[p]d-sidecar" 2>/dev/null
pkill -9 -f "[v]llm" 2>/dev/null
pkill -9 -f "[p]rime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
@@ -177,7 +185,7 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -x mooncake_client 2>/dev/null
sleep 2
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
CLEANUP_SH
@@ -239,10 +247,28 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
export VLLM_MOE_USE_DEEP_GEMM=1
{%- endif %}
export GLOO_SOCKET_IFNAME=bond0
# Bind gloo to the interface that owns LOCAL_IP (the rendezvous IP) — NIC
# names vary across clusters (bond0, eth0, ...). If the lookup fails, leave
# GLOO_SOCKET_IFNAME unset so gloo falls back to its own detection.
GLOO_IFNAME=$(ip -o -4 addr show to "$LOCAL_IP" 2>/dev/null | awk "{print \$2; exit}")
if [ -n "$GLOO_IFNAME" ]; then export GLOO_SOCKET_IFNAME=$GLOO_IFNAME; fi
export VLLM_ENGINE_READY_TIMEOUT_S=4200
export UCX_TLS=all
export UCX_NET_DEVICES=all
# Enumerate RDMA NICs for UCX/NIXL from sysfs (ibv_devices is not on the job
# PATH). Prefer InfiniBand ports and fall back to RoCE: "all" would also pick
# up non-functional devices (e.g. an Ethernet bond UCX cannot open), which
# fails NIXL backend creation. Hosts without RDMA devices keep "all" (TCP).
rdma_ports() {
for port in /sys/class/infiniband/*/ports/*; do
[ "$(cat "$port/link_layer" 2>/dev/null)" = "$1" ] || continue
grep -q ACTIVE "$port/state" 2>/dev/null || continue
dev=${port%/ports/*}
echo "$(basename "$dev"):$(basename "$port")"
done | paste -sd,
}
UCX_NET_DEVICES=$(rdma_ports InfiniBand)
[ -n "$UCX_NET_DEVICES" ] || UCX_NET_DEVICES=$(rdma_ports Ethernet)
export UCX_NET_DEVICES=${UCX_NET_DEVICES:-all}
export LD_LIBRARY_PATH="$PROJECT_DIR/third_party/ucx/lib:$PROJECT_DIR/third_party/ucx/lib/ucx:${LD_LIBRARY_PATH:-}"
export VLLM_NIXL_SIDE_CHANNEL_HOST=$LOCAL_IP
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
@@ -265,7 +291,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
{% for key, value in prefill_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
else
export UCX_NET_DEVICES=mlx5_0:1
ROLE="decode"
@@ -279,7 +305,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
{% for key, value in decode_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
fi
echo "ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT" \
@@ -288,8 +314,28 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
# Start the router on the first node of each replica (PD mode, external LB across per-rank endpoints)
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
fi
{%- if router.type == "llm-d" %}
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
# + rank) -> vLLM decode (DECODE_PORT + rank) after orchestrating remote prefill.
# Every decode node fronts its own local ranks, so launch on each (not just the
# replica head), or decode nodes beyond the head get advertised but unserved endpoints.
if [ "$ROLE" = "decode" ]; then
SIDECAR_LOG="$OUTPUT_DIR/logs/inference/sidecar_${INFER_NODE_RANK}.log"
echo "Starting pd-sidecar on $LOCAL_IP:$DECODE_SIDECAR_PORT(+rank) -> vLLM $DECODE_PORT(+rank)" | tee $SIDECAR_LOG
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
pd-sidecar \
--port $DECODE_SIDECAR_PORT \
--vllm-port $DECODE_PORT \
--kv-connector nixlv2 \
--secure-proxy=false \
--enable-ssrf-protection=false \
--inference-pool prime-rl \
--data-parallel-size $INFERENCE_DP_LOCAL \
>> $SIDECAR_LOG 2>&1 &
fi
{%- endif %}
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
@@ -306,7 +352,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
# Start the router on the first node of each replica
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
launch_router regular "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
launch_router regular "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$((REPLICA_IDX * NODES_PER_INFER_REPLICA))" "$NODES_PER_INFER_REPLICA"
fi
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + d),
@@ -335,15 +381,6 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
else
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
if [ "$TRAIN_NODE_RANK" -eq 0 ]; then
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
fi
{%- else %}
TRAIN_NODE_RANK=$SLURM_PROCID
{%- endif %}
@@ -370,6 +407,21 @@ else
@ $CONFIG_DIR/trainer.toml \
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log &
{% if num_infer_nodes > 0 %} fi{% endif %}
{% if num_infer_nodes > 0 %}
# Launch the orchestrator on one node. Default is trainer rank 0 (SLURM_PROCID ==
# NUM_INFER_NODES). With orchestrator_on_inference it moves to the last inference node
# (a decode node) to keep its rollout buffer + env workers off host-RAM-saturated
# trainer nodes. Top-level (after the role if/else) so the wait -n teardown covers it.
{% if orchestrator_on_inference %}ORCH_PROCID=$((NUM_INFER_NODES - 1)){% else %}ORCH_PROCID=$NUM_INFER_NODES{% endif %}
if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
fi
{% endif %}
# Wait for the first background job to exit and propagate its exit code. This
# turns background process crashes (router, orchestrator) into task failures
+263 -96
View File
@@ -1,6 +1,11 @@
import copy
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
import numpy as np
from prime_rl.trainer.utils import balanced_partition
from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
ROUTED_EXPERTS_DTYPE_ITEMSIZE = {
"uint8": 1,
@@ -30,17 +35,6 @@ def _slice_routed_experts(routed_experts: RoutedExperts, seq_len: int) -> Routed
)
def _append_routed_experts(dst: MicroBatch, src: MicroBatch) -> None:
dst_routed = dst.routed_experts
src_routed = src.routed_experts
assert dst_routed is not None
assert src_routed is not None
assert dst_routed.dtype == src_routed.dtype
assert dst_routed.shape[1:] == src_routed.shape[1:]
dst_routed.data += src_routed.data
dst_routed.shape[0] += src_routed.shape[0]
def _pad_routed_experts(micro_batch: MicroBatch, padding_size: int) -> None:
routed_experts = micro_batch.routed_experts
assert routed_experts is not None
@@ -49,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
@@ -78,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)
@@ -125,13 +175,14 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
loss_mask=loss_mask,
position_ids=position_ids,
inference_logprobs=inference_logprobs,
sequence_lengths=[len(input_ids)],
teacher_logprobs=teacher_logprobs,
temperatures=temperatures,
rewards=rewards,
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,
)
@@ -141,8 +192,149 @@ def _is_multimodal_sample(sample: MicroBatch) -> bool:
return sample.mm_kwargs is not None
@dataclass
class _MicroBatchBin:
samples: list[tuple[int, MicroBatch]]
length: int
@classmethod
def from_sample(cls, lora_idx: int, sample: MicroBatch) -> "_MicroBatchBin":
return cls(samples=[(lora_idx, sample)], length=len(sample.input_ids))
@property
def first_sample(self) -> MicroBatch:
return self.samples[0][1]
def can_add(self, sample: MicroBatch, max_seq_len: int) -> bool:
first_sample = self.first_sample
return (
not _is_multimodal_sample(first_sample)
and not _is_multimodal_sample(sample)
and self.length + len(sample.input_ids) <= max_seq_len
and first_sample.training_mode == sample.training_mode
and (first_sample.routed_experts is None) == (sample.routed_experts is None)
)
def add(self, lora_idx: int, sample: MicroBatch) -> None:
self.samples.append((lora_idx, sample))
self.length += len(sample.input_ids)
def workload(self, bin_cost: Callable[[Sequence[int]], int]) -> int:
return bin_cost([len(sample.input_ids) for _, sample in self.samples])
def split_by_workload(self, bin_cost: Callable[[Sequence[int]], int]) -> tuple["_MicroBatchBin", "_MicroBatchBin"]:
# Greedily place the heaviest sample on the currently lighter side (longest-processing-time).
ranked = sorted(self.samples, key=lambda pair: -bin_cost([len(pair[1].input_ids)]))
left: list[tuple[int, MicroBatch]] = []
right: list[tuple[int, MicroBatch]] = []
left_workload = right_workload = 0
for lora_idx, sample in ranked:
sample_workload = bin_cost([len(sample.input_ids)])
if left_workload <= right_workload:
left.append((lora_idx, sample))
left_workload += sample_workload
else:
right.append((lora_idx, sample))
right_workload += sample_workload
return (
_MicroBatchBin(left, sum(len(sample.input_ids) for _, sample in left)),
_MicroBatchBin(right, sum(len(sample.input_ids) for _, sample in right)),
)
def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
has_rewards = any(sample.rewards is not None for _, sample in bin_content.samples)
has_teacher_logprobs = any(sample.teacher_logprobs is not None for _, sample in bin_content.samples)
has_mm_token_type_ids = any(sample.mm_token_type_ids is not None for _, sample in bin_content.samples)
input_ids: list[int] = []
loss_mask: list[bool] = []
advantages: list[float] = []
inference_logprobs: list[float] = []
position_ids: list[int] = []
temperatures: list[float] = []
env_names: list[str] = []
rewards: list[float] | None = [] if has_rewards else None
teacher_logprobs: list[float] | None = [] if has_teacher_logprobs else None
mm_token_type_ids: list[int] | None = [] if has_mm_token_type_ids else None
routed_experts: RoutedExperts | None = None
lora_num_tokens = [0] * num_loras
for lora_idx, sample in bin_content.samples:
sample_len = len(sample.input_ids)
input_ids.extend(sample.input_ids)
loss_mask.extend(sample.loss_mask)
advantages.extend(sample.advantages)
inference_logprobs.extend(sample.inference_logprobs)
position_ids.extend(sample.position_ids)
temperatures.extend(sample.temperatures)
env_names.extend(sample.env_names)
if rewards is not None:
rewards.extend(sample.rewards if sample.rewards is not None else [float("nan")] * sample_len)
if teacher_logprobs is not None:
teacher_logprobs.extend(
sample.teacher_logprobs if sample.teacher_logprobs is not None else [0.0] * sample_len
)
if mm_token_type_ids is not None:
mm_token_type_ids.extend(
sample.mm_token_type_ids if sample.mm_token_type_ids is not None else [0] * sample_len
)
if sample.routed_experts is not None:
if routed_experts is None:
routed_experts = _copy_routed_experts(sample.routed_experts)
else:
assert routed_experts.dtype == sample.routed_experts.dtype
assert routed_experts.shape[1:] == sample.routed_experts.shape[1:]
routed_experts.data += sample.routed_experts.data
routed_experts.shape[0] += sample.routed_experts.shape[0]
lora_num_tokens[lora_idx] += sample_len
sequence_lengths = [len(sample.input_ids) for _, sample in bin_content.samples]
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
first_sample = bin_content.first_sample
return MicroBatch(
input_ids=input_ids,
advantages=advantages,
loss_mask=loss_mask,
position_ids=position_ids,
inference_logprobs=inference_logprobs,
sequence_lengths=sequence_lengths,
teacher_logprobs=teacher_logprobs,
temperatures=temperatures,
rewards=rewards,
lora_num_tokens=lora_num_tokens,
routed_experts=routed_experts,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
mm_kwargs=first_sample.mm_kwargs if _is_multimodal_sample(first_sample) else None,
training_mode=first_sample.training_mode,
)
def _expand_bins_by_splitting(
bins: list[_MicroBatchBin], target_count: int, bin_cost: Callable[[Sequence[int]], int]
) -> None:
while len(bins) < target_count:
candidates = [
(bin_content.workload(bin_cost), idx)
for idx, bin_content in enumerate(bins)
if len(bin_content.samples) > 1
]
if not candidates:
break
_, idx = max(candidates)
left, right = bins[idx].split_by_workload(bin_cost)
bins[idx] = left
bins.append(right)
def packed_samples_into_micro_bs(
samples: list[tuple[int, MicroBatch]], max_seq_len: int, num_loras: int
samples: list[tuple[int, MicroBatch]],
max_seq_len: int,
num_loras: int,
num_train_workers: int,
bin_cost: Callable[[Sequence[int]], int],
) -> list[MicroBatch]:
"""
Pack samples into micro_batch efficiently.
@@ -155,63 +347,40 @@ def packed_samples_into_micro_bs(
# Sort by (lora_idx, -length) for packing efficiency
samples.sort(key=lambda x: (x[0], -len(x[1].input_ids)))
## we create bins
micro_batches: list[MicroBatch] = []
bins: list[_MicroBatchBin] = []
for idx, sample in samples:
# Multimodal samples cannot be packed - each becomes its own micro batch
if _is_multimodal_sample(sample):
sample.lora_num_tokens = [0] * num_loras
sample.lora_num_tokens[idx] = len(sample.input_ids)
micro_batches.append(sample)
continue
# Try to find a bin that can fit this sequence (only pack text-only samples)
for bin_content in micro_batches:
# Don't pack into multimodal micro batches
if _is_multimodal_sample(bin_content):
continue
# Check if sequence fits in this bin
if (
len(bin_content.input_ids) + len(sample.input_ids) <= max_seq_len
and bin_content.training_mode == sample.training_mode
):
existing_len = len(bin_content.input_ids)
bin_content.input_ids.extend(sample.input_ids)
bin_content.loss_mask.extend(sample.loss_mask)
bin_content.advantages.extend(sample.advantages)
if sample.rewards is not None:
if bin_content.rewards is None:
bin_content.rewards = [float("nan")] * existing_len
bin_content.rewards.extend(sample.rewards)
elif bin_content.rewards is not None:
bin_content.rewards.extend([float("nan")] * len(sample.input_ids))
bin_content.inference_logprobs.extend(sample.inference_logprobs)
bin_content.temperatures.extend(sample.temperatures)
if sample.teacher_logprobs is not None:
if bin_content.teacher_logprobs is None:
bin_content.teacher_logprobs = []
bin_content.teacher_logprobs.extend(sample.teacher_logprobs)
assert (bin_content.routed_experts is None) == (sample.routed_experts is None)
if sample.routed_experts is not None:
if bin_content.routed_experts is None:
bin_content.routed_experts = _copy_routed_experts(sample.routed_experts)
else:
_append_routed_experts(bin_content, sample)
if sample.mm_token_type_ids is not None:
if bin_content.mm_token_type_ids is None:
bin_content.mm_token_type_ids = []
bin_content.mm_token_type_ids.extend(sample.mm_token_type_ids)
bin_content.env_names.extend(sample.env_names)
bin_content.position_ids.extend(sample.position_ids)
bin_content.lora_num_tokens[idx] += len(sample.input_ids)
for bin_content in bins:
if bin_content.can_add(sample, max_seq_len):
bin_content.add(idx, sample)
break
else:
sample.lora_num_tokens = [0] * num_loras
sample.lora_num_tokens[idx] = len(sample.input_ids)
micro_batches.append(sample)
bins.append(_MicroBatchBin.from_sample(idx, sample))
return micro_batches
if num_train_workers > 1:
target_count = max(
((len(bins) + num_train_workers - 1) // num_train_workers) * num_train_workers,
num_train_workers,
)
_expand_bins_by_splitting(bins, target_count, bin_cost)
return [_materialize_bin(bin_content, num_loras) for bin_content in bins]
def _distribute_group(
group: list[MicroBatch],
num_train_workers: int,
bin_cost: Callable[[Sequence[int]], int],
) -> list[list[MicroBatch]]:
# Callers pad each group to a positive multiple of num_train_workers first.
assert len(group) % num_train_workers == 0, "Number of micro batches is not divisible by number of data ranks"
if not group:
return [[] for _ in range(num_train_workers)]
weights = [bin_cost(micro_batch.sequence_lengths) for micro_batch in group]
partitions = balanced_partition(weights, num_train_workers)
return [[group[i] for i in partition] for partition in partitions]
def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBatch:
@@ -242,14 +411,16 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
micro_batch.rewards.extend([float("nan")] * padding_size)
micro_batch.loss_mask.extend([False] * padding_size)
micro_batch.position_ids.extend(list(range(padding_size)))
micro_batch.sequence_lengths.append(padding_size)
micro_batch.inference_logprobs.extend([0.0] * padding_size)
# Use temperature 1.0 for padding tokens (doesn't matter since loss_mask is False)
micro_batch.temperatures.extend([1.0] * padding_size)
if micro_batch.teacher_logprobs is not None:
micro_batch.teacher_logprobs.extend([0.0] * padding_size)
micro_batch.lora_num_tokens[-1] += (
padding_size # We send padding to the last lora so that tokens have ascending lora idx
)
if micro_batch.lora_num_tokens is not None:
micro_batch.lora_num_tokens[-1] += (
padding_size # We send padding to the last lora so that tokens have ascending lora idx
)
if micro_batch.mm_token_type_ids is not None:
micro_batch.mm_token_type_ids.extend([0] * padding_size)
if micro_batch.routed_experts is not None:
@@ -282,6 +453,7 @@ def prepare_batch(
num_train_workers: int,
idxs: list[int],
num_loras: int,
bin_cost: Callable[[Sequence[int]], int],
pad_to_multiple_of: int = 1,
) -> list[list[MicroBatch]]:
"""
@@ -295,7 +467,7 @@ def prepare_batch(
"""
all_samples = [(idx, prepare_sample(rollout, seq_len)) for idx, rollout in zip(idxs, rollouts)]
micro_batches = packed_samples_into_micro_bs(all_samples, seq_len, num_loras)
micro_batches = packed_samples_into_micro_bs(all_samples, seq_len, num_loras, num_train_workers, bin_cost)
micro_batches = [pad_micro_batch(micro_batch, pad_to_multiple_of) for micro_batch in micro_batches]
# Separate by modality so each step index has uniform modality across all ranks
@@ -306,15 +478,10 @@ def prepare_batch(
mm_batches = _pad_group_for_distribution(mm_batches, num_train_workers)
text_batches = _pad_group_for_distribution(text_batches, num_train_workers)
# Combine: all multimodal first, then all text-only. Since each group's length is
# divisible by num_train_workers, the modality boundary aligns with distribution rows.
ordered = mm_batches + text_batches
assert len(ordered) % num_train_workers == 0, "Number of micro batches is not divisible by number of data ranks"
# Distribute in strided order so each step index has the same modality across ranks
batches_per_gpu: list[list[MicroBatch]] = [[] for _ in range(num_train_workers)]
for i, batch in enumerate(ordered):
batches_per_gpu[i % num_train_workers].append(batch)
for group in (mm_batches, text_batches):
group_batches_per_gpu = _distribute_group(group, num_train_workers, bin_cost)
for worker_idx, worker_batches in enumerate(group_batches_per_gpu):
batches_per_gpu[worker_idx].extend(worker_batches)
return batches_per_gpu
+52 -22
View File
@@ -9,7 +9,7 @@ from typing import Any
import torch
from torch import Tensor, nn
from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dict
from torch.distributed.checkpoint.state_dict import get_state_dict, set_model_state_dict, set_state_dict
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
from torch.distributed.checkpoint.state_dict_saver import save as dcp_save
from torch.distributed.checkpoint.stateful import Stateful
@@ -67,8 +67,13 @@ class AppState(Stateful):
"""Extract base optimizers from wrappers like CPUOffloadOptimizer."""
return [opt.base_optimizer if isinstance(opt, CPUOffloadOptimizer) else opt for opt in self.optimizers]
def _has_cpu_offload(self) -> bool:
return any(isinstance(opt, CPUOffloadOptimizer) for opt in self.optimizers)
def state_dict(self) -> dict[str, Any]:
# Move CPU-offloaded states to GPU before checkpointing
# get_state_dict requires optimizer states to live on param.device. For an
# already-initialized CPU-offload optimizer that means staging back to GPU
# before the call; the matching offload happens after the dict is built.
for opt in self.optimizers:
if isinstance(opt, CPUOffloadOptimizer) and opt._initialized:
opt._move_states("cuda")
@@ -88,26 +93,53 @@ class AppState(Stateful):
progress_state_dict = asdict(self.progress)
state_dict["progress"] = progress_state_dict
# Move states back to CPU
# Offload optimizer states to CPU for every CPUOffloadOptimizer, including
# ones that were uninitialized on entry. dcp_load calls this method to build
# a template, and get_state_dict's internal _init_optim_state populates an
# empty optim.state with GPU tensors. Optimizer.state_dict() returns those
# values via shallow copy, so optimizer_state_dict["state"][fqn] is the same
# dict object as optim.state[param]. Replacing the entries with CPU tensors
# in place therefore flips the template too — dcp_load reads bytes from disk
# straight into CPU storage and optim.state is loaded by the time the load
# returns, without GPU optimizer state ever existing for the duration of the
# read.
has_cpu_offload = self._has_cpu_offload()
for opt in self.optimizers:
if isinstance(opt, CPUOffloadOptimizer) and opt._initialized:
if isinstance(opt, CPUOffloadOptimizer):
opt._move_states("cpu")
if has_cpu_offload:
gc.collect()
torch.cuda.empty_cache()
return state_dict
def load_state_dict(self, state_dict: dict[str, Any]):
base_optimizers = self._get_base_optimizers()
set_state_dict(
self.model, base_optimizers, model_state_dict=state_dict["model"], optim_state_dict=state_dict["optimizers"]
)
has_cpu_offload = self._has_cpu_offload()
# Re-initialize CPU offload wrappers after loading
has_cpu_offload = False
for opt in self.optimizers:
if isinstance(opt, CPUOffloadOptimizer):
opt._move_states("cpu")
opt._initialized = True
has_cpu_offload = True
if has_cpu_offload:
# When CPU offload is on, the optimizer is already loaded by the time we
# get here: state_dict() handed dcp_load a template whose tensors share
# storage with optim.state[p][k], and dcp_load wrote the checkpoint bytes
# directly into those tensors via target_tensor.copy_(...). Running
# set_state_dict on the optimizer would route the loaded CPU values
# through Optimizer.load_state_dict, whose _cast hook does
# value.to(param.dtype, param.device) and would allocate a fresh GPU
# copy of every state tensor — undoing the in-place CPU load and
# detaching optim.state from the tensors we just populated. So we only
# apply the model side here and flip the wrappers to initialized so
# subsequent steps take the steady-state path.
set_model_state_dict(self.model, model_state_dict=state_dict["model"])
for opt in self.optimizers:
if isinstance(opt, CPUOffloadOptimizer):
opt._initialized = True
else:
set_state_dict(
self.model,
base_optimizers,
model_state_dict=state_dict["model"],
optim_state_dict=state_dict["optimizers"],
)
if self.scheduler is not None:
self.scheduler.load_state_dict(state_dict["scheduler"])
@@ -115,15 +147,13 @@ class AppState(Stateful):
for key, value in state_dict["progress"].items():
setattr(self.progress, key, value)
# Reclaim GPU memory freed by moving optimizer states to CPU.
# After set_state_dict + _move_states("cpu"), the optimizer states live on CPU,
# but the state_dict (owned by dcp_load) still holds references to stale GPU
# optimizer tensors. Clearing them and flushing the CUDA cache prevents OOM on
# the first training step.
# state_dict is the same dict object that dcp_load held internally; clearing
# it drops the last references to the loaded tensor wrappers so the cuda
# allocator can release whatever blocks it cached during the read.
if has_cpu_offload:
state_dict.clear() # drop stale GPU tensor references from dcp_load
gc.collect() # break any circular references so tensors are freed
torch.cuda.empty_cache() # return freed GPU memory to CUDA
state_dict.clear()
gc.collect()
torch.cuda.empty_cache()
class CheckpointManager:
+41
View File
@@ -37,6 +37,7 @@ from prime_rl.trainer.models import (
get_custom_vlm_cls,
supports_custom_impl,
)
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import Indexer
from prime_rl.trainer.models.layers.checkpointing import (
get_supported_targets,
set_selective_activation_checkpointing,
@@ -350,6 +351,29 @@ def freeze_moe_router(model: nn.Module) -> None:
logger.info(f"Froze {num_frozen} MoE router parameters")
def freeze_sparse_indexer(model: nn.Module) -> None:
"""Freeze DSA sparse-attention indexer parameters.
The indexer's `compute_sparse_indices` forward runs under `torch.no_grad()`, so its
params never receive a gradient and cannot be trained. Left with requires_grad=True
they stay stateless in the optimizer, which breaks strict checkpoint resume: DCP
materializes optimizer state for every requires_grad param at load time, but the
stateless params were never saved -> "Missing key in checkpoint state_dict". Freezing
them keeps the saved and loaded optimizer state symmetric.
"""
logger = get_logger()
num_frozen = 0
for module in model.modules():
if isinstance(module, Indexer):
for param in module.parameters():
param.requires_grad = False
num_frozen += 1
if num_frozen > 0:
logger.info(f"Froze {num_frozen} sparse indexer parameters")
def apply_force_balanced_routing(model: nn.Module) -> None:
"""Force MoE token-choice routers into round-robin assignment for fake-data smoke tests."""
logger = get_logger()
@@ -486,6 +510,18 @@ def get_model(
model_config.use_index_cache = True
model_config.index_topk_freq = config.index_cache.topk_freq
model_config.index_topk_pattern = config.index_cache.topk_pattern
# Explicit override supersedes the model's native IndexShare schedule.
model_config.indexer_types = None
else:
# Auto-enable IndexShare from the model's own indexer schedule (e.g. GLM-5.2). The model
# reads `indexer_types` directly: shared layers reuse cached indices and carry no indexer weights.
indexer_types = getattr(model_config, "indexer_types", None)
if indexer_types and any(t == "shared" for t in indexer_types):
model_config.use_index_cache = True
logger.info(
f"Auto-enabled IndexShare from indexer_types schedule "
f"({sum(t == 'full' for t in indexer_types)}/{len(indexer_types)} full layers)"
)
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
@@ -1075,6 +1111,11 @@ def setup_model(
if config.freeze_moe_router:
freeze_moe_router(model)
# The DSA sparse-attention indexer runs its forward under torch.no_grad(), so it is
# never trainable. Freeze it so optimizer state stays symmetric across checkpoint
# save/resume. No-op for models without a sparse indexer.
freeze_sparse_indexer(model)
if config.debug.force_balanced_routing:
apply_force_balanced_routing(model)
@@ -227,7 +227,11 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
# .contiguous(): the per-layer slice is a strided view of [tokens, layers, topk]
# (dim-1 stride = layers*topk); torch.compile's MoE kernel asserts a contiguous input.
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
@@ -11,6 +11,10 @@ def _index_cache_skip_topk(config, layer_idx: int) -> bool:
if index_topk_pattern is not None:
return layer_idx < len(index_topk_pattern) and index_topk_pattern[layer_idx] == "S"
indexer_types = getattr(config, "indexer_types", None)
if indexer_types is not None:
return layer_idx < len(indexer_types) and indexer_types[layer_idx] == "shared"
return layer_idx % getattr(config, "index_topk_freq", 1) != 0
@@ -162,6 +166,7 @@ class GlmMoeDsaConfig(PretrainedConfig):
use_index_cache=False,
index_topk_freq=1,
index_topk_pattern=None,
indexer_types=None,
scoring_func="sigmoid",
topk_method="noaux_tc",
use_grouped_mm=True,
@@ -218,6 +223,7 @@ class GlmMoeDsaConfig(PretrainedConfig):
self.use_index_cache = use_index_cache
self.index_topk_freq = index_topk_freq
self.index_topk_pattern = index_topk_pattern
self.indexer_types = indexer_types
self.scoring_func = scoring_func
self.topk_method = topk_method
self.use_grouped_mm = use_grouped_mm
@@ -226,6 +232,10 @@ class GlmMoeDsaConfig(PretrainedConfig):
if not self.use_grouped_mm:
warnings.warn("not using grouped mm for moe is very slow, should only be used for debugging")
# head_dim is derived from qk_rope_head_dim (the RoPE slice). Some checkpoints (e.g. GLM-5.2)
# set head_dim=qk_nope_head_dim in config.json; drop it so PretrainedConfig.__init__ can't
# overwrite self.head_dim and break the rotary embedding dimension.
kwargs.pop("head_dim", None)
super().__init__(
pad_token_id=pad_token_id,
tie_word_embeddings=tie_word_embeddings,
@@ -158,7 +158,8 @@ class GlmMoeDsaAttention(nn.Module):
)
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, args.hidden_size, bias=args.attention_bias)
self.indexer = Indexer(args)
# IndexShare (GLM-5.2): layers that reuse cached indices carry no indexer weights.
self.indexer = Indexer(args) if not args.skip_topk else None
self.use_index_cache = args.use_index_cache
self.skip_topk = args.skip_topk
self.scaling = self.qk_head_dim ** (-0.5)
@@ -550,3 +550,71 @@ def per_block_cast_to_fp8_triton(
gran_k,
)
return out[0], sf[0]
def per_block_cast_to_fp8_tp_triton(
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Block-fp8 cast of ``x.T`` without materializing the transpose."""
assert x.dim() == 2
assert gran_k == GROUP_ALIGNMENT
rows, cols = x.shape
x3 = x.unsqueeze(0)
out = torch.empty((cols, rows), device=x.device, dtype=torch.float8_e4m3fn)
sf = torch.empty((ceil_div(cols, gran_k), ceil_div(rows, gran_k)), device=x.device, dtype=torch.float32)
grid = (1, ceil_div(rows, gran_k), ceil_div(cols, gran_k))
_grouped_per_block_fp8_kernel[grid](
x3,
out,
sf,
1,
rows,
cols,
x3.stride(0),
x3.stride(1),
x3.stride(2),
# transposed output: x's element (row, col) lands at out[col, row]
cols * rows,
1,
rows,
# transposed scales: x's tile (pid_m, pid_n) lands at sf[pid_n, pid_m]
ceil_div(cols, gran_k) * ceil_div(rows, gran_k),
1,
ceil_div(rows, gran_k),
USE_UE8M0=use_ue8m0,
BLOCK_M=gran_k,
BLOCK_N=gran_k,
num_warps=8,
)
return out, sf
def per_token_cast_to_fp8_tp_triton(
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Per-token fp8 cast of ``x.T`` without materializing the transpose."""
assert x.dim() == 2
assert gran_k == GROUP_ALIGNMENT
rows, cols = x.shape
out = torch.empty((cols, rows), device=x.device, dtype=torch.float8_e4m3fn)
sf = torch.empty((cols, ceil_div(rows, gran_k)), device=x.device, dtype=torch.float32)
grid = lambda meta: (ceil_div(cols, meta["BLOCK_M"]), ceil_div(rows, meta["BLOCK_K"]))
_per_token_fp8_kernel[grid](
x,
out,
sf,
cols,
rows,
# transposed read: the kernel's per-row amax reduces over x's rows
x.stride(1),
x.stride(0),
out.stride(0),
out.stride(1),
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_M=8,
BLOCK_K=gran_k,
num_warps=4,
)
return out, sf
@@ -12,7 +12,9 @@ import torch
from torch import nn
from prime_rl.trainer.models.kernels.fp8_utils import (
per_block_cast_to_fp8_tp_triton,
per_block_cast_to_fp8_triton,
per_token_cast_to_fp8_tp_triton,
per_token_cast_to_fp8_triton,
)
from prime_rl.utils.logger import get_logger
@@ -43,8 +45,7 @@ class _FP8BlockwiseMM(torch.autograd.Function):
grad_x = grad_weight = None
if ctx.needs_input_grad[0]:
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, False, block_size)
weight_t = weight.transpose(0, 1).contiguous()
weight_dx_fp8 = per_block_cast_to_fp8_triton(weight_t, False, block_size)
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, False, block_size)
grad_x_2d = torch.empty_like(x_2d)
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
grad_x = grad_x_2d.reshape(ctx.x_shape)
@@ -62,10 +63,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
else:
grad_output_2d_padded = grad_output_2d
x_2d_padded = x_2d
grad_output_t = grad_output_2d_padded.transpose(0, 1).contiguous()
x_t = x_2d_padded.transpose(0, 1).contiguous()
grad_output_t_fp8 = per_token_cast_to_fp8_triton(grad_output_t, False, block_size)
x_t_fp8 = per_token_cast_to_fp8_triton(x_t, False, block_size)
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, False, block_size)
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, False, block_size)
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
deep_gemm.fp8_gemm_nt(
grad_output_t_fp8,
@@ -8,6 +8,7 @@ import torch.nn as nn
from torch import Tensor
from prime_rl.utils.logger import get_logger
from prime_rl.utils.vlm import get_final_logit_softcapping
FUSED_CE_IGNORE_INDEX = -100
@@ -299,8 +300,8 @@ def inject_prime_lm_head(
logger = get_logger()
# Check for Gemma-style softcapping - dispatch to specialized implementation
final_logit_softcapping = getattr(model.config, "final_logit_softcapping", None)
# Check for Gemma-style softcapping - dispatch to specialized implementation.
final_logit_softcapping = get_final_logit_softcapping(model.config)
if final_logit_softcapping:
if fused_cross_entropy == "quack":
raise ValueError(
+39 -22
View File
@@ -955,32 +955,44 @@ class NemotronHRouter(nn.Module):
self.norm_topk_prob = norm_topk_prob
def forward(
self, x: torch.Tensor, expert_bias: torch.Tensor | None = None
self,
x: torch.Tensor,
expert_bias: torch.Tensor | None = None,
routed_experts: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
scores = F.linear(x.float(), self.gate.float()).sigmoid()
scores_for_choice = scores + self.e_score_correction_bias
if expert_bias is not None:
scores_for_choice = scores_for_choice + expert_bias
if routed_experts is not None:
# Router replay: reuse the inference engine's expert selection and
# only recompute the gating weights from the trainer's scores. The
# correction/load-balancing biases only affect selection, so they
# are intentionally skipped here.
selected_experts_indices = routed_experts
else:
scores_for_choice = scores + self.e_score_correction_bias
# Group-based routing
if self.n_group > 1:
group_scores = (
scores_for_choice.view(-1, self.n_group, self.num_experts // self.n_group)
.topk(2, dim=-1)[0]
.sum(dim=-1)
)
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
group_mask = torch.zeros_like(group_scores)
group_mask.scatter_(1, group_idx, 1)
score_mask = (
group_mask.unsqueeze(-1)
.expand(-1, self.n_group, self.num_experts // self.n_group)
.reshape(-1, self.num_experts)
)
scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
if expert_bias is not None:
scores_for_choice = scores_for_choice + expert_bias
# Group-based routing
if self.n_group > 1:
group_scores = (
scores_for_choice.view(-1, self.n_group, self.num_experts // self.n_group)
.topk(2, dim=-1)[0]
.sum(dim=-1)
)
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
group_mask = torch.zeros_like(group_scores)
group_mask.scatter_(1, group_idx, 1)
score_mask = (
group_mask.unsqueeze(-1)
.expand(-1, self.n_group, self.num_experts // self.n_group)
.reshape(-1, self.num_experts)
)
scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
selected_experts_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
selected_experts_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
top_scores = scores.gather(1, selected_experts_indices)
routing_confidence_sum = _selected_probability_mass_sum(scores, top_scores, "sigmoid")
@@ -1181,8 +1193,13 @@ class LatentMoE(nn.Module):
bs, slen, dim = x.shape
x_flat = x.view(-1, dim)
if routed_experts is not None:
# Flatten to (bs * slen, top_k); reshape (not view) since the slice is non-contiguous.
_, _, top_k = routed_experts.shape
routed_experts = routed_experts.reshape(-1, top_k)
top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum = self.router(
x_flat, self.expert_bias
x_flat, self.expert_bias, routed_experts=routed_experts
)
with torch.no_grad():
@@ -223,6 +223,7 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
routed_experts: torch.Tensor | None = None,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
@@ -266,10 +267,11 @@ class NemotronHMoELayer(GradientCheckpointingLayer):
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
routed_experts: torch.Tensor | None = None,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = self.mlp(hidden_states, routed_experts=routed_experts)
return residual + hidden_states
@@ -298,6 +300,7 @@ class NemotronHAttentionLayer(GradientCheckpointingLayer):
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
routed_experts: torch.Tensor | None = None,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.norm(hidden_states)
@@ -498,7 +501,13 @@ class NemotronHModel(NemotronHPreTrainedModel):
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
routed_experts: Optional[torch.LongTensor] = None,
) -> BaseModelOutputWithPast:
"""
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
Routed experts for each token, indexed by global layer index. Only used for router replay; slots
for non-MoE (Mamba/attention) layers are ignored.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
@@ -516,12 +525,15 @@ class NemotronHModel(NemotronHPreTrainedModel):
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids) if self.rotary_emb is not None else None
for decoder_layer in self.layers:
for layer_idx, decoder_layer in enumerate(self.layers):
# routed_experts is indexed by global layer index; non-MoE layers ignore it.
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
routed_experts=routed_experts_layer,
)
hidden_states = self.norm(hidden_states)
@@ -550,6 +562,7 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
labels: Optional[torch.LongTensor] = None,
logits_to_keep: int = 0,
temperature: Optional[torch.Tensor] = None,
routed_experts: Optional[torch.LongTensor] = None,
**kwargs,
) -> PrimeLmOutput:
if position_ids is None:
@@ -562,6 +575,7 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
)
hidden_states = outputs.last_hidden_state
+8 -3
View File
@@ -149,10 +149,15 @@ def _create_optimizer(
"""Create optimizer. If lr is None, uses config.lr."""
if lr is None:
lr = config.lr
# Only hand trainable params to the optimizer. Frozen params (e.g. the DSA sparse
# indexer, which runs under no_grad) carry no optimizer state, and including them
# breaks strict checkpoint resume (DCP materializes state for every requires_grad
# param at load time, mismatching the saved state). Muon filters internally below.
trainable_params = [p for _, p in named_params if p.requires_grad]
match config.type:
case "sgd":
return SGD(
params=[p for _, p in named_params],
params=trainable_params,
lr=lr,
weight_decay=config.weight_decay,
momentum=config.momentum,
@@ -160,7 +165,7 @@ def _create_optimizer(
)
case "adamw":
return AdamW(
params=[p for _, p in named_params],
params=trainable_params,
lr=lr,
weight_decay=config.weight_decay,
betas=(config.betas1, config.betas2),
@@ -169,7 +174,7 @@ def _create_optimizer(
return _create_muon_optimizer(config, named_params, parallel_dims, lr)
case "sign_sgd":
return SignSGD(
params=[p for _, p in named_params],
params=trainable_params,
lr=lr,
weight_decay=config.weight_decay,
)
+25 -1
View File
@@ -1,3 +1,4 @@
from collections.abc import Callable, Sequence
from pathlib import Path
from typing import TypedDict
@@ -10,7 +11,12 @@ from prime_rl.configs.trainer import FakeDataLoaderConfig
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.world import get_world
from prime_rl.transport import MicroBatch, MicroBatchReceiver, TransportConfig, setup_micro_batch_receiver
from prime_rl.transport import (
MicroBatch,
MicroBatchReceiver,
TransportConfig,
setup_micro_batch_receiver,
)
class TensorMicroBatch(TypedDict):
@@ -26,6 +32,7 @@ class TensorMicroBatch(TypedDict):
loss_mask: Bool[Tensor, "batch seq"]
temperatures: Float[Tensor, "batch seq"] # Per-token temperatures
env_names: list[str]
sequence_lengths: list[int]
# Batch level
lora_num_tokens: Int[Tensor, "n_loras"]
@@ -46,6 +53,10 @@ class TensorMicroBatch(TypedDict):
# sft → sft loss). All samples in a micro batch share the same mode.
training_mode: str
# Packer-derived metadata used for run-local debug exports.
run_id: str | None
run_step: int | None
class FakeDataLoader:
def __init__(self, config: FakeDataLoaderConfig, seq_len: int, dp_world_size: int):
@@ -84,6 +95,7 @@ class FakeDataLoader:
total_seq_len = 0
input_ids = []
position_ids = []
sequence_lengths = []
while total_seq_len < self.seq_len:
# Generate reasonably long documents
@@ -91,6 +103,7 @@ class FakeDataLoader:
if seq_len_to_generate + total_seq_len > self.seq_len:
seq_len_to_generate = self.seq_len - total_seq_len
total_seq_len += seq_len_to_generate
sequence_lengths.append(seq_len_to_generate)
tmp_input_ids = torch.randint(0, 120000, (seq_len_to_generate,), generator=generator).long()
tmp_position_ids = torch.arange(seq_len_to_generate).long()
@@ -114,12 +127,15 @@ class FakeDataLoader:
"teacher_logprobs": None,
"temperatures": torch.ones(input_ids.shape[0]).unsqueeze(0),
"env_names": ["fake"] * input_ids.shape[0],
"sequence_lengths": sequence_lengths,
"loss_mask": loss_mask.unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
"routed_experts": None,
"mm_kwargs": None,
"mm_token_type_ids": None,
"training_mode": "rl",
"run_id": None,
"run_step": None,
}
def _get_micro_batch(self, generator: torch.Generator) -> TensorMicroBatch:
@@ -142,12 +158,15 @@ class FakeDataLoader:
"teacher_logprobs": None,
"temperatures": torch.ones(self.seq_len).unsqueeze(0),
"env_names": ["fake"] * self.seq_len,
"sequence_lengths": [self.seq_len],
"loss_mask": torch.ones(self.seq_len, dtype=torch.bool).unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
"routed_experts": None,
"mm_kwargs": None,
"mm_token_type_ids": None,
"training_mode": "rl",
"run_id": None,
"run_step": None,
}
@@ -162,6 +181,7 @@ class DataLoader:
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
bin_cost: Callable[[Sequence[int]], int],
config: TransportConfig,
):
self.world = get_world()
@@ -173,6 +193,7 @@ class DataLoader:
tokenizer=tokenizer,
transport_config=config,
pad_to_multiple_of=pad_to_multiple_of,
bin_cost=bin_cost,
start_step=start_step,
)
@@ -236,6 +257,7 @@ class DataLoader:
loss_mask=torch.tensor(micro_batch.loss_mask, dtype=torch.bool).unsqueeze(0),
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
env_names=micro_batch.env_names,
sequence_lengths=micro_batch.sequence_lengths,
lora_num_tokens=torch.tensor(micro_batch.lora_num_tokens, dtype=torch.int32),
mm_kwargs=mm_kwargs,
mm_token_type_ids=torch.tensor(micro_batch.mm_token_type_ids, dtype=torch.long).unsqueeze(0)
@@ -243,6 +265,8 @@ class DataLoader:
else None,
routed_experts=routed_experts,
training_mode=micro_batch.training_mode,
run_id=micro_batch.run_id,
run_step=micro_batch.run_step,
)
+36 -2
View File
@@ -6,7 +6,7 @@ from beartype import beartype as typechecker
from jaxtyping import Bool, Float, Int, jaxtyped
from torch import Tensor
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, LossConfig
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, IPOLossConfig, LossConfig
from prime_rl.utils.utils import import_object
@@ -165,6 +165,35 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
return LossOutputs(loss=loss, metrics=metrics)
def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
advantages = inputs.advantages
loss_mask = inputs.loss_mask
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
trainer_logprobs, inference_logprobs
)
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
is_masked = abs_probs_diff > loss_config.ipo_threshold
keep_mask = loss_mask & ~is_masked
advantages = loss_config.adv_tau * advantages
pg_loss = keep_mask * advantages * importance_ratio
kl_loss = loss_mask * log_importance_ratio**2
loss = (-pg_loss + loss_config.kl_tau * kl_loss).sum()
metrics = {
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
"is_masked": _safe_mean(is_masked, loss_mask),
}
return LossOutputs(loss=loss, metrics=metrics)
def opd_loss_fn(inputs: LossInputs) -> LossOutputs:
"""
On-policy distillation loss: the default DPPO+KL math with the tau knobs
@@ -240,7 +269,8 @@ def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
- ``"opd"`` → ``opd_loss_fn`` (teacher KL as gradient signal, hardcoded
DPPO + KL knobs)
- ``"rl"`` → ``default_loss_fn(loss_config)`` for ``DefaultLossConfig``,
or the imported function for ``CustomLossConfig``.
``ipo_loss_fn(loss_config)`` for ``IPOLossConfig``, or the imported
function for ``CustomLossConfig``.
``trainer.loss`` only affects the rl path - opd and sft are independent.
"""
@@ -250,6 +280,10 @@ def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
def rl_fn(inputs: LossInputs) -> LossOutputs:
return custom_fn(inputs, **kwargs)
elif isinstance(loss_config, IPOLossConfig):
def rl_fn(inputs: LossInputs) -> LossOutputs:
return ipo_loss_fn(inputs, loss_config)
else:
def rl_fn(inputs: LossInputs) -> LossOutputs:
+47 -30
View File
@@ -4,6 +4,7 @@ import threading
import time
from abc import ABC, abstractmethod
from collections import deque
from collections.abc import Callable, Sequence
from transformers.tokenization_utils import PreTrainedTokenizer
@@ -32,6 +33,7 @@ class BasePacker(ABC):
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
):
self.logger = get_logger()
@@ -40,6 +42,7 @@ class BasePacker(ABC):
self.seq_len = seq_len
self.pad_to_multiple_of = pad_to_multiple_of
self.tokenizer = tokenizer
self.bin_cost = bin_cost
self.receiver = setup_training_batch_receiver(config)
shutil.rmtree(get_rollout_dir(self.multi_run_manager.output_dir), ignore_errors=True)
self.sender: MicroBatchSender = setup_micro_batch_sender(
@@ -84,9 +87,10 @@ class SinglePacker(BasePacker):
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, start_step)
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
assert self.multi_run_manager.max_runs == 1, "SinglePacker only supports one run"
def pack(self):
@@ -110,7 +114,14 @@ class SinglePacker(BasePacker):
num_train_workers=self.dp_world_size,
idxs=[0] * len(batch.examples),
num_loras=self.multi_run_manager.max_runs,
bin_cost=self.bin_cost,
)
# The receiver always stamps run_idx from used_idxs (a key of idx_2_id).
run_id = self.multi_run_manager.idx_2_id[batch.run_idx]
for worker_batches in micro_batch_grid:
for micro_batch in worker_batches:
micro_batch.run_id = run_id
micro_batch.run_step = batch.step
self.sender.send(micro_batch_grid)
@@ -123,9 +134,10 @@ class MultiPacker(BasePacker):
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, start_step)
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
# Per-run buffer: stores (TrainingSample, step) tuples
self.buffers: list[deque[tuple[TrainingSample, int]]] = [
deque() for _ in range(self.multi_run_manager.max_runs)
@@ -148,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:
@@ -216,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
@@ -253,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
@@ -300,13 +302,17 @@ class MultiPacker(BasePacker):
# Group samples by run_idx - each microbatch must contain samples from only ONE run
# because MultiLoRAGroupedExperts (MoE) only supports one adapter per microbatch
samples_by_run: dict[int, list[TrainingSample]] = {}
steps_by_run: dict[int, int] = {}
per_run_stats: dict[int, tuple[int, int]] = {}
for run_idx, sample, step in selected_samples:
if run_idx not in samples_by_run:
samples_by_run[run_idx] = []
steps_by_run[run_idx] = step
else:
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)
@@ -327,9 +333,15 @@ class MultiPacker(BasePacker):
num_train_workers=self.dp_world_size,
idxs=[run_idx] * len(run_samples),
num_loras=self.multi_run_manager.max_runs,
bin_cost=self.bin_cost,
)
run_id = self.multi_run_manager.idx_2_id[run_idx]
run_step = steps_by_run[run_idx]
# Merge into combined grid
for worker_idx, worker_batches in enumerate(run_micro_batch_grid):
for micro_batch in worker_batches:
micro_batch.run_id = run_id
micro_batch.run_step = run_step
all_micro_batches[worker_idx].extend(worker_batches)
self.sender.send(all_micro_batches)
@@ -341,10 +353,15 @@ def setup_packer(
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
transport_config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
) -> BasePacker:
multi_run_manager = get_multi_run_manager()
if multi_run_manager.max_runs == 1:
return SinglePacker(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, start_step)
return SinglePacker(
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
)
else:
return MultiPacker(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, start_step)
return MultiPacker(
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
)
+49 -27
View File
@@ -18,6 +18,9 @@ class DisabledTokenExporter:
def export(self, *args: Any, **kwargs: Any) -> None:
return
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
return
def close(self) -> None:
return
@@ -30,10 +33,10 @@ class TokenExporter:
) -> None:
self.rank = rank
self.output_dir = output_dir / "token_exports"
self._file: Any | None = None
self._closed = False
self._current_step: int | None = None
self._sequences_this_step = 0
self._initialized_files: set[tuple[str | None, int, int]] = set()
self._sequences_by_file: dict[tuple[str | None, int, int], int] = {}
self._pending_stable_dirs: dict[str | None, set[Path]] = {}
atexit.register(self.close)
def export(
@@ -42,17 +45,17 @@ class TokenExporter:
micro_step: int,
micro_batch: Mapping[str, Any],
model_output: Mapping[str, Tensor],
response_lengths: list[int],
sequence_lengths: list[int],
loss_config: Any,
) -> None:
if self._current_step != step:
self._start_step(step)
columns = _export_columns(micro_batch, model_output, loss_config)
_check_lengths(columns)
run_id = micro_batch.get("run_id")
export_step = micro_batch.get("run_step") if micro_batch.get("run_step") is not None else step
file_key = (run_id, export_step, self.rank)
start = 0
for micro_sequence_idx, length in enumerate(response_lengths):
for micro_sequence_idx, length in enumerate(sequence_lengths):
raw_end = start + length
end = _trim_padding(columns, start, raw_end)
if end > start and any(columns["loss_mask"][start:end]):
@@ -60,54 +63,73 @@ class TokenExporter:
{
"schema_version": SCHEMA_VERSION,
"step": step,
"export_step": export_step,
"rank": self.rank,
"micro_step": micro_step,
"micro_sequence_idx": micro_sequence_idx,
"export_sequence_idx": self._sequences_this_step,
"export_sequence_idx": self._sequences_by_file.get(file_key, 0),
"run_id": run_id,
"env_name": _first_non_empty(columns["env_names"][start:end]),
"training_mode": str(micro_batch["training_mode"]),
**_slice_columns(columns, start, end),
}
},
run_id,
export_step,
)
self._sequences_this_step += 1
self._sequences_by_file[file_key] = self._sequences_by_file.get(file_key, 0) + 1
start = raw_end
def close(self) -> None:
if self._closed:
return
self._closed = True
if self._file is not None:
self._file.close()
self._file = None
def _start_step(self, step: int) -> None:
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
# A single run step's sequences can span multiple trainer steps (the packer
# splits a run step across packs when it exceeds the token budget). Only
# finalize a run's export dir once that run step is fully consumed — the same
# `ready_to_update` signal that gates its optimizer step. ``run_id is None``
# is single-run export, where a step never spans trainer steps, so mark it now.
# The caller barriers first so a STABLE only lands after every rank flushed.
ready_run_ids = ready_run_ids or set()
for run_id in [rid for rid in self._pending_stable_dirs if rid is None or rid in ready_run_ids]:
for stable_dir in self._pending_stable_dirs.pop(run_id):
(stable_dir / "STABLE").touch()
def _export_dir(self, export_step: int, run_id: str | None) -> Path:
if run_id is not None:
return self.output_dir.parent / run_id / "token_exports" / f"step_{export_step}"
return self.output_dir / f"step_{export_step}"
def _export_file(self, export_step: int, run_id: str | None) -> Path:
if self._closed:
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
if self._file is not None:
self._file.close()
self._current_step = step
self._sequences_this_step = 0
step_dir = self.output_dir / f"step_{step}"
step_dir = self._export_dir(export_step, run_id)
try:
step_dir.mkdir(parents=True, exist_ok=True)
except FileExistsError:
if not step_dir.is_dir():
raise
self._file = (step_dir / f"rank_{self.rank}.jsonl").open("w", encoding="utf-8")
return step_dir / f"rank_{self.rank}.jsonl"
def _write(self, record: dict[str, Any]) -> None:
def _write(self, record: dict[str, Any], run_id: str | None, export_step: int) -> None:
if self._closed:
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
if self._file is None:
raise RuntimeError("Token exporter has no active step file")
self._file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
file_key = (run_id, export_step, self.rank)
mode = "a" if file_key in self._initialized_files else "w"
export_file = self._export_file(export_step, run_id)
with export_file.open(mode, encoding="utf-8") as file:
file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
self._initialized_files.add(file_key)
self._pending_stable_dirs.setdefault(run_id, set()).add(export_file.parent)
def setup_token_exporter(
config: TrainerConfig, parallel_dims: Any, world: Any, logger: Any
) -> TokenExporter | DisabledTokenExporter:
token_export_config = config.experimental.token_export
if token_export_config is None:
if not config.enable_token_export:
return DisabledTokenExporter()
if parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0:
return DisabledTokenExporter()
+25 -8
View File
@@ -46,6 +46,7 @@ from prime_rl.trainer.model import (
from prime_rl.trainer.parallel_dims import get_parallel_dims
from prime_rl.trainer.perf import get_perf_counter
from prime_rl.trainer.utils import (
build_bin_cost,
GarbageCollection,
MemoryProfiler,
Tensors,
@@ -55,7 +56,6 @@ from prime_rl.trainer.utils import (
get_ckpt_disk_metrics,
setup_torch_distributed,
print_benchmark,
get_response_lengths,
)
from prime_rl.trainer.world import get_world
from prime_rl.trainer.runs import setup_multi_run_manager, Progress, get_multi_run_manager
@@ -237,6 +237,7 @@ def train(config: TrainerConfig):
config.model.seq_len,
config.model.cp,
tokenizer,
build_bin_cost(model.config),
config.rollout_transport,
)
@@ -472,15 +473,15 @@ def train(config: TrainerConfig):
)
# Compute loss
response_lengths = get_response_lengths(position_ids)
sequence_lengths = micro_batch["sequence_lengths"]
loss, loss_tensors = compute_loss(
trainer_logprobs=out["logprobs"].squeeze().split(response_lengths),
inference_logprobs=inference_logprobs.squeeze().split(response_lengths),
teacher_logprobs=teacher_logprobs.squeeze().split(response_lengths)
trainer_logprobs=out["logprobs"].squeeze().split(sequence_lengths),
inference_logprobs=inference_logprobs.squeeze().split(sequence_lengths),
teacher_logprobs=teacher_logprobs.squeeze().split(sequence_lengths)
if teacher_logprobs is not None
else None,
advantages=advantages.squeeze().split(response_lengths),
loss_mask=loss_mask.squeeze().split(response_lengths),
advantages=advantages.squeeze().split(sequence_lengths),
loss_mask=loss_mask.squeeze().split(sequence_lengths),
loss_fns=loss_fns,
loss_scale=loss_scale,
training_mode=micro_batch["training_mode"],
@@ -512,7 +513,14 @@ def train(config: TrainerConfig):
for env_name, indices in env_to_indices.items():
tensors[f"mismatch_kl/{env_name}"].append(mismatch_kl[indices])
token_exporter.export(progress.step, micro_step, micro_batch, out, response_lengths, config.loss)
token_exporter.export(
progress.step,
micro_step,
micro_batch,
out,
sequence_lengths,
config.loss,
)
if is_tt_moe_model(model):
load_balance_stats = get_load_balance_stats(model)
@@ -534,6 +542,15 @@ def train(config: TrainerConfig):
micro_step_message += f" | Routing Conf. {tensors['routing_confidence'][-1].mean().item():.4f}"
logger.debug(micro_step_message)
if config.enable_token_export:
dist.barrier()
ready_run_ids = {
multi_run_manager.idx_2_id[idx]
for idx in multi_run_manager.ready_to_update_idxs
if idx in multi_run_manager.idx_2_id
}
token_exporter.mark_stable(ready_run_ids)
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
# across dp_cp so the final gradient is the true per-token mean over the global batch.
for param in model.parameters():
+238 -37
View File
@@ -1,10 +1,12 @@
import gc
import heapq
import json
import pickle
import shutil
import time
from collections import defaultdict
from collections.abc import Iterable
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass, field
from datetime import timedelta
from pathlib import Path
from typing import Any
@@ -28,6 +30,241 @@ from prime_rl.utils.utils import format_num, format_time, get_step_path
DEFAULT_TIMEOUT = timedelta(seconds=600)
def _text_config(model_config: Any) -> Any:
"""Unwrap a multimodal model's text config, else return the config unchanged."""
return getattr(model_config, "text_config", model_config)
def _is_mla(config: Any) -> bool:
return bool(getattr(config, "multi_latent_attention", False) or hasattr(config, "q_lora_rank"))
def _kv_channels(config: Any) -> int:
return getattr(config, "kv_channels", getattr(config, "head_dim", config.hidden_size // config.num_attention_heads))
def _qkv_projection_flops_per_token(config: Any) -> int:
"""Linear-in-seqlen FLOPs of the Q/K/V projections (per token)."""
hidden_size = config.hidden_size
num_attention_heads = config.num_attention_heads
kv_channels = _kv_channels(config)
is_mla = _is_mla(config)
qk_head_dim = getattr(config, "qk_head_dim", 0)
qk_pos_emb_head_dim = getattr(config, "qk_pos_emb_head_dim", 0)
if is_mla and getattr(config, "q_lora_rank", None) is not None:
q_flops = 2 * config.q_lora_rank * (hidden_size + num_attention_heads * (qk_head_dim + qk_pos_emb_head_dim))
else:
q_head_dim = (qk_head_dim + qk_pos_emb_head_dim) if is_mla else kv_channels
q_flops = 2 * hidden_size * num_attention_heads * q_head_dim
if is_mla and getattr(config, "kv_lora_rank", None) is not None:
v_head_dim = getattr(config, "v_head_dim", 0)
kv_flops = 2 * (
config.kv_lora_rank * (hidden_size + num_attention_heads * (qk_head_dim + v_head_dim))
+ hidden_size * qk_pos_emb_head_dim
)
else:
num_query_groups = getattr(
config, "num_query_groups", getattr(config, "num_key_value_heads", num_attention_heads)
)
kv_flops = 4 * hidden_size * num_query_groups * kv_channels
return q_flops + kv_flops
def _attention_flops_per_token_squared(config: Any) -> int:
"""Quadratic-in-seqlen FLOPs of the attention scores and values (per token^2)."""
num_attention_heads = config.num_attention_heads
kv_channels = _kv_channels(config)
if _is_mla(config):
qk_head_dim = getattr(config, "qk_head_dim", 0)
qk_pos_emb_head_dim = getattr(config, "qk_pos_emb_head_dim", 0)
v_head_dim = getattr(config, "v_head_dim", kv_channels)
return num_attention_heads * (qk_head_dim + qk_pos_emb_head_dim) + num_attention_heads * v_head_dim
return 2 * num_attention_heads * kv_channels
def _ffn_flops_per_token(hidden_size: int, ffn_hidden_size: int) -> int:
return 6 * hidden_size * ffn_hidden_size
def _dense_ffn_hidden_size(config: Any) -> int:
return getattr(
config, "ffn_hidden_size", getattr(config, "intermediate_size", getattr(config, "moe_intermediate_size", 0))
)
def _moe_ffn_hidden_size(config: Any) -> int:
"""Effective FFN width of an MoE layer: routed experts (topk) plus shared experts."""
dense_ffn = _dense_ffn_hidden_size(config)
routed_topk = getattr(config, "moe_router_topk", getattr(config, "num_experts_per_tok", 1))
moe_ffn = getattr(config, "moe_ffn_hidden_size", getattr(config, "moe_intermediate_size", dense_ffn))
return moe_ffn * routed_topk + (getattr(config, "moe_shared_expert_intermediate_size", None) or 0)
def _count_dense_and_moe_layers(config: Any) -> tuple[int, int]:
"""Split the model's layers into (dense, moe) counts."""
num_experts = getattr(config, "num_experts", getattr(config, "n_routed_experts", None))
if num_experts is None:
return config.num_hidden_layers, 0
moe_layer_freq = getattr(config, "moe_layer_freq", None)
if isinstance(moe_layer_freq, list):
num_dense = sum(1 for freq in moe_layer_freq if freq == 0)
num_moe = sum(1 for freq in moe_layer_freq if freq > 0)
elif isinstance(moe_layer_freq, int):
num_dense = sum(1 for i in range(config.num_hidden_layers) if i % moe_layer_freq != 0)
num_moe = config.num_hidden_layers - num_dense
elif getattr(config, "first_k_dense_replace", None) is not None:
num_dense = config.first_k_dense_replace
num_moe = config.num_hidden_layers - num_dense
else:
num_dense = 0
num_moe = config.num_hidden_layers
return num_dense, num_moe
def _packing_cost_coeffs(config: Any) -> tuple[int, int]:
"""Return the (linear, quadratic) coefficients of the per-sequence forward FLOPs."""
hidden_size = config.hidden_size
num_dense_layers, num_moe_layers = _count_dense_and_moe_layers(config)
qkv_per_token = _qkv_projection_flops_per_token(config)
attn_per_token_squared = _attention_flops_per_token_squared(config)
def layer_linear(ffn_hidden_size: int) -> int:
return qkv_per_token + 2 * hidden_size * hidden_size + _ffn_flops_per_token(hidden_size, ffn_hidden_size)
linear = (
num_dense_layers * layer_linear(_dense_ffn_hidden_size(config))
+ num_moe_layers * layer_linear(_moe_ffn_hidden_size(config))
+ 2 * hidden_size * config.vocab_size
)
quadratic = (num_dense_layers + num_moe_layers) * attn_per_token_squared
return linear, quadratic
def build_bin_cost(model_config: Any | None) -> Callable[[Sequence[int]], int]:
"""Build a closure scoring a packed bin by estimated forward compute.
With ``model_config=None`` the linear/quadratic coefficients are ``(1, 0)``, so
the cost reduces to the token count and balancing falls back to sequence length.
"""
if model_config is None:
linear, quadratic = 1, 0
else:
linear, quadratic = _packing_cost_coeffs(_text_config(model_config))
def bin_cost(seqlens: Sequence[int]) -> int:
return linear * sum(seqlens) + quadratic * sum(n * n for n in seqlens)
return bin_cost
@dataclass
class _WeightedSet:
total: int = 0
items: list[int] = field(default_factory=list)
def add(self, idx: int, weight: int) -> None:
self.items.append(idx)
self.total += weight
def merge(self, other: "_WeightedSet") -> None:
self.items.extend(other.items)
self.total += other.total
def __lt__(self, other: "_WeightedSet") -> bool:
if self.total != other.total:
return self.total < other.total
return self.items < other.items
class _KKState:
def __init__(self, items: list[tuple[int, int]], k: int):
self.sets = [_WeightedSet() for _ in range(k)]
for set_idx, (idx, weight) in enumerate(items):
self.sets[set_idx].add(idx, weight)
self.sets.sort(reverse=True)
@property
def spread(self) -> int:
return self.sets[0].total - self.sets[-1].total
def merge(self, other: "_KKState") -> None:
k = len(self.sets)
for i in range(k):
self.sets[i].merge(other.sets[k - 1 - i])
self.sets.sort(reverse=True)
def partitions(self) -> list[list[int]]:
return [sorted(weighted_set.items) for weighted_set in self.sets]
def __lt__(self, other: "_KKState") -> bool:
if self.spread != other.spread:
return self.spread > other.spread
return self.sets[0] > other.sets[0]
def _karmarkar_karp(weights: Sequence[int], num_partitions: int) -> list[list[int]]:
assert len(weights) >= num_partitions
assert len(weights) % num_partitions == 0
weighted_indices = sorted((weight, idx) for idx, weight in enumerate(weights))
states: list[_KKState] = []
for offset in range(0, len(weighted_indices), num_partitions):
items = [(idx, weight) for weight, idx in weighted_indices[offset : offset + num_partitions]]
heapq.heappush(states, _KKState(items, num_partitions))
while len(states) > 1:
state = heapq.heappop(states)
state.merge(heapq.heappop(states))
heapq.heappush(states, state)
return states[0].partitions()
def _partition_loads(weights: Sequence[int], partitions: list[list[int]]) -> list[int]:
return [sum(weights[i] for i in partition) for partition in partitions]
def _refine_by_swapping(weights: Sequence[int], partitions: list[list[int]]) -> list[list[int]]:
partitions = [list(partition) for partition in partitions]
loads = _partition_loads(weights, partitions)
while True:
best_swap = None
best_score = (max(loads), max(loads) - min(loads))
for left_rank in range(len(partitions)):
for right_rank in range(left_rank + 1, len(partitions)):
for left_pos, left_idx in enumerate(partitions[left_rank]):
for right_pos, right_idx in enumerate(partitions[right_rank]):
new_left = loads[left_rank] - weights[left_idx] + weights[right_idx]
new_right = loads[right_rank] - weights[right_idx] + weights[left_idx]
new_loads = list(loads)
new_loads[left_rank] = new_left
new_loads[right_rank] = new_right
score = (max(new_loads), max(new_loads) - min(new_loads))
if score < best_score:
best_score = score
best_swap = (left_rank, right_rank, left_pos, right_pos, new_loads)
if best_swap is None:
return partitions
left_rank, right_rank, left_pos, right_pos, loads = best_swap
partitions[left_rank][left_pos], partitions[right_rank][right_pos] = (
partitions[right_rank][right_pos],
partitions[left_rank][left_pos],
)
def balanced_partition(weights: Sequence[int], num_partitions: int) -> list[list[int]]:
"""Partition item indices into ``num_partitions`` groups of near-equal total weight.
Requires ``len(weights)`` to be a positive multiple of ``num_partitions``.
"""
partitions = _karmarkar_karp(weights, num_partitions)
return _refine_by_swapping(weights, partitions)
class GarbageCollection:
"""Controls Python garbage collection to avoid stragglers in distributed training.
@@ -143,42 +380,6 @@ def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: b
dist.init_process_group(backend=backend, timeout=timeout, device_id=device_id)
def get_response_lengths(position_ids: torch.Tensor) -> list[int]:
"""
Compute lengths of concatenated sequences from position_ids.
Each sequence starts at 0 and increments. When position_ids resets to 0,
it indicates the start of a new sequence. Trailing zeros (padding) are
counted as part of the last sequence.
Args:
position_ids: Tensor of shape [total_seqlen]
Returns:
List of sequence lengths
"""
position_ids = position_ids.flatten()
boundaries = [0] # Start of first sequence
for i in range(1, len(position_ids)):
if position_ids[i] == 0 and position_ids[i - 1] != 0:
# This is a potential sequence boundary (0 after non-zero)
# But only if the next element is 1 (indicating a new incrementing sequence)
# Otherwise, this 0 is padding and belongs to current sequence
if i + 1 < len(position_ids) and position_ids[i + 1] == 1:
boundaries.append(i)
# Calculate lengths based on boundaries
lengths = []
for i in range(len(boundaries)):
start = boundaries[i]
end = boundaries[i + 1] if i + 1 < len(boundaries) else len(position_ids)
lengths.append(end - start)
return lengths
def print_sample(input_ids: list[int], loss_mask: list[bool], tokenizer: PreTrainedTokenizer):
"""
Visualize the loss mask of a tokenized sample using rich.
+6 -1
View File
@@ -8,7 +8,12 @@ from prime_rl.transport.filesystem import (
FileSystemTrainingBatchReceiver,
FileSystemTrainingBatchSender,
)
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingBatch, TrainingSample
from prime_rl.transport.types import (
MicroBatch,
RoutedExperts,
TrainingBatch,
TrainingSample,
)
from prime_rl.transport.zmq import (
ZMQMicroBatchReceiver,
ZMQMicroBatchSender,
+15 -7
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,6 +77,7 @@ 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]
teacher_logprobs: list[float] | None = None
@@ -89,3 +93,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
# sft → sft loss). All samples packed into a micro batch share the same mode.
training_mode: TrainingMode = "rl"
rewards: list[float] | None = None
# Packer-derived metadata used for run-local token exports.
run_id: str | None = None
run_step: int | None = None

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