Compare commits

...
Author SHA1 Message Date
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
minh hoangandGitHub e5c9169566 chore: add tasksets/harnesses to exclude-newer ignore list (#2716)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-04 21:48:04 -07:00
65914f924f fix(configs): size dense multi-node NCCL world by inference GPU count (#2707)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The dense multi-node external-LB weight-broadcast world size was computed as total_infer_nodes * api_server_count * tp. api_server_count can resolve to the global DP size (e.g. when parallel.dp is set, or via validator ordering), which double-counts the node dimension, so the trainer's NCCL broadcast waits for more ranks than exist and init deadlocks.

Every allocated inference GPU is one NCCL rank, and the external-LB launcher starts dp_per_node TP-sharded servers per node (gpus_per_node workers/node), so size the world directly as total_infer_nodes * gpus_per_node. This matches the disaggregated path.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 15:40:54 -07:00
halleriteandGitHub b67fd12fe6 chore(renderers): bump submodule to renderers-v0.1.8.dev40 (#2718)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-04 22:13:50 +02:00
JannikStandGitHub e6998a6f41 feat: json logging for inference (vLLM) (#2466)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: json logging for inference (vLLM)

Adds [log] config to InferenceConfig and routes vLLM's stdlib loggers
(plus uvicorn / fastapi / root) through a JSON formatter matching the
trainer/orchestrator shape. Driven via VLLM_LOGGING_CONFIG_PATH so the
config crosses the multiprocessing.spawn boundary into vLLM workers.

* chore: ruff format

* fix: force VLLM_CONFIGURE_LOGGING=1 when setting LOGGING_CONFIG_PATH

vLLM raises at import if VLLM_CONFIGURE_LOGGING=0 and
VLLM_LOGGING_CONFIG_PATH is set. Setting json_logging is an explicit
opt-in to configure vLLM's logger, so override the env var rather than
crash on jobs that have it preset to 0.

* fix: emit tz-aware UTC timestamps in JsonFormatter

Match loguru's tz-aware ISO output so the platform's JsonLogsViewer
parses inference timestamps correctly. Naive timestamps are interpreted
as the viewer's local time, off by the viewer-vs-pod offset.

* fix: propagate top-level [log] settings to inference subconfig

RLConfig.auto_setup_logs already mirrors [log] into trainer and
orchestrator subconfigs. Now that InferenceConfig has its own [log]
field, propagate there too — without this, an RL run with
[log] json_logging=true at the root still emits text vLLM logs because
inference.log defaults to non-JSON.

* fix: guard None inference in auto_setup_logs

RLConfig.inference is Optional and defaults to None for setups like
elastic-inference-pool runs. The previous commit propagated [log]
unconditionally, crashing the validator on any RLConfig without an
[inference] section (caught by the test_load_configs unit tests on
configs/elastic/rl.toml).

* fix: propagate top-level [log] settings to teacher_inference

Mirrors the auto_setup_logs propagation to inference, so teacher
inference servers also pick up shared level / json_logging when they
are configured separately or auto-created without a rollout inference
to deep-copy from.

* fix: map loguru-only levels (TRACE, SUCCESS) before dictConfig

Stdlib logging does not know TRACE/SUCCESS, so setting [log] level =
"trace" or PRIME_LOG_LEVEL=trace would crash setup_vllm_env when JSON
logging is enabled. Map TRACE→DEBUG and SUCCESS→INFO before building
the dictConfig payload.

* fix: route transformers logs through JSON handler

The docstring claimed transformers was covered but the named-loggers
tuple omitted it, so HF model-loading warnings/info were emitted as
plain text in otherwise-JSON inference logs (transformers sets
propagate=False on its own logger).

* fix: preserve per-component json_logging when shared [log] omits it

Codex P2: SharedLogConfig.json_logging defaulted to False, so auto_setup_logs would clobber any per-component (inference, teacher_inference) override back to text whenever the shared [log] section wasn't set. Mirrors the existing 'level' pattern: nullable on SharedLogConfig, gate propagation on the shared value being explicitly set.
2026-06-04 22:05:52 +02:00
halleriteandGitHub 7f6ca61ecc fix(inference): restore NemotronH mixer.D after vLLM 0.22 layerwise reload (#2714)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-04 22:00:06 +02:00
minh hoangandGitHub 434c9c0a42 docker: bump to ubuntu24.04 (#2717)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
mooncake-transfer-engine 0.3.11.post1 only publishes a
manylinux_2_39_aarch64 wheel for ARM (needs glibc ≥ 2.39) and 22.04
ships with glibc 2.35
2026-06-04 12:44:09 -07:00
halleriteandGitHub 3979894bae fix(trainer): disable NemotronH HF-Hub mamba kernels for offline init (#2713)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-04 16:47:47 +02:00
JannikStandGitHub 63af82343d fix(trainer): guard against validation hook crash taking down trainer (#2698)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(trainer): don't crash trainer when validation hook fails

validate_lora_rank dereferenced student.model.lora without a None
check, so an orchestrator config with no LoRA section raised
AttributeError. The hook was called outside get_orchestrator_config's
try/except, so the exception propagated out of discover_runs through
the train loop, killed the master rank, and left worker ranks waiting
forever on rollouts that would never be written.

- Guard model.lora is None in validate_lora_rank so we reject cleanly
- Wrap hook calls in get_orchestrator_config in try/except so any
  future hook bug returns the run to the retry path instead of taking
  down the trainer

* fix(trainer): use safe fallback for hook name in error message

Validation hooks are typed as Callable, so hook.__name__ isn't
guaranteed (callable objects and functools.partial don't have it). If
such a hook raised, the exception handler itself would raise
AttributeError and defeat the try/except.

Per Codex review on #2698.
2026-06-04 18:41:03 +08:00
samsjaandGitHub 5b5f234053 add worlde (#2704)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-04 12:18:42 +02:00
f619e36b63 fix(ckpt): master-only mkdir + barrier to avoid concurrent-mkdir race on parallel FS (#2699)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Path.mkdir(exist_ok=True) re-checks self.is_dir() after EEXIST and re-raises if
it returns False. On a parallel filesystem (beegfs) with concurrent mkdir from
every trainer rank, a non-master rank can hit EEXIST while its metadata cache
hasn't seen the new inode yet -> is_dir() returns False -> FileExistsError,
crashing the trainer mid-save (observed at weights/step_180).

Guard the three all-ranks mkdir sites behind world.is_master + a barrier so only
the master creates the dir and the others wait until it exists:
- CheckpointManager.save_to_path: dataloader_dir
- CheckpointManager.save: ckpt_path.parent
- WeightCheckpointManager.save: step_path

Mirrors the existing master-only guard in WeightCheckpointManager.save_to_path.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 18:16:43 +02:00
samsjaandGitHub 563b37a9c7 fix: preserve Qwen3.5 broadcast weight names (#2690)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* exp: add qwen35 kl debug configs

* exp: lower qwen35 wordle kl drift

* fix: preserve qwen3.5 broadcast weight names

* chore: keep qwen35 debug configs local

* chore: clarify qwen3.5 weight naming bypass

* fix: use upstream qwen3.5 conversion mapping

* chore: use released transformers package

* chore: drop qwen3.5 cp patch

* chore: remove wordle env packaging
2026-06-03 07:50:18 -07:00
e7517948f2 chore(slurm): use external-LB everywhere, drop hybrid-LB (#2696)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(slurm): use external-LB everywhere, drop hybrid-LB

Unify every router-fronted vLLM launch path on external load balancing:
one API server per DP rank on PORT+k, each pinned to its TP slice of GPUs,
with the router balancing across the per-rank endpoints. This removes the
hybrid-LB mode (data_parallel_hybrid_lb / data_parallel_start_rank /
--intra-node-data-parallel-size) from both the RL and standalone-inference
SLURM templates, across multi-node and disaggregated (P/D) deployments.

- Extract the duplicated per-rank vLLM launch into a shared
  `_launch_rank.sh.j2` helper, included once and called from every launch
  site in both templates.
- Build per-rank router worker URLs (BACKEND_PORT+k for multi-node;
  PREFILL_PORT+k / DECODE_PORT+k for P/D).
- TP-correct DP group sizing (DP = nodes_per_role_replica * dp_per_node),
  fixing the latent tp>1 bug where the disaggregated inference path sized
  the group as nodes * gpus_per_node.
- Pass data_parallel_rpc_port + enable_expert_parallel to the multi-node
  standalone-inference template so per-rank MoE EP groups rendezvous
  node-locally.
- Drop the now-dead USE_DISTRIBUTED_EP gate (EP is decided directly by
  enable_expert_parallel).
- Fix a latent apostrophe in a bash -c comment ("can't" -> "cannot") that
  broke `bash -n` on multi-node non-disaggregated renders.
- Route DP rank 0 to the node-level log (node_<rank>.log, the target of the
  top-level inference.log symlink) via a shared `rank_log` helper, so
  inference.log captures real server output again instead of just the preamble;
  ranks 1+ keep their own node_<rank>_rank<k>.log.

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

* refactor(slurm): extract router launch into _launch_router helper

Pull the per-replica vllm-router invocation (repeated across the multi-node
and disaggregated launch sites in both templates) into a shared
`_launch_router.sh.j2` helper: `launch_router <mode:pd|regular> <worker_args>
<port> <policy> <log> [replica_idx]`. Call sites now resolve the worker URLs
and call the helper, instead of inlining the `vllm-router` command four times.

This localizes the router launch to one place — a future llm-d (EPP+Envoy)
backend slots in as a single branch inside the helper rather than touching
every call site.

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

* fix(slurm): per-rank metrics roles + multi-node EP DP coordinator address

Two correctness fixes for the external-LB paths:

- inference_metrics_roles: external-LB exposes one admin client per DP rank,
  but the role list was built per node. Expand it per rank
  (stride = gpus_per_node / tp) so prefill/decode labels line up with the
  per-rank ADMIN_URLS the orchestrator collects metrics from.
- multi-node MoE EP: data_parallel_address was chosen on the global DP rank,
  so every local rank after the first on the replica head got the head
  hostname instead of the head's own IP — non-zero local ranks on the head
  could fail to rendezvous with the DP coordinator when dp_local > 1. Choose
  the address per node (head ranks use LOCAL_IP, other nodes use the head
  hostname), matching the disaggregated path.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 04:29:56 +02:00
43f6261454 refactor(inference): RouterConfig on the base inference deployment (#2695)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Introduce a `RouterConfig` (currently just `vllm-router`, with `type`/`port`/
`policy`) and put `router: RouterConfig` on `BaseInferenceDeploymentConfig`,
alongside `backend_port`. Previously `router_port`/`router_policy` lived only on
the multi-node / disaggregated deployment types, so the RL launcher needed
`getattr(inference.deployment, "router_port", 8000)` to cover a multi-node
allocation running a single-node inference deployment (e.g. general_agent).

Now every deployment type carries the router config and the launchers read
`deployment.router.port` / `deployment.router.policy` directly. These are
external-LB serving config — only used when the inference is served as a fleet
behind the router (a multi-node allocation, or a standalone multi-node /
disaggregated inference); a co-located single-node server ignores them.

`RouterConfig` is a `type`-discriminated alias (single member for now), so other
router backends can be added to the union without touching call sites. The SLURM
templates are unchanged — the entrypoints still pass the same `router_port` /
`router_policy` template vars — so the rendered scripts are byte-identical.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 04:16:14 +02:00
bf7eab0640 fix(inference): require SLURM for disaggregated deployment (#2694)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
`validate_multi_node_requires_slurm` only checked `multi_node`, but a
disaggregated (P/D) deployment is equally multi-node (separate prefill/decode
node groups + NIXL) and needs SLURM. Without this, a disaggregated
`InferenceConfig` with no slurm passed validation and fell through to the local
launcher, which cannot run it.

The same `InferenceConfig` is also used nested inside `RLConfig`, where slurm
lives at the top level — so also forward top-level `[slurm]` into the nested
inference (RL P/D, e.g. examples/glm5_pd_disag, sets `[slurm]` but not
`[inference.slurm]`). The per-rank `inference.toml` already excludes `slurm`, so
each rank still runs locally — no SLURM-in-SLURM.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 02:33:43 +02:00
halleriteandGitHub 8d88f5e302 chore: bump verifiers submodule to main (v1 seq_len fix) (#2692)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-03 00:20:45 +02:00
c13409e2c1 [KV Offload]: Tiered offloading + MoonCakeStore (#2689)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(inference): tiered KV cache offload (native + mooncake, CPU/disk)

Replace the flat `inference.kv_cache_offload` (single `cpu_bytes`) with a typed,
backend-swappable, tiered config discriminated on `type`:

- native: vLLM `OffloadingConnector` (cpu) / `TieringOffloadingSpec` (cpu+disk,
  fs_python secondary). Fully self-contained.
- mooncake: per-node standalone-store (`mooncake_master` + `mooncake_client`, RDMA),
  cpu and/or disk tiers.

Composable `cpu`/`disk` tiers (cpu required, disk-only rejected); `disk.num_bytes`
is mooncake-only (native fs tier is filesystem-bounded; warns if set on native).

Centralize the vLLM `kv_transfer_config` build in
`InferenceConfig.build_kv_transfer_config` (NIXL transfer + offload composed via
`MultiConnector`); both SLURM templates stop hand-rolling the JSON and launch the
node-local Mooncake store. New `src/prime_rl/inference/mooncake.py` launches the
master+client and writes `MOONCAKE_CONFIG_PATH`; `server.py` brings it up for local
runs.

Verified:
- Single-node (Qwen3-0.6B, H200): all four configs boot + serve; native-cpu and
  mooncake-rdma both round-trip KV (store ~1.1GB / reload ~205MB).
- Multi-node 3-node SLURM disaggregated (Qwen3-30B-A3B): NIXL P/D transfer serves
  coherent output; with mooncake offload, MultiConnector[Nixl, MooncakeStore] +
  per-node RDMA store serves coherent output.

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

* chore(inference): drop unused mooncake disk num_bytes and metadata_server

- DiskOffloadTier.num_bytes: removed. Neither backend enforces a disk byte quota
  (capacity is bounded by the filesystem at disk.path), so it was a no-op knob.
- MooncakeKVCacheOffloadConfig.metadata_server: removed. The launcher always hosts
  the HTTP metadata server on the node-local master and auto-derives the URL from the
  master host.

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

* refactor(inference): launch Mooncake store in sbatch bash; add CHANGELOG

Address PR review: replace the Python launcher CLI (+ env.sh round-trip) with an
explicit bash launch in the SLURM templates, and document the breaking config change.

- New `templates/_mooncake_store.sh.j2` partial (shared via `{% include %}` by
  `inference.sbatch.j2` and `multi_node_rl.sbatch.j2`): launches the node-local
  `mooncake_master` + `mooncake_client`, writes the config JSON, and exports
  `PYTHONHASHSEED` / `MOONCAKE_CONFIG_PATH` inline — visible in the rendered script.
  Removes the hacky orphan-process CLI, the `print`, and the unquoted-`env.sh` round-trip.
- Delete `src/prime_rl/inference/mooncake.py` and the `server.py` store-launch hook.
- Mooncake offload is now SLURM-only: `inference_local` errors (when no store env is
  present) and an `RLConfig` validator rejects local RL + mooncake. Native offload is
  unchanged and still works locally. Entrypoints pass `kv_offload_{cpu_bytes,disk_path,
  device_name}` template vars.
- CHANGELOG.md: document the `inference.kv_cache_offload.cpu_bytes` -> discriminated
  `type` breaking change (per .cursor/BUGBOT.md).

Verified single-node SLURM (Qwen3-0.6B): store launches via the template bash,
MooncakeStoreConnector (standalone-store) loads, and the server serves coherent output.

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

* feat(inference): Mooncake shared distributed KV pool across nodes

Switch the Mooncake offload backend from per-node isolated stores to a single shared
distributed pool, so all inference nodes' CPU RAM (and disk) form one KV cache and a
prefix cached on any node is reusable by every other node/replica.

- `_mooncake_store.sh.j2`: the head inference node (first in the SLURM nodelist) runs the
  one master + HTTP metadata server; every node runs a client pointing at the head and
  contributes its segment. Store keys are model + parallel-rank + content-hash (no instance
  id), so the pool is reused across nodes and replicas.
- Drop the now-unused `MooncakeKVCacheOffloadConfig.master_server_address` (auto head).
- docs: describe the shared pool (total pool ≈ num_bytes × #inference-nodes).

Verified on a 2-node SLURM job (Qwen3-0.6B): one master on the head, both clients join
(2 segments), and a prefix cached on node A is served from node B over RDMA
(load_get ~160 MB cross-node hit).

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

* chore(inference): drop runtime mooncake-requires-slurm check

The RLConfig `validate_mooncake_offload_requires_slurm` config validator already guards
the misuse case; the per-request runtime check in `inference_local` (and its `import os`)
was redundant. Remove it.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 09:19:09 -07:00
samsjaandGitHub c613ec5631 feat: enable fp32 lm head by default (#2685)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-02 09:18:35 -07:00
3ce918920f feat: basic verifiers v1 training (#2637)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(deps): bump verifiers to v0.1.15.dev18 (latest main)

deps/verifiers -> e1d4f259 (v0.1.15.dev18, head of verifiers main).
This branch previously needed to pin *before* #1414 (per-token prompt
attribution to TrajectoryStep), which stuffed a non-JSON-serializable
RenderedTokens into trajectory state and broke v1's
state.assert_serializable(). That has since been fixed upstream by
#1471 (renderers <-> v1: serializable RenderedTokens), so we track
latest main again. Also includes #1462 (TasksetConfig rework) and
#1467 (typed RendererConfig).

Co-authored-by: Cursor <cursoragent@cursor.com>

* exp: reverse_text v1 smoke config

Minimal 2-GPU smoke config for the v1 path: `reverse-text` env via
`args = { v1 = true }`, in-process vf.Harness, no tools.

* refactor(orchestrator): fan out temperature at batch build

Single env-wide temperature per rollout — assume the config surface
(one [orchestrator.train.env.sampling] block per env), drop the
output -> trajectories round-trip:

- Drop `sampling_args` from REQUIRED_STATE_COLUMNS. The orchestrator
  already knows each env's temperature from its TrainEnv.sampling_args,
  so there's no reason to require envs to mirror it back through state.
  This also unblocks v1 envs, which route sampling_args through
  state["runtime"] and don't surface it at the top level.
- interleave_rollout no longer reads output["sampling_args"]["temperature"]
  or fills `completion_temperatures`; it leaves the field empty.
- TrainSink.process_group fans the env's scalar temperature out across
  each sample's completion tokens in the same loop that stamps
  advantage / reward / env_name / training_mode, before the batch is
  assembled.

TrainingSample / TrainingBatch wire format is unchanged. Trainer-side
per-token temperature scaling (scaled_logits = logits / temps) keeps
working as-is.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-01 18:44:06 -07:00
517ee5c486 fix(orchestrator): drop cache_salt for SFT teacher rollouts (#2687)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The teacher's weights are frozen, so salting its prefix-cache with the
student's policy version forces unnecessary cache invalidation on every
weight update. Send no salt when train rollouts route to the teacher
pool; student (RL/OPD train + all eval) paths keep the policy-version
salt as before.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-01 16:20:54 -07:00
b243184d19 Feat: bump vllm to 0.22 (#2686)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* Feat: bump vllm to 0.22

* fix: regenerate uv.lock against merged verifiers submodule

The merge commit locked uv.lock while deps/verifiers was still checked out
at the pre-merge commit, so the verifiers package metadata (harnesses/
tasksets editable packages, dropped nltk/textarena) was stale and failed
'uv sync --locked' in CI. Re-locked with the submodule at the merged gitlink.

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 00:55:19 +02:00
samsjaandGitHub f3ad435508 move verifieres from workspace to editable install (#2684)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* move verifieres from workspace to editable install

* move every submodule deps as editable instead of workspace
2026-06-01 15:29:19 -07:00
da9a92a79c fix(test): drop flaky step-7 reward upper bound in multi-run test (#2682)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The step-7 max_threshold=0.6 check pins an early reward value below a
boundary that run-to-run noise routinely crosses (reward bounces around
0.5-0.6 in the step 6-8 window), causing spurious failures. The
learning-curve property is already covered by check_reward_goes_up, the
final >= 0.65 check, and the step-7 >= 0.2 minimum, so the upper bound
adds no real coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-01 13:34:29 -07:00
Matej SirovatkaandGitHub 9589c04de3 [Minor]: Docs (#2680)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* Fix: advanced

* Fix: development

* Fix: overview

* Fix: scaling

* Fix: inference

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-06-01 12:27:27 -07:00
f6563ff0ee feat(orchestrator): refactor to overlap train/eval (#2639)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): add orchestrator v2 with shared train+eval scheduler

Opt-in via `orchestrator.experimental.use_orch_v2 = true`. Replaces the
step-driven outer loop of `prime_rl.orchestrator` with an async pipeline
backed by a single dispatcher that schedules both train and eval rollouts
through a shared concurrency limiter and rate limiter.

The dispatcher uses a level-triggered `SchedMode.PREFER_TRAIN | PREFER_EVAL`:
on each eval-trigger boundary it stops scheduling new train rollouts but
lets the in-flight tail drain naturally, then resumes train as soon as the
eval queue empties. Both transitions overlap on the same semaphore, so the
pool stays saturated and we recover the cost of the current "blocking eval"
behavior without cancelling work.

Module layout (src/prime_rl/orchestrator_v2/):
- `policy.py` — shared mutable `Policy(version, model_name)`
- `watcher.py` — polls broadcasts, calls `update_weights`, notifies observers
- `dispatcher.py` — shared semaphore + AsyncLimiter, PREFER_TRAIN/PREFER_EVAL,
  off-policy cancellation, partial-group handling, per-env eval triggers
- `batcher.py` — pre_batch_filters → compute_advantages (in dispatcher) →
  batch buffer → post_batch_filters → tokenize → ship; eval aggregator with
  per-`eval_step` flush
- `log_loop.py` — `IntervalLogger` task writes dispatcher gauges +
  event-loop lag to wandb on the `_timestamp` axis (async-native, decoupled
  from step semantics)
- `ckpt.py` — lean `Progress(step, last_eval_step)` checkpoint manager
- `orchestrator.py` — wires everything in `asyncio.TaskGroup`, bounded
  graceful shutdown

Config evolution (additive, non-breaking):
- `pre_batch_filters` and `post_batch_filters` fields added.
- `filters` is silently aliased to `post_batch_filters` via
  `AliasChoices` — no deprecation warning, all existing TOMLs keep parsing.
- Default pre slot registers all three filter types in monitor mode;
  default post slot is unchanged from today's `filters` default
  (zero-advantage enforced, gibberish/repetition in monitor mode). Net
  out-of-the-box behavior matches the legacy orchestrator.
- `OrchestratorExperimentalConfig.use_orch_v2: bool = False` flips the
  `rl` entrypoint to launch `orchestrator-v2` instead of `orchestrator`.
- `OrchestratorExperimentalConfig.log_loop_interval: float = 5.0` controls
  the gauge cadence.
- `BufferConfig` and `eval.cancel_inflight_rollouts_on_eval` are still
  parsed (the legacy orchestrator still uses them) but v2 simply doesn't
  consume them. Difficulty pools are replaced by `pre_batch_filters`;
  eval transitions in v2 always use the drain-switch overlap.

Entrypoint wiring:
- New `orchestrator-v2` console script in `pyproject.toml`.
- `rl` launcher picks between `orchestrator` and `orchestrator-v2` based
  on the flag.
- New `configs/debug/orch_v2.toml` overlay flips the flag for parity
  testing against the same TOML.

Refs https://github.com/PrimeIntellect-ai/prime-rl/issues/2311.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(orchestrator_v2): address review feedback

- Make `Orchestrator` a proper class with `__init__` / `setup` / `start` /
  `stop` / `shutdown` methods. No more module-level `orchestrate` coroutine —
  the new `run_orchestrator` is a thin `@clean_exit`-wrapped helper that
  instantiates the class and awaits `start()`.
- Replace the `Done` exception with a shared `orch.stopped: asyncio.Event`.
  The batcher sets it when `max_steps` is reached; `Orchestrator.start()`
  blocks on it and then drives the shutdown sequence. No more
  exception-driven control flow / `except* Done` group-unwinding.
- Rename `run` → `start` across all async components (`RolloutDispatcher`,
  `TrainBatcher`, `WeightWatcher`, `IntervalLogger`).
- Slim `TrainBatcher.__init__` to a single `orch: Orchestrator` arg
  (previously 16 wiring args). The batcher reads shared state via
  `@property` accessors on `self.orch` — no behavior change, just less
  ceremony at construction time.
- Drop all leading-underscore "private" methods and attributes on the v2
  classes — we're not designing an API. Notably, `_handle_train`,
  `_ship_batch`, `_wait_barrier`, `_fill_inflight`, `_try_schedule_*`,
  `_schedule_group_rollout`, `_handle_completed_rollout`,
  `_maybe_finalize_group`, `_select_least_loaded_client`, `_acquire`,
  `_release`, `_drop_group`, `_apply_policy_update`, `_compute_next_ckpt_step`,
  etc. all lose the underscore. Internal state (`_stopped`, `_task`, etc.)
  too.
- Remove `MAX_EMPTY_BATCH_ATTEMPTS`. If a batch has zero trainable signal,
  the batcher logs a warning and just retries on the next batch instead
  of crashing after N consecutive empties.
- Remove `drain_pending_eval` from `TrainBatcher` and the matching
  `force_eval` from `RolloutDispatcher` — not a behavior we want to
  support. Final evals at end-of-run still run via the legacy
  `EvalEnv.evaluate` path (now called directly from `Orchestrator.start()`).
- Soften the barrier stall log: drop the speculative "Trainer may be
  stuck." sentence. Most of the time inference is just faster than the
  trainer, so the message was misleading. Bumped the first-warn threshold
  from 30s → 60s while we're there.
- Revert `uv.lock` to `main` (the previous commit picked up a stray
  `wikispeedia` workspace member from `uv sync --all-extras` that wasn't
  part of this PR).

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(orchestrator_v2): decompose batcher into single-purpose components

Splits the previous catch-all ``TrainBatcher`` into four single-purpose
classes, each with explicit data-flow dependencies declared at construction
time. No more parent ``orch`` back-pointer / property-shim layer.

New module layout:

- ``batcher.py`` — ``Batcher``: pure in-memory accumulator with
  ``add / ready / pop / buffered_count``. Owns the pre-batch filters and the
  per-batch pre-filter counters. No I/O, no async, no step tracking.
- ``postprocessor.py`` — ``PostProcessor``: takes a popped batch + step
  number, runs post-batch filters, tokenizes, builds ``TrainingSample``\\ s,
  computes teacher logprobs (opd), and ships via the sender. Returns a
  ``ProcessResult`` carrying the per-rollout stats the metrics builder
  needs — so this class doesn't import pandas.
- ``eval_collector.py`` — ``EvalCollector``: buckets eval ``Trajectory``\\ s
  by ``eval_step``; flushes per-env reward / completion-len / pass@k metrics
  when the dispatcher's expected count comes back. Takes ``(expected,
  fired_envs)`` as call args instead of reaching into the dispatcher.
- ``metrics.py`` — ``MetricsBuilder``: assembles the per-step W&B dict from
  the rollout cohort + ``ProcessResult`` + dispatcher gauges. Pure-ish; only
  state is the config.

``Orchestrator`` now owns the pipeline driver loop:

- ``main_loop`` pulls trajectories off the dispatcher queue, routes train vs
  eval, drives ``batcher.add → batcher.pop`` and ``postprocessor.process``,
  builds metrics, logs to the monitor, and increments ``progress.step``.
- ``process_one_step`` is the single shipping step (ckpt save → max_steps
  check → pop → ship → barrier wait → metrics + log → step++).
- ``wait_barrier`` and ``maybe_save_ckpt`` are public helper methods on the
  orchestrator (no leading underscores; the v2 classes deliberately don't
  hide internals).

Dependency surface, post-refactor — every arrow is a real data-flow dep
declared at the call site, not a "shared context" smell:

  Batcher        ← config (batch_size / token_batch_size), pre_filters
  PostProcessor  ← config, tokenizer, renderer, mm_token_type_ids_mapping,
                   sender, teacher_inference, post_filters
  EvalCollector  ← config, monitor, eval_envs, post_filters
  MetricsBuilder ← config
  IntervalLogger ← dispatcher, policy, interval  (no more batcher refs)
  Orchestrator   ← owns all of the above

Also:

- Rename ``TrainBatcher`` → ``Batcher``: ``EvalCollector`` is the eval-side
  abstraction now, so the prefix is misleading.
- Drop the parent-pointer ``orch: Orchestrator`` constructor argument and
  the ``@property`` shim layer it forced (``dispatcher``, ``policy``,
  ``progress``, ``monitor`` etc. all read off ``self.orch`` previously).
- ``IntervalLogger`` no longer reads ``batcher.last_*`` cached state — those
  fields are gone. Step-aligned values plot fine via the per-step monitor
  log; the time-axis emit just covers dispatcher gauges + event-loop lag.
- Remove ``wikispeedia`` from ``pyproject.toml`` (stray pickup from a local
  ``uv sync --all-extras`` during dev).

Smoke: 8-step reverse-text run under v2 with the new layout, reward
0.11 → 0.24, clean event-based shutdown via ``self.stopped.set()`` at
``max_steps``.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(orchestrator_v2): rollout-as-atom + train/eval sinks with flush signals

Redesigns the data flow to be signal-based. The atomic unit emitted by the
dispatcher is now a single Rollout (one completed rollout, never a group).
Grouping moves into the sinks. Each sink owns its own flush signal:

- TrainSink groups rollouts by (env_name, example_id). When
  Rollout.is_group_complete=True arrives, the GRPO group is finalized:
  compute_advantages over the survivors, then apply_filters for the
  pre-batch pass, then drop filtered rollouts and extend batch_buf. The
  flush signal is batch_ready() — the orchestrator polls it after every
  add() and calls pop() to ship a batch.
- EvalSink groups rollouts by (env_name, eval_step). When
  Rollout.is_group_complete=True arrives, the env's eval epoch is done.
  add() returns an EvalFlush payload that the orchestrator logs.
  Filters do not apply to eval — filters are train-only by design.

Dispatcher changes:

- Trajectory (group of rollouts) replaced by Rollout (single rollout).
  maybe_finalize_group / emit_group push individual rollouts to out_q
  instead of one Trajectory per group.
- Train: the last surviving rollout of each (env, example_id) group gets
  is_group_complete=True.
- Eval: tracked per (env_name, eval_step) via eval_expected_per_env /
  eval_emitted_per_env / eval_dropped_per_env. The last expected rollout
  (emitted + dropped == expected) gets is_group_complete=True, flagging
  the env's epoch as done.
- compute_advantages is no longer called here — that's a train-sink
  concern now.
- Drops the cross-env expected_eval_counts dict and replaces it with
  per-env tracking.

Orchestrator changes:

- main_loop consumes Rollout and routes by kind. Train rollouts go to
  train_sink.add(); batch_ready() triggers process_one_step. Eval
  rollouts go to eval_sink.add(); an EvalFlush return triggers
  flush_eval (per-env metric logging on the orchestrator since it needs
  self.monitor and the logic is small).
- flush_eval is a new public method that builds per-env reward / seq-len
  / pass@k metrics from an EvalFlush and logs them via the monitor.
- post_filters is now a member field used by PostProcessor only; the
  eval path doesn't read it.

Removed:

- orchestrator_v2/batcher.py (replaced by train_sink.py)
- orchestrator_v2/eval_collector.py (replaced by eval_sink.py)

Smoke (eval.interval=5, max_steps=12, num_examples=16):

- Step 0 eval (eval_base_model) flushes cleanly: Reward 0.17.
- Step 5 eval triggers with inflight_train=121 — drain-switch overlap
  intact. Eval flushes per-env (Reward 0.54) while train continues
  (steps 6-8 ship during eval drain).
- Reward 0.14 → 0.60 over 12 steps; clean event-driven shutdown via
  self.stopped.set() at max_steps.

* refactor(orchestrator_v2): three-level sinks (rollout / group / batch)

Both TrainSink and EvalSink now have a uniform three-level processing
structure. The dispatcher emits Rollout (atomic unit) with two boundary
signals; sinks dispatch each level to a named process function whose
logic naturally lives at that scope:

  Level    When                    Method                What it does
  -------- ----------------------- --------------------- -----------------------------
  rollout  every add()             process_rollout       train: backfill + interleave (eager tokenization)
                                                         eval:  no-op
  group    is_group_done=True      process_group         train: compute_advantages + pre_batch_filters
                                                         eval:  move per-example group into env batch bucket
  batch    batch_ready (train)     process_batch         train: post_batch_filters + assemble samples + metrics
           is_batch_done (eval)                          eval:  build per-env metrics (reward, pass@k, ...)

Dispatcher Rollout dataclass:

- is_group_complete split into two boundary signals:
  - is_group_done: last rollout of the (env, example_id) group. Set for
    both train (GRPO group) and eval (per-example group).
  - is_batch_done: last rollout of an eval env-epoch (emitted+dropped ==
    expected). Always False for train — the train sink decides batch
    boundaries itself from batch_size / token_batch_size.
- emit_group sets both flags appropriately per kind.

TrainSink:

- async add(rollout) returns True when the batch is ready to pop.
- process_rollout is the eager-tokenize hook. Per-rollout tokenization
  overlaps with the dispatcher producing more rollouts, removing the
  parallel-tokenize-all-at-ship-time sync point.
- process_group runs compute_advantages, propagates advantage / reward /
  env_name onto the already-tokenized TrainingSamples, then runs the
  pre-filter pass.
- pop_batch(step, progress, gauges, ...) runs process_batch internally
  and returns a TrainBatchResult { rollouts, samples, metrics, result }.
- Owns the MetricsBuilder reference; per-batch metrics are part of
  process_batch, not a separate orchestrator step.

EvalSink:

- add(rollout) returns an EvalBatchResult when an env-epoch is complete
  (is_batch_done arrived).
- process_rollout is a no-op (kept for structural symmetry with
  TrainSink).
- process_group buckets the per-example group into the (env, eval_step)
  batch.
- process_batch / build_metrics produces the eval/{env}/ metrics dict
  (reward, pass@k, etc) — no filter calls; filters are train-only.

Orchestrator:

- main_loop is a thin router: await train_sink.add(...) — if True, run
  process_one_step; eval_sink.add(...) — if EvalBatchResult, run
  log_eval_batch.
- process_one_step is now I/O-only: save_rollouts, offload_images,
  teacher_logprobs (opd), wait_barrier, sender.send, monitor.log,
  heartbeat, ckpt save, step++. All processing already happened in the
  sink.
- log_eval_batch is a small side-effect method: save_rollouts +
  monitor.log_eval_samples + monitor.log; metrics dict comes pre-built
  from EvalSink.
- postprocessor.py is gone — its work split across TrainSink (filter +
  tokenize + samples + metrics) and orchestrator (ship I/O + opd
  logprobs + disk side effects).
- ProcessResult moved into metrics.py to avoid a circular import.

Smoke (eval.interval=5, max_steps=12, num_examples=16):

- Step 0 eval flushes cleanly: Reward 0.14.
- Step 5 eval triggers with inflight_train=115 — drain-switch overlap
  intact. Train steps 6/7/8 ship during eval drain. Eval flushes
  per-env: Reward 0.48.
- Reward 0.13 → 0.64 over 12 steps; clean event-driven shutdown.

* refactor(orchestrator_v2): unify is_batch_done trigger across train and eval

Both sinks now use the same flag — ``Rollout.is_batch_done`` — to signal the
batch boundary. The orchestrator's main loop polls a single, uniform
condition; the only difference is who stamps the flag:

- Eval: the dispatcher stamps ``is_batch_done=True`` on the last expected
  rollout of an env-epoch (emitted+dropped == expected). No change here.
- Train: ``TrainSink.add`` now stamps ``rollout.is_batch_done = True`` after
  ``process_group`` if its buffer has reached ``batch_size`` / token
  budget. The polling counterpart is ``TrainSink.is_batch_done()`` (renamed
  from ``batch_ready()`` for naming symmetry with the rollout flag).

Orchestrator main loop:

  await self.train_sink.add(rollout)
  while rollout.is_batch_done and not self.stopped.is_set():
      await self.process_one_step()
      rollout.is_batch_done = self.train_sink.is_batch_done()

Same predicate (``rollout.is_batch_done``) drives both sinks. The eval
path consumes the flag inside ``eval_sink.add``; the train path consumes
it in the main loop's ``while``.

Smoke: reverse-text 8-step run under v2, reward 0.13 → 0.36, clean
event-driven shutdown via ``self.stopped.set()`` at max_steps.

* chore(configs): replace orch_v2 debug overlay with hendrycks_math showcase

- Drop ``configs/debug/orch_v2.toml``. v2 is opt-in via a CLI flag —
  ``--orchestrator.experimental.use-orch-v2`` (or the equivalent TOML
  key) — and a one-liner overlay TOML was overkill for that.
- Add ``configs/hendrycks_math/orch_v2_demo.toml`` — a small (2 GPU,
  30 train step) eval-heavy run that makes the v2 overlap win visible
  on wall clock. 6 AIME2024 eval epochs of 30 × 4 = 120 long-reasoning
  rollouts each; under the legacy orchestrator each epoch pauses train,
  under v2 they overlap. Comment block at the top of the file shows
  how to run both side-by-side via the CLI flag.

* refactor(orchestrator_v2/ckpt): drop unused last_eval_step from Progress

The eval boundary is a strict function of ``progress.step``, ``eval.interval``,
``eval_base_model``, and ``skip_eval_on_resume`` — no extra persistent state
needed. ``progress.last_eval_step`` was only ever written (in
``log_eval_batch``) and never read; the dispatcher's own
``last_eval_step_per_env`` dict handles "don't re-trigger at the resumed
step" and is seeded from ``resume_step`` directly.

The ``Progress`` dataclass on the ckpt now carries just ``step`` + totals.
Old checkpoints containing the extra ``last_eval_step`` field load fine
— the ``hasattr(progress, key)`` guard in ``CheckpointManager.load`` skips
unknown serialized fields silently.

* refactor(orchestrator_v2): drop pre-baked metrics from batch result types

Rename `EvalBatchResult` → `EvalBatch`, `TrainBatchResult` → `TrainBatch`,
and rename `eval_step` → `step` on the eval payload. The dataclasses now
carry only the raw rollouts + per-rollout counters; the `metrics` dict is
a pure view computed at log time.

Why: the `metrics` field duplicated `rollouts` + a few scalars and forced
the orchestrator to build with a `step_time=0.0` placeholder inside
`TrainSink.pop_batch` and mutate the dict after the post-barrier wait.
Building at log time with the real timings keeps one source of truth.

- Drop `metrics` from both batch payloads; orchestrator calls
  `MetricsBuilder.build` (train) and `EvalSink.build_metrics` (eval) when
  ready to log.
- Drop `parallel_preprocess_time` / `teacher_logprobs_time` from
  `ProcessResult` (never read in v2 — tokenization is per-rollout;
  teacher logprobs is an orchestrator scalar passed to `build` directly).
- `TrainSink` no longer holds a `MetricsBuilder` ref; single-purpose
  ingest + payload assembly.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(orchestrator_v2): consolidate dataclasses + types into types.py

Move every dataclass / type alias / protocol from the orchestrator_v2
modules into a single ``types.py``. Behavioral modules (dispatcher, sinks,
watcher, log_loop, ckpt, metrics, orchestrator) now import their payloads
from one place instead of from each other.

Moved:
- ``Policy`` (was policy.py — file deleted, only contained the dataclass)
- ``Progress`` (was ckpt.py)
- ``Kind``, ``SchedMode``, ``Rollout``, ``RolloutMeta``, ``GroupState``
  (were dispatcher.py)
- ``EvalBatch`` (was eval_sink.py)
- ``TrainBatch`` (was train_sink.py)
- ``ProcessResult`` (was metrics.py)
- ``VersionObserver`` (was watcher.py)

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(configs): drop max_completion_tokens cap from orch_v2_demo

Let train/eval rollouts use the full 8k max_model_len so the demo
showcases the overlap on realistic long-reasoning AIME completions
instead of capping them at 4k.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(orchestrator_v2): move group/batch boundary signals into the sink

Previously the dispatcher stamped ``is_group_done`` / ``is_batch_done``
flags on whichever rollout it happened to iterate last in ``emit_group``.
But "last in a group" is whichever straggler finishes last — not knowable
at dispatch time — so the flag-on-rollout model was always derivative of
arrival ordering rather than a real signal.

Flip the design so the dispatcher emits every dispatched rollout (success,
env-error, empty-trajectory, task-exception, off-policy-cancel) exactly
once to ``out_q`` and the sinks own group/batch finalization by counting:

- Drop ``is_group_done`` / ``is_batch_done`` from ``Rollout``.
- ``TrainSink.add`` finalizes a group on the ``group_size``-th arrival,
  returns ``bool`` for batch-ready (was: mutate ``rollout.is_batch_done``).
- ``EvalSink.add`` finalizes a group on the ``group_size``-th arrival,
  finalizes the epoch when total arrivals reach
  ``num_examples * group_size``, returns ``EvalBatch | None``.
- Sinks decide drop / partial-train policy: filter errored rollouts before
  ``compute_advantages``; drop the whole group when the env
  ``requires_group_scoring`` and any rollout failed.
- Dispatcher synthesizes ``vf.RolloutOutput`` markers with ``error`` set
  for task exceptions and off-policy cancellations, so the sink's count-
  based finalization still fires when rollouts never produced real output.
- Drop ``eval_expected_per_env`` / ``eval_emitted_per_env`` /
  ``eval_dropped_per_env`` side-channel bookkeeping — pure dead weight
  once the sink counts arrivals itself.
- Drop ``GroupState.completed_rollouts`` / ``failed_rollouts`` — the
  dispatcher no longer accumulates rollouts before emit; ``emitted``
  counter is enough to pop the group from ``self.groups`` once every
  member has flowed out.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(configs): allow matching shared+sub values in propagator conflict check

The single-node SLURM launcher dumps the fully-resolved ``RLConfig`` to
disk and re-loads it inside the SLURM job. The dumped TOML has both the
shared-level keys (``output_dir``, ``model.name``, ``wandb.*``, ...) and
the matching sub-config keys (filled by the propagator on the original
load) populated to the same value. The old conflict check flagged
``shared is set, sub is also set`` regardless of values, so the re-load
failed with a ``Shared config conflicts with matching sub-config field(s)``
error.

Tighten the check to "shared and sub disagree" — matching values are a
harmless roundtrip (the propagator's fill-if-absent would have produced
the same thing). Genuine conflicts (e.g. shared ``model.name = "A"`` vs
``trainer.model.name = "B"``) still raise.

Covers the three sites that build ``conflicts``: the ``propagate``
helper, the ``output_dir`` block (matches against the per-target expected
value, including ``orchestrator.output_dir = f"{output_dir}/run_default"``),
and the ``wandb.name`` block (matches against the ``-trainer`` /
``-orchestrator`` suffixed form in non-shared mode).

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(orchestrator): replace legacy orchestrator with v2 implementation

Promote the v2 design to be the orchestrator. Clean deprecation — no
``use_orch_v2`` flag, no parallel ``orchestrator-v2`` console script, no
``prime_rl.orchestrator_v2`` module. The v2 sources move into
``prime_rl.orchestrator`` and the legacy files (``orchestrator.py``,
``scheduler.py``, ``buffer.py``, ``ckpt.py``) are deleted outright.

The legacy ``orchestrator`` console script keeps working — it now points
at the new ``Orchestrator(config).start()`` class. Existing TOML configs
work as-is (the public surface didn't move).

To compare against pre-v2 numbers, check out ``main`` and re-run any of
the existing configs head-to-head.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(orchestrator): UUID group IDs, pool-owned client selection, lean dispatcher inference dep

Three small cleanups that came out of post-merge review of the
orchestrator rewrite:

1. **UUIDs for dispatcher group IDs.** ``RolloutMeta.group_id`` and
   ``self.groups`` are now keyed by ``uuid.UUID`` (drop the ``self.next_group_id``
   counter + ``new_group_id`` helper). One less piece of state to reason about
   across dispatcher restarts / resume paths and zero risk of stale-counter
   collision.

2. **Client selection moves onto ``InferencePool``.** ``client_identity`` is a
   module-level helper next to the pool definitions in ``utils/client.py`` and
   ``InferencePool.select_train_client(load)`` is the public hook (implemented
   on both ``StaticInferencePool`` and ``ElasticInferencePool``). The dispatcher
   builds the load ``Counter`` from its own in-flight tracking and calls the
   pool — load tracking stays caller-side, but "wait for clients + pick least
   loaded" is now pool-side where the clients actually live.

3. **Dispatcher takes ``inference: InferencePool`` directly.** The
   ``training_mode == "sft"`` resolution (``rollout_inference = teacher_inference
   if sft else student_inference``) moves up into ``Orchestrator.setup`` where
   both pools are already in scope; the dispatcher only knows about the one
   pool it actually uses.

Also drops a few stray "v2" mentions in log strings / proc title / docstrings
that survived the previous cleanup pass.

Co-authored-by: Cursor <cursoragent@cursor.com>

* revert: restore validation.py to main

Roll back the propagator conflict-check loosening from this branch. The
single-node SLURM dump-then-reload bug it was working around is a
pre-existing issue on the launcher path; will be addressed in a separate
PR rather than ride along with this orchestrator rewrite.

Local launcher (the default ``rl_local`` path) is unaffected by the
validator either way.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(orchestrator): factor TrainSource + EvalSource out of dispatcher

Mirror the ``Train*`` / ``Eval*`` naming used everywhere else in the
orchestrator (``TrainEnvs`` / ``EvalEnvs``, ``TrainSink`` / ``EvalSink``,
``TrainBatch`` / ``EvalBatch``). Both abstractions answer the same
question — "what's the next example to schedule?" — with the asymmetry
their roles demand:

- ``TrainSource`` (was inline ``TrainEnvCycle``) — infinite pull. Same
  weighted round-robin over training envs as before; just renamed and
  moved into its own module.

- ``EvalSource`` (new) — trigger-driven finite-per-epoch pull. Owns the
  per-env example lists, per-env intervals, the per-(env, step) FIFO
  queue, ``last_eval_step_per_env``, ``eval_base_model`` startup
  handling, and ``skip_eval_on_resume`` gating. Exposes
  ``trigger(step)`` / ``trigger_at_start()`` for the dispatcher to poke,
  and ``peek`` / ``pop`` / ``bool(source)`` / ``len(source)`` for it to
  pull.

Dispatcher net loss: ~150 lines and 5 fields (``eval_queue``,
``eval_examples``, ``eval_intervals``, ``eval_step_envs``,
``eval_at_zero_pending``, ``last_eval_step_per_env``, ``resume_step``)
plus two methods (``fire_eval_epoch``, ``enqueue_eval_env``).
``RolloutDispatcher.on_new_version`` is now a 3-line delegation:
``fired = eval_source.trigger(step) ; if fired: switch_mode + log``.

Also drops ``eval_step_envs`` entirely — pure dead state: only ever
written, never read.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(orchestrator): slim dispatcher, move eval triggers to per-batch, add eval cancellation

A bundle of orchestrator/dispatcher cleanups all sitting in this PR:

**dispatcher → just a scheduler**
- ``__init__`` takes explicit params (``train_source``, ``eval_source``,
  ``inference``, ``policy``, ``max_inflight_rollouts``,
  ``tasks_per_minute``, ``group_size``, ``max_off_policy_steps_train/eval``,
  ``training_mode``) instead of the full ``OrchestratorConfig``. Sources
  are now orchestrator-owned and passed in.
- Drops ``resume_step`` — it's purely an ``EvalSource`` concern now and
  the orchestrator passes it directly to ``EvalSource``.
- ``DispatcherMetrics`` dataclass on ``types.py`` consolidates all the
  per-poll counters (cancellation by kind, error/empty by env,
  errors-by-type, total arrivals, eval_epochs_started, mode_transitions)
  with ``record_*`` helpers and ``drained()`` that returns the wandb
  shape + clears the drain counters in one shot. Replaces 6 dict/int
  fields previously scattered on the dispatcher.
- Drops the redundant ``inflight_total_permits`` property (was just an
  alias for ``inflight_permits``).
- Unifies ``try_schedule_train`` + ``try_schedule_eval`` into a single
  ``try_schedule(kind)`` + ``next_fresh_group(kind, envs)``. Same
  "continue existing group → otherwise open a fresh one" algorithm for
  both; the only asymmetry (train pulls from an infinite source vs. eval
  peeks+pops a finite queue) sits in two clearly-labeled branches of
  ``next_fresh_group``.

**eval triggers move to per-batch (orchestrator-side)**
- ``Orchestrator.process_one_step`` calls ``maybe_trigger_eval(step)``
  at the end (after ``progress.step += 1``); ``Orchestrator.start``
  calls ``maybe_trigger_eval(at_start=True)`` once before the main loop.
- ``RolloutDispatcher.on_new_version`` now does only the off-policy
  bookkeeping (bump counters, cancel stale groups). Eval epoch
  triggering is no longer tied to "we just got new weights"; it's tied
  to "we just completed a training step", which matches the conceptual
  model.

**eval cancellation + cancelled-as-errored**
- ``max_off_policy_steps_eval: int | None = None`` (default uncapped —
  preserves current behavior) on ``OrchestratorConfig``. When set, eval
  rollouts older than the cap get cancelled via the same drain-and-
  switch path as train (synthetic ``Cancelled`` rollouts flow to the
  eval sink). Train and eval caps can now diverge.
- ``EvalSink.build_metrics`` filters errored rollouts out of all stats
  (reward/seq_len/pass@k) and reports them as ``cancelled_count`` /
  ``errored_count`` / ``valid_rate`` separately. Counting failed
  attempts as reward=0 would silently bias scores down.

**``eval.eval_base_model`` renamed to ``eval.skip_first_step``**
- New default is False (no step-0 eval — opt in instead of opt out).
  The legacy ``eval_base_model`` key still parses via a silent
  ``AliasChoices`` (same boolean semantics), so configs that explicitly
  set ``eval_base_model=true|false`` keep working. Configs that relied
  on the implicit default get the new no-step-0-eval behavior.

**misc**
- Drop ``OrchestratorConfig.seed`` (hardcoded ``seed=42`` for
  ``TrainSource`` in the orchestrator — was effectively the default
  anyway).
- Drop ``eval_step_envs`` dead state (write-only).
- Drop ``record_dropped_group`` from ``DispatcherMetrics`` — group
  dropping is a sink concern now (see prior commit).

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(configs): move off-policy caps to per-side {train,eval}.max_off_policy_steps

Drop the global ``OrchestratorConfig.max_off_policy_steps_eval`` field and
instead make off-policy caps a per-side override, matching the same
shared-default / per-side-override pattern used everywhere else in the
config (e.g. ``train.sampling`` vs per-env sampling):

- ``OrchestratorConfig.max_off_policy_steps`` (already existed, default
  8): the shared default for both train and eval.
- ``TrainConfig.max_off_policy_steps: int | None = None``: per-train
  override; ``None`` inherits the global.
- ``EvalConfig.max_off_policy_steps: int | None = None``: per-eval
  override; ``None`` inherits the global.

The orchestrator resolves both sides to plain ints before passing to the
dispatcher, so the dispatcher's signature tightens from ``int | None`` to
``int`` for ``max_off_policy_steps_eval`` (caps are never "unset" by the
time they reach the dispatcher — they either come from the per-side field
or fall back to the global default).

Behavior change worth flagging: the previous ``max_off_policy_steps_eval
| None = None`` defaulted to *uncapped* (eval was never cancelled). The
new pattern defaults eval to the same cap as train (``8`` by default),
so eval rollouts that lag past the cap will now be cancelled by default.
Set ``eval.max_off_policy_steps`` to a large value if the previous
uncapped behavior is preferred.

* refactor(eval_sink): build metrics in process_batch + rename expected_for→batch_size_for

Two follow-ups from review that didn't ride along the previous commit:

- ``EvalSink.process_batch`` now builds the per-env metrics dict inline
  and stamps it on the returned ``EvalBatch.metrics`` field. Was an
  awkward two-step (``process_batch`` returned just rollouts, then the
  orchestrator separately called ``build_metrics(batch)``); per-batch
  derivations belong in the per-batch hook. ``build_metrics`` as a
  standalone method goes away.

- ``EvalSource.expected_for`` → ``batch_size_for`` (it's the same number
  the train sink calls ``batch_size`` — total rollouts per epoch).

* revert: collapse per-side off-policy caps back to global max_off_policy_steps

Roll back ``TrainConfig.max_off_policy_steps`` / ``EvalConfig.max_off_policy_steps``.
Keep just the global ``OrchestratorConfig.max_off_policy_steps``; it applies
to train and eval rollouts the same way. Eval cancellation behavior
(introduced earlier in this branch — cancelled rollouts surface as
``Cancelled`` markers, sink filters them out of stats) stays in place;
this commit only reverts the per-side override scaffolding.

* chore(config): remove wandb.shared deprecation shim

The ``SharedWandbConfig.deprecate_shared_field`` ``model_validator(mode="before")``
introduced in #2649 popped ``wandb.shared`` from input dicts with a
``FutureWarning`` so older configs that still set ``shared = true`` (or
``false``) kept loading.

The ``rl`` entrypoint always uses shared W&B mode now, the legacy split with
``-trainer`` / ``-orchestrator`` suffixes is gone, and the in-tree configs no
longer set ``shared``. Drop the shim so configs that still carry the field
fail loudly via the default ``extra = "forbid"`` instead of silently warning.

Docs and CHANGELOG updated.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(config): honor --no-wandb / --no-ckpt across shared and sub-configs

pydantic-config's CLI negation (``--no-wandb`` / ``--no-ckpt``) writes the
string ``"None"`` into the override dict, which only becomes real ``None``
later via ``BaseConfig._none_str_to_none``. ``RLConfig``'s subclass
``mode="before"`` validators run *before* that conversion, so the bare-block
enablement in ``propagate_shared_fields`` used to see the string and
re-enable ``trainer.wandb`` / ``orchestrator.wandb`` (or the ``ckpt`` pair)
with defaults — silently undoing the CLI's intent.

Tighten the bare-block check from ``get(key) is not None`` to
``isinstance(get(key), dict)``. A bare ``[wandb]`` block in TOML is ``{}``
(dict, still enables); ``--no-wandb`` produces ``"None"`` (string, now
correctly skipped). Same logic applies to ``ckpt``.

Verified end-to-end with ``cli(RLConfig, args=[..., "--no-wandb"])``:
``cfg.wandb``, ``cfg.trainer.wandb``, ``cfg.orchestrator.wandb`` are all
``None``. ``--wandb None`` and ``--no-ckpt`` behave the same. Bare
``[wandb] {}`` / ``[ckpt] {}`` blocks still enable the sub-configs.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(changelog): drop --no-wandb fix entry

It's a bug fix, not a breaking config change, so it doesn't belong in
CHANGELOG.md (which documents breaking config changes only).

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(comment): trim bare-block enablement comment

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(wandb): drop legacy-mode reference; add AGENTS rule

``docs/`` should describe the current state of the codebase, not its
history. Strip the "the legacy split has been removed" sentence from
``docs/training.md`` — readers on ``main`` don't care that there used to
be a non-shared mode — and add a ``## Docs`` rule to ``AGENTS.md`` to
codify it.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(agents): trim docs rule

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(eval_sink): drop redundant batch_arrivals counter

``EvalSink.batch_arrivals[(env, step)]`` was an arrival counter that
duplicated ``len(pending_batches[bkey])`` at the epoch-completion check
point. They could diverge mid-epoch (counter includes rollouts still
parked in ``pending_groups``; bucket only includes finalized groups), but
at the trigger point — when the last expected rollout arrives — its
group hits ``group_size``, ``process_group`` flushes the group's members
into ``pending_batches``, and the two are equal. Since ``process_group``
flushes every member of a finalized group without filtering, the bucket
size IS the arrival count at end-of-epoch.

Replace the check with ``len(self.pending_batches[bkey]) >=
self.batch_size_for(env_name)``; drop the counter field and its
matching pop in ``process_batch``.

* refactor(sinks): symmetrize TrainSink + EvalSink API; non-optional EvalSink deps

Four small alignment cleanups so the two sinks expose the same shape:

- ``EvalSink`` constructor takes ``eval_envs: EvalEnvs`` (non-optional);
  the orchestrator only constructs the sink when ``config.eval`` is set.
  Drops ``assert self.eval_envs is not None`` from ``group_size_for`` /
  ``batch_size_for`` and the conditional fallback in ``process_batch``.
  ``Orchestrator.eval_sink`` is now ``EvalSink | None``; the main loop
  only reaches the sink for ``rollout.kind == "eval"`` which only fires
  when eval is configured anyway.

- ``TrainSink.batch_buf`` → ``TrainSink.pending_batch``. Matches
  ``EvalSink.pending_batches`` naming (singular here because train has
  one batch buffer at a time; eval has multiple ``(env, step)`` epochs).

- Collapse ``TrainSink`` level 3 to just ``process_batch()`` — the same
  shape ``EvalSink`` exposes. Drops ``is_batch_done()``, ``pop_batch()``,
  and ``pop_cohort()``; the readiness check inlines into ``add()`` and
  the cohort pop inlines into ``process_batch()``. ``add()`` now returns
  ``TrainBatch | None`` directly (was ``bool`` + caller calls
  ``pop_batch``), matching ``EvalSink.add()``'s ``EvalBatch | None``.

- Drop ``self.logger`` from sink ``__init__``; inline ``get_logger()``
  at call sites instead.

Orchestrator main loop simplifies from
``batch_ready = add(); while batch_ready: process_one_step()`` to
``train_batch = add(); if train_batch is not None: process_one_step(train_batch)``.
The previous ``while``-loop's draining behavior is preserved by the
batch-threshold check: a single rollout's group adds at most ``group_size``
survivors, which can't overflow a ``batch_size`` buffer twice in one
``add()`` call (``group_size`` << ``batch_size`` in practice).

* refactor(orchestrator): quiet filter per-group logs; add per-group summary line

Two log-volume cleanups in the sinks + filter module:

- ``apply_filters`` per-group detection log (``Detected N/M rollouts
  (gibberish=…)``) drops from info → debug. It fires once per group
  finalization (4+ lines per training step at typical batch sizes), so
  is too noisy for default verbosity. Per-filter breakdowns are still
  available at debug-level.

- ``TrainSink.process_group`` and ``EvalSink.process_group`` each emit
  a single info-level summary line per finalized group with: env name,
  example_id, total rollouts, errored count, filtered count (train
  only), avg reward across survivors, and a compact per-filter
  breakdown (``filters: zero_advantage=2, gibberish=1`` or ``—``).
  Eval format adds ``eval_step`` and omits the filters slot (filters
  are train-only).

  The previous train-side warning lines for partial / all-failed /
  group-scored-dropped groups are folded into the new summary line at
  info-level with an explicit ``dropped: …`` suffix where appropriate
  (no more separate warning + summary).

* refactor(rollout): key sinks by group_id UUID, not (env, example_id)

``(env_name, example_id)`` was the de-facto group key in the sinks, but
isn't actually unique: ``TrainSource.next_example`` cycles a shuffled
dataset and the same example can be re-sampled while an earlier group is
still in flight (small datasets, fast wrap). Two physical groups for
``(env, 42)`` would have conflated in ``pending_groups[(env, 42)]``.

Carry the dispatcher's group UUID on the ``Rollout`` instead:

- Add ``Rollout.group_id: uuid.UUID`` (passed through by
  ``RolloutDispatcher.emit_rollout`` from ``meta.group_id``).
- Drop ``Rollout.env_name`` / ``Rollout.example_id`` / ``Rollout.eval_step``
  from the dataclass — they're already available via ``raw["env_name"]``,
  ``raw["example_id"]``, and a new ``raw["_eval_step"]`` (stamped on raw
  by ``emit_rollout`` for eval rollouts, mirroring how ``_samples`` /
  ``_policy_version`` are stashed).
- ``TrainSink.pending_groups`` / ``EvalSink.pending_groups`` re-key on
  ``rollout.group_id`` (truly unique per dispatched group).
- ``EvalSink.pending_batches`` keeps the ``(env_name, eval_step)`` key
  because multiple groups need to roll up into a single epoch bucket;
  read from ``raw`` instead of dataclass fields.
- ``drop_group``'s cancellation-marker emission goes through
  ``emit_rollout`` for consistency (one stamping path instead of two).

* refactor(types): rename ProcessResult→TrainBatchMetrics, add typed EvalBatchMetrics

Two parallel typed metric dataclasses, one per sink:

- ``ProcessResult`` → ``TrainBatchMetrics`` (rename only, same fields).
  ``TrainBatch.result`` → ``TrainBatch.metrics``. The dataclass holds
  per-batch counters that ``MetricsBuilder.build`` reads alongside the
  raw rollouts cohort and orchestrator-side timings.

- ``EvalBatch.metrics`` changes from ``dict[str, Any]`` to a typed
  ``EvalBatchMetrics`` dataclass (n_rollouts / n_cancelled / n_errored /
  valid_rate / reward_mean / completion_len_{mean,max,min} /
  truncation_rate / no_response_rate / n_examples / group_size +
  ``pass_at_k: dict[str, float]``). The dataclass exposes a
  ``to_wandb_dict(env_name=…, step=…)`` method that materializes the
  flat ``eval/{env}/...`` wandb shape on demand — keeps the dataclass
  typed while preserving the existing wandb keys.

  ``Orchestrator.log_eval_batch`` calls ``to_wandb_dict()`` before
  ``monitor.log`` and reads ``reward_mean`` / ``n_rollouts`` / ``n_examples``
  off the typed view for the success line.

Note on ``TrainBatch.rollouts`` vs ``samples``: they're not redundant.
``samples`` is the trainer-bound subset (filtered survivors) sent via
``sender.send``; ``rollouts`` is the full cohort needed for
``save_rollouts`` (disk), ``log_samples`` / ``log_distributions`` (wandb),
``offload_images_to_disk`` (memory hygiene), and ``MetricsBuilder.build``
(per-rollout walk). Two different consumers, both required.

* chore(filters): drop per-group detection log from apply_filters

The sink's per-group summary line already reports the per-filter
breakdown (``filters: zero_advantage=2, gibberish=1`` etc); the debug
line in ``apply_filters`` was redundant. Also drop the now-unused
``counts`` / ``total_detected`` / ``total_enforced`` accumulators.

* refactor(periodic_logger): distribute per-component; no defensive wandb

Replace the standalone ``IntervalLogger`` with a per-component
``PeriodicLogger``:

- Each async component owns its own ``PeriodicLogger`` (one for the
  dispatcher, one for the watcher, one for the orchestrator's main-loop /
  event-loop-lag concerns). Each logger has its own ``snapshot()``
  callable returning the component's live gauges.
- The shared interval comes from a single config field
  (``experimental.log_interval``, renamed from ``log_loop_interval``).
- Lifecycle is tied to the owning component: ``periodic_logger.start()``
  inside the component's ``start()`` (right after the task is registered),
  ``periodic_logger.stop()`` inside the component's ``stop()``. No more
  standalone ``log_loop`` task on the orchestrator.

W&B handling tightens:

- ``import wandb`` at the top of ``periodic_logger.py`` (no try/except).
- ``wandb.define_metric(key, step_metric="_timestamp")`` is called at
  ``PeriodicLogger.__init__`` for each explicit metric key the snapshot
  will emit — no glob patterns, no lazy first-call registration.
- ``wandb.log`` is called without try/except; gated only on the explicit
  ``wandb_enabled`` flag the component passes in (``config.wandb is not
  None``).
- ``EventLoopLagMonitor`` moves out of the old ``IntervalLogger`` and is
  owned by the orchestrator directly (its ``get_metrics()`` is the
  snapshot for the orchestrator's periodic logger).

Console output is now part of the spec: each emit logs a compact
``[<name>] key=value …`` line at info-level so steady-state component
state is visible between per-step lines, even with ``--no-wandb``.

Also: ``WeightWatcher.metrics()`` → ``WeightWatcher.gauges()`` to match
the dispatcher's ``gauges()`` convention; surface ``policy_version`` /
``update_count`` / ``last_*`` timings.

* refactor(metrics): drop dispatcher gauges/drain from step-aligned MetricsBuilder

Step-axis metrics (``MetricsBuilder.build`` → ``monitor.log(step=N)``)
and time-axis metrics (``PeriodicLogger`` → ``wandb.log`` on
``_timestamp``) now live on disjoint metric key sets. Mixing the same
key across two axes was both confusing (which axis does wandb pick?) and
wrong (``wandb.define_metric`` only supports one ``step_metric`` per key).

Changes:

- ``MetricsBuilder.build`` no longer takes ``dispatcher_gauges`` /
  ``dispatcher_drain``. The step-axis dict carries only per-batch /
  step-aligned metrics (rewards, seq_lens, filter rates, timings, ...).
- ``Orchestrator.process_one_step`` no longer calls
  ``dispatcher.drain_metrics()`` at step boundaries. The dispatcher's
  periodic logger is now the sole consumer of drained counters.
- ``RolloutDispatcher.drain_metrics`` removed; replaced by
  ``RolloutDispatcher.snapshot`` (= ``gauges() + metrics.drained()``).
  ``DispatcherMetrics.drained`` now returns a fixed key set
  (``DRAIN_KEYS``: cancelled_train_rollouts / cancelled_eval_rollouts /
  empty_rollouts_total / errored_rollouts_total / total_rollouts) so the
  periodic logger can pre-declare every key at init via
  ``wandb.define_metric``. Per-env and per-error-type drain breakdowns
  intentionally drop here — per-env appears in the step-aligned dict
  already (via the rollout walk).
- Dispatcher's ``PeriodicLogger`` snapshot uses ``self.snapshot`` and
  ``metric_keys = list(self.gauges()) + list(DispatcherMetrics.DRAIN_KEYS)``.
- Drop ``inference.get_metrics()`` from periodic flow (was previously
  merged into drain). Static pool returns ``{}`` anyway; elastic users
  can add a separate periodic logger if needed.

* chore: revert stray uv.lock edit to match origin/main

A previous commit on this branch overwrote the
``[options].exclude-newer`` timestamp with the
``0001-01-01T00:00:00Z`` backwards-compat sentinel. Restore the actual
timestamp from ``origin/main`` — ``uv sync --all-extras`` then produces
no further diff, so this single revert is all that needs to land.

* refactor(orchestrator): tighten APIs + collapse dead state

A wave of follow-up cleanups on top of the orch redesign.

API rename + co-location:

- ``Orchestrator.process_one_step`` → ``ship_train_batch``. Mirrors
  ``log_eval_batch`` on the eval side and removes the verb collision
  with ``TrainSink.process_rollout / group / batch`` (which are pure
  data transformations; the orchestrator method is I/O + lifecycle).
- Split ``sources.py`` into ``train_source.py`` + ``eval_source.py``.
  Two distinct abstractions deserved two files.
- Co-locate ``DispatcherMetrics`` and ``SchedMode`` with
  ``RolloutDispatcher`` in ``dispatcher.py``. ``types.py`` is now
  reserved for cross-module dataclasses; module-local types live next
  to their consumer.
- ``self.sched_mode`` → ``self.mode`` on the dispatcher.

Config collapse:

- Merge ``eval.skip_eval_on_resume`` into ``eval.skip_first_step``.
  Resume and cold start go through one path: the startup eval fires
  on whatever model state the orchestrator starts from, unless
  ``skip_first_step=True``. The old field is gone (not aliased — it's
  the boolean opposite, so silent aliasing would flip behavior).
- ``EvalConfig.skip_first_step`` semantics inverted to match its
  name: ``False`` (default) = run a startup eval; ``True`` = skip it.

Drain on max_steps (no out-of-band final eval pass):

- ``ship_train_batch`` flips the orchestrator into drain mode at
  ``max_steps``: ``RolloutDispatcher.disable_train_scheduling()`` stops
  new train, in-flight + any triggered eval finish through the normal
  pipeline, ``main_loop`` exits once ``dispatcher.is_idle``.
- Dropped the legacy ``await eval_env.evaluate(...)`` shutdown block —
  interval-aligned eval at the final step completes through the sink.

Dead-state removal:

- ``asyncio.Semaphore`` for the inflight cap is gone. Dispatch is
  single-task and every ``acquire`` is gated by an
  ``available_permits`` precheck, so a plain integer counter is the
  whole story. ``release(n)`` collapses to a single subtraction.
- ``EvalSource.last_eval_step`` + the ``step <= last_eval_step``
  monotonicity guard removed; ``trigger`` only has one (monotonic)
  caller.
- ``EvalSource.resume_step``, ``trigger_at_start``'s resume-step
  short-circuit, ``trigger``'s ``skip_eval_on_resume`` short-circuit,
  and the dead "stale env" branch in ``next_fresh_group`` all gone.
- ``example_id`` backfills in train + eval sources and the
  ``raw.setdefault("example_id", -1)`` fallback in
  ``RolloutDispatcher.emit_rollout`` removed — verifiers guarantees
  ``example_id: int`` on both ``BaseRolloutInput`` and ``RolloutOutput``.
- Removed the per-instance ``self.logger`` cache on the orchestrator,
  dispatcher, watcher, ckpt manager, inference-metrics collector, and
  event-loop-lag monitor; all use ``get_logger()`` at the call site.

API symmetry:

- ``EvalSource.peek``/``pop`` collapsed into a single
  ``next_example(available_permits)`` that mirrors
  ``TrainSource.next_example()``: one call commits. The per-env cost
  check lives inside the source (it owns the ``EvalEnvs`` reference);
  the dispatcher just consumes the result.

Smoke: 5-step reverse-text run completes cleanly — startup eval at
step 0, eval epochs at steps 1–5, eval interval-aligned with
max_steps=5 completes after drain starts, ``Pipeline drained,
exiting main loop`` then clean trainer shutdown.

* fix(dispatcher): emit Cancelled markers for un-scheduled rollouts on drop_group

Off-policy cancellation of a non-group-scoring eval group lost any
not-yet-dispatched rollouts. ``drop_group`` only emitted a synthetic
``Cancelled`` marker for each in-flight task, then popped the
``GroupState``; rollouts still parked in ``group.rollouts_to_schedule``
silently disappeared. The sink's per-group arrival count never reached
``target_rollouts``, so ``process_group`` never fired for that group,
the per-epoch bucket never hit ``num_examples * group_size``, and no
``EvalBatch`` was emitted — no ``Eval @ step=N env=...`` log line, no
wandb metric for that epoch.

This bit the cluster ``hendrycks_math/sanity`` run: ``aime2024`` is
non-group-scoring with ``group_size=32`` and ~3-min epochs. During each
epoch the trainer crossed enough versions to exceed
``max_off_policy_steps=8`` (default), ``drop_group`` fired mid-dispatch
on at least one group, the un-scheduled remainder was lost, the sink
starved, and the eval epoch never logged anywhere visible to the user.

Group-scoring envs were immune: they dispatch the whole group as a
single task with ``rollout_count = group_size``, so after dispatch
``rollouts_to_schedule == 0`` and the existing in-flight-task loop in
``drop_group`` emits all ``group_size`` markers in one shot.

Fix: after the in-flight loop, emit ``group.rollouts_to_schedule`` more
synthetic ``Cancelled`` markers using the last seen meta, so the sink
hits ``target_rollouts`` and both the per-group and per-epoch
finalizations fire. The cancellation count returned by ``drop_group``
includes the un-scheduled remainder too, so the off-policy metric +
warning log reflect the full cancellation.

Reproduced + verified with the rl debug config + ``--orchestrator
.max-off-policy-steps 0`` (forces cancellation on every weight update).
Before fix: epochs with any cancellation would never emit.
After fix: all 6 epochs fire, ``Eval @ step=3 ... Rollouts: 128 |
Examples: 126`` shows 2 cancelled rollouts surfaced via ``n_cancelled``
while the epoch finalizes normally.

* refactor(sources): unify next_example API + relax over-strict train precheck

- Rename ``SchedMode`` → ``DispatcherMode`` (and the wandb metric
  ``dispatcher/sched_mode`` → ``dispatcher/mode``). The "Sched" prefix
  was redundant inside the dispatcher's own namespace.

- ``self.sched_mode`` → ``self.mode`` on ``RolloutDispatcher`` (an
  earlier turn renamed only the docstring strings; this lands the
  actual identifier too).

- Unify ``TrainSource.next_example`` / ``EvalSource.next_example``
  signatures: both now take ``available_permits: int`` and return
  ``dict | None`` carrying ``env_name`` (and, for eval, ``_eval_step``)
  baked into the dict. The eval queue is ``deque[dict]`` instead of
  ``deque[tuple[str, dict, int]]``; ``enqueue`` copies the row and
  stamps ``_eval_step`` so the same example can be enqueued at multiple
  steps over the run without aliasing.

- Push the per-env cost lookup into each source. ``TrainSource``
  precomputes ``env_costs[env.name] = group_size if env.requires
  _group_scoring else 1`` at construction. The dispatcher's
  ``next_fresh_group`` collapses to a single symmetric body:

      example = source.next_example(self.available_permits)
      if example is None:
          return None
      env_name = example["env_name"]

  Dropped the standalone ``available_permits < self.group_size``
  precheck for train: it was right for group-scoring train envs (single
  task acquires ``group_size`` permits) but over-strict for per-rollout
  envs that only need 1 permit to open a fresh group. With the new
  cost-aware precheck, per-rollout train envs become responsive in the
  ``1 ≤ available_permits < group_size`` window — they can start
  dispatching immediately instead of waiting for a full group-sized
  window. Group-scoring envs unchanged.

Verified end-to-end with the rl debug config (5 train steps, eval every
step, both happy path and ``--orchestrator.max-off-policy-steps 0``
forced-cancel variant). All 6 expected eval epochs fire in both, the
mode-transition log lines use ``DispatcherMode``, and the off-policy
cancel path still surfaces ``n_cancelled`` correctly (step 3 in the
forced-cancel run shows ``Rollouts: 128 | Examples: 126``).

* refactor(orchestrator): log overhaul + drain-cancel + multi-env support

A wave of log-readability cleanups + a few small functional changes
that landed alongside.

Functional:

- ``ship_train_batch``: ``step_time`` now measures the **pipeline cycle
  time** (sink-emit → next sink-emit) instead of the orchestrator's
  ship-side I/O cost. The previous value was misleading — it overlapped
  asynchronously with rollout generation, so it always looked like
  step time was 10ms when actual throughput was several seconds per
  batch. New value is the meaningful throughput-per-step axis and
  feeds both the success log and ``time/step`` in the wandb dict.
- ``RolloutDispatcher.cancel_inflight_train_rollouts``: kill in-flight
  train rollouts at ``max_steps`` so wasted inference stops
  immediately. Eval in-flight is preserved so any interval-aligned
  eval at the final step still completes through the normal pipeline.
- ``TrainEnvConfig.group_size``: per-env group_size on the train side
  (mirrors ``EvalEnvConfig.group_size``). Propagated from the top-level
  ``OrchestratorConfig.group_size`` in the post-init validator —
  existing TOMLs unchanged.
- ``DispatcherMetrics``: dropped ``mode_transitions`` +
  ``eval_epochs_started`` (not interesting in practice).
- Silence the broader ``verifiers.*`` namespace by default; keep
  ``verifiers.serve`` routed through our loguru handler so env-server
  lifecycle logs still surface with our formatting.
- New ``configs/debug/multi_env/reverse_text.toml`` (2 train envs + 2
  eval envs at different intervals) to exercise multi-env paths in
  the debug suite. Old ``configs/multi_reverse_text/rl.toml`` removed.

Log format:

- New ``format_time`` helper in ``utils/logger.py``: ``<1s → "50ms"``,
  ``<60s → "12.3s"``, ``<1h → "1m 13s"``, ``<1d → "2h 5m"``,
  ``≥1d → "1d 3h"``. Applied across every user-facing time log.
- Train success log rewritten as ``Train step N | dt | Reward X |
  Error X% | Trainable A/B (C%) | Max Off-Policy N``, with per-env
  ``╰─ env_name | Ratio X% | Reward X | Error X% | Max Off-Policy N``
  rows joined with ``\n\t\t`` for column alignment in multi-env.
- Eval success log: ``Eval step N (env) | dt | Reward X | Error X% |
  Valid A/B (C%) | Max Off-Policy N``. Per-env elapsed via
  ``Orchestrator.eval_triggered_at[(env, step)]``.
- ``PeriodicLogger`` API: single ``collect()`` returns ``(body,
  wandb_dict)`` so drain-on-read counters fire exactly once per emit.
  Console format: ``Name       | k=v | k=v | …`` with padded name
  column so columns align across ``Event Loop`` / ``Dispatcher`` /
  ``Watcher`` rows.
- Dispatcher mode-switch log: ``Switching dispatcher mode to prefer
  {eval,train} rollouts because {reason}``. Reasons rewritten as
  full-sentence fragments.
- Eval trigger log: ``Starting evals in env1, env2 (N total
  rollouts)`` — replaces verbose ``Eval @ step=N for env(s) …``.
- ``setup_filters`` takes ``kind: str`` so the setup log distinguishes
  pre-batch vs post-batch (was identical for both).
- Stamped ``_off_policy_steps`` on each rollout's raw at emit time so
  the train/eval success log can compute per-env Max Off-Policy from
  ``batch.rollouts`` (the ``Rollout`` wrapper's ``policy_version``
  wasn't preserved through the sink).
- Added per-env ``arrivals_by_env`` + ``errors_by_env`` counters in
  ``TrainSink`` (reset per ship), carried on ``TrainBatchMetrics``
  for the Error% field. Train errored rollouts are dropped at the
  group level and don't reach ``batch.rollouts``, so they needed a
  separate counter.

Smaller log demotions / renames:

- ``Initializing {env} ({verbose config})``, ``Loaded N
  {train,eval} environment(s)`` → debug
- ``Reached max_steps`` → info (was success)
- Eval/train sink per-group ``Group | env=X example_id=Y | ...`` →
  debug; per-rollout dispatch/completion/drain events on the
  dispatcher → new debug logs ``dispatch/complete/drain {kind} |
  group=<8> env=<env> | …``
- ``Shutting down N env server(s)`` → debug
- ``Orchestrator finished.`` gets trailing newline so the rl
  entrypoint's ``Training finished!`` visually separates
- ``RL training finished!`` → ``Training finished!``
- ``EvalConfig.skip_first_step``: docstring shortened, field moved
  next to ``interval`` (semantic neighbor).

Smoke: single-env (5 steps) and multi-env (4 steps) configs both
complete cleanly with the new format. Periodic logs render as Draft 1
from the design discussion.

* refactor(eval_source): unify trigger + trigger_at_start

Collapses the two trigger methods on ``EvalSource`` into one. The
first ``trigger(step)`` call (orchestrator startup) fires every env
unconditionally — that's the startup-eval semantics, evaluating
whatever model state we begin from (base model or resumed checkpoint)
before any train rollouts. Subsequent calls use the usual ``step %
interval == 0`` per-env gating.

``eval.skip_first_step`` is now exactly what its name says: a guard on
the very first ``trigger`` call. Nothing else changes.

Tracked via ``self.first_trigger: bool = True`` flipped on the first
call. ``Orchestrator.maybe_trigger_eval`` loses its ``at_start: bool``
/ ``step: int | None`` dual-mode signature in favor of a single
``step: int`` arg; both callers (startup + post-ship) pass
``self.progress.step``.

* refactor(orchestrator): tighten attr typing, drop event_loop_lag, polish

Five small follow-ups bundled together:

- Drop the local ``EventLoopLagMonitor`` and use the verifiers one
  (``verifiers.utils.async_utils.EventLoopLagMonitor`` +
  ``EventLoopLagStats``). The verifiers monitor has the same shape —
  ``deque(maxlen=1000)`` + async ``run()`` — and adds a typed stats
  snapshot. Dropped our local warn-threshold path; the periodic log
  already surfaces lag values every interval, so a separate WARN was
  redundant.

- ``Orchestrator`` typing cleanup: declare instance attributes as
  class-level annotations instead of ``= None`` defaults, so pyright
  sees ``self.dispatcher`` etc. as non-Optional at call sites. Dropped
  seven type-narrowing asserts (``assert self.dispatcher and self
  .train_sink``, etc.). The remaining three asserts capture real
  invariants.

- ``EvalSource`` constructor takes non-Optional ``eval_envs`` /
  ``eval_config``. The orchestrator constructs it only when
  ``config.eval is not None``, so the source body is free of "is eval
  configured?" branches. Dispatcher's ``eval_source: EvalSource | None``
  parameter; the read sites (``queued_eval_examples`` / ``is_idle``)
  null-check, the scheduling paths assert (only reached when eval is
  configured).

- ``EvalConfig.validate_non_empty_envs``: model_validator asserting
  ``len(env) > 0`` so the invariant "``eval is not None`` ⇒ at least
  one eval env" holds at the config layer.

- ``EvalSource.trigger`` unified: dropped the separate
  ``trigger_at_start``. The first call to ``trigger`` (orchestrator
  startup) fires every env unconditionally — that's the startup-eval
  semantics; ``skip_first_step`` gates that one call and nothing else.
  Subsequent calls keep the ``step % interval`` per-env gating. The
  helper is also tightened to a 7-line body via tuple-swap + list
  comprehension.

- Config move: ``log_interval`` migrated from
  ``OrchestratorExperimentalConfig`` to ``LogConfig.interval`` (shared
  with trainer's ``TrainerLogConfig``). The now-empty
  ``OrchestratorExperimentalConfig`` class + ``OrchestratorConfig
  .experimental`` field are removed.

Log polish:

- Renamed ``ship_train_batch`` → ``finalize_train_batch`` and
  ``log_eval_batch`` → ``finalize_eval_batch`` so the two terminal
  per-batch methods share a verb.
- ``Train step N | dt | …`` and ``Eval step N (env) | dt | …``
  right-pad ``dt`` to 7 chars (``format_time``'s max width) so the
  ``|`` columns visually align across consecutive lines regardless of
  whether ``dt`` is ``57.4s`` or ``1m 14s``.
- Eval trigger reason strings rewritten as full-sentence fragments
  so ``Switching dispatcher mode to prefer {eval,train} rollouts
  because {reason}`` reads naturally.
- ``Orchestrator finished.`` no longer gets a trailing newline.
- ``EvalConfig.skip_first_step`` docstring shortened to only explain
  the ``True`` case.

* refactor(orchestrator): consolidate periodic logs, per-env breakdown, polish

- Unified ``PeriodicLogger`` on the orchestrator replaces the three
  separate ones (Event Loop / Dispatcher / Watcher). Single
  ``Orchestrator.collect_pipeline_view`` reads dispatcher gauges +
  drain, watcher gauges, sink batch progress, and lag stats in one
  shot. Headline carries the aggregate (total inflight, total
  finished this tick, train-batch fill); indented ``╰─`` rows break
  it down per env, with the eval rows also reporting their epoch
  progress (``batch=arrivals/expected``). Eval rows appear only when
  an epoch is accumulating.

- New ``RolloutDispatcher.inflight_by_env`` property: ``dict[(kind,
  env), count]``. ``finished_by_env`` for the same axis comes from
  the existing ``DispatcherMetrics.total_rollouts_by_env`` (drained
  per tick) — the pipeline view snapshots it before calling
  ``metrics.drained()`` so the orchestrator is the sole drain
  consumer.

- ``EvalSource.trigger`` now interleaves enqueueing across fired envs
  (round-robin via ``itertools.zip_longest``): the queue becomes
  ``A_ex1, B_ex1, A_ex2, B_ex2, …`` instead of ``A_*, then B_*``.
  Combined with ``try_schedule``'s "continue existing group" branch,
  per-example ``group_size`` rollouts still ship back-to-back
  (prefix-cache locality preserved); only the across-env ordering
  changes.

- Per-batch success logs gain ``Turns`` (avg ``len(trajectory)``) and
  ``Truncation`` (``mean(is_truncated)``) — shown in headline + per-env
  ``╰─`` rows on train, plus in the eval headline. ``EvalBatchMetrics``
  gains ``num_turns_mean`` so ``eval/<env>/num_turns/mean`` ships to
  wandb too.

- ``post_batch_filters``: dropped the ``Field(... validation_alias=
  AliasChoices("post_batch_filters", "filters"))`` shim + the
  ``OrchestratorConfig.filters`` @property. Replaced with a
  ``@model_validator(mode="before")`` that renames ``filters`` →
  ``post_batch_filters`` for TOML/CLI input. Runtime code accesses
  ``cfg.post_batch_filters`` only.

- Restored the (now empty) ``OrchestratorExperimentalConfig`` class +
  ``OrchestratorConfig.experimental`` field so adding a future
  experimental toggle doesn't need to re-introduce both at once.

- Inference engine pause/resume logs: renamed
  ``Pausing inference engines for weight update`` →
  ``Updating policy in-flight to v{step}``; demoted the ``All inference
  engines paused / resumed`` bookends to debug.

- ``Reached max_steps=N, draining pipeline`` → ``Draining pipeline``;
  the "any triggered eval will complete" tail is now "any in-flight
  evals will complete".

- ``Shutting down N env server(s)`` log trimmed (no more "waiting for
  sandbox cleanup..." trailer).

* fix(orchestrator): pipeline log per-env reconciliation + step-0 step time

- ``Orchestrator.collect_pipeline_view`` headline: drop the ``finished N``
  per-tick-delta term and replace the per-env ``dispatched / finished``
  pair with ``inflight / batch``. Per-env values now sum to the
  aggregate (``inflight`` totals match headline ``train=…, eval=…``;
  ``batch`` totals match headline ``train batch X/Y``). Previously the
  headline mixed cumulative state with tick-delta counters, so per-env
  rows visibly disagreed with the aggregate.

- Per-env ``╰─`` rows now only render when there's more than one train
  env (or more than one eval env). For single-env runs the aggregate
  already is the per-env view, so the rows were pure noise.

- Single-eval-env case folds the active epoch's progress into the
  headline (``| eval <env>@<step> batch=arrivals/expected``). Multi-eval
  still uses the per-epoch rows.

- ``TrainSink.pending_batch_by_env`` returns the per-env post-error-
  filter survivor counts currently in ``pending_batch`` — fuel for the
  per-env ``batch=…`` column above. O(pending_batch) walk; pending
  batch is bounded by ``batch_size`` so it's cheap.

- ``Orchestrator.start`` now anchors ``self.last_batch_at`` to
  ``perf_counter()`` right before ``main_loop`` (after spawning the
  dispatcher / watcher / lag tasks). Step 0's ``step_time`` now
  measures startup → first-batch wall-clock instead of reporting
  ``0ms`` — verified at ``9.3s`` on the multi-env smoke run.

* chore(orchestrator): move Error/Truncation to end of success log lines

Train + eval ``SUCCESS`` lines now order the columns by relevance:
``Reward → Trainable/Valid → Turns → Max Off-Policy`` first, then
``Error``/``Truncation`` (lower-priority diagnostics) trailing. Applies
to the train headline, train per-env ``╰─`` rows, and the eval
success line.

Before:
  Train step 0 | 9.3s | Reward 0.08 | Error 0.0% | Trainable 96/128
    (75.0%) | Turns 1.0 | Truncation 89.8% | Max Off-Policy 0

After:
  Train step 0 | 9.3s | Reward 0.08 | Trainable 96/128 (75.0%) |
    Turns 1.0 | Max Off-Policy 0 | Error 0.0% | Truncation 89.8%

* chore(trainer): use format_time for per-step success log

Per-step ``Step N | Time: …`` line in ``trainer/rl/train.py`` and
``trainer/sft/train.py`` now goes through ``format_time`` so durations
> 60s render as ``1m 5s`` / ``1h 5m`` instead of ``65.34s``. Matches the
formatting already used by the orchestrator's success lines.

* fix(dispatcher): keep dispatching eval group tails after queue empties

``RolloutDispatcher.fill_inflight`` had a bug where, once the eval
source's queue emptied, the second ``if not self.eval_source: return``
guard short-circuited ``try_schedule("eval")`` entirely — including its
step-1 branch that continues *existing* eval groups one rollout at a
time. For non-group-scoring eval envs (``requires_group_scoring=False``,
e.g. ``aime2024``), this orphaned the last group's tail: when the final
``next_example`` call popped the queue and opened group N with
``rollouts_to_schedule = group_size - 1``, the next ``fill_inflight``
iteration saw an empty queue + nonzero ``inflight_eval`` and returned
before reaching the continuation branch. The remaining ``group_size -
1`` rollouts were never dispatched, so the eval sink's per-epoch bucket
reached only ``num_examples × group_size − (group_size − 1)`` arrivals
and ``process_batch`` never fired. The epoch silently disappeared (no
``Eval step …`` log, no wandb point), and ``DispatcherMode`` eventually
flipped back to ``PREFER_TRAIN`` once inflight cleared — taking the
unfinished epoch's bookkeeping with it.

Fix: drop the early return. ``try_schedule("eval")``'s step-1 branch
continues existing eval groups regardless of source state, and step 2
(``next_fresh_group``) already returns ``None`` when the source is
empty — so an empty source naturally results in ``scheduled = False``
and ``fill_inflight`` bails on the next line.

Added a debug invariant: when the dispatcher flips
``PREFER_EVAL → PREFER_TRAIN``, walk ``self.groups`` for any eval group
with ``rollouts_to_schedule > 0`` and log an error. With this fix in
place this should never fire — but if a future change re-introduces
the orphan behavior it'll fail loudly instead of silently dropping the
epoch.

Verified on the multi-env smoke (``configs/debug/multi_env/
reverse_text.toml``): both eval epochs finalized cleanly at
``Valid 64/64 (100.0%)``, no orphan-error lines.

* feat(configs): rlm_swe qwen3-4b-thinking on 2-node slurm

Minimal RL config: Qwen3-4B-Thinking-2507 on rlm_swe default taskset
for train, SWE-Bench-Verified-Quick for eval. 65k context, 2-node SLURM
multinode (1 train × 1 infer × 8 GPUs each). Trainer cp=2 / FSDP=4 +
``flash_attention_2`` (default); inference dp=8 with hermes tool
parser. Validated via ``rl --dry-run``.

* fix(orchestrator): pipeline-view accounting + drain-switch overlap finish

Two related bugs in the eval-side pipeline view:

1. ``DispatcherMode.PREFER_EVAL → PREFER_TRAIN`` was gated on
   ``inflight_eval_count == 0`` in addition to ``not eval_source``.
   That meant once every eval example was *dispatched* but a long tail
   was still in flight (e.g. 480/480 dispatched, ~30 permits idle),
   the remaining permits stayed idle until the entire eval drained.
   The PR's drain-switch overlap explicitly promises the opposite:
   when the eval source is exhausted, train resumes scheduling while
   the eval tail completes naturally. New gate is
   ``not bool(eval_source) and no eval group has rollouts_to_schedule
   > 0`` — i.e. nothing more to dispatch for eval. The previous
   ``orphan`` sanity-check is no longer needed because that's exactly
   the new gate's invariant.

2. ``EvalSink.epoch_progress`` only counted ``pending_batches``
   (groups that have already hit ``group_size`` and been moved to
   the per-epoch bucket). Rollouts sitting in ``pending_groups``
   (partial groups not yet at ``group_size``) were invisible, so
   the pipeline log showed ``inflight 408 + batch 0 = 408`` instead
   of ``= 480 = expected``. Now ``epoch_progress`` aggregates both
   ``pending_batches`` and the per-(env, eval_step) sum across
   ``pending_groups``, so ``inflight + batch == expected`` holds
   tick-by-tick as the user expects.

Also: ``configs/rlm_swe/qwen3_4b.toml`` drops ``seq_len`` from 65536
to 4096 (orchestrator + inference ``max_model_len``) so individual
rollouts finish faster during initial dev iteration. Bump back up
for production runs.

* fix(sinks): pipeline view fills per-rollout for non-group-scoring envs

Both ``TrainSink.batch_progress`` / ``pending_batch_by_env`` and
``EvalSink.epoch_progress`` previously counted only rollouts that had
already moved from ``pending_groups`` (per-group buffer) into the
batch / per-epoch bucket — so the pipeline view ticked in ``group_size``
increments rather than per-rollout, even though the underlying envs
are per-rollout scored.

Now both counters add in-progress ``pending_groups`` rollouts for envs
where ``env.requires_group_scoring == False``. Group-scoring envs
(rubric has group-level reward funcs) still only contribute via the
finalized bucket — their rollouts only make sense as a unit, so the
counter should still jump by ``group_size`` for them.

``TrainSink.in_progress_groups`` is the shared helper that walks
``pending_groups`` with the group-scoring gate, used by both
``batch_progress`` (aggregate count + token count) and
``pending_batch_by_env`` (per-env breakdown that sums to the aggregate).

* chore(configs): drop hendrycks_math/sanity seq_len 8192 → 4096

Restores ``rlm_swe/qwen3_4b`` seq_len back to 65536 (the previous
drop was meant for the sanity config, not the rlm_swe one).

* refactor(eval_sink): rename epoch_progress → batch_progress

Mirrors ``TrainSink.batch_progress`` for consistency. Same shape and
semantics — returns a list (one entry per accumulating ``(env, eval_step)``
batch) since eval can have multiple batches in parallel.

* chore(orchestrator): reformat pipeline log + drop avg@k wandb metric

Pipeline ``PeriodicLogger`` line is now a single sentence:

  Currently {train_inflight}/{max} [(env=N, …)] inflight train
  rollouts[ and {eval_inflight} [(env=N, …)] eval rollouts]; got
  {train_batch}/{batch_size} [(env=N, …)] rollouts in training batch
  [ and {n}/{target} in {env}[, {n}/{target} in {env2}…]]

Per-env ``(env=N, …)`` breakdowns inline behind the corresponding
aggregate and only appear when ``len(train_envs) > 1`` /
``len(eval_envs) > 1``. The eval halves drop entirely when nothing
is accumulating.

Drops the redundant ``eval/<env>/avg@<group_size>`` wandb scalar from
``EvalBatchMetrics.to_wandb_dict`` — it was just ``reward/mean`` under
a different name (the ``group_size``-tagged ``avg@k`` aggregate is
semantically meaningless when ``group_size`` doesn't match the
pass-at-k denominator). ``reward/mean`` still ships.

* chore(configs): bump default LogConfig.interval 5s → 10s

Shared periodic-logger interval. 5s was a bit chatty for steady-state
RL/SFT runs; 10s keeps the pipeline view useful without dominating the
log file.

* chore(orchestrator): reword train + eval success log prefixes

- ``Train step N | …`` → ``Step N | …`` (the "train" qualifier was
  redundant; the trainer side already prefixes its log with
  ``[trainerN]`` and the orchestrator side is the only other place
  this fires).
- ``Eval step N (env) | …`` → ``Finished evaluating env from step N | …``
  (more explicit about what ``N`` is — the policy version when the
  eval epoch was triggered, not when it finished).

* chore(periodic_logger): drop name-column prefix from console emit

There's only one ``PeriodicLogger`` instance now (the orchestrator's
unified pipeline view), so the padded ``Pipeline    | …`` column
prefix is just noise. Log the ``collect()`` body verbatim instead.
Also drop ``NAME_WIDTH`` and refresh the module docstring to reflect
the single-instance design.

* chore(orchestrator): pipeline log puts batch progress before inflight

Step progress leads:

  Got {train_batch}/{batch_size} [(env=N, …)] rollouts in training
  batch[ and {n}/{target} in {env}, …]; currently {train_inflight}/
  {max} [(env=N, …)] inflight train rollouts[ and {eval_inflight}
  [(env=N, …)] eval rollouts]

Reads top-down: what we're working toward (the batch) before what's
in flight (the means to get there).

* chore(orchestrator): show batch-progress percentages in pipeline log

``Got 5/512 (1.0%) rollouts in training batch and 29/480 (6.0%) in
aime2024; …`` — percentages make it easier to glance-read how close
we are to shipping the next batch / closing the eval epoch.

* chore(configs): hendrycks_math/sanity batch 512 → 256, keep max_inflight 512

2× oversampling so the dispatcher always has rollouts pre-cooked when
one ships, instead of running at exactly batch_size and stalling.

* chore(orchestrator): drop /max from train-inflight pipeline log

``currently 61/512 inflight train rollouts`` → ``currently 61
inflight train rollouts``. The global cap doesn't add meaningful
context in steady state (and the cap is shared with eval, so the
``X/max`` reading was misleading anyway).

* chore(orchestrator): drop env list from eval-trigger mode-flip reason

``Switching dispatcher mode to prefer eval rollouts because eval was
triggered for aime2024 at step 0`` → ``…because eval was triggered at
step 0``. The next-line ``Starting evals in aime2024 (...)`` log
already names the fired env(s); no need to repeat it in the mode
transition reason.

* chore(configs): drop verbose comment on EvalConfig.validate_non_empty_envs

* chore(configs): drop verbose docstring on OrchestratorExperimentalConfig

* chore(configs): drop orch-v2 references from pre_batch_filters docstring

* chore(configs): trim verbose comment on train group_size propagation

* chore(configs): generic LogConfig.interval docstring

* chore(eval_source): drop TrainSource cross-reference from docstring

* chore(filters): revert setup_filters docstring to one-liner

* refactor(orchestrator): typed rollout dataclasses, raw stays pristine

Replace the magic-string ``raw["_x"]`` stamping pattern with typed
fields on dedicated dataclasses. ``vf.RolloutOutput`` is no longer
mutated by prime-rl; all prime-rl bookkeeping lives on the wrapper.

New types in ``orchestrator/types.py``:

- ``InflightRollout`` (was ``RolloutMeta``) — per-task scheduling state
  held by the dispatcher while a rollout is being generated.
- ``FinishedRollout`` (was ``Rollout``) — the atomic unit on the
  dispatcher's output queue. Holds ``raw`` + ``env_name`` /
  ``example_id`` / ``group_id`` / ``policy_version`` / ``off_policy_steps``
  on typed fields. Convenience properties: ``error``, ``reward``,
  ``is_truncated`` (read from ``raw``).
- ``TrainRollout(FinishedRollout)`` — adds ``samples`` (populated by
  ``TrainSink.process_rollout``), ``advantage`` (set by
  ``compute_advantages``), ``is_filtered`` + ``filter_results`` (set
  by ``apply_filters``).
- ``EvalRollout(FinishedRollout)`` — adds ``eval_step`` (policy version
  at trigger time; the eval sink's bucket key).

``FinishedRollout.to_dict()`` materializes the dataclass + ``raw``
back into a single ``vf.RolloutOutput``-shaped dict at I/O boundaries
(``save_rollouts``, ``monitor.log_samples`` / ``log_eval_samples``),
so the JSONL on disk and the wandb sample tables are unchanged
shape-wise.

Knock-on changes:

- ``RolloutDispatcher.out_q: Queue[FinishedRollout]``. ``emit_rollout``
  builds ``TrainRollout`` / ``EvalRollout`` directly — no more
  ``raw[...] = ...`` lines.
- Sinks accept ``TrainRollout`` / ``EvalRollout``; pending buffers are
  typed lists. ``main_loop`` discriminates via ``isinstance``.
- ``apply_filters(rollouts: list[TrainRollout])`` + ``RolloutFilter
  .check(rollout: TrainRollout)``: filters read ``rollout.raw`` for
  trajectory inspection, ``rollout.advantage`` for the zero-advantage
  check; they write ``rollout.is_filtered`` / ``rollout.filter_results``.
- ``compute_advantages(rollouts: list[TrainRollout])`` writes to
  ``rollout.advantage``. The public ``AdvantageFn`` API
  (``AdvantageInputs.rollouts: list[vf.RolloutOutput]``) is unchanged
  — custom advantage functions still receive raw vf dicts.
- ``MetricsBuilder.build`` and the orchestrator's train/eval success
  log lines read attributes off the dataclasses; ``r["env_name"]`` /
  ``r["advantage"]`` / ``r.get("_off_policy_steps", 0)`` all become
  attribute accesses.

No public API or wandb / TOML config surface change. The on-disk
rollout JSONL keeps the same shape via ``.to_dict()``.

* fix(trajectories): thread env_name as kwarg into interleave_rollout

Followup to the typed-rollout refactor: ``raw`` no longer carries
``env_name`` (prime-rl metadata moved to the dataclass), but
``interleave_rollout`` → ``make_sample`` was still reading
``output["env_name"]`` to populate ``TrainingSample.env_name``,
which now KeyErrors.

Pass ``env_name`` as an explicit kwarg from ``TrainSink.process_rollout``
(reads ``rollout.env_name``) so the helper doesn't depend on
prime-rl-stamped fields on ``raw``. ``TrainingSample.env_name`` still
gets overwritten by ``process_group`` later, but having it set
correctly at ``make_sample`` time avoids the empty-string window for
log/debug paths that introspect samples before group finalize.

Smoke verified: 3 train steps + 2 eval epochs on
``configs/debug/multi_env/reverse_text.toml`` — both ``Finished
evaluating`` lines and ``Step N`` lines render cleanly, no errors.

* chore(types): drop ``_``-prefix from rollout metadata keys in to_dict

The ``_``-prefix convention used to mark "prime-rl-stamped, not env-
provided" fields on the in-memory raw vf dict. Since the typed-rollout
refactor those fields no longer live on ``raw`` at all — they're
dataclass attrs — so the public-key prefix is meaningless. Rename in
``to_dict`` (used at I/O boundaries):

- ``_policy_version`` → ``policy_version``
- ``_off_policy_steps`` → ``off_policy_steps``
- ``_eval_step`` → ``eval_step``

Also rename the internal-queue handoff key from ``EvalSource`` →
``RolloutDispatcher`` for symmetry:

- ``example["_eval_step"]`` → ``example["eval_step"]``

Verified on the multi-env smoke: JSONL on disk now uses the public
keys (no leading underscore), and downstream rollout consumers can
introspect prime-rl metadata without the magic-string convention.

* feat(types): add FinishedRollout.rollout_id; fix advantage grouping

- New per-rollout UUID ``FinishedRollout.rollout_id`` (default
  ``uuid.uuid4()``). The only safe key for tracing a specific rollout
  through its lifecycle (dispatch → sink → batch → JSONL on disk).
  Neither ``(env_name, example_id)`` nor ``group_id`` is unique on
  its own — the same example can be re-sampled as multiple groups,
  and one group contains ``group_size`` rollouts. ``to_dict()`` now
  emits ``rollout_id`` + ``group_id`` (both as strings) alongside the
  rest of the prime-rl metadata.

- ``compute_advantages`` was grouping rollouts by ``(env_name,
  example_id)`` — wrong when the same example is concurrently in
  flight as two distinct groups (small datasets, multi-epoch eval).
  Two distinct groups would have been merged into one for advantage
  computation, polluting the GRPO baseline. Switched to grouping by
  ``group_id`` (the dispatcher's UUID — unique by construction).

Smoke verified on the multi-env config: 64 rollouts in step-0 eval
have 64 distinct ``rollout_id``\\ s and 16 distinct ``group_id``\\ s
(64 rollouts / 4 group_size = 16 groups), all visible in the JSONL.

* chore(orchestrator): reword eval success log 'Finished evaluating' -> 'Evaluated X (Step N)'

* refactor(advantage): drop grouping logic, cache advantage_fn on the sink

``TrainSink.process_group`` already calls ``compute_advantages`` with a
single group's survivors, so the internal ``defaultdict[group_id]``
re-grouping was always a no-op (always one bucket). Rename to
``assign_advantages``, drop the grouping, and just call ``advantage_fn``
on the rollouts as one cohort.

Also cache the ``advantage_fn`` once at ``TrainSink.__init__`` via
``setup_advantage_fn(config)`` — previously it was rebuilt per
``process_group`` call, which for ``CustomAdvantageConfig`` does an
``import_object`` per group. Now built once.

``AdvantageInputs.rollouts: list[vf.RolloutOutput]`` (public API)
unchanged.

Verified on the multi-env smoke: 3 train steps + 2 eval epochs ship
cleanly; advantage shape preserved.

* chore(orchestrator): drop Valid X/Y from eval success log (redundant with Error %)

* chore(orchestrator): bump per-env success-log indent by one space

* fix(orchestrator): drop_group orphan, empty-batch spin, resume eval dup

Three legit bugs from the recent audit:

1. ``RolloutDispatcher.drop_group`` orphaned the unscheduled tail of a
   group when ``last_meta`` was ``None`` — reachable via the multi-group
   off-policy-cancellation race (group A's drop yields at
   ``out_q.put``, group B's last inflight task completes naturally
   between ``on_new_version``'s snapshot and ``drop_group(B)`` running,
   so by the time we reach group B's drop, ``self.inflight`` has no
   entries for B). For non-group-scoring envs with
   ``rollouts_to_schedule > 0`` on B, the sink waits forever for
   ``group_size`` arrivals. Fix: synthesize a minimal
   ``InflightRollout`` from the ``GroupState`` when ``last_meta is
   None`` and emit the markers; sink finalizes the partial group.

2. ``Orchestrator.finalize_train_batch`` spun forever when every batch
   yielded ``n_trainable == 0`` (e.g. zero-advantage enforce on a
   homogeneous-reward dataset, mis-configured pre/post filters). Added
   a ``consecutive_empty_batches`` counter; abort after
   ``MAX_CONSECUTIVE_EMPTY_BATCHES = 10`` with a clear error pointing
   at the filter / difficulty configuration. The counter resets on
   the first non-empty batch.

3. ``EvalSource.trigger`` re-fired interval-aligned envs on resume
   from a checkpoint (e.g. resume at step 50 with ``interval=50`` →
   the eval that already completed pre-checkpoint runs again). Two
   complementary guards:
     - ``Progress.last_eval_step_by_env: dict[str, int]`` (new field,
       persisted via the existing ``CheckpointManager``) records the
       last fired step per env. ``EvalSource.trigger`` reads + writes
       this dict via a shared reference; envs are skipped when
       ``step <= last_eval_step_by_env[env]``.
     - ``EvalSource.__init__`` takes ``is_resumed: bool`` (wired from
       the orchestrator's ``resume_step is not None``). On resume the
       startup-eval "fire all" behaviour is suppressed entirely so the
       user doesn't get a duplicate baseline at the resumed step.

The ``Progress`` change is backwards-compatible with existing
checkpoints — the load loop uses ``setattr`` on a fresh ``Progress()``
that already has the default ``{}``, so an old checkpoint without
the field just leaves it empty.

Verified on the multi-env smoke run: 3 train steps + 2 eval epochs
ship cleanly with the new wiring.

* chore(orchestrator): drop 'Starting orchestrator step N' info log

* refactor(dispatcher): rename + slim down wandb metrics

Periodic-axis metric shape changes (``_timestamp`` axis):

Removed:
- ``dispatcher/inflight_permits`` (redundant with ``inflight_train``+``eval``)
- ``dispatcher/available_permits`` (derivable from ``max_inflight``)
- ``dispatcher/total_rollouts`` (was unused after the pipeline-view
  refactor stopped reading it)
- ``dispatcher/empty_rollouts_total`` (empty trajectories are folded
  into ``errored`` — they're flagged with ``error.error = "EmptyTrajectory"``
  already, so the separate counter was redundant)

Renamed:
- ``dispatcher/queued_eval_examples`` → ``dispatcher/queued/eval``
- ``dispatcher/cancelled_train_rollouts`` → ``dispatcher/cancelled/train``
- ``dispatcher/cancelled_eval_rollouts`` → ``dispatcher/cancelled/eval``
- ``dispatcher/errored_rollouts_total``  → ``dispatcher/errored/train`` +
  ``dispatcher/errored/eval`` (split by kind)
- ``watcher/last_update_weights_time_s`` → ``watcher/last_update_weights_time``
- ``watcher/last_wait_for_ckpt_time_s``  → ``watcher/last_wait_for_ckpt_time``

Added: per-env breakdowns under each cancelled/errored prefix:
- ``dispatcher/cancelled/<env>`` (sum across kinds, per env name)
- ``dispatcher/errored/<env>``

``DispatcherMetrics`` now tracks ``(kind, env_name) → count`` instead
of separate ``cancelled_train_rollouts`` / ``cancelled_eval_rollouts``
ints and a flat ``errored_rollouts_by_env`` dict. ``record_cancellation``
and ``record_error`` take ``env_name`` explicitly. The static
``DRAIN_KEYS`` constant becomes a ``drain_keys(train_envs, eval_envs)``
classmethod so the orchestrator can pre-register the per-env keys for
``wandb.define_metric`` at construction time.

``handle_completed_rollout`` no longer calls ``record_empty`` —
empty trajectories are promoted to ``error.error = "EmptyTrajectory"``
and counted via the regular ``record_error`` path.

Verified on the multi-env smoke run: 3 train steps + 2 eval epochs,
no errors.

* chore(orchestrator): drop verbose attribute-schema comment block

* chore: trim excessive code comments + docstrings

Pass over every file in the diff to drop comments that just narrate the
code or repeat what the names already say. Kept comments only where
they add non-obvious intent / constraints / invariants.

Removed leftover references to pre-PR / legacy logic (e.g. the
``orchestrator v2`` naming, ``no asyncio.Semaphore needed``, ``no buffer
state`` rationales, the multi-paragraph rationale for the
``filters → post_batch_filters`` alias, the ``client`` / ``model``
shortcuts rationale, etc.). The aliases themselves are retained as
documented current backward-compat behaviour, just without the
historical justification.

No behaviour change; smoke verified on the multi-env config.

* refactor(types): trim types.py 255 → 212 lines

- Consolidate three ``to_dict`` overrides into one ``FinishedRollout``
  method that walks ``dataclasses.fields(self)`` so train-only fields
  (``samples`` / ``advantage`` / ``is_filtered`` / ``filter_results``)
  and eval-only fields (``eval_step``) pick themselves up via subclass
  inheritance. UUID fields stringify automatically; ``filter_results``
  still renames to ``filters`` for the JSONL view; ``samples`` and
  ``raw`` stay skipped.
- Drop section dividers and the multi-paragraph module docstring.
- Slim per-dataclass docstrings to single lines / single paragraphs.

Verified the JSONL output keys are unchanged (``rollout_id``,
``group_id``, ``env_name``, ``example_id``, ``policy_version``,
``off_policy_steps``, ``advantage``, ``is_filtered``, ``filters``)
on the multi-env smoke run.

* test: fix unit tests for typed rollouts + dropped modules

- Delete ``test_buffer.py`` and ``test_scheduler.py`` — the
  ``Buffer`` / ``Scheduler`` modules were removed entirely.
- Update ``test_filters.py`` to construct ``TrainRollout``\\ s instead
  of raw dicts: ``apply_filters`` and ``RolloutFilter.check`` now take
  typed rollouts, assertions read ``r.filter_results`` /
  ``r.is_filtered`` / ``r.reward`` / ``r.raw["..."]``.
- Update ``test_advantage.py``: ``compute_advantages`` was renamed to
  ``assign_advantages`` and no longer groups internally (the sink
  groups by ``group_id`` upstream and calls ``assign_advantages``
  per group). Replaces the old grouping tests with three single-group
  tests; the ``default_advantage_fn`` tests over ``AdvantageInputs``
  are unchanged.
- Update ``test_orchestrator_setup.py``: patch the renderer factory
  at its source (``renderers.base.create_renderer``) since
  ``setup_student_inference_pool`` does a deferred import; drop the
  ``logger=`` arg that no longer exists.
- Update ``test_trajectories.py``'s ``interleave_rollout`` shim to
  pass ``env_name`` as a kwarg (the helper no longer reads it from
  the rollout dict).

CPU unit suite: 443 passed, 6 skipped. Trainer-side GPU tests
(``test_qwen3_5_moe`` / ``test_qwen3_5_moe_vlm``) still fail without
CUDA, which is the same on ``main``.

* refactor(configs): drop obsolete buffer + cancel-inflight fields

Remove four config surfaces that the new orchestrator never reads:

- ``EvalConfig.cancel_inflight_rollouts_on_eval`` — the drain-switch
  overlap (PREFER_TRAIN ⇄ PREFER_EVAL transitions level-triggered on
  ``EvalSource`` emptiness) replaces it.
- ``OrchestratorConfig.buffer = BufferConfig()`` field — default-
  instantiated, never accessed.
- ``BufferConfig`` class (seed / easy_threshold / hard_threshold /
  easy_fraction / hard_fraction / online_difficulty_filtering /
  hash_keys + the threshold validator) — replaced by
  ``pre_batch_filters``.
- ``CheckpointConfig.skip_buffer`` — no buffer to skip-load.

Public TOMLs (``configs/{math_group, nemotron_debug, wiki_search,
hendrycks_math, nemotron_4node}/rl.toml``) had inert
``[orchestrator.buffer]`` blocks that would now fail
``extra=forbid``; stripped them.

The private submodule (``configs/private/``) still references these
keys in several files — those need to be updated separately.

## Breaking

Existing configs that set any of the four removed keys will now
raise ``ValidationError: Extra inputs are not permitted``. Migration:
- ``cancel_inflight_rollouts_on_eval``: delete (drain-switch handles it).
- ``buffer.online_difficulty_filtering = true`` → set
  ``pre_batch_filters`` with ``ZeroAdvantageFilterConfig(enforce=True)``
  (the default) and drop the buffer block.
- ``buffer.easy_threshold`` / ``hard_threshold`` / ``easy_fraction`` /
  ``hard_fraction`` / ``hash_keys`` / ``seed``: no replacement.
- ``ckpt.skip_buffer``: delete.

CPU unit suite: 76 passed in the orchestrator subset.

* refactor: read seq/completion lens from vf.RolloutOutput.token_usage

Drop get_prompt_len / get_seq_len / get_completion_len from vf_utils
and read final_input_tokens / final_output_tokens directly from
vf.RolloutOutput["token_usage"] at the call sites. Verifiers populates
these for every real rollout; synthetic error markers set them to 0.

Semantically equivalent to the old trajectory-walking helpers (final
context size at end of rollout) but a direct field read from the source
of truth.

* fix(orchestrator): revert eval reward key to avg@N; migrate example buffer blocks

- EvalBatchMetrics: log eval reward as avg@{group_size} (matches main),
  drop n_rollouts/n_examples/valid_rate from wandb output, add
  num_turns/{min,max} alongside num_turns/mean.
- examples: replace removed [orchestrator.buffer] blocks. Configs that used
  online_difficulty_filtering migrate to an enforced zero_advantage
  pre-batch filter; threshold-only (difficulty-pool) blocks are dropped.

* feat(configs): warn + migration guide for removed [orchestrator.buffer]

Add a before-validator that pops the removed buffer block so legacy
configs still parse, and emits a FutureWarning. When
online_difficulty_filtering was set, the warning includes the direct
replacement (enforced zero_advantage pre-batch filter); otherwise it
notes difficulty pools are removed with no replacement.

* chore(configs): restore unchanged docstrings/comments to minimize diff

Revert incidental docstring/comment trims in fold_student_shortcuts and
the renderer/pool_size validators (and max_off_policy_steps) back to
main's wording. These functions' logic is unchanged; only their comments
had been reworded, adding review noise.

* feat(rlm-swe): single-node qwen3.5-4b config; pin rlm-swe as workspace member

- New configs/rlm_swe/qwen35_4b.toml: 4+4 GPU single-node, seq_len=65536,
  cp=2 + cp_style=ulysses (Qwen3.5 hybrid attention rejects ring style),
  max_inflight_rollouts=512, pre_run_command that cleans matching sandboxes.
- Add deps/research-environments/environments/rlm_swe to the workspace +
  the envs extra so `uv sync --all-extras` installs it; previously
  runtime-installed via `prime env install`, so each sbatch's in-job sync
  uninstalled it before `uv run rl` could import the env.
- Drop the now-superseded configs/rlm_swe/qwen3_4b.toml.

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

* feat(rlm-swe): qwen3.5-4b config contents + workspace install for rlm-swe

Settings inside the renamed config:
- Single-node 4+4 GPUs, seq_len=65536, max_inflight_rollouts=512.
- trainer.model.cp=2 with cp_style="ulysses" — Qwen3.5 is a hybrid
  linear-attention/SSM arch and rejects cp_style="ring".
- pre_run_command kills any sandboxes labelled rlm-swe-qwen35-4b so
  stale sandboxes from a prior run never linger.
- Output under /beegfs/mika/ instead of /beegfs/outputs/.

Workspace plumbing for rlm-swe:
- Add deps/research-environments/environments/rlm_swe as a workspace
  member with the corresponding tool.uv.sources entry.
- Add rlm-swe to the envs extra so `uv sync --all-extras` installs it.
  Previously it was runtime-installed via `prime env install`, so each
  sbatch's in-job sync uninstalled it before `uv run rl` could import.

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

* fix: eval metric correctness + integration-test log parsing

- eval_sink: completion_len/* uses final_output_tokens only (was
  final_input+output), matching envs.py and the historical metric meaning.
- eval_sink: average each pass@k only over examples that produced it
  (skip missing high-k), matching pandas NaN-skipping; fixes downward
  bias on errored eval epochs.
- dispatcher: drop the per-rollout dispatch + per-group complete debug
  logs (too fine-grained).
- tests/utils: parse the new orchestrator log format (Reward without a
  colon; eval line reports Reward instead of Avg@K=).

* refactor(orchestrator): pipeline-log clarity, per-rollout offload, lifecycle + cleanup

- Pipeline log: split train batch progress (pending_batch, capped at target)
  from a separate "(+N buffered)" partial-group count; unified inflight tail
  "(train=, eval= | per-env)"; eval batch shown as "{env} done/total (pct)".
- Image offload moved from per-batch to per-rollout (TrainSink.process_rollout),
  freeing base64 image memory as rollouts arrive instead of at ship.
- Consolidated vf_utils.py into orchestrator/utils.py (inlined trivial
  get_num_turns); moved setup_student_inference_pool there too.
- Renamed Orchestrator.shutdown() -> stop() to match component start/stop.
- Per-group finalization logs now say "Finished group"; stripped trailing
  periods from comments; dropped the Orchestrator class docstring.
- Moved configs/hendrycks_math/sanity.toml -> configs/debug/hendrycks_sanity/rl.toml;
  multi_env config uses unique train/eval env names.

* feat(rlm-swe): multinode 1 train + 1 infer node, inference dp=8

Move qwen3.5-4b off single-node 4+4 to a 2-node split (1 train, 1 infer)
to relieve the inference decode bottleneck (KV ~57%, ~190 reqs queued on
capacity across only 4 infer GPUs). Trainer keeps cp=2 -> dp_shard=4 on
the full 8-GPU train node.

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

* feat(rlm-swe): add 1h per-rollout timeout on swebench eval

Caps each eval rollout at 3600s wall-clock (-> timeout_seconds) so the
long-tail SWE-bench rollouts can't hold inference capacity indefinitely.

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

* fix(rlm-swe): cp=4 to fix trainer OOM on step 1

22513 OOM'd in loss.backward() on the first step (4B, 8 GPU, dp_shard=4
cp=2, seq_len 65536, full AC; ~1GB over). Bumping context parallel to
cp=4 (dp_shard=2) splits the 65k sequence across 4 GPUs, ~halving
backward activation memory.

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

* chore: update uv.lock to match pyproject (fix `uv sync --locked` in CI)

The lockfile went stale relative to pyproject.toml (openai-harmony
requires-dist spec drift), so the CPU CI's `uv sync --all-extras --locked`
install step failed. Regenerated via `uv lock`; `--locked` now passes.

* refactor(trainer): match orchestrator log format (drop colons after labels)

Trainer step / micro-step / validation lines now use `Loss 0.34` style
(space, no colon) to match the orchestrator's success-line format.
Updated the integration-test parsers (check_loss_goes_down,
check_avg_mismatch_kl_in_range) to colon-optional patterns, backward
compatible with the old format.

* refactor(trainer): drop "Time" label from step line (match orch)

Trainer step line now shows the time unlabeled and right-aligned to 7
chars (Step N |   44.5s | Loss ...), matching the orchestrator's success
line exactly. Also align format_time's docstring with vf.print_time.

* feat(rlm-swe): 2 inference nodes (dp=16) to double decode throughput

num_infer_nodes 1->2 and inference dp 8->16 (8/node x 2 nodes, tp=1).
data_parallel_size_local auto-derives to 8. Total alloc now 3 nodes
(1 train + 2 infer). Relieves the rollout-throughput bottleneck that
makes SWE batch fill (~36min/step) slow.

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

* fix(rlm-swe): inference dp is per-node — set dp=8 (not 16)

dp in multi-node inference is per-node (data_parallel_size_local),
multiplied by num_infer_nodes internally. dp=16 double-counted →
inference_world_size=32. dp=8 × 2 infer nodes = 16 global ranks.

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

* feat(rlm-swe): 2 independent inference replicas instead of cross-node DP

num_infer_nodes=2 builds ONE inference instance spanning 2 nodes
(cross-node DP coordinator → slow/fragile rendezvous). For a 4B model
on 1 GPU we want 2 independent single-node replicas behind the router:
num_infer_nodes=1 + num_infer_replicas=2 (dp=8/node → 16 infer GPUs).
Same 2x throughput, no cross-node coordination.

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

* fix(orchestrator): warn (not success) when cleanup is forced

start()'s teardown now logs a forced-cleanup warning when main_loop is
interrupted (signal CancelledError / KeyboardInterrupt / error) instead
of the clean-exit success line, so an interrupted run is distinguishable
from a true completion.

* chore(orchestrator): remove dead print_benchmark from utils

print_benchmark was unused in the orchestrator package (the trainers use
the copy in trainer/utils.py); drop it and its now-orphaned pandas / rich
/ format_time / Any imports.

* fix(orchestrator): eval the student (not teacher) in SFT; ckpt drain off-by-one

- Eval rollouts now always go to the student inference pool + student
  policy name. Previously the dispatcher used the single rollout pool for
  both train and eval, so in SFT mode (rollout pool = teacher) eval
  evaluated the *teacher* (fixed ~0.8), masking student progress. Add a
  dedicated eval_inference pool to the dispatcher; train still uses the
  rollout pool (teacher in SFT).
- maybe_save_ckpt: skip step >= max_steps - 1 (was == max_steps - 1) so
  the drain-entry step (== max_steps, never shipped) doesn't double-save
  a checkpoint at an interval boundary.
- CHANGELOG: document the orchestrator breaking config changes.

* fix(orchestrator): per-env group_size in solve rates; group by group_id

- MetricsBuilder: solve_all now compares each problem's summed reward to
  its own env's group_size (was the top-level group_size), fixing
  solve_all/effective_batch_size for per-env group_size overrides.
- Group all per-problem metrics by the rollout's group_id (UUID) instead
  of (env_name, example_id), which collides across envs / oversampling.
- alphabet_sort integration test: run 10 steps (was 5).

* chore(configs): consolidate multimodal configs under configs/debug

Finish moving the color-codeword multimodal configs out of the
configs/multimodal/ dir: drop the unused rl_color_codeword.toml /
rl_color_codeword_test.toml and trim the renamed
configs/debug/multimodal.toml header. The dir is now empty.

* fix(orchestrator): eval through the eval (chat) client, not the renderer

Eval rollouts were generated via select_train_client (the renderer/token
train client) instead of get_eval_client (chat-completions). That changed
the eval generation path vs the legacy orchestrator (which used the chat
eval client), producing a consistent eval-score offset. Route eval groups
through pool.get_eval_client() so eval matches the legacy path; train
still uses the renderer/token train client.

* test(reverse_text): lower min reward threshold 0.65 -> 0.6

* fix(orchestrator): restore checkpoint resume compat with pre-rewrite runs

- Drop Progress.last_eval_step_by_env (and its EvalSource plumbing). It
  only suppressed a redundant eval epoch when resuming exactly at an
  eval-interval step; the first_trigger/is_resumed guard already prevents
  re-running the startup eval on resume. Progress is now back to main's
  shape (step + totals).
- Rename the orchestrator checkpoint file state.pt -> progress.pt to match
  the previous orchestrator. With the Progress shape restored, resuming via
  ckpt.resume_step from an old checkpoint now works (no FileNotFoundError,
  no migration needed).

* fix(orchestrator): gate dispatcher on lead instead of blocking ship

Replaces the ship-time async barrier with a dispatcher-side gate owned by
the orchestrator. The old wait_barrier blocked main_loop, which is also the
only consumer of dispatcher.out_q — when on_new_version (called by the
watcher under update_lock) emitted enough Cancelled markers to fill the
queue, its out_q.put blocked, the watcher never advanced policy.version,
and the barrier never released. With max_off_policy_steps=0 every version
bump cancels every inflight rollout, so the queue routinely overflowed.

The dispatcher now exposes a dispatch_allowed asyncio.Event; fill_inflight
returns early when clear. The orchestrator toggles it via the public
update_dispatch_gate based on (progress.step + 1) - policy.version vs
TARGET_LAG. It runs after sender.send (step advances) and from a new
on_new_version observer hook (policy advances). main_loop never blocks, so
on_new_version's puts always have a consumer.

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

* fix(dispatcher): claim drop_group tasks atomically before emitting

drop_group used to interleave dict mutations with awaits on emit_rollout
(which yields when out_q is full). During a yield, handle_completed_rollout
could pop a task drop_group hadn't reached yet, leaving the snapshot stale.
drop_group then re-popped (returning None — discarded), double-released the
permits, and emitted a second set of Cancelled markers for that rollout.

Split into a sync claim sweep (pop + release, no awaits) followed by the
async emit loop. By the time we start awaiting, every dropped task is
already out of self.inflight, so handle_completed_rollout's existing
None-guard bails out cleanly. No defensive None-checks in drop_group itself.

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

* feat(rlm-swe): enable prefix caching + language-model-only inference

- enable_prefix_caching=true ([inference] field): big win for SWE's long
  shared multi-turn prefixes.
- language_model_only=true (via [inference.vllm_extra]; it's a vLLM
  MultiModalConfig arg, no prime-rl field): Qwen3.5-4B is a VL model, so
  skip the vision tower for text-only SWE.

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

* feat(rlm-swe): disable thinking in the qwen3.5 renderer

Set [orchestrator.renderer] name="qwen3.5", enable_thinking=false
(Qwen35RendererConfig field) — text-only SWE, no <think> traces. Was
relying on the auto renderer (default thinking on for 4B).

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

* feat(rlm-swe): bump main run to 400 steps (non-thinking)

The on-main config is the non-thinking version (enable_thinking=false)
+ prefix caching + language_model_only. Run length 100 -> 400.

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

* feat(rlm-swe): re-enable thinking on the main config

Flip enable_thinking back to true on the on-main qwen3.5 config (keeps
prefix caching + language_model_only + 400 steps).

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

* fix(orchestrator): only skip ckpt at the drain-entry step, not max_steps-1

maybe_save_ckpt's near_end guard skipped step >= max_steps - 1, which also
skipped the last *shipped* step (max_steps - 1). The trainer saves a
checkpoint there (its is_last_step is max_steps, so it only skips 0 and
max_steps), so the orchestrator skipping max_steps-1 left a trainer ckpt
with no matching orchestrator Progress -> ckpt.resume_step = max_steps-1
(when it's an interval boundary) hit FileNotFoundError. The only real
double-save is at max_steps (drain-entry + final save in start()), so skip
only that. Now aligns with the trainer's is_last_step.

* chore(orchestrator): review responses (rename Kind, drop config aliases, doc cleanup)

- Rename the Kind type alias to RolloutKind (types.py + dispatcher.py).
- Remove the `filters` -> `post_batch_filters` before-validator alias and the
  `[orchestrator.buffer]` warn-and-drop validator. Both keys now hard-error
  (extra_forbidden); migrate the two bundled configs that used `filters`
  (configs/debug/multimodal.toml, examples/glm5_pd_disag/rl.toml) to
  post_batch_filters.
- Trim docstrings that referenced old/removed code: assign_advantages,
  TrainBatchMetrics (group-level error drop), post_batch_filters (filters alias).

* docs(changelog): filters/buffer are hard removals, not aliased/warned

The filters->post_batch_filters alias and the [orchestrator.buffer]
warn-and-drop before-validators were removed, so both keys now fail
validation (extra="forbid"). Update the CHANGELOG entries that still
claimed backward-compat parsing.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-01 12:03:19 -07:00
107 changed files with 6896 additions and 6039 deletions
-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
+10
View File
@@ -2,6 +2,16 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
- **`orchestrator.eval.eval_base_model` → `orchestrator.eval.skip_first_step`** (semantics inverted): `eval_base_model = true` becomes `skip_first_step = false` (the default — run the step-0 eval before any train rollouts). No alias; configs setting `eval_base_model` must rename.
- **`orchestrator.eval.skip_eval_on_resume` (and its alias `skip_eval_on_restart`) removed**: folded into `skip_first_step`. Resume no longer re-fires an already-completed eval (deduped via per-env last-eval-step tracking in the checkpointed progress).
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval` removed**: the drain-switch overlap (stop scheduling new train, let in-flight train drain while eval queues) is now the only eval transition mode.
- **`ckpt.skip_buffer` removed**: there is no buffer to skip.
- **`[orchestrator.buffer]` removed** (difficulty pools): the whole block and every key (`seed`, `easy_threshold`, `hard_threshold`, `easy_fraction`, `hard_fraction`, `online_difficulty_filtering`, `hash_keys`) are gone, with no alias — `extra="forbid"` rejects the block, so existing configs must delete it. To preserve `online_difficulty_filtering = true`, enforce the zero-advantage pre-batch filter: `[[orchestrator.pre_batch_filters]]\ntype = "zero_advantage"\nenforce = true`.
- **`orchestrator.filters` → `orchestrator.post_batch_filters`** (renamed, no alias): existing configs setting `[[orchestrator.filters]]` must rename to `[[orchestrator.post_batch_filters]]` (`extra="forbid"` rejects the old key). A new `pre_batch_filters` list is also available. Filters are **train-only** now — eval rollouts are no longer filtered.
- **`orchestrator.max_off_policy_steps` now also applies to eval** (behavior change, field unchanged): eval rollouts that fall more than `max_off_policy_steps` versions behind the policy are cancelled, same as train. (2026-05-29)
- **`sampling.min_tokens`, `sampling.repetition_penalty`, `sampling.seed` removed**: Dropped from both `TrainSamplingConfig` and `EvalSamplingConfig` (group-level `[orchestrator.train.sampling]` / `[orchestrator.eval.sampling]` and per-env `[[orchestrator.train.env.sampling]]` / `[[orchestrator.eval.env.sampling]]`). `min_tokens` suppressed natural EOS, `repetition_penalty` distorts the on-policy sampling distribution, and `seed` wasn't pulling its weight — none belonged on the supported config surface. Existing configs setting any of these must delete the field. Hard-deprecation, no migration window. (2026-05-27)
- **`wandb.shared` removed**: The deprecation shim that popped `wandb.shared` from input dicts with a `FutureWarning` (introduced in #2649) is gone. The `rl` entrypoint always uses shared W&B mode now, and existing configs that still set `wandb.shared = true` (or `false`) will fail validation. Drop the field from your config. (2026-05-27)
- **`max_async_level` and `strict_async_level` removed**: The async-execution semantics between trainer and orchestrator are now design invariants, not config knobs. The trainer always runs exactly one step ahead of inference, and the orchestrator always adopts the freshest checkpoint that doesn't violate the one-step barrier. The shared top-level `max_async_level`, the per-sub-config `trainer.max_async_level` / `orchestrator.max_async_level`, and `orchestrator.strict_async_level` have all been removed. Existing configs setting any of these must drop the field; the previous defaults (`max_async_level = 1`, `strict_async_level = false`) match the new hardcoded behavior. Bench mode no longer bypasses the weight-ckpt wait (the `int(1e9)` workaround is gone) and `multimodal/rl_color_codeword_feat_renderer.toml`'s prior `max_async_level = 0` (fully synchronous on-policy) is no longer expressible. (2026-05-25)
+1 -1
View File
@@ -1,7 +1,7 @@
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
# Build stage - multi-arch base (supports amd64 + arm64)
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu22.04 AS builder
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 AS builder
LABEL maintainer="prime intellect"
LABEL repository="prime-rl"
+11 -2
View File
@@ -55,10 +55,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 +110,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.
+1 -1
View File
@@ -1,4 +1,4 @@
max_steps = 5
max_steps = 10
seq_len = 2048
[ckpt]
@@ -1,5 +1,5 @@
max_steps = 3000
seq_len = 8192
seq_len = 4096
[wandb]
project = "hendrycks-math-debug"
@@ -9,7 +9,8 @@ name = "hendrycks-math-sanity"
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
batch_size = 256
max_inflight_rollouts = 512
group_size = 8
[[orchestrator.train.env]]
@@ -30,7 +31,7 @@ group_size = 16
[trainer.model.compile]
[inference.model]
max_model_len = 8192
max_model_len = 4096
[log]
level = "debug"
+52
View File
@@ -0,0 +1,52 @@
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-multi-env"
[orchestrator]
training_mode = "rl"
batch_size = 128
group_size = 16
[orchestrator.renderer]
name = "qwen3"
# -- multi train envs --
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-train-1"
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-train-2"
# -- multi eval envs --
[orchestrator.eval]
interval = 10
num_examples = 16
group_size = 4
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text-eval-1"
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text-eval-2"
interval = 5
[trainer.optim]
lr = 3e-6
[inference]
gpu_memory_utilization = 0.5
[inference.model]
max_model_len = 128
+75
View File
@@ -0,0 +1,75 @@
# 2-GPU debug RL run for the multimodal (renderer) path: Qwen3-VL-4B on
# color-codeword. Sized to actually learn (reward should trend up) while
# staying 2-GPU friendly. Exercises RendererClient + Qwen3VLRenderer end-to-end.
max_steps = 15
seq_len = 4096
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
gpus_per_node = 2
[orchestrator]
batch_size = 256
group_size = 16
# Image processor is CPU-bound and dominates for VLMs; returns diminish past 4.
pool_size = 4
# Step 0 on Qwen3-VL-4B vs color-codeword can be uniform (all-correct or
# all-wrong), so don't enforce zero-advantage dropping or training would crash
# before any progress.
[[orchestrator.post_batch_filters]]
type = "gibberish"
[[orchestrator.post_batch_filters]]
type = "repetition"
[[orchestrator.post_batch_filters]]
type = "zero_advantage"
enforce = false
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
# MODEL_RENDERER_MAP to Qwen3VLRenderer at runtime; no explicit name needed.
[trainer]
[trainer.model]
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[trainer.optim]
lr = 3e-6
[inference]
[inference.model]
# Workaround for vLLM 0.20.1 Qwen3-VL deepstack buffer bug: when num_scheduled_tokens
# (188) gets padded up to the next cudagraph_capture_size (192), the model's
# _set_deepstack_input_embeds sizes the buffer to 188 but forward() runs with 192,
# triggering "Requested more deepstack tokens than available in buffer". Eager mode
# skips the padding so num_input_tokens == num_scheduled_tokens.
enforce_eager = true
[inference.parallel]
dp = 1
tp = 1
[wandb]
project = "debug"
name = "multimodal"
tags = ["qwen3vl-4b", "color-codeword", "renderer"]
+31
View File
@@ -0,0 +1,31 @@
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"
-4
View File
@@ -20,10 +20,6 @@ id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[orchestrator.eval]
interval = 10
-4
View File
@@ -23,10 +23,6 @@ name = "acereason-math"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
ratio = 0.5
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[orchestrator.eval]
interval = 50
-59
View File
@@ -1,59 +0,0 @@
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
group_size = 16
# -- train envs --
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-1"
[orchestrator.train.env.sampling]
max_completion_tokens = 127
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-2"
# -- eval envs --
[orchestrator.eval]
interval = 5
[orchestrator.eval.sampling]
max_completion_tokens = 512
[[orchestrator.eval.env]]
id = "reverse-text"
name = "eval-default"
num_examples = 32
group_size = 4
[[orchestrator.eval.env]]
id = "reverse-text"
name = "eval-custom"
num_examples = 16
group_size = 2
interval = 10
[orchestrator.eval.env.sampling]
max_completion_tokens = 256
temperature = 0.5
[trainer.optim]
lr = 3e-6
[inference] # Default inference config
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
-34
View File
@@ -1,34 +0,0 @@
max_steps = 15
seq_len = 4096
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
[trainer]
[trainer.model]
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[trainer.optim]
lr = 3e-6
[inference]
[inference.parallel]
dp = 1
@@ -1,94 +0,0 @@
# 20-step Qwen3-VL-4B RL run on color-codeword using the renderer multimodal path.
#
# Pair with rl_color_codeword_main_mito.toml for an A/B comparison: same env,
# same hyperparameters, same step count — only difference is the inference
# client. The feat-branch run uses the new RendererClient + Qwen3VLRenderer
# (renderers package with multimodal support); the main-branch baseline uses
# the existing TITO chat-completions path through the inference server.
#
# Compare in W&B project ``multimodal-renderer``:
# - ``kl/sampler_vs_trainer`` should be ~0 on this branch (the renderer
# produces byte-identical tokens to what the trainer re-tokenizes) and
# can spike on main when BPE drifts mid-rollout.
# - ``reward`` and ``loss`` should track within noise — same model, same
# env, same hyperparameters.
# - ``bridge_break_rate`` is renderer-only; surfaces multi-turn extension
# failures.
max_steps = 20
seq_len = 4096
output_dir = "outputs/rl_color_codeword_feat_renderer"
clean_output_dir = true
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
gpus_per_node = 2
[orchestrator]
batch_size = 16
group_size = 8
# 64 concurrent rollouts (batch_size=16 × group_size=4) want
# more than one tokenizer slot to avoid serialization queueing. The
# image processor (CPU-bound) dominates for VLMs so returns diminish
# past 4; bump to 4 as the default for multimodal runs.
pool_size = 4
# Track zero-advantage groups but don't drop them — we're validating the
# multimodal renderer path on 20 steps, not optimizing training efficiency.
# Step 0 on Qwen3-VL-4B vs color-codeword is likely uniform (all-correct or
# all-wrong) so enforce=True would crash before any training happens.
[[orchestrator.filters]]
type = "gibberish"
[[orchestrator.filters]]
type = "repetition"
[[orchestrator.filters]]
type = "zero_advantage"
enforce = false
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 2, max_turns = 2, num_examples = 100, seed = 42 }
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
# MODEL_RENDERER_MAP to Qwen3VLRenderer at runtime; no explicit name needed.
[trainer]
[trainer.model]
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[trainer.optim]
lr = 3e-6
[inference]
[inference.model]
# Workaround for vLLM 0.20.1 Qwen3-VL deepstack buffer bug: when num_scheduled_tokens
# (188) gets padded up to the next cudagraph_capture_size (192), the model's
# _set_deepstack_input_embeds sizes the buffer to 188 but forward() runs with 192,
# triggering "Requested more deepstack tokens than available in buffer". Eager mode
# skips the padding so num_input_tokens == num_scheduled_tokens.
enforce_eager = true
[inference.parallel]
dp = 1
tp = 1
[wandb]
project = "multimodal-renderer"
name = "feat-renderer-20step-r8-i2-t2-onpolicy"
tags = ["qwen3vl-4b", "color-codeword", "renderer", "feat-branch", "mm-kwargs-generic", "on-policy"]
@@ -1,35 +0,0 @@
max_steps = 3
seq_len = 2048
output_dir = "outputs/rl_color_codeword_test"
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
[orchestrator]
batch_size = 16
group_size = 2
[orchestrator.train.sampling]
max_completion_tokens = 32
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 2, num_examples = 100, seed = 42 }
[trainer]
[trainer.model]
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[trainer.optim]
lr = 3e-6
[inference]
[inference.parallel]
dp = 1
-4
View File
@@ -55,10 +55,6 @@ id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[orchestrator.eval]
interval = 10
-4
View File
@@ -54,10 +54,6 @@ id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[orchestrator.eval]
interval = 10
Submodule configs/private deleted from 70c3503e1d
+99
View File
@@ -0,0 +1,99 @@
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]]
id = "rlm_swe"
name = "rlm-swe-r2e"
num_workers = 4
[orchestrator.train.env.args]
labels = ["rlm-swe-qwen35-4b"]
[orchestrator.prime_monitor]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
id = "rlm_swe"
name = "rlm-swe-swebench-verified-quick"
num_workers = 4
timeout = 3600
[orchestrator.eval.env.args]
task_type = "swebench"
dataset_name = "PrimeIntellect/SWE-Bench-Verified-Quick"
labels = ["rlm-swe-qwen35-4b"]
# --- 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
-3
View File
@@ -33,9 +33,6 @@ oversampling_factor = 2.0
[orchestrator.train.sampling]
max_completion_tokens = 512
[orchestrator.buffer]
online_difficulty_filtering = true
[[orchestrator.train.env]]
id = "wiki-search"
+1 -1
+1 -1
+7 -9
View File
@@ -36,18 +36,17 @@ impl = "custom" # or "hf" to force the HF path
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
The custom path enables EP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
The custom path enables you to set EP, CP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
### Expert Parallelism Backends
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
- **`torch`** (default): TorchTitan's all-to-all collective. Works everywhere, no extra install.
- **`deepep`**: Custom kernels from DeepEP. Faster but requires DeepEP build (`bash scripts/install_deep_gemm.sh`, `bash scripts/install_ep_kernels.sh`) and tuning of `deepep_num_sms` (default 20) and `deepep_token_chunk_size` for your hardware.
- **`deepep`**: Utilizes DeepEP's custom all-to-all collectives. This provides better performance if EP dimension spans multiple nodes. We provide pre-built binaries for H100/H200 with cuda runtime 12.9 installed, you can install them by running `uv sync --all-extras`.
DeepEP requires some careful tuning to achieve optimal performance, tuning parameters are `deepep_num_sms` and `deepep_token_chunk_size`.
DeepEP intranode dispatch derives the RDMA channel count as `deepep_num_sms / 2`. Lower SM count leaves more for compute; higher speeds up dispatch. Useful starting points: 16–24 SMs on H100, 20–40 on B200.
When you enable DeepEP, gradient clipping is auto-disabled (`optim.max_norm` set to `None`) because the kernels don't currently support it.
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
## Multimodal Training
@@ -80,7 +79,7 @@ language_model_attr = "model.language_model"
# freeze_vision_encoder = true # default; set false to fine-tune the encoder
```
A bad attribute path errors immediately — no silent fallbacks. The weight-broadcast key prefix is derived as `{language_model_attr}.layers.` automatically.
The weight-broadcast key prefix is derived as `{language_model_attr}.layers.` automatically.
To add a new model family permanently, append an entry to `VLM_REGISTRY` in `src/prime_rl/utils/vlm.py`.
@@ -116,7 +115,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
@@ -138,8 +137,7 @@ curl -s http://<decode_node>:8200/metrics | grep num_requests_waiting
If prefill queues and decode is idle, add prefill nodes (and vice versa).
**UCX 1.19 requirement.** NVSHMEM needs UCX ≥ 1.19 for multi-GPU CUDA. Most clusters ship UCX 1.17 via HPC-X, which manifests as `cuStreamCreate: invalid device context` errors during DeepEP internode dispatch. Check with `/opt/hpcx/ucx/bin/ucx_info -v` and, if needed, build from source:
**UCX 1.19 requirement.** NVSHMEM needs UCX ≥ 1.19 for multi-GPU CUDA. If your cluster doesn't ship with UCX >=1.19, you can build it from source with the following command:
```bash
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
```
+16
View File
@@ -167,6 +167,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):
+9
View File
@@ -129,3 +129,12 @@ What to look for:
- **Loss reasonable.** Not NaN, not stuck.
Don't expect reward to climb meaningfully in 20 steps on a random model.
### Requirements for merging a new model
Before merging a new model, you need to ensure the following:
- The model is correctly registered and defines and all the required methods - such as `convert_hf_layer_to_tt` and `convert_tt_layer_to_hf`.
- The small smoke test passes.
In the PR that adds the new model, you also need to provide a table covering the KL mismatch across 20 steps on `math` environment with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not met, the PR will not be merged (unless reasonable justification is provided). This is to ensure all our models are consistent and their implementations match the implementations in the inference framework.
+269
View File
@@ -0,0 +1,269 @@
# Inference
This page covers the inference configuration and the supported features/deployment shapes. It covers how to scale the inference server from a single GPU to 1000s of GPUs that run agentic workloads at the speed of light with all the bells and whistles configured.
## Table of Contents
- [Overview](#overview)
- [Single-Node](#single-node)
- [Multi-Node](#multi-node)
- [Multi-replica](#multi-replica)
- [Wide-EP](#wide-ep)
- [P/D Dissagregation](#pd-dissagregation)
- [Router](#router)
- [Routing policies](#routing-policies)
- [Advanced Configuration](#advanced-configuration)
- [KV Cache Offload](#kv-cache-offload)
- [Optimized P/D disaggregation deployment](#optimized-pd-disaggregation-deployment)
- [Other vLLM features](#other-vllm-features)
- [Router Replay](#router-replay)
## Overview
`prime-rl` chooses to use `vLLM` as the inference engine. We aim to stay up-to-date with the latest vLLM features, being at-most 1 version behind the latest stable release. This allows us to use the latest features from vLLM as soon as they are released - such as router replay, CPU KV cache offload, and more.
We support 3 distinct deployment shapes:
- [Single-Node](#single-node) - Runs the inference server on a single node. Useful for debugging, small scale experiments or smaller models. The default deployment shape.
- [Multi-Node](#multi-node) - Runs the inference server on multiple nodes. Useful for large scale experiments or larger models, where latency is not a concern - i.e. single turn inference, long context inference, etc.
- [Disaggregated](#disaggregated) - Runs the inference server on multiple nodes, but disaggregates the prefill and decode stages. Useful for large scale experiments or larger models, where latency is a concern and multi-node deployment creates very high E2E rollout latency, such as agentic workflows.
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `router_port`, `backend_port`, etc.
```toml
[inference.deployment]
type = "single_node" # or "multi_node" or "disaggregated"
```
To configure the inference server, you can use the `InferenceConfig` field. This is a config-field that allows you to set the inference server-specific knobs. Most of these are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
```toml
[inference]
model = "PrimeIntellect/INTELLECT-3"
...
```
We will now walk through the supported features and deployment shapes in detail, starting with the single-node deployment.
## Single-Node
The single-node deployment is the default deployment shape. It runs the inference server on a single node. It is useful for debugging, small scale experiments or smaller models. You can configure the single-node deployment with the `SingleNodeInferenceDeploymentConfig` config-field.
```toml
[inference.deployment]
type = "single_node"
```
This deployment shape runs the inference server on a single node, if configured with NVLink enabled, it allows you more freedom in terms of parallelism configurations.
```toml
[inference]
enable_expert_parallel = true # defaults to False
[inference.parallel]
tp = 2
dp = 4
[inference.deployment]
type = "single_node"
```
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required `orchestrator.max_inflight_requests`. Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.enable_expert_parallel` or `inference.parallel.tp` to maximize the available GPU memory.
You can also increase the available KV cache memory by enabling `inference.kv_cache_offload`. More details in the [Advanced Configuration](#advanced-configuration) section.
## Multi-Node
This deployment shape branches into 2 sub-shapes:
- [Multi-replica](#multi-replica) - Runs the inference server on multiple nodes, but each node runs an independent vLLM replica. You can think of this as a for-loop over single-node deployments.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
### Multi-replica
This deployment shape runs the inference server on multiple nodes, but each node runs an independent vLLM replica.
Parallelism configuration is the same as the single-node deployment. The shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.deployment.num_nodes` to the number of nodes you want to run the inference server on.
```toml
[inference.deployment]
type = "multi_node"
num_nodes = 2
[inference]
model = "PrimeIntellect/INTELLECT-3"
[inference.parallel]
tp = 2
dp = 4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing 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.
### Wide-EP
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.enable_expert_parallel = true`.
```toml
[inference.deployment]
type = "multi_node"
num_nodes = 2
[inference]
model = "PrimeIntellect/INTELLECT-3"
enable_expert_parallel = true
[inference.parallel]
tp = 2
dp = 8
```
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tp = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
## P/D Dissagregation
This is the most advanced deployment shape. It allows you to disaggregate the prefill and decode stages, with KV cache flowing between them. This is useful for large scale deployments, where there are high requirements on latency, such as agentic workflows spanning 100s of turns.
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and `inference.deployment.num_prefill_nodes` and `inference.deployment.num_decode_nodes` to the number of nodes you want to run the prefill and decode stages on.
```toml
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 2
num_decode_nodes = 2
```
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode node groups. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of replicas you want to run.
```toml
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 2
num_decode_nodes = 2
num_prefill_replicas = 2
num_decode_replicas = 1
```
Now the total deployment will span 6 nodes - 2x2 for prefill and 1x2 for decode. 2 prefill replicas will run on 2 nodes each - total of 4 nodes for prefill. 1 decode replica will run on 2 nodes for decode.
We also allow you to configure the total amount of inference replicas - this is useful if you'd like to multiply the above configuration by a factor of `k`, each running behind a separate `vllm-router` instance.
```toml
[deployment] # this is a top-level RL deployment, not inference.deployment!!
type = "multi_node"
num_train_nodes = 4
num_infer_nodes = 6 # this is per-replica
num_infer_replicas = 3
```
This will run 3 inference replicas, each running on 6 nodes. Each replica will run on 2x2 nodes for prefill and 1x2 nodes for decode. The total deployment will span 18 nodes. This will also spin-up 3 separate `vllm-router` instances.
## Router
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.
Right now, router handles 2 most important things:
- Request routing - KV cache re-use and balanced routing
- P/D disaggregation - handling the prefill and decode stages separately
### Routing policies
The 2 policies you might want to configure are:
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - this works by hashing a request header to determine where to route the request to. You can configure what to hash by setting
`orchestrator.student.client.extra_headers_from_state` to the header the `router` expects to be set.
We set it to a sensible default, that works with all verifiers environments.
```toml
[orchestrator.student.client.extra_headers_from_state]
X-Session-ID = "trajectory_id" # this is the default - each rollout has a unique trajectory_id and router expects X-Session-ID
```
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
## Advanced Configuration
### KV Cache Offload
Maximizing KV-Cache space is crucial to support high-concurrency workloads. You can offload the KV cache to CPU memory (and, behind it, disk) by setting `inference.kv_cache_offload`. It is a discriminated config with two composable tiers, `cpu` and `disk`: a `cpu` tier is always required, and an optional `disk` tier is layered behind it (GPU → DRAM → disk). Disk-only is not supported.
The `type` field selects the backend:
- `native` — vLLM's built-in offloading. CPU-only uses `OffloadingConnector`; CPU+disk uses `TieringOffloadingSpec` (a CPU primary tier with a filesystem secondary tier). Fully self-contained — no extra processes.
- `mooncake` — a [Mooncake](https://github.com/kvcache-ai/Mooncake) **shared distributed store** (SLURM only). One `mooncake_master` + metadata server runs on the head inference node; every inference node runs a `mooncake_client` that contributes its DRAM (and, with `disk`, SSD) segment to that *single* pool. Because blocks are keyed by model + parallel rank + content hash (no instance id), a prefix cached by one node/replica is reusable by all of them over RDMA — pooling every node's CPU RAM into one KV cache. Use `native` for local/single-process runs.
```toml
# Native CPU offload (reserves 128GB of CPU KV cache for this instance)
[inference.kv_cache_offload]
type = "native"
[inference.kv_cache_offload.cpu]
num_bytes = 128_000_000_000 # 128GB
# Native CPU + disk tiering (self-contained)
[inference.kv_cache_offload]
type = "native"
[inference.kv_cache_offload.cpu]
num_bytes = 128_000_000_000
[inference.kv_cache_offload.disk]
path = "/scratch/kv" # disk capacity is bounded by the filesystem
# Mooncake CPU + disk (per-node distributed store, RDMA)
[inference.kv_cache_offload]
type = "mooncake"
[inference.kv_cache_offload.cpu]
num_bytes = 128_000_000_000
[inference.kv_cache_offload.disk]
path = "/scratch/kv"
```
For `native`, `cpu.num_bytes` is the aggregate CPU KV pool for the instance (vLLM shards it across workers). For `mooncake`, `cpu.num_bytes` is the DRAM each node contributes to the shared pool (so the total pool ≈ `num_bytes × #inference-nodes`); the store uses RDMA, so it requires an RDMA-capable fabric. Enabling offload automatically enables prefix caching.
### Optimized P/D disaggregation deployment
For optimal P/D disaggregation deployment, we automatically set the decode `all2all_backend` to `deepep_low_latency` and the prefill `all2all_backend` to `deepep_high_throughput`. We currently don't support customizing all2all backends for P/D disaggragation out of the box. You can do this by overriding the slurm template only.
For KV cache transfer, we utilize the NIXL connector. This is the default and only currently supported connector. We aim to support more advanced options, such as D->P transfer, or Mooncake Connector in the future.
For configuring various knobs with environment variables, we enable you to configure prefill and decode environment variables separately. This is useful if you want to configure different environment variables for the prefill and decode stages.
```toml
[inference.deployment]
type = "disaggregated"
prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
decode_env_overrides = {"VLLM_DEEP_GEMM_WARMUP"="skip"}
```
### Other vLLM features
We support various other vLLM features. Some of those, such as `enable_dbo`, `enable_eplb` are exposed as a top-level config fields. For those that are not, you can configure them by setting `inference.vllm_extra` to the desired value.
```toml
[inference.vllm_extra]
headless = true
```
### Router Replay
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.enable_return_routed_experts = true`.
```toml
[trainer]
enable_router_replay = true # this will also auto-set the inference.enable_return_routed_experts = true
[inference]
enable_return_routed_experts = true
```
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend increasing `orchestrator.*.env.num_workers` to allow for more parallelization on the verifiers side.
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
+1
View File
@@ -7,6 +7,7 @@
"overview",
"configuration",
"training",
"inference",
"scaling",
"algorithms",
"advanced",
+4 -3
View File
@@ -8,9 +8,9 @@ A `prime-rl` RL run is three cooperating processes:
![Architecture](assets/architecture.png)
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). Supports data + tensor + expert parallelism (with `deepep` and `flashinfer` all-to-all backends and EPLB), FP8 inference, prefill/decode disaggregation behind a `vllm-router`, CPU KV-cache offload, and *router replay* (the routed-expert mask is returned to the trainer for FP8 MoE numerical parity). Weights are pushed in place through a custom `update_weights` endpoint over filesystem or NCCL transports.
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). We are trying to stay up-to-date with the latest vLLM features, you can read more about the supported features and deployment options in the dedicated [inference documentation](inference.md).
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment).
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses the filesystem (or NCCL for synchronous setups). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
@@ -20,7 +20,7 @@ The three processes communicate through configurable transports — by default t
curl -sSL https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/main/scripts/install.sh | bash
```
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`research-environments`](https://github.com/PrimeIntellect-ai/research-environments) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, MoE-only installs (DeepGEMM / DeepEP / NIXL), or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`research-environments`](https://github.com/PrimeIntellect-ai/research-environments) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
You need at least one NVIDIA GPU (RTX 3090/4090/5090, A100, H100, H200, or B200). Single-GPU runs are supported for debugging; production RL is typically 1× inference node + 1+ trainer nodes.
@@ -38,6 +38,7 @@ The `rl` entrypoint reads `examples/reverse_text/rl.toml`, splits it into per-pr
- **[Configuration](configuration.md)** — TOML composition, CLI overrides, dry-run.
- **[Training](training.md)** — Launch and observe RL and SFT runs.
- **[Inference](inference.md)** — vLLM-backed server (or fleet) holding the current policy.
- **[Scaling](scaling.md)** — Single-GPU through multi-node clusters via FSDP / EP / CP and SLURM.
- **[Algorithms](algorithms.md)** — Async semantics, loss / advantage / filter plugins, trajectory merging.
- **[Advanced](advanced.md)** — Custom modeling, multimodal, LoRA, multi-tenant, P/D inference.
+11 -4
View File
@@ -1,6 +1,6 @@
# Scaling
This page covers how to scale `prime-rl` from a single GPU to a 1000-GPU cluster: single-node and multi-node deployments, FSDP / expert parallelism / context parallelism, and throughput benchmarking. For knobs that fit on one box, see [Training](training.md) first. For prefill/decode disaggregated inference, see [Advanced](advanced.md#disaggregated-prefilldecode-inference).
This page covers how to scale `prime-rl` from a single GPU to a 1000-GPU cluster: single-node and multi-node deployments, FSDP / expert parallelism / context parallelism, and throughput benchmarking. See [Training](training.md) for detailed documentation of the trainer configuration and [Inference](inference.md) for the inference configuration.
## Table of Contents
@@ -90,7 +90,7 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
### Expert Parallelism
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
```toml
[trainer.model]
@@ -103,14 +103,14 @@ ep_comm_backend = "torch" # or "deepep"
### Context Parallelism
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Only available with the custom impl and flash-attention.
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
```toml
[trainer.model]
impl = "custom"
attn = "flash_attention_2" # or fa3 / fa4
cp = 2 # CP degree
cp_style = "ring" # "ulysses" for non-FA kernels
cp_style = "ulysses" # "ring"
```
### Activation Checkpointing and Offloading
@@ -129,6 +129,13 @@ mode = "selective"
targets = ["norm", "attn_proj"] # see Reference for the full list per architecture
```
We reccomend also using `ac_offloading` and `ac_offloading.max_inflight_activations = 5` to further reduce the memory footprint in tradeoff for some throughput. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput:
```toml
[trainer.model.ac_offloading]
max_inflight_activations = 5
```
### Optimizer Offloading
Offloading optimizer states to CPU is a near-free memory win at low GPU counts:
+3 -4
View File
@@ -77,10 +77,9 @@ name = "code"
ratio = 0.2
args = { pool_size = 512 }
[orchestrator.buffer]
easy_threshold = 1.0
online_difficulty_filtering = true
seed = 42
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[orchestrator.eval]
interval = 25
+1 -6
View File
@@ -77,15 +77,10 @@ id = "mini-swe-agent-plus"
name = "swe-bench-verified-quick"
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
[[orchestrator.filters]]
[[orchestrator.post_batch_filters]]
type = "gibberish"
enforce = true
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
seed = 42
[inference]
enable_expert_parallel = true
# we need <0.85 bc glm5 layers are too large for 0.85
-5
View File
@@ -62,11 +62,6 @@ id = "mini-swe-agent-plus"
name = "swe-bench-verified-quick"
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
seed = 42
[inference.parallel]
tp = 8
-4
View File
@@ -46,10 +46,6 @@ id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[inference.parallel]
tp = 4
dp = 2
-5
View File
@@ -58,10 +58,5 @@ interval = 25
[[orchestrator.eval.env]]
id = "aime2025"
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
seed = 42
[inference.parallel]
tp = 8
-5
View File
@@ -59,10 +59,5 @@ id = "mini-swe-agent-plus"
name = "swe-bench-verified-quick"
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
seed = 42
[inference.parallel]
tp = 8
+3 -2
View File
@@ -40,8 +40,9 @@ name = "qwen3-4b-wiki-search"
[orchestrator.train.sampling]
max_completion_tokens = 512
[orchestrator.buffer]
online_difficulty_filtering = true
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[[orchestrator.train.env]]
id = "primeintellect/wiki-search"
@@ -5,7 +5,7 @@ from typing import Annotated, Any, Literal, TypeAlias
from pydantic import Field, model_validator
from pydantic_config import BaseConfig
from prime_rl.configs.shared import BaseModelConfig, SlurmConfig
from prime_rl.configs.shared import BaseModelConfig, LogConfig, SlurmConfig
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
@@ -86,9 +86,71 @@ class WeightBroadcastConfig(BaseConfig):
"""Weight broadcast transport."""
class KVCacheOffloadConfig(BaseConfig):
cpu_bytes: int = Field(1_000_000_000, gt=0)
"""CPU bytes available for KV cache offloading per worker."""
class CPUOffloadTier(BaseConfig):
num_bytes: int = Field(..., gt=0)
"""CPU/DRAM offload capacity. For the ``native`` backend this is vLLM's aggregate ``cpu_bytes_to_use`` (scaled across workers internally). For the ``mooncake`` backend this is the per-node store client's DRAM segment (``-global_segment_size``)."""
class DiskOffloadTier(BaseConfig):
path: Path
"""Filesystem root for the disk tier. For ``native`` this is the ``fs_python`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
class BaseKVCacheOffloadConfig(BaseConfig):
cpu: CPUOffloadTier | None = None
"""CPU/DRAM offload tier. Always required — disk-only offload is not supported."""
disk: DiskOffloadTier | None = None
"""Optional disk tier, layered behind the CPU tier (GPU → DRAM → disk)."""
@model_validator(mode="after")
def valid_tiers(self):
# Both backends support only two shapes: cpu-only or cpu+disk. Native disk
# tiering needs a CPU primary tier; Mooncake standalone-store needs a DRAM
# staging tier. Disk-only is rejected for both.
if self.cpu is None:
raise ValueError("inference.kv_cache_offload requires a cpu tier (disk-only offload is not supported).")
return self
class NativeKVCacheOffloadConfig(BaseKVCacheOffloadConfig):
type: Literal["native"] = "native"
"""vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs_python`` disk secondary). Fully self-contained — no external processes."""
def to_connector_dict(self) -> dict[str, Any]:
assert self.cpu is not None
extra: dict[str, Any] = {"cpu_bytes_to_use": int(self.cpu.num_bytes)}
if self.disk is not None:
extra["spec_name"] = "TieringOffloadingSpec"
extra["secondary_tiers"] = [{"type": "fs_python", "root_dir": str(self.disk.path)}]
return {
"kv_connector": "OffloadingConnector",
"kv_role": "kv_both",
"kv_connector_extra_config": extra,
}
class MooncakeKVCacheOffloadConfig(BaseKVCacheOffloadConfig):
type: Literal["mooncake"] = "mooncake"
"""Mooncake distributed store offloading (SLURM only). One ``mooncake_master`` + metadata server runs on the head inference node; every node runs a ``mooncake_client`` contributing its segment to the single shared pool, so prefixes cached on any node are reusable by all. The cpu tier sizes each node's DRAM segment; the optional disk tier adds an SSD tier."""
device_name: str = ""
"""RDMA device name(s) for the store (empty = auto-detect)."""
def to_connector_dict(self) -> dict[str, Any]:
# Addresses/sizes/tiers are realized by the per-node store launch in the sbatch
# template (MOONCAKE_CONFIG_PATH JSON); blocks are keyed by model + parallel rank +
# content hash (no instance id), so the shared pool is reused across nodes/replicas.
return {
"kv_connector": "MooncakeStoreConnector",
"kv_role": "kv_both",
"kv_connector_extra_config": {},
}
KVCacheOffloadConfig: TypeAlias = Annotated[
NativeKVCacheOffloadConfig | MooncakeKVCacheOffloadConfig, Field(discriminator="type")
]
# Valid vLLM max_lora_rank values (from vllm/config/lora.py)
@@ -105,10 +167,33 @@ All2AllBackend = Literal[
]
class VllmRouterConfig(BaseConfig):
"""PrimeIntellect vllm-router fronting the per-rank (external-LB) endpoints."""
type: Literal["vllm-router"] = "vllm-router"
port: int = 8000
"""Port the router listens on — becomes the client-facing router URL."""
policy: str = "consistent_hash"
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
# Discriminated on ``type`` so additional router backends can be added to the
# union (a single member needs no discriminator yet).
RouterConfig: TypeAlias = VllmRouterConfig
class BaseInferenceDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
"""GPUs per node."""
backend_port: int = 8100
"""Port for the per-rank vLLM backend instances."""
router: RouterConfig = VllmRouterConfig()
"""Router fronting the per-rank endpoints."""
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
type: Literal["single_node"] = "single_node"
@@ -121,15 +206,6 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
num_nodes: int = Field(2, ge=1)
"""Inference nodes."""
router_port: int = 8000
"""Port for the vllm-router."""
backend_port: int = 8100
"""Port for vLLM backend instances."""
router_policy: str = "consistent_hash"
"""vllm-router routing policy (e.g. ``consistent_hash``, ``round_robin``)."""
# Disaggregated prefill/decode inference. Each replica is split into separate
# prefill and decode node groups. Requires NIXL for KV transfer and a vllm-router
@@ -152,18 +228,12 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
num_decode_replicas: int = Field(1, ge=1)
"""Independent decode vLLM instances. Must evenly divide ``num_decode_nodes``."""
router_port: int = 8000
"""Port for the vllm-router on each replica."""
prefill_port: int = 8100
"""Port for prefill vLLM instances."""
decode_port: int = 8200
"""Port for decode vLLM instances."""
router_policy: str = "consistent_hash"
"""vllm-router routing policy (e.g. ``consistent_hash``, ``round_robin``)."""
prefill_env_overrides: dict[str, str] = {}
"""Extra environment variables exported only on prefill nodes."""
@@ -207,6 +277,9 @@ class InferenceConfig(BaseConfig):
parallel: ParallelConfig = ParallelConfig()
"""Multi-node and multi-GPU parallelism (TP, DP, PP)."""
log: LogConfig = LogConfig()
"""Logging configuration."""
enable_lora: bool = False
"""Enable LoRA. Forwarded as ``--enable-lora``."""
@@ -256,17 +329,20 @@ class InferenceConfig(BaseConfig):
"""Enable dual batch overlap (DBO). Forwarded as ``--enable-dbo``."""
use_deep_gemm: bool = False
"""Enable vLLM DeepGEMM FP8 kernels. Only works with per-tensor FP8 quantization (e.g. GLM-5-FP8)."""
"""Enable vLLM DeepGEMM FP8 kernels ``VLLM_USE_DEEP_GEMM=1``. Only works with block-wise FP8 quantization (e.g. GLM-5-FP8)."""
weight_broadcast: WeightBroadcastConfig = WeightBroadcastConfig()
kv_cache_offload: KVCacheOffloadConfig | None = None
"""CPU KV cache offload for inference workers. Standard inference uses vLLM's ``OffloadingConnector``. Disaggregated P/D deployments combine it with NIXL through ``MultiConnector`` in the SLURM launcher."""
"""KV cache offload for inference workers, as composable CPU/disk tiers. Discriminated on ``type``: ``native`` (vLLM ``OffloadingConnector``/``TieringOffloadingSpec``, self-contained) or ``mooncake`` (per-node Mooncake distributed store). Disaggregated P/D combines the chosen connector with NIXL through ``MultiConnector``."""
use_pd_kv_transfer: bool = False
"""Auto-set for disaggregated P/D: emit the NIXL transfer connector. Persisted into the per-node config (which drops ``deployment``) so the connector is still built per worker. Not meant to be set by hand."""
enable_return_routed_experts: bool = False
"""Return routed experts in responses. Forwarded as ``--enable-return-routed-experts``."""
enable_fp32_lm_head: bool = False
enable_fp32_lm_head: bool = True
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
vllm_extra: dict[str, Any] = {}
@@ -289,8 +365,8 @@ class InferenceConfig(BaseConfig):
@model_validator(mode="after")
def validate_multi_node_requires_slurm(self):
if self.deployment.type == "multi_node" and self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
if self.deployment.type in ("multi_node", "disaggregated") and self.slurm is None:
raise ValueError("Must use SLURM for multi-node / disaggregated deployment.")
return self
@model_validator(mode="after")
@@ -307,6 +383,7 @@ class InferenceConfig(BaseConfig):
def auto_setup_disaggregated(self):
"""Auto-configure inference for disaggregated P/D: enable EP and compute DP."""
if self.deployment.type == "disaggregated":
self.use_pd_kv_transfer = True
if "enable_expert_parallel" not in self.model_fields_set:
self.enable_expert_parallel = True
if "enable_eplb" not in self.model_fields_set:
@@ -368,6 +445,35 @@ class InferenceConfig(BaseConfig):
self.api_server_count = 1 # LoRA requires only one API server
return self
def build_kv_transfer_config(self) -> dict[str, Any] | None:
"""Build the single vLLM ``kv_transfer_config`` from the transfer + offload connectors.
Disaggregated P/D always uses NIXL for prefill→decode transfer. KV cache offload (if
configured) contributes its own connector. When both are present they are composed via
``MultiConnector``. Returns None when neither applies.
"""
connectors: list[dict[str, Any]] = []
if self.use_pd_kv_transfer:
connectors.append(
{
"kv_connector": "NixlConnector",
"kv_role": "kv_both",
"kv_connector_extra_config": {"num_threads": 1},
}
)
if self.kv_cache_offload is not None:
connectors.append(self.kv_cache_offload.to_connector_dict())
if not connectors:
return None
if len(connectors) == 1:
return connectors[0]
return {
"kv_connector": "MultiConnector",
"kv_role": "kv_both",
"kv_connector_extra_config": {"connectors": connectors},
}
def to_vllm(self) -> Namespace:
"""Convert InferenceConfig to vLLM-compatible Namespace."""
namespace = Namespace()
@@ -411,18 +517,9 @@ class InferenceConfig(BaseConfig):
# Set `logprobs_mode` to `processed_logprobs` by default
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
if self.kv_cache_offload is not None:
rsetattr(
namespace,
"kv_transfer_config",
{
"kv_connector": "OffloadingConnector",
"kv_role": "kv_both",
"kv_connector_extra_config": {
"cpu_bytes_to_use": int(self.kv_cache_offload.cpu_bytes),
},
},
)
kv_transfer_config = self.build_kv_transfer_config()
if kv_transfer_config is not None:
rsetattr(namespace, "kv_transfer_config", kv_transfer_config)
# Pass prime-rl-specific flags through vLLM's additional_config dict;
# workers read these via get_current_vllm_config().additional_config.
@@ -143,6 +143,49 @@ class EvalSamplingConfig(BaseConfig):
return data
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"),
]
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."""
@@ -210,6 +253,15 @@ class TrainEnvConfig(EnvConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
"""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()
@@ -296,6 +348,10 @@ class EvalConfig(BaseConfig):
interval: int = Field(100, ge=1)
"""Step interval at which to evaluate the model."""
skip_first_step: bool = False
"""If True, skip the startup eval that otherwise runs before any
train rollouts."""
@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."""
@@ -325,6 +381,16 @@ class EvalConfig(BaseConfig):
env.num_workers = max(1, math.ceil(max_concurrent / 256))
return self
@model_validator(mode="after")
def validate_non_empty_envs(self):
if not self.env:
raise ValueError(
"EvalConfig must define at least one env. Either drop the "
"[orchestrator.eval] block entirely (to disable eval) or "
"add a [[orchestrator.eval.env]] block."
)
return self
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [env.resolved_name for env in self.env]
@@ -335,17 +401,6 @@ class EvalConfig(BaseConfig):
)
return self
eval_base_model: bool = True
"""Evaluate the base model we are training on."""
skip_eval_on_resume: bool = Field(
True, validation_alias=AliasChoices("skip_eval_on_resume", "skip_eval_on_restart")
)
"""When resuming the orchestrator from a checkpoint, skip the (potentially redundant) online eval that would otherwise run immediately at the resumed step."""
cancel_inflight_rollouts_on_eval: bool = False
"""Cancel in-flight training rollouts before starting online evals. Avoids congestion (no training + eval rollouts at the same time) at the cost of slower training steps as the pipeline has to refill after each eval."""
class CheckpointConfig(BaseConfig):
interval: int | None = Field(None, ge=1)
@@ -366,81 +421,6 @@ class CheckpointConfig(BaseConfig):
skip_progress: bool = False
"""Skip loading the progress from checkpoint."""
skip_buffer: bool = False
"""Skip loading the buffer from checkpoint."""
class BufferConfig(BaseConfig):
seed: int | None = None
"""Random seed for the buffer. When set, sampling from the buffer is deterministic."""
easy_threshold: float | None = None
"""Average-reward threshold above which a problem is classified ``easy``."""
hard_threshold: float | None = None
"""Average-reward threshold below which a problem is classified ``hard``."""
easy_fraction: float = Field(0.0, ge=0, le=1)
"""Fraction of easy problems to convert to ``normal`` when resuming or starting training. Only problems with difficulty ``normal`` are sampled."""
hard_fraction: float = Field(0.0, ge=0, le=1)
"""Fraction of hard problems to convert to ``normal`` when resuming or starting training. Only problems with difficulty ``normal`` are sampled."""
online_difficulty_filtering: bool = False
"""Filter rollouts based on difficulty. When True, rollouts with average reward 0.0 or 1.0 are not added to the buffer."""
hash_keys: list[str] = Field(["env_name", "prompt"], min_length=1)
"""Keys used to compute example hashes. Used to match examples from buffer checkpoints and determine buffer resume behavior."""
@model_validator(mode="after")
def validate_thresholds(self):
if self.easy_threshold is not None and self.hard_threshold is not None:
assert self.easy_threshold > self.hard_threshold, "easy_threshold must be greater than hard_threshold."
return self
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):
@@ -542,7 +522,7 @@ class OrchestratorConfig(BaseConfig):
"""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."""
opts into MITO (``openai_chat_completions``)."""
pool_size: int | None = Field(None, ge=1)
"""Number of renderer slots shared across concurrent rollouts. Bump
@@ -569,12 +549,25 @@ class OrchestratorConfig(BaseConfig):
eval: EvalConfig | None = None
"""Evaluation configuration."""
buffer: BufferConfig = BufferConfig()
advantage: AdvantageConfig | None = DefaultAdvantageConfig()
filters: list[FilterConfig] = [GibberishFilterConfig(), RepetitionFilterConfig(), ZeroAdvantageFilterConfig()]
"""Rollout filters. Each filter can ``monitor`` (default) or ``enforce`` (skip rollouts)."""
pre_batch_filters: list[FilterConfig] = [
GibberishFilterConfig(enforce=False),
RepetitionFilterConfig(enforce=False),
ZeroAdvantageFilterConfig(enforce=False),
]
"""Filters applied *before* a rollout enters the training batch buffer.
All three filter types are registered in monitor mode by default; flip ``enforce=true`` per type
to drop matching rollouts before they consume a slot in the batch (e.g. a zero-advantage group
never makes it into a training batch)."""
post_batch_filters: list[FilterConfig] = [
GibberishFilterConfig(),
RepetitionFilterConfig(),
ZeroAdvantageFilterConfig(),
]
"""Filters applied *after* a batch has been assembled. Each filter annotates each rollout;
rollouts flagged by an enforcing filter are still recorded but not shipped to the trainer."""
log: LogConfig = LogConfig()
@@ -634,9 +627,6 @@ class OrchestratorConfig(BaseConfig):
bench: bool = False
"""Benchmark mode. Sets ``max_steps`` to 5 and disables W&B."""
seed: int | None = 42
"""Random seed for the orchestrator."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
@@ -759,18 +749,20 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def validate_unique_filter_types(self):
types = [f.type for f in self.filters]
if len(types) != len(set(types)):
raise ValueError(f"Duplicate filter types: {types}. Each filter type may only appear once.")
for slot_name in ("pre_batch_filters", "post_batch_filters"):
types = [f.type for f in getattr(self, slot_name)]
if len(types) != len(set(types)):
raise ValueError(
f"Duplicate filter types in {slot_name}: {types}. Each filter type may only appear once per slot."
)
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":
"""Teacher-backed SFT rolls out via the teacher's plain chat-completions
endpoint; the renderer client doesn't apply. When no teacher is
configured, SFT uses the student rollout path and keeps the renderer."""
if self.training_mode == "sft" and self.teacher is not None:
self.renderer = None
return self
@@ -780,8 +772,8 @@ class OrchestratorConfig(BaseConfig):
has_teacher = self.teacher is not None
if self.training_mode == "rl" and has_teacher:
raise ValueError("orchestrator.teacher must not be set when training_mode = 'rl'.")
if self.training_mode in ("opd", "sft") and not has_teacher:
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
if self.training_mode == "opd" and not has_teacher:
raise ValueError("orchestrator.teacher must be configured when training_mode = 'opd'.")
return self
@model_validator(mode="after")
@@ -883,6 +875,16 @@ class OrchestratorConfig(BaseConfig):
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.group_size:
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
# Propagate the top-level ``group_size`` into each train env that didn't set its own.
for env_cfg in self.train.env:
if "group_size" not in env_cfg.model_fields_set:
env_cfg.group_size = self.group_size
# Propagate the top-level ``advantage`` into each train env that didn't set its own.
for env_cfg in self.train.env:
if "advantage" not in env_cfg.model_fields_set:
env_cfg.advantage = self.advantage
# Resolve train env num_workers from max_inflight_rollouts
for env_cfg in self.train.env:
if env_cfg.num_workers == "auto":
@@ -51,10 +51,10 @@ class RLExperimentalConfig(BaseConfig):
class SharedLogConfig(BaseConfig):
level: str | None = None
"""Log level for trainer and orchestrator. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
"""Log level for trainer, orchestrator, and inference. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
json_logging: bool = False
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.)."""
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.). Propagated to trainer, orchestrator, and inference."""
class SharedWandbConfig(BaseConfig):
@@ -448,6 +448,20 @@ class RLConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_mooncake_offload_requires_slurm(self):
if (
self.slurm is None
and self.inference is not None
and self.inference.kv_cache_offload is not None
and self.inference.kv_cache_offload.type == "mooncake"
):
raise ValueError(
"Mooncake KV offload requires SLURM — the per-node store is launched by the sbatch "
"template. Use inference.kv_cache_offload.type='native' for local runs."
)
return self
@model_validator(mode="after")
def auto_setup_deployment(self):
if self.deployment.type == "single_node": # single-node
@@ -534,11 +548,14 @@ class RLConfig(BaseConfig):
self.inference.api_server_count = dp_per_node
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
# Compute inference_world_size from actual worker count per server:
# each api_server runs tp workers that participate in collective_rpc.
api_server_count = self.inference.api_server_count if self.inference else 1
tp = self.inference.parallel.tp if self.inference else 1
total_infer_workers = self.deployment.total_infer_nodes * api_server_count * tp
# Every allocated inference GPU is a NCCL rank in the weight broadcast.
# The external-LB launcher starts dp_per_node (= gpus_per_node / tp)
# TP-sharded servers per node, i.e. gpus_per_node workers per node, so use
# the GPU count directly. Deriving it from api_server_count double-counts:
# api_server_count can resolve to the *global* DP size, making the node
# factor count twice and NCCL wait for ranks that never connect. Matches
# the disaggregated path below.
total_infer_workers = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
assert self.trainer.weight_broadcast.type == "nccl"
self.trainer.weight_broadcast.host = "0.0.0.0"
self.trainer.weight_broadcast.inference_world_size = total_infer_workers
@@ -566,7 +583,13 @@ class RLConfig(BaseConfig):
total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
if "inference_metrics_roles" not in self.orchestrator.model_fields_set:
role_order = ["prefill"] * infer_deploy.num_prefill_nodes + ["decode"] * infer_deploy.num_decode_nodes
# External-LB: one admin client per DP rank, so roles expand per rank
# (stride = dp_local = gpus_per_node / tp). ADMIN_URLS lists all prefill
# ranks, then all decode ranks, per replica — match that order.
stride = self.deployment.gpus_per_node // self.inference.parallel.tp
role_order = ["prefill"] * (infer_deploy.num_prefill_nodes * stride) + ["decode"] * (
infer_deploy.num_decode_nodes * stride
)
self.orchestrator.inference_metrics_roles = role_order * self.deployment.num_infer_replicas
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
assert self.trainer.weight_broadcast.type == "nccl"
@@ -158,6 +158,9 @@ class LogConfig(BaseConfig):
log_data: bool = False
"""Log the first data sample at startup."""
interval: float = Field(10.0, gt=0)
"""Interval (seconds) for periodic logs across components."""
class TrainerLogConfig(LogConfig):
ranks_filter: list[int] = [0]
@@ -84,8 +84,13 @@ def propagate_shared_fields(data: Any) -> Any:
)
# [log]
propagate("log.level", "trainer.log.level", "orchestrator.log.level")
propagate("log.json_logging", "trainer.log.json_logging", "orchestrator.log.json_logging")
propagate("log.level", "trainer.log.level", "orchestrator.log.level", "inference.log.level")
propagate(
"log.json_logging",
"trainer.log.json_logging",
"orchestrator.log.json_logging",
"inference.log.json_logging",
)
# [ckpt] leaves. (Bare empty ``[ckpt]`` block enablement is at the end.)
# ``orchestrator.ckpt`` has no ``output_dir`` field — trainer-only.
@@ -127,6 +132,12 @@ def propagate_shared_fields(data: Any) -> Any:
propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps")
propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len")
# [slurm] → inference: a multi-node RL run drives its inference deployment under
# the same SLURM allocation, so the nested inference inherits [slurm]. This is
# what lets the nested InferenceConfig's multi-node / disaggregated SLURM check
# pass (the per-rank inference.toml drops slurm, so each rank still runs locally).
propagate("slurm", "inference.slurm")
# output_dir: orchestrator gets a ``/run_default`` subdir so trainer +
# orchestrator nest under the same experiment root without colliding.
# Conflicts are reported against the *transformed* sub-config value, not
+49 -77
View File
@@ -6,6 +6,7 @@ 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",
@@ -17,8 +18,9 @@ dependencies = [
"torchvision",
"torchaudio",
"torchdata>=0.11.0",
"transformers",
"vllm>=0.21.0",
"transformers==5.6.2",
"vllm>=0.22.0",
"mooncake-transfer-engine>=0.3.10.post2",
"wandb>=0.26.1",
"ring-flash-attn>=0.1.8",
"prime>=0.6.4",
@@ -26,6 +28,7 @@ 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",
@@ -76,7 +79,6 @@ envs = [
"math-python",
"math500",
"mini-swe-agent-plus",
"mini-swe-agent-plus-rlm",
"mmlu-pro",
"opencode-cp",
"opencode-deepdive",
@@ -84,10 +86,12 @@ envs = [
"opencode-science",
"opencode-swe",
"reverse-text",
"rlm-swe",
"science-env",
"simpleqa-verified",
"tau2-bench",
"wiki-search",
"wordle",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64'",
@@ -126,43 +130,6 @@ dev = [
"ruff>=0.12.1",
]
[tool.uv.workspace]
members = [
"packages/prime-rl-configs",
"deps/pydantic-config",
"deps/verifiers",
"deps/renderers",
"deps/verifiers/environments/alphabet_sort",
"deps/verifiers/environments/math_python",
"deps/verifiers/environments/reverse_text",
"deps/verifiers/environments/wiki_search",
"deps/research-environments/environments/aime2024",
"deps/research-environments/environments/aime2025",
"deps/research-environments/environments/code_env",
"deps/research-environments/environments/color_codeword",
"deps/research-environments/environments/deepdive",
"deps/research-environments/environments/general_agent",
"deps/research-environments/environments/gpqa",
"deps/research-environments/environments/hle",
"deps/research-environments/environments/ifeval",
"deps/research-environments/environments/livecodebench",
"deps/research-environments/environments/logic_env",
"deps/research-environments/environments/math500",
"deps/research-environments/environments/math_env",
"deps/research-environments/environments/mini_swe_agent_plus",
"deps/research-environments/environments/mini_swe_agent_plus_rlm",
"deps/research-environments/environments/mmlu_pro",
"deps/research-environments/environments/opencode_cp",
"deps/research-environments/environments/opencode_deepdive",
"deps/research-environments/environments/opencode_math",
"deps/research-environments/environments/opencode_science",
"deps/research-environments/environments/opencode_swe",
"deps/research-environments/environments/science_env",
"deps/research-environments/environments/simpleqa_verified",
"deps/research-environments/environments/tau2_bench",
]
[tool.uv]
# Enforce a uv version that supports the friendly-duration form
# (`"7 days"`) in the static pyproject parser. Older uvs silently parse
@@ -181,9 +148,10 @@ environments = [
override-dependencies = [
"nvidia-cudnn-cu12>=9.15",
"nvidia-cutlass-dsl>=4.4.1",
"transformers>=5.1.0.dev0",
"transformers==5.6.2",
"torch>=2.9.0",
"openenv-core",
"verifiers[packages]>=0.1.15.dev150",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -218,6 +186,8 @@ 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
@@ -227,49 +197,51 @@ deep-gemm = false
nixl-cu12 = false
[tool.uv.sources]
prime-rl-configs = { workspace = true }
verifiers = { workspace = true }
renderers = { workspace = true }
aime2024 = { workspace = true }
aime2025 = { workspace = true }
alphabet-sort = { workspace = true }
code-env = { workspace = true }
color-codeword = { workspace = true }
deepdive = { workspace = true }
general-agent = { workspace = true }
gpqa = { workspace = true }
hle = { workspace = true }
ifeval = { workspace = true }
livecodebench = { workspace = true }
logic-env = { workspace = true }
math-env = { workspace = true }
math-python = { workspace = true }
math500 = { workspace = true }
mini-swe-agent-plus = { workspace = true }
mini-swe-agent-plus-rlm = { workspace = true }
mmlu-pro = { workspace = true }
opencode-cp = { workspace = true }
opencode-deepdive = { workspace = true }
opencode-math = { workspace = true }
opencode-science = { workspace = true }
opencode-swe = { workspace = true }
reverse-text = { workspace = true }
science-env = { workspace = true }
simpleqa-verified = { workspace = true }
tau2-bench = { workspace = true }
wiki-search = { workspace = true }
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
aime2024 = { path = "deps/research-environments/environments/aime2024", editable = true }
aime2025 = { path = "deps/research-environments/environments/aime2025", editable = true }
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
code-env = { path = "deps/research-environments/environments/code_env", editable = true }
color-codeword = { path = "deps/research-environments/environments/color_codeword", editable = true }
deepdive = { path = "deps/research-environments/environments/deepdive", editable = true }
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
gpqa = { path = "deps/research-environments/environments/gpqa", editable = true }
harnesses = { path = "deps/verifiers/packages/harnesses", editable = true }
hle = { path = "deps/research-environments/environments/hle", editable = true }
ifeval = { path = "deps/research-environments/environments/ifeval", editable = true }
livecodebench = { path = "deps/research-environments/environments/livecodebench", editable = true }
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
math500 = { path = "deps/research-environments/environments/math500", editable = true }
mini-swe-agent-plus = { path = "deps/research-environments/environments/mini_swe_agent_plus", editable = true }
mmlu-pro = { path = "deps/research-environments/environments/mmlu_pro", editable = true }
opencode-cp = { path = "deps/research-environments/environments/opencode_cp", editable = true }
opencode-deepdive = { path = "deps/research-environments/environments/opencode_deepdive", editable = true }
opencode-math = { path = "deps/research-environments/environments/opencode_math", editable = true }
opencode-science = { path = "deps/research-environments/environments/opencode_science", editable = true }
opencode-swe = { path = "deps/research-environments/environments/opencode_swe", editable = true }
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
tasksets = { path = "deps/verifiers/packages/tasksets", editable = true }
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "c1c3424" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
prime-pydantic-config = { workspace = true }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
vllm = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/vllm-0.21.0+cu129.r42434.pr39568.a106aa6-cp38-abi3-manylinux_2_34_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.22.0/vllm-0.22.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.22.0/vllm-0.22.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
@@ -300,7 +272,7 @@ select = ["F", "I"]
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
[tool.ruff.lint.isort]
# `prime_rl` is split across two workspace wheels (prime-rl + prime-rl-configs).
# `prime_rl` is split across two editable wheels (prime-rl + prime-rl-configs).
# Without this, ruff classifies prime_rl.configs.* as third-party because it
# doesn't live under src/.
known-first-party = ["prime_rl"]
+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"
+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!"
}
-1
View File
@@ -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
+1 -3
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
+6
View File
@@ -34,6 +34,12 @@ uv run rl @ examples/reverse_text/rl.toml --dry-run
- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`)
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
- SLURM: single- and multi-node
- Environment packages: before launching a config with a non-core verifier env id,
verify the package imports under `uv run` (for example
`uv run python -c "import importlib.util; print(importlib.util.find_spec('rlm_swe'))"`).
If a local env exists under `deps/research-environments/environments/` but does not
import, add it to the root `pyproject.toml` env extra, workspace members, and
`[tool.uv.sources]`, then run `uv sync --all-extras`.
## `sft` — SFT training
+16 -8
View File
@@ -36,6 +36,9 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
is_disaggregated = config.deployment.type == "disaggregated"
dp_per_node = config.deployment.gpus_per_node // config.parallel.tp
offload = config.kv_cache_offload
is_mooncake = offload is not None and offload.type == "mooncake"
template_vars = dict(
**config.slurm.template_vars,
config_path=config_path,
@@ -45,7 +48,11 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
num_nodes=getattr(config.deployment, "num_nodes", 1),
port=config.server.port,
disaggregated=is_disaggregated,
kv_offload=config.kv_cache_offload is not None,
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,
kv_offload_disk_path=str(offload.disk.path) if (is_mooncake and offload.disk is not None) else "",
kv_offload_device_name=offload.device_name if is_mooncake else "",
)
is_multi_node = config.deployment.type == "multi_node"
@@ -58,19 +65,20 @@ 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_port=config.deployment.router.port,
router_policy=config.deployment.router.policy,
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,
kv_offload_cpu_bytes=int(config.kv_cache_offload.cpu_bytes) if config.kv_cache_offload else 0,
)
elif is_multi_node:
template_vars.update(
router_port=config.deployment.router_port,
router_port=config.deployment.router.port,
backend_port=config.deployment.backend_port,
router_policy=config.deployment.router_policy,
router_policy=config.deployment.router.policy,
data_parallel_rpc_port=config.data_parallel_rpc_port,
enable_expert_parallel=config.enable_expert_parallel,
)
script = template.render(**template_vars)
@@ -83,7 +91,7 @@ def inference_slurm(config: InferenceConfig):
"""Run inference via SLURM."""
assert config.slurm is not None
logger = setup_logger("info")
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
config_dir = get_config_dir(config.output_dir)
exclude = (
@@ -119,7 +127,7 @@ def inference_local(config: InferenceConfig):
"""Run inference locally."""
from prime_rl.inference.server import setup_vllm_env
logger = setup_logger("info")
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
if config.dry_run:
logger.success("Dry run complete. To start inference locally, remove --dry-run from your command.")
+2 -2
View File
@@ -19,9 +19,9 @@ from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Orchestrator")
config = cli(OrchestratorConfig)
from prime_rl.orchestrator.orchestrator import orchestrate
from prime_rl.orchestrator.orchestrator import run_orchestrator
asyncio.run(orchestrate(config))
asyncio.run(run_orchestrator(config))
if __name__ == "__main__":
+17 -15
View File
@@ -194,12 +194,7 @@ def rl_local(config: RLConfig):
"orchestrator starts, otherwise rollouts will hang."
)
# Start orchestrator process
orchestrator_cmd = [
"orchestrator",
"@",
(config_dir / ORCHESTRATOR_TOML).as_posix(),
]
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_TOML).as_posix()]
logger.info("Starting orchestrator process")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
with open(log_dir / "orchestrator.log", "w") as log_file:
@@ -313,7 +308,7 @@ def rl_local(config: RLConfig):
cleanup_processes(processes)
sys.exit(1)
logger.success("RL training finished!")
logger.success("Training finished!")
# Cleanup threads and processes
cleanup_threads(monitor_threads)
@@ -341,6 +336,16 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
template = env.get_template(config.slurm.template_path.name)
offload = config.inference.kv_cache_offload if config.inference is not None else None
is_mooncake = offload is not None and offload.type == "mooncake"
mooncake_vars = dict(
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,
kv_offload_disk_path=str(offload.disk.path) if (is_mooncake and offload.disk is not None) else "",
kv_offload_device_name=offload.device_name if is_mooncake else "",
)
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
@@ -366,7 +371,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_port=infer_deploy.router.port,
prefill_port=infer_deploy.prefill_port,
decode_port=infer_deploy.decode_port,
inference_tp=config.inference.parallel.tp,
@@ -375,10 +380,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
prefill_env_overrides=infer_deploy.prefill_env_overrides,
decode_env_overrides=infer_deploy.decode_env_overrides,
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
kv_offload=config.inference.kv_cache_offload is not None,
kv_offload_cpu_bytes=int(config.inference.kv_cache_offload.cpu_bytes)
if config.inference.kv_cache_offload
else 0,
**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)),
)
@@ -394,13 +396,13 @@ 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=getattr(config.inference.deployment, "router_port", 8000) if config.inference else 8000,
backend_port=getattr(config.inference.deployment, "backend_port", 8100) if config.inference else 8100,
router_port=config.inference.deployment.router.port if config.inference else 8000,
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,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
dp_per_node=(config.deployment.gpus_per_node // config.inference.parallel.tp) if config.inference else 1,
kv_offload=config.inference is not None and config.inference.kv_cache_offload is not None,
**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)),
)
+88
View File
@@ -0,0 +1,88 @@
"""Stdlib `logging`-based JSON formatter and dictConfig for vLLM.
Trainer and orchestrator emit JSON via loguru
(`prime_rl.utils.logger.json_sink`). vLLM uses Python's stdlib
`logging` and spawns workers via `multiprocessing.spawn`, so we can't
share the loguru sink directly. We emit the same flat shape from a
stdlib `Formatter` and drive it via a dictConfig file pointed to by
`VLLM_LOGGING_CONFIG_PATH` — env vars cross the spawn boundary, so
worker processes inherit the same logging config.
"""
import datetime
import json
import logging
import tempfile
import traceback
from pathlib import Path
from typing import Any
class JsonFormatter(logging.Formatter):
"""Emit one JSON object per record matching `build_log_entry` in
`prime_rl.utils.logger` so the platform's JsonLogsViewer renders
inference rows identically to trainer / orchestrator rows."""
def format(self, record: logging.LogRecord) -> str:
entry: dict[str, Any] = {
"timestamp": datetime.datetime.fromtimestamp(record.created, tz=datetime.timezone.utc).isoformat(),
"level": record.levelname,
"message": record.getMessage(),
"module": record.module,
"function": record.funcName,
"line": record.lineno,
}
if record.exc_info:
entry["exception"] = "".join(traceback.format_exception(*record.exc_info))
return json.dumps(entry, default=str)
# Loguru-only level names that stdlib `logging` doesn't recognize.
# Mapped to the nearest stdlib level so `dictConfig` accepts them.
_LOGURU_TO_STDLIB = {"TRACE": "DEBUG", "SUCCESS": "INFO"}
def build_dict_config(level: str = "info") -> dict[str, Any]:
"""`logging.config.dictConfig` payload that routes vLLM, uvicorn,
fastapi, and the root logger through `JsonFormatter` to stdout.
Used inline for the parent process and serialized to disk for vLLM
workers (via `VLLM_LOGGING_CONFIG_PATH`).
"""
upper = _LOGURU_TO_STDLIB.get(level.upper(), level.upper())
handler = {
"class": "logging.StreamHandler",
"formatter": "prime_rl_json",
"level": upper,
"stream": "ext://sys.stdout",
}
# Each named logger is configured explicitly: vLLM, uvicorn, and
# transformers all set propagate=False on their own loggers, so a
# root-only setup wouldn't reach them.
named = ("vllm", "uvicorn", "uvicorn.error", "uvicorn.access", "fastapi", "transformers")
return {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"prime_rl_json": {
"()": "prime_rl.inference.json_logging.JsonFormatter",
},
},
"handlers": {"stdout_json": handler},
"loggers": {
"": {"handlers": ["stdout_json"], "level": upper},
**{name: {"handlers": ["stdout_json"], "level": upper, "propagate": False} for name in named},
},
}
def write_logging_config(level: str = "info") -> Path:
"""Persist a dictConfig JSON to a temp path. Caller sets the path on
`VLLM_LOGGING_CONFIG_PATH` so vLLM (and its spawned workers) load
the same config at import time."""
config = build_dict_config(level)
fd, path_str = tempfile.mkstemp(prefix="prime_rl_logging_", suffix=".json")
path = Path(path_str)
with open(fd, "w", encoding="utf-8") as f:
json.dump(config, f)
return path
-115
View File
@@ -18,8 +18,6 @@ def transformers_v5_compat():
_patch_qwen35_lora()
_patch_lora_key_prefix()
monkey_patch_deep_gemm_silu_mul_quant_int64()
monkey_patch_dp_engine_core_pause_resume_deadlock()
monkey_patch_vllm_layerwise_reload_alias_buffers()
monkey_patch_vllm_padded_input_scrub()
monkey_patch_return_routed_experts_with_nixl_connector()
@@ -68,38 +66,6 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
def monkey_patch_vllm_layerwise_reload_alias_buffers():
# vLLM's layerwise reload materializes each buffer as an independent tensor
# and then copies it back into the original kernel storage. When a buffer
# aliases a parameter (e.g. NemotronH Mamba's mixer.conv_weights, a view of
# mixer.conv1d.weight), the buffer copy stamps garbage into the parameter's
# storage *after* the parameter has been correctly reloaded. Skip the copy
# for any buffer that shares storage with a parameter; _place_kernel_tensors
# re-registers the original view, which trivially reflects the parameter.
# Remove this patch once https://github.com/vllm-project/vllm/pull/42481 is
# included in the vLLM release we pin/use.
from vllm.logger import init_logger
from vllm.model_executor.model_loader.reload import layerwise as reload_layerwise
logger = init_logger(__name__)
def _copy_and_restore_kernel_tensors(layer: torch.nn.Module, info: reload_layerwise.LayerReloadingInfo):
assert info.kernel_tensors is not None
parameters, buffers = info.kernel_tensors
param_storage_ptrs = {p.untyped_storage().data_ptr() for p in layer.parameters(recurse=True)}
for name, param in parameters.items():
param.data.copy_(getattr(layer, name))
for name, buffer in buffers.items():
if buffer.untyped_storage().data_ptr() in param_storage_ptrs:
continue
buffer.data.copy_(getattr(layer, name))
reload_layerwise._place_kernel_tensors(layer, info)
reload_layerwise._copy_and_restore_kernel_tensors = _copy_and_restore_kernel_tensors
logger.warning("Enabled vLLM layerwise reload alias-buffer patch.")
@triton.jit
def _silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel(
y_ptr,
@@ -782,87 +748,6 @@ def monkey_patch_harmony_stop_token_propagation():
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
def monkey_patch_dp_engine_core_pause_resume_deadlock():
"""Fix DP pause/resume deadlocks around weight updates.
Bug 1 (job 3756): while paused, START_DP_WAVE can wake idle ranks into the
DP loop. Those ranks then run dummy batches and hit DP collectives while
other ranks are still in NCCL weight transfer.
Bug 2 (jobs 3769/3771): resume ties the DP running state to local
unfinished requests, but the DP wave state is global. Ranks with no local
work still need to re-enter the loop so they can participate in the same
DP collectives as ranks that are resuming remote-KV or decode work.
Fix:
- ignore START_DP_WAVE wakeups while paused
- on resume, wake every DP rank and force an immediate global unfinished
sync instead of waiting for the normal 32-step cadence
This also bypasses vLLM's two-phase DP pause implementation
(https://github.com/vllm-project/vllm/pull/39366), which makes resume
reject states that our weight-update flow can validly hit.
"""
from vllm.config import ParallelConfig
from vllm.v1.core.sched.interface import PauseState
from vllm.v1.engine import EngineCoreOutputs, EngineCoreRequestType
from vllm.v1.engine.core import DPEngineCoreProc, EngineCore, EngineCoreProc
from vllm.v1.request import Request
_base_add_request = EngineCore.add_request
_base_handle_client_request = EngineCoreProc._handle_client_request
_base_pause_complete = EngineCoreProc._pause_complete
_base_resume_scheduler = EngineCoreProc.resume_scheduler
def _patched_add_request(self, request: Request, request_wave: int = 0):
_base_add_request(self, request, request_wave)
if self.has_coordinator and request_wave != self.current_wave:
if request_wave > self.current_wave:
self.current_wave = request_wave
elif not self.engines_running and self.scheduler.pause_state == PauseState.UNPAUSED:
self.engines_running = True
self.output_queue.put_nowait((-1, EngineCoreOutputs(start_wave=self.current_wave)))
def _patched_handle_client_request(self, request_type, request):
if request_type == EngineCoreRequestType.START_DP_WAVE:
new_wave, exclude_eng_index = request
if exclude_eng_index != self.engine_index and new_wave >= self.current_wave:
self.current_wave = new_wave
if not self.engines_running and self.scheduler.pause_state == PauseState.UNPAUSED:
self.engines_running = True
else:
_base_handle_client_request(self, request_type, request)
def _patched_pause_complete(self) -> bool:
self.pending_pause = False
self.ignore_start_dp_wave = False
return _base_pause_complete(self)
def _patched_resume_scheduler(self):
was_paused = self.scheduler.pause_state != PauseState.UNPAUSED
self.pending_pause = False
self.ignore_start_dp_wave = False
_base_resume_scheduler(self)
if was_paused:
self.engines_running = True
self._force_dp_running_state_sync = True
def _patched_has_global_unfinished_reqs(self, local_unfinished: bool) -> bool:
self.step_counter += 1
if getattr(self, "_force_dp_running_state_sync", False):
self._force_dp_running_state_sync = False
return ParallelConfig.has_unfinished_dp(self.dp_group, local_unfinished)
if self.step_counter % 32 != 0:
return True
return ParallelConfig.has_unfinished_dp(self.dp_group, local_unfinished)
DPEngineCoreProc.add_request = _patched_add_request
DPEngineCoreProc._handle_client_request = _patched_handle_client_request
DPEngineCoreProc._pause_complete = _patched_pause_complete
DPEngineCoreProc.resume_scheduler = _patched_resume_scheduler
DPEngineCoreProc._has_global_unfinished_reqs = _patched_has_global_unfinished_reqs
def monkey_patch_no_moe_lora():
"""This disables LoRA for MoE layers and makes them pick better kernels.
+16
View File
@@ -1,3 +1,4 @@
import logging.config
import os
from prime_rl.configs.inference import InferenceConfig
@@ -17,6 +18,21 @@ def setup_vllm_env(config: InferenceConfig):
if config.enable_lora:
os.environ["VLLM_ALLOW_RUNTIME_LORA_UPDATING"] = "True"
if config.log.json_logging:
# Route vLLM's stdlib loggers through a JSON formatter matching
# trainer / orchestrator. The env var (not in-process dictConfig)
# is what reaches vLLM's spawned workers.
from prime_rl.inference.json_logging import build_dict_config, write_logging_config
config_path = write_logging_config(config.log.level)
# vLLM raises if VLLM_LOGGING_CONFIG_PATH is set while
# VLLM_CONFIGURE_LOGGING=0 (its supported way to disable logger
# setup). Force it on — opting into JSON logging is an explicit
# request to configure vLLM's logger.
os.environ["VLLM_CONFIGURE_LOGGING"] = "1"
os.environ["VLLM_LOGGING_CONFIG_PATH"] = str(config_path)
logging.config.dictConfig(build_dict_config(config.log.level))
def main():
config = cli(InferenceConfig)
+43 -1
View File
@@ -24,6 +24,37 @@ else:
logger = init_logger("vllm.inference.vllm.worker_nccl")
# NemotronH mixer.D is dropped by vLLM 0.22's layerwise online-reload path (left uninitialized).
_RELOAD_CORRUPTED_SUFFIXES = (".mixer.D",)
def _restore_reload_corrupted_params(model: Module, received: dict[str, torch.Tensor]) -> None:
"""Work around a vLLM 0.22 layerwise-reload bug for NemotronH.
The online reload drops the weight load for every Mamba layer's ``mixer.D`` (the SSD skip
connection), leaving it as uninitialized ``empty_strided`` memory -- it reads back as garbage
(NaN/inf) and the logits go NaN after a weight update. The received broadcast value is correct,
so restore D from it via the param's own ``weight_loader``. Remove once the upstream bug is fixed.
"""
def _layer_key(name: str) -> str:
index = name.find("layers.")
return name[index:] if index >= 0 else name
received_by_key = {_layer_key(name): tensor for name, tensor in received.items()}
for name, param in model.named_parameters():
if not name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
continue
tensor = received_by_key.get(_layer_key(name))
if tensor is None:
continue
tensor = tensor.to(device=param.device)
weight_loader = getattr(param, "weight_loader", None)
if weight_loader is not None:
weight_loader(param, tensor)
elif tensor.shape == param.shape:
param.data.copy_(tensor.to(param.dtype))
def receive_integer(communicator: PyNcclCommunicator) -> int:
"""Receive an integer from the trainer master rank using NCCL communicator."""
@@ -148,9 +179,20 @@ class NCCLWeightUpdateWorker(Worker):
update_mla_absorbed_weights(model)
return
# vLLM 0.22's layerwise reload drops NemotronH mixer.D's weight load (see
# _restore_reload_corrupted_params). Capture the correct received value to restore after.
received_reload_fix: dict[str, torch.Tensor] = {}
def _capture_reload_fix(weights):
for name, tensor in weights:
if name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
received_reload_fix[name] = tensor.detach().to("cpu", copy=True)
yield name, tensor
load_weights_checkpoint_layerwise(
model,
state_iter,
_capture_reload_fix(state_iter),
self.model_runner.model_config,
self.vllm_config,
)
_restore_reload_corrupted_params(model, received_reload_fix)
+22 -26
View File
@@ -1,12 +1,16 @@
from collections import defaultdict
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable
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
from prime_rl.configs.orchestrator import (
AdvantageConfig,
CustomAdvantageConfig,
@@ -14,7 +18,7 @@ from prime_rl.configs.orchestrator import (
TokensLengthPenaltyConfig,
TurnsLengthPenaltyConfig,
)
from prime_rl.orchestrator.vf_utils import get_model_completion_len, get_num_turns, get_tool_response_len
from prime_rl.orchestrator.utils import get_model_completion_len, get_tool_response_len
from prime_rl.utils.utils import import_object
@@ -40,7 +44,7 @@ Expected signature:
...
The function receives a single group and returns a list of advantages with one
entry per rollout. `compute_advantages` calls it once per group.
entry per rollout. `assign_advantages` calls it on one already-grouped cohort.
"""
@@ -64,7 +68,7 @@ def default_advantage_fn(
)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
costs = torch.tensor([get_num_turns(r) for r in inputs.rollouts], dtype=rewards.dtype)
costs = torch.tensor([len(r["trajectory"]) for r in inputs.rollouts], dtype=rewards.dtype)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
return AdvantageOutputs(advantages=(rewards - rewards.mean()).tolist())
@@ -124,28 +128,20 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
return advantage_fn
def compute_advantages(
rollouts: list[vf.RolloutOutput],
advantage_config: AdvantageConfig | None,
def assign_advantages(
rollouts: list["TrainRollout"], # noqa: F821 (forward ref)
advantage_fn: AdvantageFn | None,
) -> None:
"""Computes advantages from rollouts, grouped by (env_name, example_id), and
stores them in-place on the rollouts.
`advantage_fn` is called once per group, so groups may have varying sizes
(partial-group training drops failed rollouts rather than rescheduling them).
"""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``.
"""
if not advantage_config:
if advantage_fn is None:
for rollout in rollouts:
rollout["advantage"] = rollout["reward"]
rollout.advantage = rollout.reward
return
advantage_fn = setup_advantage_fn(advantage_config)
groups_by_example: dict[tuple[str, int], list[vf.RolloutOutput]] = defaultdict(list)
for rollout in rollouts:
groups_by_example[(rollout["env_name"], rollout["example_id"])].append(rollout)
for group in groups_by_example.values():
result = advantage_fn(AdvantageInputs(rollouts=group))
for rollout, advantage in zip(group, result.advantages):
rollout["advantage"] = advantage
result = advantage_fn(AdvantageInputs(rollouts=[r.raw for r in rollouts]))
for rollout, advantage in zip(rollouts, result.advantages):
rollout.advantage = advantage
-323
View File
@@ -1,323 +0,0 @@
from __future__ import annotations
import hashlib
import json
import random
from collections import defaultdict
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING, cast
import verifiers as vf
from verifiers.utils.save_utils import make_serializable
from prime_rl.configs.orchestrator import BufferConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import format_num, mean, mean_normalize
if TYPE_CHECKING:
from prime_rl.orchestrator.envs import TrainEnv, TrainEnvs
POOLS = ["easy", "normal", "hard"]
class _EnvBuffer:
"""Manages examples and difficulty pools for a single env."""
def __init__(self, env: TrainEnv, config: BufferConfig):
self.env_name = env.name
self.config = config
dataset = env.get_dataset(seed=config.seed)
if "example_id" not in dataset.column_names:
dataset = dataset.map(lambda ex, idx: {**ex, "example_id": idx}, with_indices=True)
assert len(dataset) > 0, f"Dataset for {env.name} must contain at least one example."
assert "example_id" in dataset.column_names, f"Dataset for {env.name} must contain an `example_id` column."
assert "prompt" in dataset.column_names, f"Dataset for {env.name} must contain a `prompt` column."
self.examples: dict[int, dict] = {}
for example in map(partial(cast, dict), dataset):
example["env_name"] = env.name
self.examples[example["example_id"]] = example
self.easy_examples: list[dict] = []
self.hard_examples: list[dict] = []
self.reset_step_metrics()
@property
def num_normal(self) -> int:
return len(self.examples)
@property
def num_total(self) -> int:
return self.num_normal + len(self.easy_examples) + len(self.hard_examples)
def sample_example(self) -> dict:
key = random.choice(tuple(self.examples))
return self.examples[key]
def get_example_hash(self, example: dict) -> str:
hash_keys = [key for key in self.config.hash_keys if key in example]
assert hash_keys, "No hashable keys found in example."
return hashlib.sha256(json.dumps([example[key] for key in hash_keys]).encode()).hexdigest()
def update_pools(self, example_id: int, avg_reward: float) -> str:
"""Assign example to pool based on reward. Returns pool name."""
if self.config.easy_threshold is not None and avg_reward >= self.config.easy_threshold:
pool = "easy"
elif self.config.hard_threshold is not None and avg_reward <= self.config.hard_threshold:
pool = "hard"
else:
pool = "normal"
if pool != "normal" and example_id in self.examples:
example = self.examples.pop(example_id)
target = self.easy_examples if pool == "easy" else self.hard_examples
target.append(example)
self.num_examples_per_step[pool] += 1
return pool
def reset_step_metrics(self) -> None:
zero = lambda: {p: 0 for p in POOLS}
self.num_examples_per_step = zero()
self.num_rollouts_per_step = zero()
def get_metrics(self) -> dict[str, float]:
metrics = {}
num_examples = sum(self.num_examples_per_step.values())
num_rollouts = sum(self.num_rollouts_per_step.values())
for pool in ["easy", "hard"]:
if num_examples:
metrics[f"evicted_examples/{self.env_name}/{pool}"] = self.num_examples_per_step[pool] / num_examples
if num_rollouts:
metrics[f"filtered_rollouts/{self.env_name}/{pool}"] = self.num_rollouts_per_step[pool] / num_rollouts
pool_counts = [len(self.easy_examples), self.num_normal, len(self.hard_examples)]
pool_ratios = mean_normalize(pool_counts)
for pool, ratio in zip(POOLS, pool_ratios):
metrics[f"pool/{self.env_name}/{pool}"] = ratio
self.reset_step_metrics()
return metrics
class Buffer:
"""Manages multiple Buffers with env-ratio-aware sampling."""
def __init__(self, envs: TrainEnvs, config: BufferConfig):
self.config = config
self.logger = get_logger()
if config.seed is not None:
random.seed(config.seed)
self.env_buffers: dict[str, _EnvBuffer] = {}
for env in envs:
self.env_buffers[env.name] = _EnvBuffer(env, config)
self.env_names = envs.names
total = sum(eb.num_total for eb in self.env_buffers.values())
self.logger.debug(
f"Initialized buffer with {format_num(total, precision=0)} example(s) "
f"in {len(self.env_names)} environment(s)"
)
env_ratios = [env.config.ratio for env in envs]
if any(r is not None for r in env_ratios):
env_ratio = mean_normalize(env_ratios)
self.env_probs = dict(zip(self.env_names, env_ratio))
self.logger.debug(
f"Sampling buffer according to provided environment ratios "
f"({', '.join(f'{k}={v:.2f}' for k, v in self.env_probs.items())})"
)
else:
env_counts = [self.env_buffers[name].num_normal for name in self.env_names]
env_ratio = mean_normalize(env_counts)
self.env_probs = dict(zip(self.env_names, env_ratio))
self.logger.debug(
f"Sampling buffer according to natural environment distribution "
f"({', '.join(f'{k}={v:.2f}' for k, v in self.env_probs.items())})"
)
self.rollout_buffer: list[vf.RolloutOutput] = []
def sample_examples(self, n: int) -> list[dict]:
"""Samples n examples across envs, respecting env ratios."""
non_empty = [name for name, eb in self.env_buffers.items() if eb.examples]
if not non_empty:
raise ValueError("No environments left with examples.")
weights = [self.env_probs[name] for name in non_empty]
return [self.env_buffers[name].sample_example() for name in random.choices(non_empty, weights=weights, k=n)]
def update(self, rollouts: list[vf.RolloutOutput]):
"""Updates buffer state with completed rollouts."""
rollouts_by_example = defaultdict(list)
for rollout in rollouts:
rollouts_by_example[(rollout["env_name"], rollout["example_id"])].append(rollout)
for (env_name, example_id), example_rollouts in rollouts_by_example.items():
eb = self.env_buffers[env_name]
avg_reward = mean([r["reward"] for r in example_rollouts])
eb.update_pools(example_id, avg_reward)
if self.config.online_difficulty_filtering:
if avg_reward == 0.0:
eb.num_rollouts_per_step["hard"] += len(example_rollouts)
continue
elif avg_reward == 1.0:
eb.num_rollouts_per_step["easy"] += len(example_rollouts)
continue
eb.num_rollouts_per_step["normal"] += len(example_rollouts)
self.rollout_buffer.extend(example_rollouts)
def sample_rollouts(self, n: int) -> list[vf.RolloutOutput]:
"""Samples the latest n rollouts from the buffer."""
n = min(n, len(self.rollout_buffer))
sampled = self.rollout_buffer[-n:]
self.rollout_buffer = self.rollout_buffer[:-n]
return sampled
def save(self, path: Path) -> None:
"""Saves pool assignments and rollout buffer."""
path.mkdir(parents=True, exist_ok=True)
def write_jsonl(lst: list, filepath: Path) -> None:
with open(filepath, "w") as f:
for item in lst:
f.write(json.dumps(item, default=make_serializable) + "\n")
all_easy = [ex for eb in self.env_buffers.values() for ex in eb.easy_examples]
all_hard = [ex for eb in self.env_buffers.values() for ex in eb.hard_examples]
write_jsonl(all_easy, path / "easy_examples.jsonl")
write_jsonl(all_hard, path / "hard_examples.jsonl")
write_jsonl(self.rollout_buffer, path / "rollout_buffer.jsonl")
def load(self, path: Path) -> None:
"""Loads pool assignments and rollouts from checkpoint."""
def read_jsonl(filepath: Path) -> list[dict]:
with open(filepath, "r") as f:
return [json.loads(line) for line in f]
saved_easy = read_jsonl(path / "easy_examples.jsonl")
saved_hard = read_jsonl(path / "hard_examples.jsonl")
saved_rollouts = cast(list[vf.RolloutOutput], read_jsonl(path / "rollout_buffer.jsonl"))
if not any(saved_easy) and not any(saved_hard) and not any(saved_rollouts):
self.logger.debug("No easy/ hard examples or rollouts found in checkpoint")
return
# Build hash lookup across all env buffers: env -> (hash -> example_id)
hash_lookup: dict[str, dict[str, int]] = defaultdict(dict)
all_hashes: set[str] = set()
for env_name, eb in self.env_buffers.items():
for example_id, example in eb.examples.items():
h = eb.get_example_hash(example)
if h in all_hashes:
self.logger.warning(
f"Duplicate example hash found based on hash_keys={self.config.hash_keys}. "
"Overwriting with latest example. This may cause unexpected behavior when resuming the buffer."
)
hash_lookup[env_name][h] = example_id
all_hashes.add(h)
def move_saved_pool(saved_examples: list[dict], pool_name: str) -> int:
num_moved = 0
for example in saved_examples:
# Use any env buffer to compute hash (hash_keys are config-level)
first_eb = next(iter(self.env_buffers.values()))
h = first_eb.get_example_hash(example)
for env_name, env_hashes in hash_lookup.items():
if h in env_hashes:
example_id = env_hashes[h]
eb = self.env_buffers[env_name]
matched = eb.examples.pop(example_id, None)
if matched is not None:
target = eb.easy_examples if pool_name == "easy" else eb.hard_examples
target.append(matched)
num_moved += 1
break
return num_moved
if any(saved_easy):
num_moved = move_saved_pool(saved_easy, "easy")
self.logger.debug(f"Loaded {num_moved}/{len(saved_easy)} example(s) to easy pool from checkpoint.")
if num_moved != len(saved_easy):
self.logger.warning(
f"Could not move {len(saved_easy) - num_moved} example(s) from checkpoint to easy pool. "
"This usually means you resumed with an env mix that does not contain all previous examples."
)
if any(saved_hard):
num_moved = move_saved_pool(saved_hard, "hard")
self.logger.debug(f"Moved {num_moved}/{len(saved_hard)} example(s) to hard pool from checkpoint.")
if num_moved != len(saved_hard):
self.logger.warning(
f"Could not move {len(saved_hard) - num_moved} example(s) from checkpoint to hard pool. "
"This usually means you resumed with an env mix that does not contain all previous examples."
)
if any(saved_rollouts):
valid = [r for r in saved_rollouts if r.get("env_name") in self.env_names]
self.rollout_buffer.extend(valid)
self.logger.debug(f"Loaded {len(valid)} rollout(s) from checkpoint.")
def convert_to_normal(eb: _EnvBuffer, pool: list[dict], fraction: float) -> int:
if fraction <= 0.0 or not pool:
return 0
num_to_move = round(len(pool) * fraction)
if num_to_move <= 0:
return 0
for _ in range(num_to_move):
example = random.choice(pool)
pool.remove(example)
eb.examples[example["example_id"]] = example
return num_to_move
for eb in self.env_buffers.values():
n_easy = len(eb.easy_examples)
moved = convert_to_normal(eb, eb.easy_examples, self.config.easy_fraction)
self.logger.debug(f"Converted {moved}/{n_easy} example(s) back to normal from easy pool ({eb.env_name}).")
n_hard = len(eb.hard_examples)
moved = convert_to_normal(eb, eb.hard_examples, self.config.hard_fraction)
self.logger.debug(f"Converted {moved}/{n_hard} example(s) back to normal from hard pool ({eb.env_name}).")
def get_metrics(self) -> dict[str, float]:
metrics = {}
# Aggregate cross-env totals
total_examples_per_pool = {p: 0 for p in POOLS}
total_rollouts_per_pool = {p: 0 for p in POOLS}
for eb in self.env_buffers.values():
for p in POOLS:
total_examples_per_pool[p] += eb.num_examples_per_step[p]
total_rollouts_per_pool[p] += eb.num_rollouts_per_step[p]
total_examples = sum(total_examples_per_pool.values())
total_rollouts = sum(total_rollouts_per_pool.values())
for pool in ["easy", "hard"]:
if total_examples:
metrics[f"evicted_examples/{pool}"] = total_examples_per_pool[pool] / total_examples
if total_rollouts:
metrics[f"filtered_rollouts/{pool}"] = total_rollouts_per_pool[pool] / total_rollouts
total_normal = sum(eb.num_normal for eb in self.env_buffers.values())
total_easy = sum(len(eb.easy_examples) for eb in self.env_buffers.values())
total_hard = sum(len(eb.hard_examples) for eb in self.env_buffers.values())
pool_ratios = mean_normalize([total_easy, total_normal, total_hard])
for pool, ratio in zip(POOLS, pool_ratios):
metrics[f"pool/{pool}"] = ratio
# Per-env metrics
for eb in self.env_buffers.values():
metrics.update(eb.get_metrics())
return metrics
+35 -73
View File
@@ -1,93 +1,55 @@
"""Checkpoint manager for ``Progress``. Layout:
``<output_dir>/checkpoints/step_N/orchestrator/progress.pt``."""
from __future__ import annotations
import time
from dataclasses import asdict, dataclass
from dataclasses import asdict
from pathlib import Path
import torch
from prime_rl.configs.orchestrator import CheckpointConfig
from prime_rl.orchestrator.buffer import Buffer
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import get_ckpt_dir, get_step_path
@dataclass
class Progress:
step: int = 0
total_tokens: int = 0
total_samples: int = 0
total_problems: int = 0
from prime_rl.orchestrator.types import Progress
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_ckpt_dir, get_step_path
class CheckpointManager:
"""Utility class to save and load orchestrator checkpoints to resume orchestrator."""
def __init__(self, output_dir: Path, config: CheckpointConfig):
def __init__(self, output_dir: Path, config: CheckpointConfig) -> None:
self.config = config
self.ckpt_dir = get_ckpt_dir(output_dir)
self.logger = get_logger()
def get_ckpt_path(self, step: int) -> Path:
return get_step_path(self.ckpt_dir, step) / "orchestrator"
def save_to_path(
self,
ckpt_path: Path,
progress: Progress,
buffer: Buffer,
):
self.logger.debug(f"Saving orchestrator checkpoint to {ckpt_path}")
start_time = time.perf_counter()
# Save progress
with open(ckpt_path / "progress.pt", "wb") as f:
torch.save({"progress": progress}, f)
# Save buffer
buffer.save(ckpt_path / "buffer")
self.logger.debug(f"Orchestrator checkpoint saved in {time.perf_counter() - start_time:.2f} seconds")
def load_from_path(self, ckpt_path: Path, progress: Progress, buffer: Buffer) -> None:
"""Loads a checkpoint from a given path in-place."""
self.logger.debug(f"Loading checkpoint from {ckpt_path}")
start_time = time.perf_counter()
# Load progress
if self.config.skip_progress:
self.logger.info("Skipping progress loading from checkpoint")
else:
with open(ckpt_path / "progress.pt", "rb") as f:
state = torch.load(f, weights_only=False)
# Set progress in-place
for key, value in asdict(state["progress"]).items():
setattr(progress, key, value)
# Load buffer
if self.config.skip_buffer:
self.logger.info("Skipping buffer loading from checkpoint")
else:
buffer.load(ckpt_path / "buffer")
self.logger.debug(f"Orchestrator checkpoint loaded in {time.perf_counter() - start_time:.2f} seconds")
def load(self, progress: Progress, buffer: Buffer, step: int) -> None:
"""Loads a checkpoint from a given path."""
ckpt_path = self.get_ckpt_path(step)
if not ckpt_path.exists():
raise FileNotFoundError(f"Checkpoint not found at {ckpt_path}")
self.load_from_path(ckpt_path, progress, buffer)
def save(
self,
progress: Progress,
buffer: Buffer,
step: int,
) -> None:
"""Saves the full checkpoint state for a specified step."""
def save(self, progress: Progress, step: int) -> None:
ckpt_path = self.get_ckpt_path(step)
ckpt_path.mkdir(parents=True, exist_ok=True)
self.save_to_path(ckpt_path, progress, buffer)
start = time.perf_counter()
with open(ckpt_path / "progress.pt", "wb") as f:
torch.save({"progress": progress}, f)
get_logger().debug(
f"Orchestrator checkpoint saved to {ckpt_path} in {format_time(time.perf_counter() - start)}"
)
def load(self, progress: Progress, step: int) -> None:
ckpt_path = self.get_ckpt_path(step)
state_file = ckpt_path / "progress.pt"
if not state_file.exists():
raise FileNotFoundError(f"Orchestrator checkpoint not found at {state_file}")
get_logger().debug(f"Loading checkpoint from {state_file}")
start = time.perf_counter()
if self.config.skip_progress:
get_logger().info("Skipping progress loading from checkpoint")
else:
with open(state_file, "rb") as f:
state = torch.load(f, weights_only=False)
saved: Progress = state["progress"]
for key, value in asdict(saved).items():
if hasattr(progress, key):
setattr(progress, key, value)
get_logger().debug(f"Orchestrator checkpoint loaded in {format_time(time.perf_counter() - start)}")
def setup_ckpt_manager(output_dir: Path, config: CheckpointConfig | None) -> CheckpointManager | None:
+693
View File
@@ -0,0 +1,693 @@
"""RolloutDispatcher: schedules rollouts under a shared permit counter.
- Capacity (``max_inflight_rollouts``) is shared across train + eval.
A group-scoring task that runs N rollouts in one call reserves N permits.
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
- 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.
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
schedule next. Transitions are level-triggered (driven by the eval
source's emptiness), so in-flight rollouts of the opposite kind drain
naturally on either side of an eval boundary.
- ``on_new_version`` (called by the watcher) bumps ``off_policy_steps`` on
in-flight train rollouts and drops groups past ``max_off_policy_steps``.
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.
"""
from __future__ import annotations
import asyncio
import uuid
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from enum import Enum, auto
from typing import Literal
import verifiers 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,
RolloutKind,
TrainRollout,
)
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
from prime_rl.utils.client import InferencePool, client_identity
from prime_rl.utils.logger import get_logger
class DispatcherMode(Enum):
"""Which kind of work the dispatcher schedules next."""
PREFER_TRAIN = auto()
PREFER_EVAL = auto()
@dataclass
class DispatcherMetrics:
"""Per-tick drain counters for the orchestrator's periodic log.
``drained()`` returns the current values and clears them; point-in-time
gauges live on ``RolloutDispatcher.gauges`` instead."""
cancelled_by_kind_env: dict[tuple[Literal["train", "eval"], str], int] = field(
default_factory=lambda: defaultdict(int)
)
errored_by_kind_env: dict[tuple[Literal["train", "eval"], str], int] = field(
default_factory=lambda: defaultdict(int)
)
def record_cancellation(self, *, kind: Literal["train", "eval"], env_name: str, n: int = 1) -> None:
self.cancelled_by_kind_env[(kind, env_name)] += n
def record_error(self, *, kind: Literal["train", "eval"], env_name: str) -> None:
self.errored_by_kind_env[(kind, env_name)] += 1
def drained(self, *, train_envs: set[str], eval_envs: set[str]) -> dict[str, float]:
"""Return per-tick counters and clear them. Emits the full pre-
registered key set every tick (zero when no activity) so the wandb
time axis stays dense and ``define_metric`` lines up."""
out: dict[str, float] = {}
for kind in ("train", "eval"):
envs = train_envs if kind == "train" else eval_envs
cancelled_total = sum(self.cancelled_by_kind_env.get((kind, e), 0) for e in envs)
errored_total = sum(self.errored_by_kind_env.get((kind, e), 0) for e in envs)
out[f"dispatcher/cancelled/{kind}"] = float(cancelled_total)
out[f"dispatcher/errored/{kind}"] = float(errored_total)
for env in train_envs | eval_envs:
out[f"dispatcher/cancelled/{env}"] = float(
self.cancelled_by_kind_env.get(("train", env), 0) + self.cancelled_by_kind_env.get(("eval", env), 0)
)
out[f"dispatcher/errored/{env}"] = float(
self.errored_by_kind_env.get(("train", env), 0) + self.errored_by_kind_env.get(("eval", env), 0)
)
self.cancelled_by_kind_env.clear()
self.errored_by_kind_env.clear()
return out
@staticmethod
def drain_keys(*, train_envs: set[str], eval_envs: set[str]) -> list[str]:
"""Full set of keys ``drained`` may emit; used by the periodic
logger for ``wandb.define_metric``."""
keys = [
"dispatcher/cancelled/train",
"dispatcher/cancelled/eval",
"dispatcher/errored/train",
"dispatcher/errored/eval",
]
for env in train_envs | eval_envs:
keys.append(f"dispatcher/cancelled/{env}")
keys.append(f"dispatcher/errored/{env}")
return keys
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
cancellation; the orchestrator triggers eval epochs."""
def __init__(
self,
*,
train_envs: TrainEnvs,
eval_envs: EvalEnvs | None,
train_source: TrainSource,
eval_source: EvalSource | None,
inference: InferencePool,
eval_inference: InferencePool,
policy: Policy,
max_inflight_rollouts: int,
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
self.eval_envs = eval_envs
# Train rollouts go to ``inference`` (the teacher in SFT mode);
# eval always evaluates the student, so it uses ``eval_inference``.
self.inference = inference
self.eval_inference = eval_inference
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
self.inflight_permits = 0
self.rate_limiter: AsyncLimiter | None = (
AsyncLimiter(tasks_per_minute, time_period=60) if tasks_per_minute else None
)
self.inflight: dict[asyncio.Task, InflightRollout] = {}
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.mode: DispatcherMode = DispatcherMode.PREFER_TRAIN
# Set by the orchestrator after the final train step; pipeline then
# winds down without scheduling new train rollouts
self.train_scheduling_disabled: bool = False
self.metrics = DispatcherMetrics()
# Orchestrator-owned gate. When clear, ``fill_inflight`` returns
# without scheduling new groups. The dispatcher itself doesn't know
# *why* — the orchestrator toggles this based on step / policy lead.
self.dispatch_allowed = asyncio.Event()
self.dispatch_allowed.set()
self.stopped = asyncio.Event()
self.task: asyncio.Task | None = None
@property
def train_model_name(self) -> str:
"""Model name for *train* rollouts. In SFT mode train data comes from
the teacher pool, so use its model name; otherwise the live student
policy. (Eval always uses ``policy.model_name`` — the student.)"""
if self.training_mode == "sft":
return self.inference.model_name
return self.policy.model_name
@property
def inflight_train_count(self) -> int:
return sum(m.rollout_count for m in self.inflight.values() if m.kind == "train")
@property
def inflight_eval_count(self) -> int:
return sum(m.rollout_count for m in self.inflight.values() if m.kind == "eval")
@property
def available_permits(self) -> int:
return self.max_inflight - self.inflight_permits
@property
def inflight_by_env(self) -> dict[tuple[RolloutKind, str], int]:
counts: dict[tuple[RolloutKind, str], int] = defaultdict(int)
for meta in self.inflight.values():
counts[(meta.kind, meta.env_name)] += meta.rollout_count
return dict(counts)
@property
def queued_eval_examples(self) -> int:
return len(self.eval_source) if self.eval_source is not None else 0
@property
def is_idle(self) -> bool:
"""True once nothing is in flight, no eval queued, and ``out_q`` is
empty — the pipeline has fully drained."""
eval_drained = self.eval_source is None or not self.eval_source
return not self.inflight and eval_drained and self.out_q.empty()
def disable_train_scheduling(self) -> None:
"""Stop scheduling new train rollouts; in-flight train + any
triggered eval drain naturally."""
self.train_scheduling_disabled = True
@property
def max_off_policy_level(self) -> int:
steps = [m.off_policy_steps for m in self.inflight.values() if m.kind == "train"]
return max(steps) if steps else 0
@property
def mean_off_policy_level(self) -> float:
steps = [m.off_policy_steps for m in self.inflight.values() if m.kind == "train"]
return sum(steps) / len(steps) if steps else 0.0
# ── lifecycle ──────────────────────────────────────────────────────────
async def start(self) -> None:
"""Single dispatch loop: schedule, wait, collect, repeat."""
self.task = asyncio.current_task()
try:
while not self.stopped.is_set():
await self.fill_inflight()
if not self.inflight:
# No work — sleep briefly. Eval triggers from the
# orchestrator wake the next iteration via a mode flip
try:
await asyncio.wait_for(self.stopped.wait(), timeout=0.1)
except asyncio.TimeoutError:
pass
continue
done, _pending = await asyncio.wait(
list(self.inflight.keys()),
return_when=asyncio.FIRST_COMPLETED,
timeout=0.5, # wake periodically to re-check fill (mode flips)
)
for task in done:
await self.handle_completed_rollout(task)
except asyncio.CancelledError:
return
async def stop(self) -> None:
self.stopped.set()
await self.cancel_inflight_rollouts()
if self.task is not None:
await safe_cancel(self.task)
self.task = None
async def on_new_version(self, step: int) -> None:
"""Bump off-policy counters and drop groups past
``max_off_policy_steps`` (drop_group emits ``Cancelled`` markers so
the sink still finalizes the partial group). Eval rollouts are not
aged because they are tied to their start-time policy version."""
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.add(meta.group_id)
for gid in stale_groups:
removed = await self.drop_group(gid)
cancelled += removed
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 fill_inflight(self) -> None:
"""Schedule new rollouts up to ``max_inflight``, honoring
``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
if self.mode == DispatcherMode.PREFER_EVAL:
# PREFER_EVAL is only entered when the orchestrator triggers
# eval, which requires ``eval_source`` to be configured
assert self.eval_source is not None
eval_has_work = bool(self.eval_source) or any(
g.kind == "eval" and g.rollouts_to_schedule > 0 for g in self.groups.values()
)
if not eval_has_work:
# Eval source + all eval groups fully dispatched. Flip
# to PREFER_TRAIN so any remaining permits go to train
# while the in-flight eval tail completes naturally
self.switch_mode(DispatcherMode.PREFER_TRAIN, reason="the eval queue drained")
continue
scheduled = await self.try_schedule("eval")
if not scheduled:
return
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
def switch_mode(self, new_mode: DispatcherMode, *, reason: str) -> None:
if new_mode == self.mode:
return
prefer = "eval" if new_mode == DispatcherMode.PREFER_EVAL else "train"
get_logger().info(f"Switching dispatcher mode to prefer {prefer} rollouts because {reason}")
self.mode = new_mode
async def try_schedule(self, kind: RolloutKind) -> bool:
"""Schedule one rollout of ``kind``: prefer continuing an existing
group (keeps prefix-cache hits); otherwise open a fresh group from
the corresponding source. Returns False if nothing could be
scheduled."""
if kind == "train" and self.train_scheduling_disabled:
return False
envs = self.train_envs if kind == "train" else self.eval_envs
if envs is None:
return False
for gid, group in list(self.groups.items()):
if group.kind != kind or group.rollouts_to_schedule <= 0:
continue
env = envs.get(group.env_name)
cost = group.rollouts_to_schedule if env.requires_group_scoring else 1
if cost <= self.available_permits:
return await self.schedule_group_rollout(gid, group)
fresh = self.next_fresh_group(kind, envs)
if fresh is None:
return False
gid = uuid.uuid4()
self.groups[gid] = fresh
return await self.schedule_group_rollout(gid, fresh)
def next_fresh_group(self, kind: RolloutKind, envs) -> GroupState | None:
"""Pop the next example from the corresponding source and wrap it in
a ``GroupState``. Returns ``None`` if the source is empty or the
picked env's permit cost doesn't fit."""
if kind == "train":
source = self.train_source
else:
assert self.eval_source is not None
source = self.eval_source
example = source.next_example(self.available_permits)
if example is None:
return None
env_name = example["env_name"]
group_size = envs.get(env_name).config.group_size
eval_step: int | None = example.get("eval_step") if kind == "eval" else None
return GroupState(
kind=kind,
env_name=env_name,
example=example,
rollouts_to_schedule=group_size,
target_rollouts=group_size,
eval_step=eval_step,
policy_version_at_start=self.policy.version,
)
async def schedule_group_rollout(self, group_id: uuid.UUID, group: GroupState) -> bool:
"""Dispatch one ``run_rollout`` / ``run_group`` task for this group.
Returns False only if we couldn't even schedule one rollout (no clients
ready, no permits). Returns True after issuing one task — the caller
loops to keep scheduling.
"""
# Train rollouts use the rollout pool (teacher in SFT) via the
# renderer/token train client. Eval always evaluates the student and
# goes through the eval client (chat-completions) — the same path the
# legacy orchestrator used, so eval scores stay comparable.
if group.kind == "eval":
pool, model_name = self.eval_inference, self.policy.model_name
else:
pool, model_name = self.inference, self.train_model_name
# Pin a single client per group to keep prefix-cache hits
if group.pinned_client is None:
if group.kind == "eval":
client = await pool.get_eval_client()
else:
load = Counter(
client_identity(m.client_config) for m in self.inflight.values() if m.client_config is not None
)
client = await pool.select_train_client(load)
if group_id not in self.groups:
return False
group.pinned_client = client
else:
client = group.pinned_client
env_collection = self.train_envs if group.kind == "train" else self.eval_envs
if env_collection is None:
return False
env = env_collection.get(group.env_name)
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
group.rollouts_to_schedule = 0
await self.acquire(permits)
task: asyncio.Task = asyncio.create_task(
env.run_group(
client=client,
example=group.example,
model_name=model_name,
group_size=permits,
cache_salt=cache_salt,
)
)
else:
permits = 1
group.rollouts_to_schedule -= 1
await self.acquire(permits)
task = asyncio.create_task(
env.run_rollout(
client=client,
example=group.example,
model_name=model_name,
cache_salt=cache_salt,
)
)
self.inflight[task] = InflightRollout(
kind=group.kind,
env_name=group.env_name,
group_id=group_id,
policy_version=group.policy_version_at_start,
rollout_count=permits,
client_config=client,
eval_step=group.eval_step,
)
return True
async def acquire(self, n: int) -> None:
"""Reserve ``n`` permits + rate-limit each one. Caller must precheck
``available_permits >= n``; this is not a blocking acquire."""
for _ in range(n):
if self.rate_limiter is not None:
await self.rate_limiter.acquire()
self.inflight_permits += 1
def release(self, n: int) -> None:
self.inflight_permits -= n
async def handle_completed_rollout(self, task: asyncio.Task) -> None:
"""Emit every dispatched rollout exactly once to ``out_q``. Task
exceptions synthesize ``meta.rollout_count`` error markers so the
sink's count-to-``group_size`` finalization still triggers.
Cancelled tasks (popped by ``drop_group``) raise ``CancelledError``
and are discarded — ``drop_group`` already emitted their markers.
"""
meta = self.inflight.pop(task, None)
if meta is None:
return # already handled by drop_group / cancel_inflight_rollouts
self.release(meta.rollout_count)
group = self.groups.get(meta.group_id)
is_synth_exception = False
try:
result = task.result()
rollouts: list[vf.RolloutOutput] = 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)
]
is_synth_exception = True
for r in rollouts:
if r.get("error") is None and len(r.get("trajectory") or []) == 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": "",
}
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")
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)}"
)
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``.
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:
assert eval_step is not None, "eval rollout missing eval_step"
rollout = EvalRollout(**common, 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)
# Sync claim phase: pop matching tasks from ``self.inflight`` and
# release their permits in one non-yielding sweep. After this loop
# the dropped tasks are no longer reachable from ``self.inflight``,
# so ``handle_completed_rollout``'s existing None-guard makes the
# subsequent async emit phase race-free.
claimed: list[tuple[asyncio.Task, InflightRollout]] = []
for task, meta in list(self.inflight.items()):
if meta.group_id != group_id:
continue
del self.inflight[task]
self.release(meta.rollout_count)
claimed.append((task, meta))
tasks_to_cancel = [task for task, _ in claimed]
inflight_cancelled = sum(meta.rollout_count for _, meta in claimed)
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)
# 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
# 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:
fallback_meta = last_meta or InflightRollout(
kind=group.kind,
env_name=group.env_name,
group_id=group_id,
policy_version=group.policy_version_at_start,
rollout_count=1,
eval_step=group.eval_step,
)
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)
cancelled = inflight_cancelled + unscheduled_cancelled
if cancelled > 0:
meta_for_log = last_meta or (
InflightRollout(
kind=group.kind,
env_name=group.env_name,
group_id=group_id,
policy_version=group.policy_version_at_start if group else 0,
rollout_count=1,
eval_step=group.eval_step,
)
if group is not None
else None
)
if meta_for_log is not None:
self.metrics.record_cancellation(kind=meta_for_log.kind, env_name=meta_for_log.env_name, n=cancelled)
get_logger().debug(
f"drain {meta_for_log.kind} | group={str(group_id)[:8]} env={meta_for_log.env_name} | "
f"cancelled={cancelled} (inflight={inflight_cancelled} unscheduled={unscheduled_cancelled})"
)
if tasks_to_cancel:
await safe_cancel_all(tasks_to_cancel)
return cancelled
async def cancel_inflight_rollouts(self) -> None:
"""Cancel all in-flight rollouts. Used on shutdown — doesn't emit
markers since the sinks are being torn down anyway."""
for meta in self.inflight.values():
self.metrics.record_cancellation(kind=meta.kind, env_name=meta.env_name, n=meta.rollout_count)
self.release(meta.rollout_count)
tasks = list(self.inflight.keys())
self.inflight.clear()
self.groups.clear()
if tasks:
await safe_cancel_all(tasks)
async def cancel_inflight_train_rollouts(self) -> int:
"""Cancel in-flight train rollouts, leaving eval alone. Used by the
orchestrator at ``max_steps`` so triggered eval can still complete
through the pipeline while wasted train inference is short-circuited."""
train_tasks: list[asyncio.Task] = []
train_group_ids: set[uuid.UUID] = set()
cancelled = 0
for task, meta in list(self.inflight.items()):
if meta.kind != "train":
continue
self.inflight.pop(task, None)
self.release(meta.rollout_count)
self.metrics.record_cancellation(kind="train", env_name=meta.env_name, n=meta.rollout_count)
cancelled += meta.rollout_count
train_tasks.append(task)
train_group_ids.add(meta.group_id)
for gid in train_group_ids:
self.groups.pop(gid, None)
if train_tasks:
await safe_cancel_all(train_tasks)
return cancelled
# ── metrics ────────────────────────────────────────────────────────────
def gauges(self) -> dict[str, float]:
"""Instantaneous, read-only gauges sampled by the periodic logger."""
return {
"dispatcher/inflight_train": float(self.inflight_train_count),
"dispatcher/inflight_eval": float(self.inflight_eval_count),
"dispatcher/queued/eval": float(self.queued_eval_examples),
"dispatcher/mode": float(self.mode == DispatcherMode.PREFER_EVAL),
"dispatcher/groups_in_flight": float(len(self.groups)),
"dispatcher/off_policy_level_max": float(self.max_off_policy_level),
"dispatcher/off_policy_level_mean": self.mean_off_policy_level,
}
+16 -156
View File
@@ -1,27 +1,21 @@
from __future__ import annotations
import asyncio
import atexit
import multiprocessing as mp
import time
from collections.abc import Awaitable, Callable, Iterator, Sequence
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
from prime_rl.configs.orchestrator import EnvConfig, EvalEnvConfig, TrainEnvConfig
from prime_rl.orchestrator.eval_utils import compute_pass_at_k
from prime_rl.orchestrator.vf_utils import get_completion_len
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.utils.logger import get_logger
REQUIRED_STATE_COLUMNS = ["trajectory", "sampling_args"]
REQUIRED_STATE_COLUMNS = ["trajectory"]
class Env:
@@ -31,7 +25,7 @@ class Env:
self.config = config
self.sampling_args: dict = {}
get_logger().info(f"Initializing {config.resolved_name} ({config})")
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._env_server_process: BaseProcess | None = None
@@ -104,8 +98,10 @@ class Env:
self._env_server_process = process
return address
def _sampling_args_with_salt(self, cache_salt: str) -> dict:
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
@@ -124,7 +120,7 @@ class Env:
client: vf.ClientConfig,
example: dict,
model_name: str,
cache_salt: str,
cache_salt: str | None,
) -> vf.RolloutOutput:
"""Run a single rollout for an example."""
return await self.env.run_rollout(
@@ -143,7 +139,7 @@ class Env:
example: dict,
model_name: str,
group_size: int,
cache_salt: str,
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(
@@ -169,6 +165,11 @@ class TrainEnv(Env):
def __init__(self, config: TrainEnvConfig):
super().__init__(config)
self.sampling_args = config.sampling.to_sampling_args()
# Built once — custom advantage funcs do an ``import_object`` we don't
# want to pay per group. ``None`` = reward-only path.
self.advantage_fn: AdvantageFn | None = (
setup_advantage_fn(config.advantage) if config.advantage is not None else None
)
def get_dataset(self, seed: int | None = None):
return self.env.get_dataset(seed=seed)
@@ -182,147 +183,6 @@ class EvalEnv(Env):
self.sampling_args = config.sampling.to_sampling_args()
self.examples = self.env.get_eval_dataset(n=config.num_examples).to_list()
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": get_completion_len(o),
"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
EnvT = TypeVar("EnvT", bound=Env)
@@ -370,7 +230,7 @@ class Envs(Generic[EnvT]):
if not processes:
return
logger = get_logger()
logger.info(f"Shutting down {len(processes)} env server(s), waiting for sandbox cleanup...")
logger.debug(f"Shutting down {len(processes)} env server(s)")
for p in processes:
p.terminate()
for p in processes:
+160
View File
@@ -0,0 +1,160 @@
"""EvalSink: three-level rollout sink for eval epochs.
Same shape as ``TrainSink``, but no tokenization / advantages / filters:
1. ``process_rollout`` — no-op.
2. ``process_group`` — at ``group_size`` arrivals, move the rollouts
(errored ones included) into the ``(env, eval_step)`` bucket.
3. ``process_batch`` — at ``num_examples × group_size`` arrivals, build
the ``EvalBatchMetrics`` and return an ``EvalBatch``.
``add()`` returns ``EvalBatch | None``.
"""
from __future__ import annotations
import uuid
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.utils.logger import get_logger
class EvalSink:
"""Constructed only when eval is configured."""
def __init__(self, *, eval_envs: EvalEnvs) -> None:
self.eval_envs = eval_envs
self.pending_groups: dict[uuid.UUID, list[EvalRollout]] = 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)
def add(self, rollout: EvalRollout) -> 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
self.process_rollout(rollout)
bkey = (env_name, rollout.eval_step)
self.pending_groups[rollout.group_id].append(rollout)
if len(self.pending_groups[rollout.group_id]) >= self.group_size_for(env_name):
self.process_group(rollout.group_id)
if len(self.pending_batches[bkey]) >= self.batch_size_for(env_name):
return self.process_batch(bkey)
return None
def group_size_for(self, env_name: str) -> int:
return self.eval_envs.get(env_name).config.group_size
def batch_size_for(self, env_name: str) -> int:
"""``num_examples × group_size`` — total rollouts expected for one
epoch of ``env_name``."""
env = self.eval_envs.get(env_name)
return len(env.examples) * env.config.group_size
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
"""One entry per accumulating ``(env, eval_step)`` batch:
``(env_name, eval_step, batch_count, expected, buffered)``.
``batch_count`` is finalized-group survivors in ``pending_batches``;
``buffered`` is partial-group arrivals from non-group-scoring envs."""
batch_counts: dict[tuple[str, int], int] = {bkey: len(bucket) for bkey, bucket in self.pending_batches.items()}
buffered: dict[tuple[str, int], int] = {}
for rollouts in self.pending_groups.values():
if not rollouts:
continue
env_name = rollouts[0].env_name
if self.eval_envs.get(env_name).requires_group_scoring:
continue
bkey = (env_name, rollouts[0].eval_step)
buffered[bkey] = buffered.get(bkey, 0) + len(rollouts)
return [
(
env_name,
eval_step,
batch_counts.get((env_name, eval_step), 0),
self.batch_size_for(env_name),
buffered.get((env_name, eval_step), 0),
)
for (env_name, eval_step) in set(batch_counts) | set(buffered)
]
# ── level 1: per-rollout (no-op for eval) ─────────────────────────────
def process_rollout(self, rollout: EvalRollout) -> None:
"""No-op. Eval rollouts don't need trainer-bound tokenization; the
method exists to keep the three-level structure uniform with
``TrainSink``.
"""
return None
# ── level 2: per-group (move into batch bucket) ───────────────────────
def process_group(self, group_id: uuid.UUID) -> None:
group = self.pending_groups.pop(group_id, [])
if not group:
return
env_name = group[0].env_name
example_id = group[0].example_id
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]
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"rollouts={len(group)} (errored={num_errored}) | reward={avg_reward:.4f}"
)
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
"""Build ``EvalBatchMetrics`` and return the finalized ``EvalBatch``.
Errored rollouts (env failures, cancellations, task exceptions) are
excluded from reward / pass@k / seq_len aggregation (including them
at reward=0 would bias the score down) and surfaced separately as
``n_cancelled`` / ``n_errored``."""
env_name, step = key
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]
metrics = EvalBatchMetrics(
n_rollouts=n_total,
n_cancelled=n_cancelled,
n_errored=n_errored,
)
if valid:
rewards = [r.reward for r in valid]
lens = [r.raw["token_usage"]["final_output_tokens"] 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.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]] = {}
for r in valid:
by_example.setdefault(r.example_id, []).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:
pass_at_k_per_example = [compute_pass_at_k(rs) for rs in by_example.values()]
keys = set().union(*(d.keys() for d in pass_at_k_per_example))
for k in keys:
values = [d[k] for d in pass_at_k_per_example if k in d]
metrics.pass_at_k[k] = float(sum(values) / len(values))
return EvalBatch(env_name=env_name, step=step, rollouts=rollouts, metrics=metrics)
+87
View File
@@ -0,0 +1,87 @@
"""EvalSource: trigger-driven, finite-per-epoch pull of eval examples.
The orchestrator pokes ``trigger(step)`` after each ship + once at
startup; the dispatcher pulls via ``next_example(available_permits)``
until ``bool(source) == False``. Constructed only when eval is
configured."""
from __future__ import annotations
from collections import deque
from itertools import zip_longest
from prime_rl.configs.orchestrator import EvalConfig
from prime_rl.orchestrator.envs import EvalEnvs
class EvalSource:
"""Finite-per-epoch source of eval examples."""
def __init__(
self,
eval_envs: EvalEnvs,
eval_config: EvalConfig,
*,
is_resumed: bool = False,
) -> None:
self.eval_envs = eval_envs
self.eval_config = eval_config
self.examples_by_env: dict[str, list[dict]] = {}
self.intervals: dict[str, int] = {}
for env in eval_envs:
rows: list[dict] = []
for ex in env.examples:
row = dict(ex)
row["env_name"] = env.name
rows.append(row)
self.examples_by_env[env.name] = rows
self.intervals[env.name] = env.config.interval
self.queue: deque[dict] = deque()
# On resume we skip the startup eval; on fresh start the first
# trigger fires every env (subject to ``skip_first_step``)
self.first_trigger = not is_resumed
def trigger(self, step: int) -> list[str]:
"""Fire eligible envs for ``step`` and return their names. On resume
``first_trigger`` is False, so the startup/base eval doesn't re-run."""
is_first, self.first_trigger = self.first_trigger, False
if is_first and self.eval_config.skip_first_step:
return []
fired: list[str] = []
for name, interval in self.intervals.items():
if is_first or step % interval == 0:
fired.append(name)
# Round-robin across fired envs (A₁, B₁, A₂, B₂, …) so the
# dispatcher rotates at example granularity. ``try_schedule``'s
# continue-group branch still keeps each example's group_size
# rollouts back-to-back, so per-example prefix-cache locality holds
iters = [iter(self.examples_by_env[name]) for name in fired]
for round_examples in zip_longest(*iters):
for example in round_examples:
if example is None:
continue
row = dict(example)
row["eval_step"] = step
self.queue.append(row)
return fired
def next_example(self, available_permits: int) -> dict | None:
"""Pop the next eval example if the head's permit cost fits in
``available_permits``; otherwise leave it for a later call."""
if not self.queue:
return None
head = self.queue[0]
env = self.eval_envs.get(head["env_name"])
cost = env.config.group_size if env.requires_group_scoring else 1
if cost > available_permits:
return None
return self.queue.popleft()
def __bool__(self) -> bool:
return bool(self.queue)
def __len__(self) -> int:
return len(self.queue)
@@ -1,83 +0,0 @@
import asyncio
from time import perf_counter
import numpy as np
from prime_rl.utils.logger import get_logger
class EventLoopLagMonitor:
"""A class to monitor how busy the main event loop is."""
def __init__(
self,
interval: float = 0.1,
max_window_size: int = 10000,
warn_p90_lag_threshold: float = 1.0,
warn_p99_lag_threshold: float = 5.0,
warn_max_lag_threshold: float = 30.0,
):
assert (
interval > 0
and max_window_size > 0
and warn_p90_lag_threshold > 0
and warn_p99_lag_threshold > 0
and warn_max_lag_threshold > 0
)
self.interval = interval
self.max_window_size = max_window_size
self.warn_p90_lag_threshold = warn_p90_lag_threshold
self.warn_p99_lag_threshold = warn_p99_lag_threshold
self.warn_max_lag_threshold = warn_max_lag_threshold
self.logger = get_logger()
self.lags = []
async def measure_lag(self):
"""Measures event loop lag by asynchronously sleeping for interval seconds"""
next_time = perf_counter() + self.interval
await asyncio.sleep(self.interval)
now = perf_counter()
lag = now - next_time
return lag
async def run(self):
"""Infinite loop to periodically measure event loop lag. Should be started as background task."""
while True:
lag = await self.measure_lag()
self.lags.append(lag)
if len(self.lags) > self.max_window_size:
self.lags.pop(0)
def reset(self):
"""Reset the list of measured lags."""
self.lags = []
def get_metrics(self) -> dict[str, float]:
"""Compute metrics for the event loop lag over the last window_size measurements."""
window_size = int(min(self.max_window_size, len(self.lags)))
if window_size <= 0:
return {}
last_lags = np.array(self.lags[-window_size:])
mean_lag = float(np.mean(last_lags))
med_lag = float(np.median(last_lags))
p90_lag = float(np.percentile(last_lags, 90))
p99_lag = float(np.percentile(last_lags, 99))
min_lag = float(np.min(last_lags))
max_lag = float(np.max(last_lags))
if (
p90_lag > self.warn_p90_lag_threshold
or p99_lag > self.warn_p99_lag_threshold
or max_lag > self.warn_max_lag_threshold
):
self.logger.warning(
f"Detected busy event loop. Measured {mean_lag:.1f}s (min={min_lag:.1f}s, med={med_lag:.1f}s, p90={p90_lag:.1f}s, p99={p99_lag:.1f}s, max={max_lag:.1f}s) event loop lag over the last {len(last_lags)} measurement(s)"
)
return {
"event_loop_lag/min": min_lag,
"event_loop_lag/mean": mean_lag,
"event_loop_lag/med": med_lag,
"event_loop_lag/p90": p90_lag,
"event_loop_lag/p99": p99_lag,
"event_loop_lag/max": max_lag,
}
+28 -43
View File
@@ -6,15 +6,18 @@ When enforce=True, detected rollouts are skipped entirely during training and
are not sent to the trainer. Reward is kept as-is for baseline calculation.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Protocol
import verifiers as vf
from typing import TYPE_CHECKING, Protocol
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
@dataclass
class FilterResult:
@@ -26,7 +29,7 @@ class RolloutFilter(Protocol):
name: str
enforce: bool
def check(self, rollout: vf.RolloutOutput) -> FilterResult: ...
def check(self, rollout: "TrainRollout") -> FilterResult: ...
@dataclass
@@ -46,9 +49,9 @@ class GibberishFilter:
logprob_threshold: float
enforce: bool = False
def check(self, rollout: vf.RolloutOutput) -> FilterResult:
def check(self, rollout: "TrainRollout") -> FilterResult:
global_idx = 0
for step in rollout["trajectory"]:
for step in rollout.raw["trajectory"]:
tokens = step["tokens"]
if tokens is None:
continue
@@ -76,10 +79,10 @@ class RepetitionFilter:
logprob_threshold: float
enforce: bool = False
def check(self, rollout: vf.RolloutOutput) -> FilterResult:
def check(self, rollout: "TrainRollout") -> FilterResult:
consecutive = 0
global_idx = 0
for step in rollout["trajectory"]:
for step in rollout.raw["trajectory"]:
tokens = step["tokens"]
if tokens is None:
continue
@@ -96,18 +99,14 @@ class RepetitionFilter:
@dataclass
class ZeroAdvantageFilter:
"""Flags rollouts with zero advantage.
This filter is applied after advantages are computed and checks if the
rollout's advantage field is zero.
"""
"""Flags rollouts whose computed advantage is zero (e.g. all rollouts in a
GRPO group earned the same reward, so the centered advantage collapses)."""
name: str
enforce: bool = True
def check(self, rollout: vf.RolloutOutput) -> FilterResult:
advantage = rollout.get("advantage")
if advantage is not None and advantage == 0.0:
def check(self, rollout: "TrainRollout") -> FilterResult:
if rollout.advantage is not None and rollout.advantage == 0.0:
return FilterResult(detected=True)
return FilterResult(detected=False)
@@ -136,11 +135,11 @@ def setup_filter(config: FilterConfig, vocab_size: int) -> RolloutFilter:
raise ValueError(f"Unknown filter type: {config.type}")
def setup_filters(configs: list[FilterConfig], vocab_size: int) -> list[RolloutFilter]:
def setup_filters(configs: list[FilterConfig], vocab_size: int, *, kind: str) -> list[RolloutFilter]:
"""Create RolloutFilters from a list of filter configs."""
filters = [setup_filter(config, vocab_size) for config in configs]
if filters:
get_logger().info(f"Configured {len(filters)} rollout filter(s):")
get_logger().info(f"Configured {len(filters)} {kind} rollout filter(s):")
for config, filt in zip(configs, filters):
mode = "Enforcing" if filt.enforce else "Monitoring"
params = ", ".join(f"{k}={v}" for k, v in config.model_dump().items())
@@ -148,41 +147,27 @@ def setup_filters(configs: list[FilterConfig], vocab_size: int) -> list[RolloutF
return filters
def apply_filters(filters: list[RolloutFilter], rollouts: list[vf.RolloutOutput]) -> None:
"""Flag rollouts in-place with per-filter detection and drop decision.
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.
Each rollout gets a `filters` dict with per-filter detection booleans and
an `is_filtered` bool that is True iff an enforcing filter detected it.
First matching filter wins per rollout (no double-counting). Reward and
trajectory tokens are left untouched so the rollout can still contribute
to baseline calculations and metric aggregation.
Each rollout's ``filter_results`` dict records per-filter detection bools;
``is_filtered`` is True iff an enforcing filter detected it. First matching
filter wins per rollout (no double-counting). Reward and trajectory tokens
are left untouched so the rollout can still contribute to baseline
calculations and metric aggregation.
"""
for rollout in rollouts:
rollout["filters"] = {f.name: False for f in filters}
rollout["is_filtered"] = False
rollout.filter_results = {f.name: False for f in filters}
rollout.is_filtered = False
if not filters:
return
counts: dict[str, int] = {f.name: 0 for f in filters}
total_detected = 0
total_enforced = 0
for rollout in rollouts:
for filt in filters:
result = filt.check(rollout)
if result.detected:
counts[filt.name] += 1
total_detected += 1
rollout["filters"][filt.name] = True
rollout.filter_results[filt.name] = True
if filt.enforce:
rollout["is_filtered"] = True
total_enforced += 1
rollout.is_filtered = True
break
if total_detected > 0:
enforced_msg = f", enforced {total_enforced}" if total_enforced > 0 else ""
get_logger().info(
f"Detected {total_detected}/{len(rollouts)} rollouts "
f"({', '.join(f'{name}={c}' for name, c in counts.items() if c > 0)})" + enforced_msg
)
@@ -392,7 +392,6 @@ class InferenceMetricsCollector:
def __init__(self, admin_clients: list[AsyncClient], roles: list[str | None] | None = None):
self.endpoints = build_metrics_endpoints(admin_clients, roles=roles)
self.logger = get_logger()
self.metric_history: dict[str, deque[float]] = {}
self.previous: dict[str, TimedRollup] = {}
self.task: asyncio.Task | None = None
@@ -406,7 +405,7 @@ class InferenceMetricsCollector:
try:
await self.collect_and_log()
except Exception as e:
self.logger.debug(f"Inference metrics poll failed: {e!r}")
get_logger().debug(f"Inference metrics poll failed: {e!r}")
await asyncio.sleep(POLL_INTERVAL)
self.task = asyncio.create_task(poll_loop())
@@ -420,7 +419,7 @@ class InferenceMetricsCollector:
response.raise_for_status()
return response.text
except Exception as e:
self.logger.debug(f"Failed to fetch metrics from {endpoint.client.base_url}: {e!r}")
get_logger().debug(f"Failed to fetch metrics from {endpoint.client.base_url}: {e!r}")
return None
results = await asyncio.gather(*[fetch(endpoint) for endpoint in self.endpoints])
+199
View File
@@ -0,0 +1,199 @@
"""MetricsBuilder: assembles the per-step W&B dict. No I/O, no side effects."""
from __future__ import annotations
from typing import Any
import pandas as pd
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.types import Progress, TrainBatchMetrics, TrainRollout
class MetricsBuilder:
def __init__(self, config: OrchestratorConfig) -> None:
self.config = config
def build(
self,
*,
step: int,
rollouts: list[TrainRollout],
metrics: TrainBatchMetrics,
progress: Progress,
step_time: float,
save_ckpt_time: float,
teacher_logprobs_time: float,
pre_filter_seen: int,
pre_filter_dropped: int,
pre_filter_dropped_by_name: dict[str, int],
) -> dict[str, Any]:
"""Builds the per-step W&B dict. Stable metric names so
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
)
results_df = pd.DataFrame(
{
"group_id": [r.group_id for r in rollouts],
"example_id": [r.example_id 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
],
"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],
}
)
metrics_df = pd.DataFrame([(r.raw.get("metrics") or {}) for r in rollouts])
filter_df = pd.DataFrame([r.filter_results for r in rollouts])
timing_df = self.timing_df(rollouts)
# Each group's full-solve threshold is its own env's group_size (envs
# can override the top-level group_size).
env_group_size = {env.resolved_name: env.group_size for env in self.config.train.env}
def compute_solve_rates(df):
grouped = df.groupby("group_id")
reward_per_problem = grouped.reward.sum()
solve_none = (reward_per_problem == 0).mean()
expected = grouped.env_name.first().map(env_group_size)
solve_all = (reward_per_problem == expected).mean()
return solve_none, solve_all, 1 - solve_none - solve_all
by_example = results_df.groupby("group_id")
solve_none, solve_all, effective_batch_size = compute_solve_rates(results_df)
to_log: dict[str, Any] = {
"progress/tokens": num_tokens,
"progress/prefill_tokens": metrics.num_prefill_tokens,
"progress/decode_tokens": metrics.num_decode_tokens,
"progress/samples": num_rollouts,
"progress/problems": num_unique_examples,
"progress/total_tokens": progress.total_tokens,
"progress/total_samples": progress.total_samples,
"progress/total_problems": progress.total_problems,
"seq_len/all/mean": by_example.seq_len.mean().mean(),
"seq_len/all/max": by_example.seq_len.mean().max(),
"seq_len/all/min": by_example.seq_len.mean().min(),
"prefill_len/all/mean": by_example.prefill_len.mean().mean(),
"prefill_len/all/max": by_example.prefill_len.mean().max(),
"prefill_len/all/min": by_example.prefill_len.mean().min(),
"decode_len/all/mean": by_example.decode_len.mean().mean(),
"decode_len/all/max": by_example.decode_len.mean().max(),
"decode_len/all/min": by_example.decode_len.mean().min(),
"is_truncated/all/mean": by_example.is_truncated.mean().mean(),
"is_truncated/all/max": by_example.is_truncated.mean().max(),
"stop_condition/all/generation_truncated": (
results_df.is_truncated & (results_df.stop_condition != "prompt_too_long")
).mean(),
**{
f"stop_condition/all/{sc}": rate
for sc, rate in results_df.stop_condition.dropna().value_counts(normalize=True).items()
},
"samples_per_rollout/all/mean": by_example.samples_per_rollout.mean().mean(),
"samples_per_rollout/all/max": by_example.samples_per_rollout.mean().max(),
"samples_per_rollout/all/min": by_example.samples_per_rollout.mean().min(),
"num_turns/all/mean": by_example.num_turns.mean().mean(),
"num_turns/all/max": by_example.num_turns.mean().max(),
"num_turns/all/min": by_example.num_turns.mean().min(),
**{
f"timing/all/{key}/{stat}": getattr(
timing_df[key].groupby(results_df.group_id).mean(),
stat,
)()
for key in timing_df.columns
for stat in ("mean", "max", "min")
},
"reward/all/mean": by_example.reward.mean().mean(),
"reward/all/max": by_example.reward.mean().max(),
"reward/all/min": by_example.reward.mean().min(),
"solve_none/all": solve_none,
"solve_all/all": solve_all,
"effective_batch_size/all": effective_batch_size,
**{f"batch/{env}": r for env, r in results_df.env_name.value_counts(normalize=True).items()},
"time/step": step_time,
"time/teacher_logprobs": teacher_logprobs_time,
"time/save_ckpt": save_ckpt_time,
"filters/all/is_filtered": results_df.is_filtered.astype(float).mean(),
**{f"filters/all/{name}": filter_df[name].astype(float).mean() for name in filter_df.columns},
"step": step,
}
# Per-env metrics
per_env_columns = [
"seq_len",
"prefill_len",
"decode_len",
"is_truncated",
"samples_per_rollout",
"num_turns",
]
for env, env_df in results_df.groupby("env_name"):
env_by_example = env_df.groupby("group_id")
for col in per_env_columns:
to_log[f"{col}/{env}/mean"] = env_by_example[col].mean().mean()
to_log[f"{col}/{env}/max"] = env_by_example[col].mean().max()
if col != "is_truncated":
to_log[f"{col}/{env}/min"] = env_by_example[col].mean().min()
env_timing_df = timing_df.loc[env_df.index]
for key in timing_df.columns:
per_example = env_timing_df.groupby(env_df["group_id"])[key].mean()
to_log[f"timing/{env}/{key}/mean"] = per_example.mean()
to_log[f"timing/{env}/{key}/max"] = per_example.max()
to_log[f"timing/{env}/{key}/min"] = per_example.min()
to_log[f"reward/{env}/mean"] = env_by_example.reward.mean().mean()
to_log[f"reward/{env}/max"] = env_by_example.reward.mean().max()
to_log[f"reward/{env}/min"] = env_by_example.reward.mean().min()
sn, sa, eb = compute_solve_rates(env_df)
to_log[f"solve_none/{env}"] = sn
to_log[f"solve_all/{env}"] = sa
to_log[f"effective_batch_size/{env}"] = eb
to_log[f"stop_condition/{env}/generation_truncated"] = (
env_df.is_truncated & (env_df.stop_condition != "prompt_too_long")
).mean()
for sc, rate in env_df.stop_condition.dropna().value_counts(normalize=True).items():
to_log[f"stop_condition/{env}/{sc}"] = rate
env_metrics_df = metrics_df.loc[env_df.index] if not metrics_df.empty else metrics_df
for metric in metrics_df.columns:
to_log[f"metrics/{env}/{metric}"] = env_metrics_df.groupby(env_df["group_id"])[metric].mean().mean()
to_log[f"filters/{env}/is_filtered"] = env_df.is_filtered.astype(float).mean()
env_filter_df = filter_df.loc[env_df.index] if not filter_df.empty else filter_df
for name in filter_df.columns:
to_log[f"filters/{env}/{name}"] = env_filter_df[name].astype(float).mean()
# Dispatcher / watcher gauges live on the ``_timestamp`` axis via
# the periodic logger — keep this dict step-axis only
if pre_filter_seen > 0:
to_log["pre_filters/all/dropped_rate"] = pre_filter_dropped / pre_filter_seen
for name, count in pre_filter_dropped_by_name.items():
to_log[f"pre_filters/all/{name}/rate"] = count / pre_filter_seen
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
]
)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,64 @@
"""PeriodicLogger: orchestrator's pipeline view, fires every ``interval``
seconds. ``collect()`` returns ``(console_body, wandb_payload)`` in one
call so drain-on-read counters fire exactly once per tick. Wandb writes
land on the ``_timestamp`` axis."""
from __future__ import annotations
import asyncio
import time
from typing import Callable
import wandb
from prime_rl.utils.async_utils import safe_cancel
from prime_rl.utils.logger import get_logger
class PeriodicLogger:
def __init__(
self,
*,
name: str,
collect: Callable[[], tuple[str, dict[str, float]]],
metric_keys: list[str],
interval: float,
wandb_enabled: bool,
) -> None:
self.name = name
self.collect = collect
self.interval = interval
self.wandb_enabled = wandb_enabled
self.task: asyncio.Task | None = None
self.stopped = asyncio.Event()
if self.wandb_enabled:
for key in metric_keys:
wandb.define_metric(key, step_metric="_timestamp")
async def start(self) -> None:
self.task = asyncio.create_task(self.run(), name=f"{self.name}_periodic_logger")
async def run(self) -> None:
try:
while not self.stopped.is_set():
try:
await asyncio.wait_for(self.stopped.wait(), timeout=self.interval)
except asyncio.TimeoutError:
pass
self.emit()
except asyncio.CancelledError:
return
def emit(self) -> None:
body, payload = self.collect()
get_logger().info(body)
if self.wandb_enabled and payload:
payload["_timestamp"] = time.time()
wandb.log(payload)
async def stop(self) -> None:
self.stopped.set()
if self.task is not None:
await safe_cancel(self.task)
self.task = None
-591
View File
@@ -1,591 +0,0 @@
from __future__ import annotations
import asyncio
import time
from collections import Counter, defaultdict
from dataclasses import dataclass, field
import verifiers as vf
from aiolimiter import AsyncLimiter
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.buffer import Buffer
from prime_rl.orchestrator.envs import TrainEnvs
from prime_rl.orchestrator.vf_utils import get_seq_len
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import ProgressTracker, get_logger
from prime_rl.utils.utils import (
get_broadcast_dir,
get_latest_ckpt_step,
get_step_path,
wait_for_path,
)
@dataclass
class InflightRequest:
"""Metadata for an in-flight request."""
off_policy_steps: int
client_config: vf.ClientConfig
env_name: str
group_id: int | None = None
rollout_count: int = 1
@dataclass
class GroupState:
"""Tracks the state of a rollout group (one example × N rollouts)."""
example: dict
rollouts_to_schedule: int
completed_rollouts: list[vf.RolloutOutput] = field(default_factory=list)
pinned_client: vf.ClientConfig | None = None
failed_rollouts: int = 0
class Scheduler:
"""
Asynchronously manages scheduling of rollout requests and policy updates.
Keeps a constant number of rollouts in-flight (continuous batching) and
updates the policy as soon as it becomes available.
References:
- AReal: https://arxiv.org/abs/2505.24298v1
- PipelineRL: https://arxiv.org/abs/2509.19128v1
"""
def __init__(
self,
train_envs: TrainEnvs,
student_inference: InferencePool,
teacher_inference: InferencePool | None,
buffer: Buffer,
config: OrchestratorConfig,
max_inflight_rollouts: int,
max_off_policy_steps: int,
tasks_per_minute: int | None,
lora_name: str | None = None,
):
self.logger = get_logger()
if tasks_per_minute is not None:
self.rate_limiter = AsyncLimiter(max_rate=tasks_per_minute, time_period=60)
else:
self.rate_limiter = None
self.train_envs = train_envs
self.buffer = buffer
self.config = config
self.batch_size = config.batch_size
self.token_batch_size = config.token_batch_size
self.group_size = config.group_size
self.max_inflight_rollouts = max_inflight_rollouts
self.max_off_policy_steps = max_off_policy_steps
self.lora_name = lora_name
self.json_logging = config.log.json_logging
# student_inference is the weight-sync target. teacher_inference is set
# in opd (for logprobs) and sft (for rollouts). rollout_inference is
# whichever pool serves train rollouts for this mode.
self.student_inference = student_inference
self.teacher_inference = teacher_inference
if config.training_mode == "sft":
assert teacher_inference is not None
self.rollout_inference = teacher_inference
else:
self.rollout_inference = student_inference
# model_name is the name to send on rollout requests - matches the rollout pool
self.model_name = self.rollout_inference.model_name
group_scoring_envs = [env.name for env in train_envs if env.requires_group_scoring]
if group_scoring_envs:
self.logger.info(f"Group rollout scoring active for env(s): {', '.join(group_scoring_envs)}")
# Track in-flight requests: task -> info
self.inflight_requests: dict[asyncio.Task, InflightRequest] = {}
# Track in-progress groups while rollouts are generated independently.
self.next_group_id = 0
self.groups: dict[int, GroupState] = {}
self.step, self.ckpt_step = 0, 0
self.checkpoint_ready = asyncio.Event()
self.checkpoint_ready.set()
self.update_weights_time, self.wait_for_ckpt_time = 0, 0
self.update_policy_task: asyncio.Task | None = None
self.inflight_policy_update_task: asyncio.Task | None = None
self.policy_update_lock = asyncio.Lock()
self.cancelled_rollouts_count = 0
self.empty_rollouts_by_env: dict[str, int] = defaultdict(int)
self.errored_rollouts_by_env: dict[str, int] = defaultdict(int)
self.errors_by_type: dict[str, int] = defaultdict(int)
self.total_rollouts_by_env: dict[str, int] = defaultdict(int)
self.dropped_groups_by_env: dict[str, int] = defaultdict(int)
self.last_batch_generation_time = 0.0
@property
def uses_token_batching(self) -> bool:
return self.token_batch_size is not None
@property
def batch_target(self) -> int:
if self.uses_token_batching:
assert self.token_batch_size is not None
return self.token_batch_size
assert self.batch_size is not None
return self.batch_size
def get_batch_progress_increment(self, rollouts: list[vf.RolloutOutput]) -> int:
if self.uses_token_batching:
return sum(get_seq_len(rollout) for rollout in rollouts)
return len(rollouts)
def finalize_batch_rollouts(self, rollouts: list[vf.RolloutOutput]) -> list[vf.RolloutOutput]:
if self.batch_size is None:
return rollouts
return rollouts[: self.batch_size]
async def cancel_inflight_rollouts(self):
"""Cancel all in-flight rollout requests."""
count = sum(info.rollout_count for info in self.inflight_requests.values())
await safe_cancel_all(list(self.inflight_requests))
self.inflight_requests.clear()
self.groups.clear()
self.cancelled_rollouts_count += count
@staticmethod
def _client_identity(c: vf.ClientConfig) -> tuple[str, str | None]:
return (
c.api_base_url,
c.extra_headers.get("X-data-parallel-rank"),
)
async def _select_least_loaded_client(self) -> vf.ClientConfig:
"""Select the client with the fewest in-flight tasks.
Uses (api_base_url, dp_rank) as identity rather than client_idx so that
load tracking survives elastic pool refreshes (which reassign indices).
"""
clients = self.rollout_inference.train_clients
while not clients:
await asyncio.sleep(1)
clients = self.rollout_inference.train_clients
inflight = Counter(self._client_identity(info.client_config) for info in self.inflight_requests.values())
return min(clients, key=lambda c: inflight[self._client_identity(c)])
async def drop_group(self, group_id: int) -> int:
"""Drop a group and cancel any remaining in-flight rollouts for it. Returns the number of cancelled rollouts."""
tasks_to_cancel = []
rollout_count = 0
for task, info in list(self.inflight_requests.items()):
if info.group_id != group_id:
continue
self.inflight_requests.pop(task, None)
tasks_to_cancel.append(task)
rollout_count += info.rollout_count
self.groups.pop(group_id, None)
await safe_cancel_all(tasks_to_cancel)
return rollout_count
async def schedule_rollout(self, group_id: int):
"""Asynchronously schedules a rollout request (or a group request for group-scoring envs)."""
if self.rate_limiter:
await self.rate_limiter.acquire()
group = self.groups.get(group_id)
if group is None or group.rollouts_to_schedule <= 0:
return
if group.pinned_client is not None:
client_config = group.pinned_client
else:
client_config = await self._select_least_loaded_client()
if group_id not in self.groups:
return
group.pinned_client = client_config
env_name = group.example["env_name"]
env = self.train_envs.get(env_name)
cache_salt = str(self.ckpt_step)
if env.requires_group_scoring:
rollout_count = group.rollouts_to_schedule
group.rollouts_to_schedule = 0
task = asyncio.create_task(
env.run_group(
client=client_config,
example=group.example,
model_name=self.model_name,
group_size=rollout_count,
cache_salt=cache_salt,
)
)
else:
rollout_count = 1
group.rollouts_to_schedule -= 1
task = asyncio.create_task(
env.run_rollout(
client=client_config,
example=group.example,
model_name=self.model_name,
cache_salt=cache_salt,
)
)
self.inflight_requests[task] = InflightRequest(
off_policy_steps=0,
client_config=client_config,
env_name=env_name,
group_id=group_id,
rollout_count=rollout_count,
)
@property
def inflight_rollout_count(self) -> int:
return sum(info.rollout_count for info in self.inflight_requests.values())
@property
def inflight_sample_count(self) -> int:
pending = sum(g.rollouts_to_schedule for g in self.groups.values())
return self.inflight_rollout_count + pending
async def _schedule_next_request(self) -> bool:
remaining_capacity = self.max_inflight_rollouts - self.inflight_rollout_count
if remaining_capacity <= 0:
return False
for group_id, group in self.groups.items():
if group.rollouts_to_schedule <= 0:
continue
env = self.train_envs.get(group.example["env_name"])
cost = group.rollouts_to_schedule if env.requires_group_scoring else 1
if cost <= remaining_capacity:
await self.schedule_rollout(group_id=group_id)
return True
if remaining_capacity < self.group_size:
return False
example = self.buffer.sample_examples(n=1)[0]
group_id = self.next_group_id
self.next_group_id += 1
self.groups[group_id] = GroupState(example=example, rollouts_to_schedule=self.group_size)
await self.schedule_rollout(group_id=group_id)
return True
async def _fill_inflight_requests(self) -> None:
while await self._schedule_next_request():
pass
async def update_policy_loop(self):
"""Continuously checks for new policy checkpoints."""
while True:
await self.maybe_update_policy()
await asyncio.sleep(1)
def _compute_next_ckpt_step(self) -> int:
# The orchestrator always runs one step ahead of the trainer, so we must advance to at
# least step - 1. We additionally adopt anything fresher the trainer has already
# broadcast (so a fast trainer briefly running on-policy is fine). ``latest_ckpt_step``
# is non-negative so it also clamps a self.step == 0 startup.
latest_ckpt_step = get_latest_ckpt_step(get_broadcast_dir(self.config.output_dir)) or 0
return max(self.step - 1, latest_ckpt_step)
async def _apply_policy_update(self, next_ckpt_step: int) -> None:
# If we're advancing to step - 1, the trainer hasn't broadcast it yet (otherwise
# we would've picked something newer); block until the file lands.
if next_ckpt_step == max(self.step - 1, 0):
self.logger.info(
f"Orchestrator paused: waiting for trainer to broadcast checkpoint {next_ckpt_step} "
f"(orchestrator is one step ahead). Training is progressing normally."
)
self.checkpoint_ready.clear()
wait_for_ckpt_start_time = time.perf_counter()
await wait_for_path(get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step) / "STABLE")
self.wait_for_ckpt_time = time.perf_counter() - wait_for_ckpt_start_time
self.logger.info(
f"Orchestrator resumed: checkpoint {next_ckpt_step} ready (after {self.wait_for_ckpt_time:.2f}s)"
)
self.logger.debug(
f"Got new policy with step {next_ckpt_step}. Updating weights and cancelling old rollout requests."
)
update_weights_start_time = time.perf_counter()
weights_path = get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step)
await self.student_inference.update_weights(weights_path, lora_name=self.lora_name, step=next_ckpt_step)
self.update_weights_time = time.perf_counter() - update_weights_start_time
self.logger.debug(f"Updated weights to step {next_ckpt_step} in {self.update_weights_time:.2f}s")
self.ckpt_step = next_ckpt_step
if self.lora_name is not None:
self.student_inference.update_model_name(self.lora_name)
# Only redirect rollout requests to the new LoRA when rollouts come from
# student inference (rl/opd). In sft, rollouts go to the teacher and
# the student's LoRA name is irrelevant to them.
if self.rollout_inference is self.student_inference:
self.model_name = self.lora_name
self.checkpoint_ready.set()
await self._update_off_policy()
async def _get_or_start_policy_update_task(self, next_ckpt_step: int) -> asyncio.Task:
async with self.policy_update_lock:
task = self.inflight_policy_update_task
if task is not None and not task.done():
return task
task = asyncio.create_task(self._apply_policy_update(next_ckpt_step))
self.inflight_policy_update_task = task
def _clear_inflight_policy_update(done_task: asyncio.Task) -> None:
if self.inflight_policy_update_task is done_task:
self.inflight_policy_update_task = None
task.add_done_callback(_clear_inflight_policy_update)
return task
async def maybe_update_policy(self):
"""Updates the policy to the latest available checkpoint. Aborts rollout requests that are older than the max retention steps."""
while True:
next_ckpt_step = self._compute_next_ckpt_step()
if next_ckpt_step <= self.ckpt_step:
return
task = await self._get_or_start_policy_update_task(next_ckpt_step)
await asyncio.shield(task)
async def _update_off_policy(self) -> None:
stale_group_ids = {
info.group_id
for info in self.inflight_requests.values()
if info.group_id is not None and info.off_policy_steps >= self.max_off_policy_steps
}
tasks_to_increment = [
task
for task, info in list(self.inflight_requests.items())
if info.group_id is None or info.group_id not in stale_group_ids
]
counts = await asyncio.gather(*(self.drop_group(gid) for gid in stale_group_ids))
removed = sum(counts)
for task in tasks_to_increment:
info = self.inflight_requests.get(task)
if info is None:
continue
info.off_policy_steps += 1
self.cancelled_rollouts_count += removed
if removed:
self.logger.warning(
f"Cancelled {removed} old rollout requests (will refill naturally). "
f"Consider increasing max_off_policy_steps to avoid this."
)
async def generate_batch(self, step: int) -> list[vf.RolloutOutput]:
"""Continuously generates a batch of rollouts."""
self.step = step
# Cancel the previous update policy task to avoid concurrent updates
if self.update_policy_task is not None:
await safe_cancel(self.update_policy_task)
# Manually check the async barrier before starting the step, then re-create the update policy loop
# This ensures the orchestrator stays at most one step ahead of the trainer, while still
# listening for policy updates mid-step.
await self.maybe_update_policy()
self.update_policy_task = asyncio.create_task(self.update_policy_loop())
batch_start_time = time.perf_counter()
self.logger.debug("Starting to generate batch rollouts")
batch_rollouts: list[vf.RolloutOutput] = []
batch_progress = 0
pbar = ProgressTracker(
total=self.batch_target, desc="Generating rollouts (train)", json_logging=self.json_logging, step=step
)
while batch_progress < self.batch_target:
await self._fill_inflight_requests()
inflight_tasks = list(self.inflight_requests.keys())
finished_tasks, _ = await asyncio.wait(
inflight_tasks,
return_when=asyncio.FIRST_COMPLETED,
)
await self.checkpoint_ready.wait()
for finished_task in finished_tasks:
if batch_progress >= self.batch_target:
break
rollout_info = self.inflight_requests.pop(finished_task, None)
if rollout_info is None:
continue
group_id = rollout_info.group_id
env_name = rollout_info.env_name
try:
group = self.groups.get(group_id)
if group is None:
continue
result = finished_task.result()
rollouts: list[vf.RolloutOutput] = result if isinstance(result, list) else [result]
self.total_rollouts_by_env[env_name] += len(rollouts)
# Partition rollouts into valid vs failed and tally per-rollout
# error metrics. Tally every failure (group-scoring envs return
# N rollouts per task) so error-rate metrics aren't deflated.
env = self.train_envs.get(env_name)
valid_rollouts: list[vf.RolloutOutput] = []
for rollout in rollouts:
if rollout["error"] is not None:
self.errored_rollouts_by_env[env_name] += 1
self.errors_by_type[rollout["error"]["error"]] += 1
self.logger.warning(
f"Rollout failed in group {group_id} ({env_name}) - "
f"{rollout['error']['error_chain_repr']}"
)
elif len(rollout["trajectory"]) == 0:
self.empty_rollouts_by_env[env_name] += 1
self.logger.warning(f"Empty trajectory in group {group_id} ({env_name})")
else:
rollout["env_name"] = env_name
valid_rollouts.append(rollout)
num_failed = len(rollouts) - len(valid_rollouts)
group.failed_rollouts += num_failed
# Group-scoring envs compute scores over all N rollouts
# together; the surviving rollouts carry scores computed against
# the (now-missing) failed ones, so partial salvage is unsafe.
# Drop the whole group on any failure.
if num_failed > 0 and env.requires_group_scoring:
self.dropped_groups_by_env[env_name] += 1
self.logger.warning(
f"Dropping group-scored group {group_id} ({env_name}) after rollout failure"
)
await self.drop_group(group_id)
continue
group.completed_rollouts.extend(valid_rollouts)
# Wait until every dispatched rollout has come back (succeeded
# or failed) before finalizing. The group may finalize as a
# partial group (< group_size) when some rollouts
# errored - downstream advantage computation groups by
# (env_name, example_id), so variable-size groups are fine.
if len(group.completed_rollouts) + group.failed_rollouts < self.group_size:
continue
if not group.completed_rollouts:
self.dropped_groups_by_env[env_name] += 1
self.logger.warning(
f"Dropping group {group_id} ({env_name}) - all {self.group_size} rollouts failed"
)
self.groups.pop(group_id, None)
continue
if group.failed_rollouts > 0:
self.logger.warning(
f"Partial group {group_id} ({env_name}) - "
f"{len(group.completed_rollouts)}/{self.group_size} valid "
f"({group.failed_rollouts} failed)"
)
completed_rollouts = self.groups.pop(group_id).completed_rollouts
except asyncio.CancelledError:
if group_id is not None:
await self.drop_group(group_id)
continue
except Exception as e:
self.logger.warning(f"Rollout failed: {e}")
if group_id is not None:
await self.drop_group(group_id)
continue
self.buffer.update(completed_rollouts)
accepted_rollouts = self.buffer.sample_rollouts(n=len(completed_rollouts))
batch_rollouts.extend(accepted_rollouts)
progress_increment = self.get_batch_progress_increment(accepted_rollouts)
batch_progress += progress_increment
pbar.update(progress_increment)
await self._fill_inflight_requests()
batch_rollouts = self.finalize_batch_rollouts(batch_rollouts)
pbar.close()
self.last_batch_generation_time = time.perf_counter() - batch_start_time
return batch_rollouts
async def stop(self) -> None:
await self.cancel_inflight_rollouts()
if self.update_policy_task is not None:
await safe_cancel(self.update_policy_task)
self.update_policy_task = None
if self.inflight_policy_update_task is not None:
await safe_cancel(self.inflight_policy_update_task)
self.inflight_policy_update_task = None
@property
def max_off_policy_level(self) -> int:
steps = [info.off_policy_steps for info in self.inflight_requests.values()]
if not steps:
return 0
return max(steps)
@property
def mean_off_policy_level(self) -> float:
steps = [info.off_policy_steps for info in self.inflight_requests.values()]
if not steps:
return 0
return sum(steps) / len(steps)
@property
def async_level(self) -> int:
return self.step - self.ckpt_step
def get_metrics(self) -> dict[str, float]:
total_rollouts = sum(self.total_rollouts_by_env.values())
metrics = {
"time/wait_for_ckpt": self.wait_for_ckpt_time,
"time/update_weights": self.update_weights_time,
"scheduler/async_level": self.async_level,
"scheduler/inflight_rollouts": self.inflight_rollout_count,
"scheduler/inflight_samples": self.inflight_sample_count,
"scheduler/cancelled_rollouts": self.cancelled_rollouts_count,
"empty_rollouts/all": sum(self.empty_rollouts_by_env.values()) / max(total_rollouts, 1),
"errored_rollouts/all": sum(self.errored_rollouts_by_env.values()) / max(total_rollouts, 1),
"dropped_groups/all": sum(self.dropped_groups_by_env.values()),
"off_policy_level/all/max": self.max_off_policy_level,
"off_policy_level/all/mean": self.mean_off_policy_level,
}
for env_name in self.total_rollouts_by_env:
env_total = max(self.total_rollouts_by_env[env_name], 1)
metrics[f"empty_rollouts/{env_name}"] = self.empty_rollouts_by_env.get(env_name, 0) / env_total
metrics[f"errored_rollouts/{env_name}"] = self.errored_rollouts_by_env.get(env_name, 0) / env_total
for env_name, count in self.dropped_groups_by_env.items():
metrics[f"dropped_groups/{env_name}"] = count
for error_type, count in self.errors_by_type.items():
metrics[f"error/{error_type}/count"] = count
by_env: dict[str, list[int]] = {}
for info in self.inflight_requests.values():
by_env.setdefault(info.env_name, []).append(info.off_policy_steps)
for env_name, steps in by_env.items():
metrics[f"off_policy_level/{env_name}/max"] = max(steps)
metrics[f"off_policy_level/{env_name}/mean"] = sum(steps) / len(steps)
self.cancelled_rollouts_count = 0
self.empty_rollouts_by_env.clear()
self.errored_rollouts_by_env.clear()
self.errors_by_type.clear()
self.total_rollouts_by_env.clear()
self.dropped_groups_by_env.clear()
# Add train pool metrics (e.g. elastic pool server counts)
metrics.update(self.rollout_inference.get_metrics())
return metrics
+312
View File
@@ -0,0 +1,312 @@
"""TrainSink: three-level rollout sink for the training side.
1. ``process_rollout`` — eager per-rollout tokenization (overlaps with
dispatcher producing more rollouts). Errored rollouts skip this.
2. ``process_group`` — filters errored rollouts, computes advantages over
survivors, runs the pre-batch filter pass.
3. ``process_batch`` — applies post-batch filter annotations and assembles
the trainer-bound ``TrainingSample`` list. Returns a ``TrainBatch``.
``add()`` returns ``TrainBatch | None``. I/O concerns (ship to trainer,
save_rollouts, monitor.log, teacher logprobs) live on the orchestrator.
"""
from __future__ import annotations
import asyncio
import uuid
from collections import defaultdict
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.transport import TrainingSample
from prime_rl.utils.logger import get_logger
class TrainSink:
"""Three-level train sink. Constructed once, fed via ``add(rollout)``."""
def __init__(
self,
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,
pre_filters: list[RolloutFilter],
post_filters: list[RolloutFilter],
) -> None:
assert (batch_size is None) != (token_batch_size is None), (
"Exactly one of batch_size / token_batch_size must be set"
)
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
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
# earlier group is still in flight
self.pending_groups: dict[uuid.UUID, list[TrainRollout]] = defaultdict(list)
self.pending_batch: list[TrainRollout] = []
# Reset by the orchestrator after each ship via ``reset_pre_filter_stats``
self.pre_filter_seen = 0
self.pre_filter_dropped = 0
self.pre_filter_dropped_by_name: dict[str, int] = {}
# Per-env arrival / error counters since the last ship; reset in
# ``process_batch``. Fuel for the per-env success log breakdown
self.arrivals_by_env: dict[str, int] = defaultdict(int)
self.errors_by_env: dict[str, int] = defaultdict(int)
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]]:
"""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]] = []
for rollouts in self.pending_groups.values():
if not rollouts:
continue
env_name = rollouts[0].env_name
if self.train_envs.get(env_name).requires_group_scoring:
continue
out.append(rollouts)
return out
def batch_progress(self) -> tuple[int, int, str]:
"""``(current, target, unit)`` for the train batch — counts only
``pending_batch`` (survivors of finalized groups, queued for the
trainer), so it's an honest 0→target fill. Partial-group arrivals are
reported separately by ``buffered_count()``."""
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"
def buffered_count(self) -> int:
"""Rollouts that have arrived but sit in not-yet-complete groups
(non-group-scoring envs) — buffered in the sink ahead of the batch."""
return sum(len(group) for group in self.in_progress_groups())
def pending_batch_by_env(self) -> dict[str, int]:
"""Per-env breakdown of ``batch_progress()`` (``pending_batch`` only);
values sum to the aggregate."""
counts: dict[str, int] = defaultdict(int)
for r in self.pending_batch:
counts[r.env_name] += 1
return dict(counts)
async def add(self, rollout: TrainRollout) -> 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:
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):
self.process_group(rollout.group_id)
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)
)
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:
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,
env_name=rollout.env_name,
)
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
when ``requires_group_scoring`` and any failed), assign advantages,
run pre-batch filters, append survivors to ``pending_batch``."""
group = self.pending_groups.pop(group_id, [])
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]
num_errored = len(group) - len(survivors)
# Group-scoring envs: any failure makes survivors' rewards unsafe
# (computed relative to the missing ones)
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"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"rollouts={len(group)} (errored={num_errored}) | dropped: all failed"
)
return
assign_advantages(survivors, self.train_envs.get(env_name).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).
temperature = env.sampling_args["temperature"]
for r in survivors:
for sample in r.samples:
sample.advantage = r.advantage
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)
if self.pre_filters:
apply_filters(self.pre_filters, survivors)
filtered_by_name: dict[str, int] = {}
num_filtered = 0
for r in survivors:
self.pre_filter_seen += 1
if r.is_filtered:
self.pre_filter_dropped += 1
num_filtered += 1
for name, hit in r.filter_results.items():
if hit:
self.pre_filter_dropped_by_name[name] = self.pre_filter_dropped_by_name.get(name, 0) + 1
filtered_by_name[name] = filtered_by_name.get(name, 0) + 1
continue
# Reset annotations so the post-batch filter pass starts clean
r.filter_results = {}
r.is_filtered = False
self.pending_batch.append(r)
# Per-group summary. One line per finalized group; per-filter
# detection breakdown lives at debug level in ``apply_filters``
rewards = [r.reward for r in survivors]
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"rollouts={len(group)} (errored={num_errored}, filtered={num_filtered}) | "
f"reward={avg_reward:.4f} | filters: {filter_str}"
)
def process_batch(self) -> TrainBatch:
"""Pop a cohort off ``pending_batch`` (by rollout count when
``batch_size`` is set, by token count when ``token_batch_size`` is
set), apply post-batch filter annotations, and assemble the
trainer-bound ``TrainingSample`` list. Overflow stays for the next
batch."""
if self.batch_size is not None:
cohort = self.pending_batch[: self.batch_size]
self.pending_batch = self.pending_batch[self.batch_size :]
else:
assert self.token_batch_size is not None
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"]
cut = i + 1
if running >= self.token_batch_size:
break
cohort = self.pending_batch[:cut]
self.pending_batch = self.pending_batch[cut:]
if self.post_filters:
apply_filters(self.post_filters, cohort)
# Samples are pre-built by ``process_rollout``; ``process_group``
# already set advantage/reward on each sample
samples: list[TrainingSample] = []
prefill_lens: list[int] = []
decode_lens: list[int] = []
samples_per_rollout: list[int] = []
num_prefill = 0
num_decode = 0
for r in cohort:
samples_per_rollout.append(len(r.samples))
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
decode += sample_decode
prefill += sample_prefill
if not r.is_filtered:
samples.append(sample)
prefill_lens.append(prefill)
decode_lens.append(decode)
num_prefill += prefill
num_decode += decode
n_trainable = sum(1 for r in cohort if not r.is_filtered)
metrics = TrainBatchMetrics(
n_trainable=n_trainable,
num_prefill_tokens=num_prefill,
num_decode_tokens=num_decode,
rollout_prefill_lens=prefill_lens,
rollout_decode_lens=decode_lens,
samples_per_rollout=samples_per_rollout,
samples_shipped=len(samples),
arrivals_by_env=dict(self.arrivals_by_env),
errors_by_env=dict(self.errors_by_env),
)
self.arrivals_by_env.clear()
self.errors_by_env.clear()
return TrainBatch(rollouts=cohort, samples=samples, metrics=metrics)
def reset_pre_filter_stats(self) -> None:
self.pre_filter_seen = 0
self.pre_filter_dropped = 0
self.pre_filter_dropped_by_name.clear()
+59
View File
@@ -0,0 +1,59 @@
"""TrainSource: weighted round-robin across train envs, infinite pull.
Weights default to configured ``ratio`` (when every env sets one) or to
per-env dataset size. ``next_example`` reshuffles on cursor exhaustion."""
from __future__ import annotations
import random
from prime_rl.orchestrator.envs import TrainEnvs
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``."""
def __init__(self, train_envs: TrainEnvs, *, seed: int | None) -> None:
self.rng = random.Random(seed)
self.envs = list(train_envs)
if not self.envs:
raise ValueError("TrainSource needs at least one train env")
self.examples: dict[str, list[dict]] = {}
self.cursors: dict[str, int] = {}
# Group-scoring envs reserve ``group_size`` permits up front;
# 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)
self.rng.shuffle(rows)
self.examples[env.name] = rows
self.cursors[env.name] = 0
self.env_costs[env.name] = env.config.group_size if env.requires_group_scoring else 1
self.env_names = [e.name for e in self.envs]
configured_ratios = [e.config.ratio for e in self.envs]
if all(r is not None for r in configured_ratios):
self.weights: list[float] = [float(r) for r in configured_ratios] # type: ignore[arg-type]
else:
self.weights = [float(len(self.examples[name])) for name in self.env_names]
def next_example(self, available_permits: int) -> dict | None:
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
if self.env_costs[env_name] > available_permits:
return None
rows = self.examples[env_name]
cursor = self.cursors[env_name]
if cursor >= len(rows):
self.rng.shuffle(rows)
cursor = 0
example = rows[cursor]
self.cursors[env_name] = cursor + 1
return example
+4 -6
View File
@@ -204,6 +204,8 @@ def backfill_rollout_tokens(
def interleave_rollout(
output: vf.RolloutOutput,
mm_token_type_ids_mapping: dict[int, int] | None = None,
*,
env_name: str = "",
) -> list[TrainingSample] | None:
"""
Convert vf.RolloutOutput to trainable rollouts by interleaving trajectory steps
@@ -236,8 +238,6 @@ def interleave_rollout(
return None
has_error = output["error"] is not None
# this field should be guaranteed because we set temperature in get_sampling_args
temperature = output["sampling_args"]["temperature"]
def prepare_step_tokens(step: vf.TrajectoryStep, step_idx: int) -> dict[str, Any] | None:
tokens = step["tokens"]
@@ -302,10 +302,10 @@ def interleave_rollout(
completion_ids=completion_ids,
completion_mask=completion_mask,
completion_logprobs=list(tokens["completion_logprobs"]),
completion_temperatures=[temperature] * len(completion_ids),
completion_temperatures=[],
teacher_logprobs=None,
advantage=None,
env_name=output["env_name"],
env_name=env_name,
mm_token_type_ids=None,
routed_experts=None, # deferred — finalized at end of interleave_rollout
)
@@ -375,7 +375,6 @@ def interleave_rollout(
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))
sample.completion_temperatures.extend([temperature] * len(new_prompt_ids))
# Extend with new completion tokens
completion_ids = tokens["completion_ids"]
@@ -385,7 +384,6 @@ def interleave_rollout(
else:
sample.completion_mask.extend(tokens["completion_mask"])
sample.completion_logprobs.extend(tokens["completion_logprobs"])
sample.completion_temperatures.extend([temperature] * len(completion_ids))
step_routed = tokens.get("routed_experts")
state = sample_routed_state.get(id(sample))
+208
View File
@@ -0,0 +1,208 @@
"""Shared dataclasses for the orchestrator. Data carriers only; no behavior."""
from __future__ import annotations
import uuid
from dataclasses import dataclass, field, fields
from typing import Literal, Protocol
import verifiers as vf
from prime_rl.transport import TrainingSample
@dataclass
class Policy:
"""Mutable shared view of the policy. Passed by reference so observers
see new versions immediately."""
version: int = 0
model_name: str = ""
@dataclass
class Progress:
"""Persistent counters; ``step`` is the trainer-aligned step."""
step: int = 0
total_tokens: int = 0
total_samples: int = 0
total_problems: int = 0
RolloutKind = Literal["train", "eval"]
@dataclass
class InflightRollout:
"""Per-task scheduling state in the dispatcher; one entry per in-flight
``run_rollout`` / ``run_group`` task."""
kind: RolloutKind
env_name: str
group_id: uuid.UUID
policy_version: int
rollout_count: int
client_config: vf.ClientConfig | None = None
off_policy_steps: int = 0
eval_step: int | None = None
@dataclass
class GroupState:
"""Per-group dispatcher state: what's left to schedule + the pinned
client (for prefix-cache hits)."""
kind: RolloutKind
env_name: str
example: dict
rollouts_to_schedule: int
target_rollouts: int
emitted: int = 0
eval_step: int | None = None
pinned_client: vf.ClientConfig | None = None
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."""
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)
@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
@dataclass
class TrainBatchMetrics:
"""Per-batch aggregates from ``TrainSink.process_batch``; consumed by
``MetricsBuilder.build``. ``arrivals_by_env`` / ``errors_by_env`` count
rollouts at the sink."""
n_trainable: int
num_prefill_tokens: int
num_decode_tokens: int
rollout_prefill_lens: list[int]
rollout_decode_lens: list[int]
samples_per_rollout: list[int]
samples_shipped: int
arrivals_by_env: dict[str, int] = field(default_factory=dict)
errors_by_env: dict[str, int] = field(default_factory=dict)
@dataclass
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]
samples: list[TrainingSample]
metrics: TrainBatchMetrics
@dataclass
class EvalBatchMetrics:
"""Typed per-batch metrics from ``EvalSink.process_batch``. Final wandb
dict derived via ``to_wandb_dict`` at log time."""
n_rollouts: int
n_cancelled: int
n_errored: int
n_examples: int = 0
group_size: int = 1
reward_mean: float = 0.0
completion_len_mean: float = 0.0
completion_len_max: float = 0.0
completion_len_min: float = 0.0
truncation_rate: float = 0.0
no_response_rate: float = 0.0
num_turns_mean: float = 0.0
num_turns_min: float = 0.0
num_turns_max: float = 0.0
pass_at_k: dict[str, float] = field(default_factory=dict)
def to_wandb_dict(self, *, env_name: str, step: int) -> dict[str, float]:
prefix = f"eval/{env_name}"
out: dict[str, float] = {
"step": float(step),
f"{prefix}/cancelled_count": float(self.n_cancelled),
f"{prefix}/errored_count": float(self.n_errored),
}
if self.n_examples > 0:
out[f"{prefix}/avg@{self.group_size}"] = self.reward_mean
out[f"{prefix}/completion_len/mean"] = self.completion_len_mean
out[f"{prefix}/completion_len/max"] = self.completion_len_max
out[f"{prefix}/completion_len/min"] = self.completion_len_min
out[f"{prefix}/is_truncated/mean"] = self.truncation_rate
out[f"{prefix}/no_response/mean"] = self.no_response_rate
out[f"{prefix}/num_turns/mean"] = self.num_turns_mean
out[f"{prefix}/num_turns/min"] = self.num_turns_min
out[f"{prefix}/num_turns/max"] = self.num_turns_max
for k, v in self.pass_at_k.items():
out[f"{prefix}/{k}"] = v
return out
@dataclass
class EvalBatch:
"""One env's eval epoch. ``metrics`` is the typed view from
``EvalSink.process_batch``."""
env_name: str
step: int
rollouts: list[EvalRollout]
metrics: EvalBatchMetrics
class VersionObserver(Protocol):
"""Notified after each policy update; walked by the watcher after it
mutates ``Policy``."""
async def on_new_version(self, step: int) -> None: ...
+75 -56
View File
@@ -1,82 +1,101 @@
import asyncio
import logging
import time
from concurrent.futures import ThreadPoolExecutor
from itertools import cycle
from pathlib import Path
from typing import Any
import pandas as pd
import orjson
import verifiers as vf
from rich.console import Console
from rich.table import Table
from verifiers.utils.client_utils import setup_openai_client
from verifiers.utils.save_utils import make_serializable
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.transport import TrainingSample
from prime_rl.utils.logger import get_logger
from prime_rl.utils.client import setup_inference_pool
from prime_rl.utils.logger import InterceptHandler, get_logger
from prime_rl.utils.utils import (
format_time,
get_broadcast_dir,
get_ckpt_dir,
get_step_path,
)
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``)."""
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")
inference_pool = await setup_inference_pool(
client_config,
model_name=model_name,
train_client_type="openai_chat_completions",
eval_client_type="openai_chat_completions",
)
return None, 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."""
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))
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
"""Intercepts verifiers logging and routes through prime-rl logger with optional prefix."""
vf_logger = logging.getLogger(logger)
vf_logger.handlers.clear()
vf_logger.addHandler(InterceptHandler(prefix=prefix))
vf_logger.setLevel(level.upper())
vf_logger.propagate = False
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 print_benchmark(history: dict[str, list[Any]]) -> None:
"""
Print benchmark results as rich table. Shows formatted step time values.
First N rows show the per-step values, and the last row shows the mean,
std, min, and max values.
"""
history.pop("step")
assert all(len(v) for v in history.values()), "All metrics must have logged the same number of steps"
# Turn metric history into pd.DataFrame
df = pd.DataFrame(dict(history.items()))
columns = {
"time/step": "Step Time",
}
df = df.rename(columns=columns)
df = df[list(columns.values())]
df = df.iloc[1:] # Exclude first row
# Setup console
console = Console()
table = Table(title="Benchmark")
# Add columns
table.add_column("Step", justify="right")
for col in df.columns:
table.add_column(col, justify="center", style="magenta")
# Add formatted rows
formatted_df = pd.DataFrame(columns=df.columns)
formatted_df["Step Time"] = df["Step Time"].apply(format_time)
for step, row in formatted_df.iterrows():
table.add_row(*([str(step)] + [str(x) for x in row]))
# Separator
num_table_columns = 1 + len(df.columns)
table.add_row(*([""] * num_table_columns))
# Add row for formatted, aggregated statistics
mean_df = df.describe().loc[["mean", "std", "min", "max"], :]
formatted_mean_df = pd.DataFrame(columns=mean_df.columns)
formatted_mean_df["Step Time"] = mean_df["Step Time"].apply(format_time)
mean_row = ["Overall"] + formatted_mean_df.T.apply(
lambda row: f"{row['mean']} ± {row['std']} [{row['min']}, {row['max']}]", axis=1
).tolist()
table.add_row(*mean_row)
# Display table
console.print(table)
async def compute_teacher_logprobs(
clients: list[vf.ClientConfig],
model_name: str,
-98
View File
@@ -1,98 +0,0 @@
import logging
from pathlib import Path
import orjson
import verifiers as vf
from verifiers.utils.save_utils import make_serializable
from prime_rl.utils.logger import InterceptHandler
# TODO: remove once usage is tracked by verifiers
def get_prompt_len(output: vf.RolloutOutput) -> int:
"""
Computes the number of prompt tokens from vf.RolloutOutput. Defined as the
number of prompt ids from the first trajectory step. If raw tokens are not
available, falls back to checking the usage of the first response.
"""
if not output["trajectory"]:
return 0
first_step = output["trajectory"][0]
if first_step["tokens"] is not None:
return len(first_step["tokens"]["prompt_ids"])
first_step_response = first_step["response"]
return (first_step_response.get("usage") or {}).get("prompt_tokens", 0)
# TODO: remove once usage is tracked by verifiers
def get_seq_len(output: vf.RolloutOutput) -> int:
"""
Computes the number of tokens from vf.RolloutOutput. Defined as the sum of prompt
and completion tokens from the last trajectory step. If raw tokens are not
available, falls back to checking the usage of the last response.
"""
if not output["trajectory"]:
return 0
last_step = output["trajectory"][-1]
if last_step["tokens"] is not None:
return len(last_step["tokens"]["prompt_ids"]) + len(last_step["tokens"]["completion_ids"])
last_step_response = last_step["response"]
return (last_step_response.get("usage") or {}).get("total_tokens", 0)
# TODO: remove once usage is tracked by verifiers
def get_completion_len(output: vf.RolloutOutput) -> int:
"""
Computes the number of completion tokens from vf.RolloutOutput. Defined as
the difference between the total number of tokens and the number of prompt
tokens.
"""
return get_seq_len(output) - get_prompt_len(output)
def get_model_completion_len(output: vf.RolloutOutput) -> int:
"""
Computes the number of model-generated completion tokens across all turns.
Unlike get_completion_len, this excludes environment responses injected
between turns in multi-turn rollouts.
"""
return sum(len(step["tokens"]["completion_ids"]) for step in output["trajectory"] if step.get("tokens"))
def get_num_turns(output: vf.RolloutOutput) -> int:
"""Number of turns (trajectory steps) in a rollout."""
return len(output["trajectory"])
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 if no harness metric is
present, which makes this a no-op for envs without tool-response accounting.
"""
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."""
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))
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
"""Intercepts verifiers logging and routes through prime-rl logger with optional prefix."""
vf_logger = logging.getLogger(logger)
vf_logger.handlers.clear()
vf_logger.addHandler(InterceptHandler(prefix=prefix))
vf_logger.setLevel(level.upper())
vf_logger.propagate = False
+122
View File
@@ -0,0 +1,122 @@
"""WeightWatcher: polls the broadcast dir, advances ``Policy``, notifies
observers (dispatcher → off-policy cancel). Standalone async task; the
orchestrator's barrier bounds the in-flight lead."""
from __future__ import annotations
import asyncio
import time
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.types import Policy, VersionObserver
from prime_rl.utils.async_utils import safe_cancel
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_broadcast_dir, get_step_path, wait_for_path
from prime_rl.utils.utils import get_latest_ckpt_step
class WeightWatcher:
"""``await watcher.start()`` to drive the polling loop until ``stop()``."""
def __init__(
self,
config: OrchestratorConfig,
*,
policy: Policy,
inference: InferencePool,
observers: list[VersionObserver],
lora_name: str | None,
ckpt_step: int = 0,
poll_interval: float = 1.0,
) -> None:
self.config = config
self.policy = policy
self.inference = inference
self.observers = observers
self.lora_name = lora_name
self.ckpt_step = ckpt_step
self.poll_interval = poll_interval
self.last_update_weights_time: float = 0.0
self.last_wait_for_ckpt_time: float = 0.0
self.update_count: int = 0
self.task: asyncio.Task | None = None
self.update_lock = asyncio.Lock()
self.stopped = asyncio.Event()
async def start(self) -> None:
self.task = asyncio.current_task()
try:
while not self.stopped.is_set():
next_step = self.compute_next_ckpt_step()
if next_step > self.ckpt_step:
await self.apply_policy_update(next_step)
await asyncio.sleep(self.poll_interval)
except asyncio.CancelledError:
return
async def stop(self) -> None:
self.stopped.set()
if self.task is not None:
await safe_cancel(self.task)
self.task = None
def compute_next_ckpt_step(self) -> int:
"""Next checkpoint to adopt — at least ``policy.version`` (we stay
one step ahead of the trainer) plus anything fresher already
published in ``broadcasts/``."""
broadcast_dir = get_broadcast_dir(self.config.output_dir)
latest_ckpt_step = get_latest_ckpt_step(broadcast_dir) or 0
return max(self.policy.version, latest_ckpt_step)
async def apply_policy_update(self, next_step: int) -> None:
async with self.update_lock:
if next_step <= self.ckpt_step:
# Another caller raced us — bail without re-applying
return
broadcast_dir = get_broadcast_dir(self.config.output_dir)
weights_path = get_step_path(broadcast_dir, next_step)
stable_marker = weights_path / "STABLE"
if not stable_marker.exists():
get_logger().info(
f"Orchestrator paused: waiting for trainer to broadcast checkpoint {next_step}. "
"Training is progressing normally."
)
t0 = time.perf_counter()
await wait_for_path(stable_marker)
self.last_wait_for_ckpt_time = time.perf_counter() - t0
get_logger().info(
f"Orchestrator resumed: checkpoint {next_step} ready (after {format_time(self.last_wait_for_ckpt_time)})"
)
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)
self.last_update_weights_time = time.perf_counter() - t1
self.update_count += 1
get_logger().debug(f"Updated weights to step {next_step} in {format_time(self.last_update_weights_time)}")
self.ckpt_step = next_step
self.policy.version = next_step
if self.lora_name is not None:
self.inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
for observer in self.observers:
try:
await observer.on_new_version(next_step)
except Exception as exc:
get_logger().warning(
f"Observer {type(observer).__name__}.on_new_version({next_step}) raised: {exc!r}"
)
def gauges(self) -> dict[str, float]:
return {
"watcher/policy_version": float(self.policy.version),
"watcher/update_count": float(self.update_count),
"watcher/last_update_weights_time": self.last_update_weights_time,
"watcher/last_wait_for_ckpt_time": self.last_wait_for_ckpt_time,
}
+28
View File
@@ -0,0 +1,28 @@
{# Shared external-LB vLLM launch helper, included once per template and called
from every per-rank launch site (multi-node and disaggregated).
One vLLM API server per DP rank, pinned to its GPU slice. #}
# rank_log <node_rank> <k> — DP rank 0 logs to the node-level file (node_<rank>.log,
# the target of the top-level inference.log symlink) so it captures real server output;
# ranks 1+ get their own node_<rank>_rank<k>.log.
rank_log() {
if [ "$2" -eq 0 ]; then
echo "$OUTPUT_DIR/logs/inference/node_$1.log"
else
echo "$OUTPUT_DIR/logs/inference/node_$1_rank$2.log"
fi
}
# 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"
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" &
else
CUDA_VISIBLE_DEVICES="$gpus" "${cmd[@]}" 2>&1 | tee -a "$log" &
fi
}
@@ -0,0 +1,17 @@
{# 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]
launch_router() {
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-}"
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"
--worker-startup-timeout-secs 4200 --log-level debug)
if [ "$mode" = pd ]; then
cmd+=(--vllm-pd-disaggregation $worker_args)
else
cmd+=(--worker-urls $worker_args)
fi
"${cmd[@]}" >> "$log" 2>&1 &
}
@@ -0,0 +1,39 @@
{#- Mooncake distributed store (shared pool across inference nodes) for KV cache offload.
One master + HTTP metadata server runs on the head inference node (first in the SLURM
nodelist); every inference node runs a client that contributes its DRAM/SSD segment to
that single pool, so any node can reuse prefixes cached by any other. Included by the
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. -#}
# ---- Mooncake distributed store (shared pool across inference nodes) ----
MC_DIR="$OUTPUT_DIR/mooncake/node_${INFER_NODE_RANK}"
mkdir -p "$MC_DIR"
export PYTHONHASHSEED=0
export MOONCAKE_CONFIG_PATH="$MC_DIR/config.json"
# The head inference node (first in the nodelist) hosts the one master + metadata server.
MC_HEAD=$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -1)
MC_MASTER="$MC_HEAD:50051"
MC_METADATA="http://$MC_HEAD:8080/metadata"
{%- if kv_offload_disk_path %}
mkdir -p "{{ kv_offload_disk_path }}"
export MOONCAKE_OFFLOAD_FSDIR="{{ kv_offload_disk_path }}"
export MOONCAKE_OFFLOAD_FILE_STORAGE_PATH="{{ kv_offload_disk_path }}"
export MOONCAKE_OFFLOAD_ENABLE_EVICTION=true
{%- 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 &
{%- 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 &
{%- endif %}
fi
# Every node waits for the shared master + metadata, then contributes its segment.
for _ in $(seq 1 120); do timeout 1 bash -c "echo > /dev/tcp/$MC_HEAD/50051" 2>/dev/null && break; sleep 1; done
for _ in $(seq 1 120); do timeout 1 bash -c "echo > /dev/tcp/$MC_HEAD/8080" 2>/dev/null && break; sleep 1; done
mooncake_client -host=$LOCAL_IP -port=50052 -master_server_address=$MC_MASTER -metadata_server=$MC_METADATA -protocol=rdma -global_segment_size={{ kv_offload_cpu_bytes }}{% if kv_offload_device_name %} -device_names={{ kv_offload_device_name }}{% endif %}{% if kv_offload_disk_path %} -enable_offload=true{% endif %} > "$MC_DIR/client.log" 2>&1 &
for _ in $(seq 1 60); do timeout 1 bash -c "echo > /dev/tcp/$LOCAL_IP/50052" 2>/dev/null && break; sleep 1; done
cat > "$MOONCAKE_CONFIG_PATH" <<MOONCAKE_JSON
{"mode":"standalone-store","global_segment_size":0,"local_buffer_size":4294967296,"protocol":"rdma","device_name":"{{ kv_offload_device_name }}","master_server_address":"$MC_MASTER","metadata_server":"$MC_METADATA","enable_offload":{% if kv_offload_disk_path %}true{% else %}false{% endif %}}
MOONCAKE_JSON
echo "[mooncake] node ${INFER_NODE_RANK} ($SLURMD_NODENAME) joined shared pool: master=$MC_MASTER segment=$LOCAL_IP:50052"
+84 -80
View File
@@ -43,6 +43,7 @@ export RPC_PORT={{ data_parallel_rpc_port }}
{%- elif num_nodes > 1 %}
export ROUTER_PORT={{ router_port }}
export BACKEND_PORT={{ backend_port }}
export RPC_PORT={{ data_parallel_rpc_port }}
{%- endif %}
# Paths
@@ -78,26 +79,32 @@ for ((r=0; r<NUM_NODES/NODES_PER_REPLICA; r++)); do
INFER_URLS="${INFER_URLS:+$INFER_URLS,}http://${router_host}:${ROUTER_PORT}/v1"
REPLICA_ROUTER_ARGS=""
# External-LB: one --prefill/--decode endpoint per DP rank (PORT + k) on each node.
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
node_idx=$((replica_base + p))
host="${HOSTNAMES[$node_idx]}"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:${PREFILL_PORT}"
host="${HOSTNAMES[$((replica_base + p))]}"
for ((k=0; k<{{ dp_per_node }}; k++)); do
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
done
done
for ((d=0; d<NUM_DECODE_NODES; d++)); do
node_idx=$((replica_base + NUM_PREFILL_NODES + d))
host="${HOSTNAMES[$node_idx]}"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:${DECODE_PORT}"
host="${HOSTNAMES[$((replica_base + NUM_PREFILL_NODES + d))]}"
for ((k=0; k<{{ dp_per_node }}; k++)); do
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
done
done
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
done
export INFER_URLS
export ALL_ROUTER_ARGS
{%- elif num_nodes > 1 %}
# Single router on node 0, all nodes as backends
# External LB: one router on node 0; one endpoint per DP rank (BACKEND_PORT + dp_local) on every node.
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
DP_PER_NODE={{ dp_per_node }}
ROUTER_ARGS=""
for host in ${HOSTNAMES[@]}; do
ROUTER_ARGS="$ROUTER_ARGS http://${host}:${BACKEND_PORT}"
for ((d=0; d<DP_PER_NODE; d++)); do
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))"
done
done
export INFER_URLS
export ROUTER_ARGS
@@ -130,9 +137,13 @@ srun bash -s <<'CLEANUP_SH'
# which pkill -f does not see because -f only matches the cmdline.
pkill -9 "vllm" 2>/dev/null
pkill -9 "vllm::.*" 2>/dev/null
# Mooncake store (master + client) left over from a prior offload run. -x matches
# the exact process name, so it never hits the worktree path (e.g. mooncake-baby).
pkill -9 -x mooncake_master 2>/dev/null
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::" | grep -v grep | wc -l)
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | 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
@@ -158,9 +169,14 @@ srun --kill-on-bad-exit=1 bash -c '
INFER_NODE_RANK=$SLURM_PROCID
LOCAL_IP=$(hostname -I | awk "{print \$1}")
{% include '_launch_rank.sh.j2' %}
{% include '_launch_router.sh.j2' %}
{%- if kv_offload %}
ulimit -l unlimited
{%- endif %}
{%- if kv_offload_mooncake %}
{% include "_mooncake_store.sh.j2" %}
{%- endif %}
{% if disaggregated -%}
# NVSHMEM libs for DeepEP — ensure the rpath target exists on all nodes
@@ -178,29 +194,41 @@ 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
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
{%- if kv_offload %}
PREFILL_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
{%- else %}
PREFILL_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
{%- endif %}
{%- if kv_offload %}
DECODE_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
{%- else %}
DECODE_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
{%- endif %}
# The kv_transfer_config (NIXL transfer + any KV offload connector) is built in
# InferenceConfig.to_vllm() from the per-node config, so it is no longer assembled here.
DECODE_COMPILE_CFG='"'"'{"cudagraph_mode":"FULL_DECODE_ONLY"}'"'"'
DP_PER_NODE={{ dp_per_node }}
TP=$((GPUS_PER_NODE / DP_PER_NODE))
# Determine outer replica (P/D pair) and role
REPLICA_IDX=$((INFER_NODE_RANK / NODES_PER_REPLICA))
RANK_IN_REPLICA=$((INFER_NODE_RANK % NODES_PER_REPLICA))
@@ -211,21 +239,14 @@ srun --kill-on-bad-exit=1 bash -c '
ROLE="prefill"
SUB_REPLICA=$((RANK_IN_REPLICA / NODES_PER_PREFILL_REPLICA))
ROLE_RANK=$((RANK_IN_REPLICA % NODES_PER_PREFILL_REPLICA))
EP=$((NODES_PER_PREFILL_REPLICA * GPUS_PER_NODE))
DP=$((NODES_PER_PREFILL_REPLICA * DP_PER_NODE))
PORT=$PREFILL_PORT
START_RANK=$((ROLE_RANK * GPUS_PER_NODE))
HEAD_HOST="${HOSTNAMES[$((REPLICA_BASE + SUB_REPLICA * NODES_PER_PREFILL_REPLICA))]}"
{% for key, value in prefill_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
if [ "$ROLE_RANK" -eq 0 ]; then
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\", \"data_parallel_hybrid_lb\": true, \"kv_transfer_config\": $PREFILL_KV_CFG, $ROLE_EXTRA}"
else
VLLM_EXTRA="{\"data_parallel_address\": \"$HEAD_HOST\", \"data_parallel_start_rank\": $START_RANK, \"data_parallel_hybrid_lb\": true, \"kv_transfer_config\": $PREFILL_KV_CFG, $ROLE_EXTRA}"
fi
else
# ── Decode node ──
export UCX_NET_DEVICES=mlx5_0:1
@@ -233,80 +254,63 @@ srun --kill-on-bad-exit=1 bash -c '
RANK_IN_DECODE=$((RANK_IN_REPLICA - NUM_PREFILL_NODES))
SUB_REPLICA=$((RANK_IN_DECODE / NODES_PER_DECODE_REPLICA))
ROLE_RANK=$((RANK_IN_DECODE % NODES_PER_DECODE_REPLICA))
EP=$((NODES_PER_DECODE_REPLICA * GPUS_PER_NODE))
DP=$((NODES_PER_DECODE_REPLICA * DP_PER_NODE))
PORT=$DECODE_PORT
START_RANK=$((ROLE_RANK * GPUS_PER_NODE))
HEAD_HOST="${HOSTNAMES[$((REPLICA_BASE + NUM_PREFILL_NODES + SUB_REPLICA * NODES_PER_DECODE_REPLICA))]}"
{% for key, value in decode_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
if [ "$ROLE_RANK" -eq 0 ]; then
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\", \"data_parallel_hybrid_lb\": true, \"kv_transfer_config\": $DECODE_KV_CFG, $ROLE_EXTRA}"
else
VLLM_EXTRA="{\"data_parallel_address\": \"$HEAD_HOST\", \"data_parallel_start_rank\": $START_RANK, \"data_parallel_hybrid_lb\": true, \"kv_transfer_config\": $DECODE_KV_CFG, $ROLE_EXTRA}"
fi
fi
echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK EP=$EP PORT=$PORT LOCAL_IP=$LOCAL_IP" \
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" \
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
# Start vllm-router on the first prefill node of each replica (background)
# Start the router on the first prefill node of each replica (external LB across per-rank endpoints)
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
ROUTER_LOG="$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log"
echo "Starting vllm-router on $LOCAL_IP:$ROUTER_PORT for replica $REPLICA_IDX" | tee $ROUTER_LOG
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
vllm-router \
--policy {{ router_policy }} \
--vllm-pd-disaggregation \
$REPLICA_ROUTER_ARGS \
--host 0.0.0.0 \
--port $ROUTER_PORT \
--intra-node-data-parallel-size {{ dp_per_node }} \
--worker-startup-timeout-secs 4200 \
--log-level debug \
>> $ROUTER_LOG 2>&1 &
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router_policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
fi
uv run inference \
@ $CONFIG_PATH \
--server.host 0.0.0.0 \
--server.port $PORT \
--parallel.dp $EP \
--data-parallel-rpc-port $RPC_PORT \
--vllm-extra "$VLLM_EXTRA" \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
# 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
# group rooted on the role-replica head (HEAD_HOST); the router balances across the per-rank
# endpoints. The kv_transfer_config is built in InferenceConfig.to_vllm() from the config.
if [ "$ROLE_RANK" -eq 0 ]; then DP_ADDR=$LOCAL_IP; else DP_ADDR=$HEAD_HOST; fi
for k in $(seq 0 $((DP_PER_NODE - 1))); do
GLOBAL_RANK=$((ROLE_RANK * DP_PER_NODE + k))
RANK_GPUS=$(seq -s, $((k * TP)) $((k * TP + TP - 1)))
RANK_EXTRA="{\"data_parallel_address\": \"$DP_ADDR\", \"data_parallel_rank\": $GLOBAL_RANK, $ROLE_EXTRA}"
launch_inference_rank "$((PORT + k))" "$RANK_GPUS" "$DP" "$RPC_PORT" "$RANK_EXTRA" "$((5600 + k))" "$(rank_log "$INFER_NODE_RANK" "$k")"
done
{%- elif num_nodes > 1 %}
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False
DP_PER_NODE={{ dp_per_node }}
TP=$((GPUS_PER_NODE / DP_PER_NODE))
EP={{ "1" if enable_expert_parallel else "0" }}
# Start router on node 0
# Start the router on node 0 (balances across per-rank endpoints — no intra-node DP header)
if [ "$INFER_NODE_RANK" -eq 0 ]; then
ROUTER_LOG="$OUTPUT_DIR/logs/inference/router.log"
echo "Starting vllm-router on $LOCAL_IP:$ROUTER_PORT" | tee $ROUTER_LOG
vllm-router \
--policy {{ router_policy }} \
--worker-urls $ROUTER_ARGS \
--host 0.0.0.0 \
--port $ROUTER_PORT \
--intra-node-data-parallel-size {{ dp_per_node }} \
--worker-startup-timeout-secs 4200 \
--log-level debug \
>> $ROUTER_LOG 2>&1 &
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router_policy }}" "$OUTPUT_DIR/logs/inference/router.log"
fi
uv run inference \
@ $CONFIG_PATH \
--server.host 0.0.0.0 \
--server.port $BACKEND_PORT \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
# each pinned to its TP slice of GPUs. Each node is an independent replica, so any MoE EP
# group is node-local (rendezvous on LOCAL_IP); dense models run independent engines.
for ((d=0; d<DP_PER_NODE; d++)); do
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
if [ "$EP" -eq 1 ]; then
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
else
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
fi
done
{%- else %}
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" | tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
# Required for graph compilation to work
+84 -107
View File
@@ -48,12 +48,6 @@ export DECODE_PORT={{ decode_port }}
{%- else -%}
export BACKEND_PORT={{ backend_port }}
export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parallel else "0" }}
# Enable distributed EP mode only when expert parallelism spans multiple inference nodes per replica.
export USE_DISTRIBUTED_EP=0
if [ "$INFERENCE_ENABLE_EXPERT_PARALLEL" -eq 1 ] && [ "$NODES_PER_INFER_REPLICA" -gt 1 ]; then
USE_DISTRIBUTED_EP=1
fi
{%- endif %}
{%- endif %}
@@ -94,17 +88,22 @@ for ((r=0; r<NUM_INFER_REPLICAS; r++)); do
INFER_URLS="${INFER_URLS:+$INFER_URLS }http://${router_host}:${ROUTER_PORT}/v1"
REPLICA_ROUTER_ARGS=""
# External-LB: one prefill/decode endpoint per DP rank (PORT + k) on each node.
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
node_idx=$((replica_base + p))
host="${INFER_HOSTS[$node_idx]}"
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:${PREFILL_PORT}/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:${PREFILL_PORT}"
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((PREFILL_PORT + k))/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
done
done
for ((d=0; d<NUM_DECODE_NODES; d++)); do
node_idx=$((replica_base + NUM_PREFILL_NODES + d))
host="${INFER_HOSTS[$node_idx]}"
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:${DECODE_PORT}/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:${DECODE_PORT}"
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((DECODE_PORT + k))/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
done
done
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
done
@@ -118,8 +117,11 @@ for ((r=0; r<NUM_INFER_REPLICAS; r++)); do
for ((n=0; n<NODES_PER_INFER_REPLICA; n++)); do
node_idx=$((head_idx + n))
host="${INFER_HOSTS[$node_idx]}"
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:${BACKEND_PORT}/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS http://${host}:${BACKEND_PORT}"
# External-LB: one endpoint per DP rank (BACKEND_PORT + dp_local) on each node.
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + k))/v1"
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS http://${host}:$((BACKEND_PORT + k))"
done
done
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
done
@@ -130,9 +132,6 @@ export ALL_ROUTER_ARGS
echo "INFER_HOSTS=${INFER_HOSTS[*]}"
echo "INFER_URLS=${INFER_URLS}"
echo "ADMIN_URLS=${ADMIN_URLS}"
{%- if not is_disaggregated %}
echo "USE_DISTRIBUTED_EP=${USE_DISTRIBUTED_EP}"
{%- endif %}
{%- endif %}
echo "HOSTNAMES=${HOSTNAMES[*]}"
@@ -172,9 +171,13 @@ srun bash -s <<'CLEANUP_SH'
# which pkill -f does not see because -f only matches the cmdline.
pkill -9 "vllm" 2>/dev/null
pkill -9 "vllm::.*" 2>/dev/null
# Mooncake store (master + client) left over from a prior offload run. -x matches
# the exact process name, so it never hits the worktree path (e.g. mooncake-baby).
pkill -9 -x mooncake_master 2>/dev/null
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::" | grep -v grep | wc -l)
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | 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
@@ -213,6 +216,9 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
{%- if kv_offload %}
ulimit -l unlimited
{%- endif %}
{%- if kv_offload_mooncake %}
{% include "_mooncake_store.sh.j2" %}
{%- endif %}
REPLICA_IDX=$((INFER_NODE_RANK / NODES_PER_INFER_REPLICA))
@@ -221,6 +227,10 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
echo "INFER_NODE_RANK=$INFER_NODE_RANK REPLICA=$REPLICA_IDX RANK_IN_REPLICA=$RANK_IN_REPLICA LOCAL_IP=$LOCAL_IP" \
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
CONFIG_PATH="$CONFIG_DIR/inference.toml"
{% include '_launch_rank.sh.j2' %}
{% include '_launch_router.sh.j2' %}
{% if is_disaggregated -%}
# PD disaggregated: NIXL KV transfer + role-based inference
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
@@ -229,25 +239,35 @@ 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
{%- if kv_offload %}
PREFILL_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
{%- else %}
PREFILL_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
{%- endif %}
# The kv_transfer_config (NIXL transfer + any KV offload connector) is built in
# InferenceConfig.to_vllm() from the per-node config, so it is no longer assembled here.
{%- if kv_offload %}
DECODE_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
{%- else %}
DECODE_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
{%- endif %}
DECODE_COMPILE_CFG='"'"'{"cudagraph_mode":"FULL_DECODE_ONLY"}'"'"'
REPLICA_BASE=$((REPLICA_IDX * NODES_PER_INFER_REPLICA))
@@ -283,95 +303,52 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
echo "ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT" \
| tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
if [ "$DP" -gt 1 ]; then
if [ "$ROLE" = "prefill" ]; then
KV_CFG_TO_USE="$PREFILL_KV_CFG"
else
KV_CFG_TO_USE="$DECODE_KV_CFG"
fi
if [ "$ROLE_RANK" -eq 0 ]; then
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\", \"data_parallel_hybrid_lb\": true, \"kv_transfer_config\": $KV_CFG_TO_USE, $ROLE_EXTRA}"
else
VLLM_EXTRA="{\"data_parallel_address\": \"$HEAD_HOST\", \"data_parallel_start_rank\": $START_RANK, \"data_parallel_hybrid_lb\": true, \"kv_transfer_config\": $KV_CFG_TO_USE, $ROLE_EXTRA}"
fi
else
if [ "$ROLE" = "prefill" ]; then
VLLM_EXTRA="{\"kv_transfer_config\": $PREFILL_KV_CFG, $ROLE_EXTRA}"
else
VLLM_EXTRA="{\"kv_transfer_config\": $DECODE_KV_CFG, $ROLE_EXTRA}"
fi
fi
# Start vllm-router on the first node of each replica (PD mode)
# 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
ROUTER_LOG="$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log"
echo "Starting vllm-router (PD) on $LOCAL_IP:$ROUTER_PORT for replica $REPLICA_IDX" | tee $ROUTER_LOG
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
vllm-router \
--policy consistent_hash \
--vllm-pd-disaggregation \
$REPLICA_ROUTER_ARGS \
--host 0.0.0.0 \
--port $ROUTER_PORT \
--intra-node-data-parallel-size {{ dp_per_node }} \
--worker-startup-timeout-secs 4200 \
>> $ROUTER_LOG 2>&1 &
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
fi
uv run inference \
@ $CONFIG_DIR/inference.toml \
--server.host 0.0.0.0 \
--server.port $PORT \
--parallel.dp $DP \
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
--vllm-extra "$VLLM_EXTRA" \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
# 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
# group rooted on the role-replica head (HEAD_HOST); the router balances across the per-rank
# endpoints. The kv_transfer_config is built in InferenceConfig.to_vllm() from the config.
if [ "$ROLE_RANK" -eq 0 ]; then DP_ADDR=$LOCAL_IP; else DP_ADDR=$HEAD_HOST; fi
for k in $(seq 0 $((INFERENCE_DP_LOCAL - 1))); do
GLOBAL_RANK=$((START_RANK + k))
RANK_GPUS=$(seq -s, $((k * INFERENCE_TP)) $((k * INFERENCE_TP + INFERENCE_TP - 1)))
RANK_EXTRA="{\"data_parallel_address\": \"$DP_ADDR\", \"data_parallel_rank\": $GLOBAL_RANK, $ROLE_EXTRA}"
launch_inference_rank "$((PORT + k))" "$RANK_GPUS" "$DP" "$INFERENCE_DATA_PARALLEL_RPC_PORT" "$RANK_EXTRA" "$((5600 + k))" "$(rank_log "$INFER_NODE_RANK" "$k")"
done
{%- else -%}
# Start vllm-router on the first node of each replica
# Start the router on the first node of each replica
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
ROUTER_LOG="$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log"
echo "Starting vllm-router on $LOCAL_IP:$ROUTER_PORT for replica $REPLICA_IDX" | tee $ROUTER_LOG
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
vllm-router \
--policy consistent_hash \
--worker-urls $REPLICA_ROUTER_ARGS \
--host 0.0.0.0 \
--port $ROUTER_PORT \
--intra-node-data-parallel-size {{ dp_per_node }} \
--worker-startup-timeout-secs 4200 \
>> $ROUTER_LOG 2>&1 &
launch_router regular "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
fi
if [ "$USE_DISTRIBUTED_EP" -eq 1 ]; then
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
REPLICA_HEAD_HOST="${HOSTNAMES[$((REPLICA_IDX * NODES_PER_INFER_REPLICA))]}"
INFER_DP_START_RANK=$((RANK_IN_REPLICA * INFERENCE_DP_LOCAL))
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\", \"data_parallel_hybrid_lb\": true}"
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + d),
# each pinned to its TP slice of GPUs; the router balances across the per-rank
# endpoints. For MoE the ranks form one external-LB DP group (EP all2all spans
# them) rooted on the replica-head DP coordinator. data_parallel_address is
# per-node, not per-rank: every rank on the head reaches the coordinator via the
# head LOCAL_IP, ranks on other nodes via the head hostname (matches the P/D path).
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
REPLICA_HEAD_HOST="${HOSTNAMES[$((REPLICA_IDX * NODES_PER_INFER_REPLICA))]}"
INFER_GROUP_DP=$((NODES_PER_INFER_REPLICA * INFERENCE_DP_LOCAL))
if [ "$RANK_IN_REPLICA" -eq 0 ]; then DP_ADDR="$LOCAL_IP"; else DP_ADDR="$REPLICA_HEAD_HOST"; fi
for ((d=0; d<INFERENCE_DP_LOCAL; d++)); do
RANK_GPUS=$(seq -s, $((d * INFERENCE_TP)) $((d * INFERENCE_TP + INFERENCE_TP - 1)))
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
if [ "$INFERENCE_ENABLE_EXPERT_PARALLEL" -eq 1 ]; then
GLOBAL_DP_RANK=$((RANK_IN_REPLICA * INFERENCE_DP_LOCAL + d))
RANK_EXTRA="{\"data_parallel_rank\": $GLOBAL_DP_RANK, \"data_parallel_address\": \"$DP_ADDR\"}"
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$INFER_GROUP_DP" "$INFERENCE_DATA_PARALLEL_RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
else
VLLM_EXTRA="{\"data_parallel_address\": \"$REPLICA_HEAD_HOST\", \"data_parallel_start_rank\": $INFER_DP_START_RANK, \"data_parallel_hybrid_lb\": true}"
# Dense: independent single-engine servers (no DP linkage).
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
fi
uv run inference \
@ $CONFIG_DIR/inference.toml \
--server.host 0.0.0.0 \
--server.port $BACKEND_PORT \
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
--vllm-extra "$VLLM_EXTRA" \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
else
uv run inference \
@ $CONFIG_DIR/inference.toml \
--server.host 0.0.0.0 \
--server.port $BACKEND_PORT \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
fi
done
{%- endif %}
else
@@ -426,7 +403,7 @@ REMAINING_PIDS=$(jobs -p)
# in-flight trainer checkpoint on this node finish, and — because the task has
# not exited yet — keeps --kill-on-bad-exit from reaping checkpointing trainers
# on peer nodes. We then propagate the exit code so the allocation tears down. A
# clean (zero) exit can't trip --kill-on-bad-exit, so we tear down immediately.
# clean (zero) exit cannot trip --kill-on-bad-exit, so we tear down immediately.
if [ "$EXIT_CODE" -ne 0 ]; then
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for in-flight checkpoints to flush before teardown"
sleep {{ cleanup_grace_period }}
+68 -26
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:
@@ -171,7 +201,12 @@ class CheckpointManager:
# Checkpoint the local dataloader
if dataloader is not None:
dataloader_dir = path / "dataloader"
dataloader_dir.mkdir(parents=True, exist_ok=True)
# Only the master creates the dir; the rest wait at a barrier. On a
# parallel FS (beegfs), concurrent mkdir from every rank can re-raise
# FileExistsError (EEXIST + stale is_dir() metadata).
if self.world.is_master:
dataloader_dir.mkdir(parents=True, exist_ok=True)
torch.distributed.barrier()
torch.save(dataloader.state_dict(), dataloader_dir / f"rank_{self.world.rank}.pt")
# Save sharded state
@@ -239,7 +274,11 @@ class CheckpointManager:
) -> None:
"""Save the full checkpoint state for a specified step."""
ckpt_path = self.get_ckpt_path(step)
ckpt_path.parent.mkdir(parents=True, exist_ok=True)
# Master-only mkdir + barrier: concurrent mkdir from every rank can
# re-raise FileExistsError on a parallel FS (see save_to_path).
if self.world.is_master:
ckpt_path.parent.mkdir(parents=True, exist_ok=True)
torch.distributed.barrier()
self.save_to_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
bisect.insort(self.ckpt_steps, step)
@@ -390,7 +429,11 @@ class WeightCheckpointManager:
):
"""Save a HF-compatible weight-only checkpoint for a given step."""
step_path = self.get_step_path(step)
step_path.mkdir(parents=True, exist_ok=True)
# Master-only mkdir + barrier: concurrent mkdir from every rank can
# re-raise FileExistsError on a parallel FS (EEXIST + stale is_dir()).
if self.world.is_master:
step_path.mkdir(parents=True, exist_ok=True)
torch.distributed.barrier()
# Gather all weights on master rank
self.logger.debug("Gathering weights on master rank for weight checkpoint")
@@ -420,7 +463,6 @@ class WeightCheckpointManager:
f"Converted PrimeRL format to HF format in {time.perf_counter() - start_time:.2f} seconds"
)
else:
# For regular transformers models, revert internal format to original HF hub format
from transformers.core_model_loading import revert_weight_conversion
self.logger.debug("Reverting transformers internal format to HF hub format for weight checkpoint")
+11 -2
View File
@@ -79,7 +79,7 @@ def _patch_qwen3_5_moe_conversion_mapping():
incorrectly maps qwen3_5_moe → qwen2_moe, which assumes per-expert 2D checkpoint weights,
causing revert_weight_conversion to produce wrong shapes during weight broadcasting.
Remove once the pinned transformers commit fixes this.
Remove once an official Transformers release fixes this.
"""
from transformers.conversion_mapping import (
get_checkpoint_conversion_mapping,
@@ -99,7 +99,7 @@ def _patch_qwen3_5_text_position_ids():
"""Fix Qwen3.5 passing 3D MRoPE position_ids to decoder layers instead of 2D text_position_ids.
Upstream fix: https://github.com/huggingface/transformers/pull/44399
Remove once the pinned transformers commit includes this fix.
Remove once an official Transformers release includes this fix.
"""
import inspect
@@ -518,6 +518,15 @@ def get_model(
logger.debug(f"Loaded model config ({model_config.to_dict()})")
# NemotronH: transformers' Mamba2 mixer __init__ calls lazy_load_kernel("mamba-ssm" /
# "causal-conv1d") whenever config.use_mamba_kernels is set. That hub-kernel path is gated only
# by whether the `kernels` package is importable (NOT by USE_HUB_KERNELS) and resolves from the
# HF Hub, which hard-crashes under HF_HUB_OFFLINE=1. prime-rl swaps in its own mamba_ssm Triton
# SSD kernels via _patch_mamba2_use_triton_ssd, so the hub kernels are redundant; disable them
# to keep model init offline-safe.
if getattr(model_config, "model_type", "") == "nemotron_h":
model_config.use_mamba_kernels = False
if config.debug.num_layers is not None:
# VLM configs nest num_hidden_layers under text_config
target_config = getattr(model_config, "text_config", model_config)
@@ -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,
+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
@@ -46,7 +46,6 @@ class FileSystemWeightBroadcast(WeightBroadcast):
if isinstance(model, PreTrainedModelPrimeRL) and model.is_prime_state_dict(state_dict):
model.convert_to_hf(state_dict)
else:
# For regular transformers models, revert internal format to original HF hub format
from transformers.core_model_loading import revert_weight_conversion
state_dict = revert_weight_conversion(model, state_dict)
+11 -11
View File
@@ -25,7 +25,7 @@ from prime_rl.utils.cp import (
setup_cp_params,
shard_for_cp,
)
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.logger import format_time, setup_logger
from prime_rl.trainer.rl.loss import (
compute_entropy,
compute_loss,
@@ -525,13 +525,13 @@ def train(config: TrainerConfig):
tensors[key].append(loss_tensor.detach().to("cpu"))
# Debug log with *local, micro step* stats
micro_step_message = f"Micro Step {micro_step}/{len(micro_batches)} | Loss: {tensors['loss'][-1].mean().item():.4f} | Entropy: {tensors['entropy/all'][-1].mean().item():.4f}"
micro_step_message = f"Micro Step {micro_step}/{len(micro_batches)} | Loss {tensors['loss'][-1].mean().item():.4f} | Entropy {tensors['entropy/all'][-1].mean().item():.4f}"
if micro_batch["training_mode"] != "sft":
micro_step_message += f" | Mismatch KL: {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
micro_step_message += f" | Mismatch KL {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
if "max_vio" in tensors:
micro_step_message += f" | Max Vio: {tensors['max_vio'][-1].mean().item():.4f}"
micro_step_message += f" | Max Vio {tensors['max_vio'][-1].mean().item():.4f}"
if "routing_confidence" in tensors:
micro_step_message += f" | Routing Conf.: {tensors['routing_confidence'][-1].mean().item():.4f}"
micro_step_message += f" | Routing Conf. {tensors['routing_confidence'][-1].mean().item():.4f}"
logger.debug(micro_step_message)
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
@@ -583,16 +583,16 @@ def train(config: TrainerConfig):
# Log step metrics
step_time = time.perf_counter() - step_start_time
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Loss: {tensor_stats['loss/mean']:.4f} | Entropy: {tensor_stats['entropy/all/mean']:.4f}"
step_message = f"Step {progress.step} | {format_time(step_time):>7} | Loss {tensor_stats['loss/mean']:.4f} | Entropy {tensor_stats['entropy/all/mean']:.4f}"
if "mismatch_kl/all/mean" in tensor_stats:
step_message += f" | Mismatch KL: {tensor_stats['mismatch_kl/all/mean']:.4f}"
step_message += f" | Mismatch KL {tensor_stats['mismatch_kl/all/mean']:.4f}"
if grad_norm is not None:
step_message += f" | Grad. Norm: {grad_norm:.4f}"
step_message += f" | LR: {current_lr:.2e} | Throughput: {throughput:.0f} tokens/s | MFU: {mfu:.1f}% | Peak Mem.: {peak_memory:.1f} GiB"
step_message += f" | Grad. Norm {grad_norm:.4f}"
step_message += f" | LR {current_lr:.2e} | Throughput {throughput:.0f} tokens/s | MFU {mfu:.1f}% | Peak Mem. {peak_memory:.1f} GiB"
if "max_vio/mean" in tensor_stats:
step_message += f" | Max Vio: {tensor_stats['max_vio/mean']:.4f}"
step_message += f" | Max Vio {tensor_stats['max_vio/mean']:.4f}"
if "routing_confidence/mean" in tensor_stats:
step_message += f" | Routing Conf.: {tensor_stats['routing_confidence/mean']:.4f}"
step_message += f" | Routing Conf. {tensor_stats['routing_confidence/mean']:.4f}"
logger.success(step_message)
# Log performance metrics
+8 -1
View File
@@ -247,7 +247,12 @@ class MultiRunManager:
# Run registered validation hooks
for hook in self._config_validation_hooks:
is_valid, error_message = hook(config)
try:
is_valid, error_message = hook(config)
except Exception as e:
hook_name = getattr(hook, "__name__", type(hook).__name__)
is_valid = False
error_message = f"Validation hook {hook_name} crashed: {e}"
if not is_valid:
self.logger.error(f"Run {run_id}: {error_message}")
if error_path.parent.exists():
@@ -510,6 +515,8 @@ def setup_multi_run_manager(
trainer_lora = lora_config
def validate_lora_rank(orch_config: "OrchestratorConfig") -> tuple[bool, str]:
if orch_config.student.model.lora is None:
return False, "student.model.lora is required when trainer is configured with LoRA"
# Default to trainer's rank/alpha if not specified
if orch_config.student.model.lora.rank is None:
orch_config.student.model.lora.rank = trainer_lora.rank
+6 -6
View File
@@ -22,7 +22,7 @@ from prime_rl.configs.sft import SFTConfig
from prime_rl.utils.cp import setup_cp_params, shard_for_cp
from prime_rl.trainer.runs import Progress, get_multi_run_manager, setup_multi_run_manager
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.logger import format_time, setup_logger
from prime_rl.trainer.optim import setup_optimizer
from prime_rl.trainer.scheduler import setup_scheduler
from prime_rl.trainer.model import (
@@ -325,7 +325,7 @@ def train(config: SFTConfig):
if mean_loss != mean_loss:
logger.warning(f"Validation at step {step} had no valid tokens")
else:
logger.success(f"Validation | Step {step} | Loss: {mean_loss:.4f}")
logger.success(f"Validation | Step {step} | Loss {mean_loss:.4f}")
monitor.log({"val/loss": mean_loss, "step": step}, step=step)
gc_handler = GarbageCollection(config.gc.interval) if config.gc else None
@@ -501,15 +501,15 @@ def train(config: SFTConfig):
# Log step metrics
step_time = time.perf_counter() - step_start_time
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Loss: {batch_loss:.4f}"
step_message = f"Step {progress.step} | {format_time(step_time):>7} | Loss {batch_loss:.4f}"
if grad_norm is not None:
step_message += f" | Grad. Norm: {grad_norm:.4f}"
step_message += f" | LR: {current_lr:.2e} | Throughput: {throughput:.0f} tokens/s | MFU: {mfu:.1f}% | Peak Mem.: {peak_memory:.1f}/{max_memory:.1f} GiB ({peak_memory / max_memory * 100:.1f}%)"
step_message += f" | Grad. Norm {grad_norm:.4f}"
step_message += f" | LR {current_lr:.2e} | Throughput {throughput:.0f} tokens/s | MFU {mfu:.1f}% | Peak Mem. {peak_memory:.1f}/{max_memory:.1f} GiB ({peak_memory / max_memory * 100:.1f}%)"
if is_moe_model:
for name, label in (("max_vio", "Max Vio"), ("routing_confidence", "Routing Conf.")):
value = moe_stats[name].item()
if value > 0:
step_message += f" | {label}: {value:.4f}"
step_message += f" | {label} {value:.4f}"
logger.success(step_message)
# Log progress metrics
+6 -3
View File
@@ -2,6 +2,7 @@ from pathlib import Path
from time import time
import zmq
import zmq.asyncio
from prime_rl.configs.shared import ZMQTransportConfig
from prime_rl.trainer.runs import get_multi_run_manager
@@ -20,8 +21,10 @@ class ZMQTrainingBatchSender(TrainingBatchSender):
def __init__(self, output_dir: Path, transport: ZMQTransportConfig):
super().__init__(output_dir)
self.context = zmq.Context.instance()
self.socket: zmq.Socket = self.context.socket(zmq.PUSH)
# Async context so ``send`` yields instead of blocking the orchestrator
# event loop when the trainer is slow and we hit SNDHWM.
self.context = zmq.asyncio.Context.instance()
self.socket: zmq.asyncio.Socket = self.context.socket(zmq.PUSH)
self.socket.setsockopt(zmq.SNDHWM, transport.hwm)
self.socket.connect(f"tcp://{transport.host}:{transport.port}")
@@ -35,7 +38,7 @@ class ZMQTrainingBatchSender(TrainingBatchSender):
async def send(self, batch: TrainingBatch) -> None:
payload = self.encoder.encode(batch)
self.logger.debug(f"Sending batch {batch.step} to {self.sender_id}")
self.socket.send_multipart([self.sender_id, payload], copy=False)
await self.socket.send_multipart([self.sender_id, payload], copy=False)
def close(self) -> None:
try:
+80 -42
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import os
from collections.abc import Mapping
from itertools import cycle
from pathlib import Path
from typing import Protocol, runtime_checkable
@@ -11,11 +12,21 @@ import verifiers as vf
from httpx import AsyncClient
from openai import NotFoundError
from renderers import RendererConfig
from tenacity import retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.logger import get_logger
# Identity tuple used by ``select_train_client`` to key load counts. ``api_base_url``
# distinguishes servers; ``X-data-parallel-rank`` distinguishes DP shards within a
# server, since the router uses that header to route to specific GPU ranks.
ClientIdentity = tuple[str, str | None]
def client_identity(client: vf.ClientConfig) -> ClientIdentity:
"""Stable identity for load balancing across inference clients."""
return (client.api_base_url, client.extra_headers.get("X-data-parallel-rank"))
@runtime_checkable
class InferencePool(Protocol):
@@ -44,6 +55,15 @@ class InferencePool(Protocol):
"""Get next eval client in round-robin fashion."""
...
async def select_train_client(self, load: Mapping[ClientIdentity, int]) -> vf.ClientConfig:
"""Pick the train client with lowest in-flight load.
Waits for at least one train client to be available, then returns
the one with the smallest ``load[client_identity(client)]``. The
caller owns the in-flight counter; the pool just picks against it.
"""
...
async def wait_for_ready(self, model_name: str, timeout: int | None = None) -> None:
"""Wait for inference pool to be ready."""
...
@@ -106,6 +126,11 @@ class StaticInferencePool:
async def get_eval_client(self) -> vf.ClientConfig:
return next(self._eval_cycle)
async def select_train_client(self, load: Mapping[ClientIdentity, int]) -> vf.ClientConfig:
while not self.train_clients:
await asyncio.sleep(0.5)
return min(self.train_clients, key=lambda c: load[client_identity(c)])
async def wait_for_ready(self, model_name: str, timeout: int | None = None) -> None:
await check_health(
self._admin_clients, timeout=timeout if timeout is not None else self._wait_for_ready_timeout
@@ -278,8 +303,8 @@ async def check_health(
NCCL_READY_MARKER = "NCCL_READY"
def _is_retryable_pause_error(exception: BaseException) -> bool:
"""Check if an exception should trigger a retry for pausing engines."""
def _is_retryable_admin_error(exception: BaseException) -> bool:
"""Check if an exception should trigger a retry for an admin op (pause/resume/update_weights)."""
if isinstance(exception, httpx.HTTPStatusError):
# Retry on transient server errors (5xx, e.g. engine briefly unresponsive);
# client errors (4xx) won't fix themselves on retry.
@@ -292,48 +317,56 @@ def _is_retryable_pause_error(exception: BaseException) -> bool:
return False
# Per-attempt and total bounds for `/pause`. Pausing drains in-flight requests
# (mode="keep"), so a single attempt can legitimately take a while, but the global
# admin AsyncClient uses `timeout=None`, so a stuck server would hang the weight
# update forever. `_READ_TIMEOUT` converts a hang into a TimeoutException so
# tenacity retries; `_TOTAL` is the wall-clock budget across all retries.
PAUSE_READ_TIMEOUT_S = 120.0
PAUSE_TOTAL_TIMEOUT_S = 300.0
# Per-attempt read timeout for admin ops, overridable per call. The admin
# AsyncClient uses `timeout=None`, so without this a stuck server would hang the
# weight update forever: the read timeout converts a hang into a TimeoutException
# that tenacity retries. Sized for `/pause`, which drains in-flight requests
# (mode="keep") and so can legitimately take a while.
ADMIN_TIMEOUT_S = 300.0
# `/update_weights` runs a collective NCCL receive across all DP workers, which
# can take longer than the other admin ops.
UPDATE_WEIGHTS_TIMEOUT_S = 720.0
async def _pause_engines(admin_clients: list[AsyncClient]) -> None:
"""Pause all inference engines, waiting for in-flight requests to drain."""
logger = get_logger()
logger.info("Pausing inference engines for weight update")
async def _admin_post(client: AsyncClient, path: str, *, timeout_s: float = ADMIN_TIMEOUT_S, **kwargs) -> None:
"""POST an admin op with a bounded per-attempt timeout, retrying transient errors.
@retry(
retry=retry_if_exception(_is_retryable_pause_error),
stop=stop_after_delay(PAUSE_TOTAL_TIMEOUT_S) | stop_after_attempt(10),
The total wall-clock budget across all retries is twice the per-attempt timeout.
"""
async for attempt in AsyncRetrying(
retry=retry_if_exception(_is_retryable_admin_error),
stop=stop_after_delay(2 * timeout_s) | stop_after_attempt(10),
wait=wait_exponential(multiplier=1, min=1, max=10),
reraise=True,
)
async def _pause(client: AsyncClient) -> None:
response = await client.post(
"/pause",
params={"mode": "keep", "clear_cache": "false"},
timeout=httpx.Timeout(connect=10.0, read=PAUSE_READ_TIMEOUT_S, write=60.0, pool=10.0),
)
response.raise_for_status()
):
with attempt:
response = await client.post(
path,
timeout=httpx.Timeout(connect=10.0, read=timeout_s, write=60.0, pool=10.0),
**kwargs,
)
response.raise_for_status()
await asyncio.gather(*[_pause(client) for client in admin_clients])
logger.info("All inference engines paused")
async def _pause_engines(admin_clients: list[AsyncClient], *, step: int) -> None:
"""Pause all inference engines, waiting for in-flight requests to drain."""
logger = get_logger()
logger.info(f"Updating policy in-flight to v{step}")
await asyncio.gather(
*[_admin_post(client, "/pause", params={"mode": "keep", "clear_cache": "false"}) for client in admin_clients]
)
logger.debug("All inference engines paused")
async def _resume_engines(admin_clients: list[AsyncClient]) -> None:
"""Resume all inference engines after weight update."""
"""Resume all inference engines after weight update.
Resuming is idempotent (it just clears the paused flag), so retrying transient
failures is safe; a dropped /resume would leave engines paused indefinitely.
"""
logger = get_logger()
async def _resume(client: AsyncClient) -> None:
response = await client.post("/resume")
response.raise_for_status()
await asyncio.gather(*[_resume(client) for client in admin_clients])
logger.info("All inference engines resumed")
await asyncio.gather(*[_admin_post(client, "/resume") for client in admin_clients])
logger.debug("All inference engines resumed")
async def update_weights(
@@ -358,13 +391,8 @@ async def update_weights(
if lora_name is not None and weight_dir is not None:
await load_lora_adapter(admin_clients, lora_name, weight_dir)
else:
async def _update_weights(admin_client: AsyncClient, weight_dir: str | None) -> None:
response = await admin_client.post("/update_weights", json={"weight_dir": weight_dir})
response.raise_for_status()
# Pause engines so all DP workers drain in-flight work and can join the NCCL broadcast
await _pause_engines(admin_clients)
await _pause_engines(admin_clients, step=step)
try:
# Create ready marker before servers enter receive path (used by NCCL broadcast)
@@ -374,7 +402,17 @@ async def update_weights(
nccl_ready_file.touch()
logger.debug(f"Created NCCL_READY marker at {nccl_ready_file}")
await asyncio.gather(*[_update_weights(admin_client, weight_dir_posix) for admin_client in admin_clients])
await asyncio.gather(
*[
_admin_post(
admin_client,
"/update_weights",
json={"weight_dir": weight_dir_posix},
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
)
for admin_client in admin_clients
]
)
finally:
await _resume_engines(admin_clients)
+7 -1
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
import asyncio
import socket
import time
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Literal
@@ -21,7 +22,7 @@ from httpx import AsyncClient
from renderers import RendererConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.client import load_lora_adapter, setup_admin_clients, setup_clients
from prime_rl.utils.client import ClientIdentity, client_identity, load_lora_adapter, setup_admin_clients, setup_clients
from prime_rl.utils.logger import get_logger
# --- Shared discovery functions ---
@@ -230,6 +231,11 @@ class ElasticInferencePool:
self._eval_index += 1
return client
async def select_train_client(self, load: Mapping[ClientIdentity, int]) -> vf.ClientConfig:
while not self.train_clients:
await asyncio.sleep(self.sync_interval)
return min(self.train_clients, key=lambda c: load[client_identity(c)])
@property
def admin_clients(self) -> list[AsyncClient]:
return list(self._admin_clients.values())
+25
View File
@@ -245,3 +245,28 @@ class ProgressTracker:
percent = int(100 * self.current / self.total)
if percent > self._last_logged_percent:
self._emit_progress(percent)
def format_time(seconds: float) -> str:
"""
Format a time in seconds to a human-readable format:
- >1d -> Xd Yh
- >1h -> Xh Ym
- >1m -> Xm Ys
- <1s -> Xms
- Else: Xs
"""
if seconds < 1:
return f"{seconds * 1000:.0f}ms"
if seconds < 60:
return f"{seconds:.1f}s"
if seconds < 3600:
m, s = divmod(seconds, 60)
return f"{int(m)}m {int(s)}s"
if seconds < 86400:
h, rem = divmod(seconds, 3600)
m = rem // 60
return f"{int(h)}h {int(m)}m"
d, rem = divmod(seconds, 86400)
h = rem // 3600
return f"{int(d)}d {int(h)}h"
+2 -2
View File
@@ -93,7 +93,7 @@ def test_reward_in_range(rl_process: ProcessResult, test_no_error, output_dir: P
"""Tests that the reward is in range in the RL process"""
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
check_reward_in_range(orchestrator_stdout, min_threshold=0.65)
check_reward_in_range(orchestrator_stdout, min_threshold=0.6)
def test_mismatch_kl_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
@@ -113,4 +113,4 @@ def test_reward_in_range_resume(rl_resume_process: ProcessResult, test_no_error_
"""Tests that the reward is in range in the RL resume process"""
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
check_reward_in_range(orchestrator_stdout, min_threshold=0.65)
check_reward_in_range(orchestrator_stdout, min_threshold=0.6)
@@ -406,7 +406,7 @@ def test_reward_in_range(multi_run_result: dict[str, ProcessResult], output_dir:
with open(log_file, "r") as f:
lines = strip_escape_codes(f.read()).splitlines()
if name in ["beta", "gamma"]:
check_reward_in_range(lines, step=7, min_threshold=0.2, max_threshold=0.6)
check_reward_in_range(lines, step=7, min_threshold=0.2)
check_reward_in_range(lines, min_threshold=0.65)
elif name in ["alpha_resume", "beta_resume"]:
check_reward_in_range(lines, min_threshold=0.65)
+35 -92
View File
@@ -1,4 +1,5 @@
import math
import uuid
import pytest
@@ -11,10 +12,11 @@ from prime_rl.configs.orchestrator import (
from prime_rl.orchestrator.advantage import (
AdvantageInputs,
AdvantageOutputs,
compute_advantages,
assign_advantages,
default_advantage_fn,
setup_advantage_fn,
)
from prime_rl.orchestrator.types import TrainRollout
def _make_rollout(
@@ -247,104 +249,45 @@ def test_efficiency_turns_penalty():
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
def test_compute_advantages_with_config():
rewards = [1.0, 0.5, 0.8, 0.2, 0.9, 0.1]
lengths = [10, 12, 8, 15, 11, 9]
rollouts = [_make_rollout(r, l, example_id=i // 3) for i, (r, l) in enumerate(zip(rewards, lengths))]
compute_advantages(rollouts, advantage_config=DefaultAdvantageConfig())
advantages = [r["advantage"] for r in rollouts]
assert len(advantages) == 6
assert sum(advantages[:3]) == pytest.approx(0.0, abs=1e-5)
assert sum(advantages[3:]) == pytest.approx(0.0, abs=1e-5)
def test_compute_advantages_no_cross_group_leakage():
"""Per-problem grouping: each problem must be centered against its own mean, in-order.
Two problems with very different reward scales — cross-group leakage would pull the
small-scale group's advantages toward the large-scale group's mean (and vice versa).
Distinct positional values also catch ordering bugs in the group→flat round-trip.
"""
rewards = [10.0, 20.0, 30.0, 0.0, 0.1, 0.2]
rollouts = [_make_rollout(r, example_id=i // 3) for i, r in enumerate(rewards)]
compute_advantages(rollouts, advantage_config=DefaultAdvantageConfig())
advantages = [r["advantage"] for r in rollouts]
assert advantages == pytest.approx([-10.0, 0.0, 10.0, -0.1, 0.0, 0.1], abs=1e-5)
def test_compute_advantages_without_config():
rewards = [1.0, 0.5, 0.8]
lengths = [10, 12, 8]
rollouts = [_make_rollout(r, l) for r, l in zip(rewards, lengths)]
compute_advantages(rollouts, advantage_config=None)
advantages = [r["advantage"] for r in rollouts]
assert advantages == rewards
def test_compute_advantages_partial_groups():
"""Partial groups (size < group_size) are advantaged against their own mean.
Two groups of different sizes must round-trip cleanly: each group's advantages
must sum to zero and not leak into the other.
"""
# Group A (example_id=0): 4 rollouts. Group B (example_id=1): 2 rollouts.
rollouts = [
_make_rollout(1.0, example_id=0),
_make_rollout(0.0, example_id=0),
_make_rollout(1.0, example_id=0),
_make_rollout(0.0, example_id=0),
_make_rollout(0.3, example_id=1),
_make_rollout(0.7, example_id=1),
def _train_rollouts(rewards: list[float]) -> list[TrainRollout]:
"""Wrap a list of rewards into ``TrainRollout``\\ s sharing a single
``group_id`` — ``assign_advantages`` works on one group at a time
(the sink groups by ``group_id`` upstream)."""
gid = uuid.uuid4()
return [
TrainRollout(
raw={"reward": r, "trajectory": []},
env_name="test",
example_id=0,
group_id=gid,
policy_version=0,
off_policy_steps=0,
)
for r in rewards
]
compute_advantages(rollouts, advantage_config=DefaultAdvantageConfig())
advantages = [r["advantage"] for r in rollouts]
# Group A: mean=0.5, advantages=[0.5, -0.5, 0.5, -0.5]
assert advantages[:4] == pytest.approx([0.5, -0.5, 0.5, -0.5], abs=1e-5)
# Group B: mean=0.5, advantages=[-0.2, 0.2]
assert advantages[4:] == pytest.approx([-0.2, 0.2], abs=1e-5)
def test_assign_advantages_writes_field():
rollouts = _train_rollouts([1.0, 0.5, 0.8])
fn = setup_advantage_fn(DefaultAdvantageConfig())
assign_advantages(rollouts, fn)
advs = [r.advantage for r in rollouts]
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
def test_compute_advantages_singleton_group_gets_zero_advantage():
"""A group of size 1 has reward == mean, so its advantage is 0 (filterable downstream)."""
rollouts = [
_make_rollout(0.5, example_id=0),
_make_rollout(0.8, example_id=0),
_make_rollout(0.3, example_id=1), # singleton group
]
compute_advantages(rollouts, advantage_config=DefaultAdvantageConfig())
advantages = [r["advantage"] for r in rollouts]
# Group 0: mean=0.65, advantages=[-0.15, 0.15]
assert advantages[:2] == pytest.approx([-0.15, 0.15], abs=1e-5)
# Group 1 (singleton): advantage=0
assert advantages[2] == pytest.approx(0.0, abs=1e-5)
def test_assign_advantages_without_fn_is_reward():
"""``advantage_fn=None`` falls back to ``advantage = reward``."""
rollouts = _train_rollouts([1.0, 0.5, 0.8])
assign_advantages(rollouts, None)
assert [r.advantage for r in rollouts] == [1.0, 0.5, 0.8]
def test_compute_advantages_disambiguates_example_id_across_envs():
"""example_id=0 in env A and example_id=0 in env B must not be grouped together."""
rollouts = [
_make_rollout(1.0, env_name="env_a", example_id=0),
_make_rollout(0.0, env_name="env_a", example_id=0),
_make_rollout(100.0, env_name="env_b", example_id=0),
_make_rollout(200.0, env_name="env_b", example_id=0),
]
compute_advantages(rollouts, advantage_config=DefaultAdvantageConfig())
advantages = [r["advantage"] for r in rollouts]
# env_a group: mean=0.5, advantages=[0.5, -0.5]
assert advantages[:2] == pytest.approx([0.5, -0.5], abs=1e-5)
# env_b group: mean=150, advantages=[-50, 50]
assert advantages[2:] == pytest.approx([-50.0, 50.0], abs=1e-5)
def test_assign_advantages_singleton_group_is_zero():
"""A group of size 1 has reward == mean, so its advantage is 0."""
rollouts = _train_rollouts([0.7])
fn = setup_advantage_fn(DefaultAdvantageConfig())
assign_advantages(rollouts, fn)
assert rollouts[0].advantage == pytest.approx(0.0, abs=1e-6)
def test_setup_advantage_fn_with_custom_config():
-233
View File
@@ -1,233 +0,0 @@
import random
from unittest.mock import MagicMock
import pytest
import verifiers as vf
from datasets import Dataset
from prime_rl.configs.orchestrator import BufferConfig, EnvConfig
from prime_rl.orchestrator.buffer import Buffer
from prime_rl.orchestrator.envs import Envs, TrainEnv
def make_env(name: str, vf_env: vf.Environment, **config_kwargs) -> TrainEnv:
"""Create a TrainEnv without calling vf.load_environment."""
config = EnvConfig(id=name, name=name, **config_kwargs)
env = TrainEnv.__new__(TrainEnv)
env.config = config
env._env = vf_env
env._env_client = None
env._env_server_process = None
env.sampling_args = {}
return env
def make_envs(env_dict: dict[str, TrainEnv]) -> Envs:
"""Create an Envs container from a dict of Env instances."""
envs = Envs.__new__(Envs)
envs._envs = env_dict
return envs
@pytest.fixture(autouse=True)
def set_seed():
random.seed(42)
@pytest.fixture
def mock_openai_client():
"""Return a mocked OpenAI client."""
return MagicMock()
@pytest.fixture
def dummy_dataset() -> Dataset:
"""Return a dummy dataset with 5 examples."""
return Dataset.from_dict(
{
"question": ["q0", "q1", "q2", "q3", "q4"],
"answer": ["a0", "a1", "a2", "a3", "a4"],
}
)
@pytest.fixture
def dummy_envs(mock_openai_client, dummy_dataset) -> Envs:
"""Return an Envs with two dummy envs."""
env_a = vf.SingleTurnEnv(
client=mock_openai_client,
model="test-model",
dataset=dummy_dataset,
rubric=vf.Rubric(),
)
env_b = vf.SingleTurnEnv(
client=mock_openai_client,
model="test-model",
dataset=dummy_dataset,
rubric=vf.Rubric(),
)
return make_envs(
{
"env_a": make_env("env_a", env_a),
"env_b": make_env("env_b", env_b),
}
)
@pytest.fixture
def make_rollouts():
def _make_rollouts(
buffer: Buffer, env_name: str, indices: list[int], rewards: list[float]
) -> list[vf.RolloutOutput]:
all_rollouts = []
eb = buffer.env_buffers[env_name]
examples = list(eb.examples.values())
for idx, reward in zip(indices, rewards):
example = examples[idx]
rollouts = [
vf.RolloutOutput(
example_id=example["example_id"],
task=example["env_name"],
prompt=example["prompt"],
prompt_ids=[0],
prompt_mask=[1],
completion_ids=[1],
completion_mask=[1],
completion_logprobs=[0.0],
is_truncated=False,
reward=reward,
advantage=1.0,
metrics={},
)
] * 2
for r in rollouts:
r["env_name"] = env_name
all_rollouts.extend(rollouts)
return all_rollouts
return _make_rollouts
def get_normal_count(buffer: Buffer) -> int:
return sum(eb.num_normal for eb in buffer.env_buffers.values())
def test_buffer_init_and_sample(dummy_envs):
buffer = Buffer(dummy_envs, BufferConfig())
assert buffer.env_buffers["env_a"].num_normal == 5
assert buffer.env_buffers["env_b"].num_normal == 5
samples = buffer.sample_examples(2)
assert len(samples) == 2
def test_buffer_problem_pool_assignment(dummy_envs, make_rollouts):
"""Problems are moved to easy/hard pools based on reward thresholds."""
buffer = Buffer(dummy_envs, BufferConfig(easy_threshold=1.0, hard_threshold=0.0))
buffer.update(make_rollouts(buffer, "env_a", list(range(5)), rewards=[1.0, 1.0, 0.5, 0.5, 0.0]))
assert len(buffer.env_buffers["env_a"].easy_examples) == 2
assert len(buffer.env_buffers["env_a"].hard_examples) == 1
# 2 normal from env_a + 5 from env_b = 7
assert get_normal_count(buffer) == 7
def test_buffer_online_difficulty_filtering(dummy_envs, make_rollouts):
"""With online_difficulty_filtering=True, only partial reward rollouts are kept."""
buffer = Buffer(
dummy_envs,
BufferConfig(online_difficulty_filtering=True),
)
buffer.update(make_rollouts(buffer, "env_a", list(range(5)), rewards=[1.0, 0.5, 0.0, 0.5, 0.5]))
# Only 3 problems with reward 0.5 -> 6 rollouts kept
assert len(buffer.rollout_buffer) == 6
def test_buffer_no_filtering_by_default(dummy_envs, make_rollouts):
"""With online_difficulty_filtering=False (default), all rollouts are kept."""
buffer = Buffer(dummy_envs, BufferConfig())
buffer.update(make_rollouts(buffer, "env_a", list(range(5)), rewards=[1.0, 0.5, 0.0, 0.5, 0.5]))
# All 5 problems -> 10 rollouts kept
assert len(buffer.rollout_buffer) == 10
def test_buffer_save_load_with_conversion(dummy_envs, make_rollouts, tmp_path):
"""Easy/hard problems are partially converted to normal on load."""
buffer = Buffer(dummy_envs, BufferConfig(easy_threshold=1.0, hard_threshold=0.0))
buffer.update(make_rollouts(buffer, "env_a", list(range(5)), rewards=[1.0, 1.0, 0.5, 0.5, 0.0]))
buffer.save(tmp_path / "buffer")
new_buffer = Buffer(dummy_envs, BufferConfig(easy_fraction=0.5, hash_keys=["prompt", "env_name"]))
new_buffer.load(tmp_path / "buffer")
# 1 of 2 easy problems converted to normal
assert len(new_buffer.env_buffers["env_a"].easy_examples) == 1
# 2 were normal + 5 from env_b + 1 converted from easy = 8
assert get_normal_count(new_buffer) == 8
def test_buffer_env_ratios(mock_openai_client, dummy_dataset):
env_a = vf.SingleTurnEnv(client=mock_openai_client, model="test-model", dataset=dummy_dataset, rubric=vf.Rubric())
env_b = vf.SingleTurnEnv(client=mock_openai_client, model="test-model", dataset=dummy_dataset, rubric=vf.Rubric())
envs = make_envs(
{
"env_a": make_env("env_a", env_a, ratio=0.8),
"env_b": make_env("env_b", env_b, ratio=0.2),
}
)
buffer = Buffer(envs, BufferConfig())
assert buffer.env_buffers["env_a"].num_normal == 5
assert buffer.env_buffers["env_b"].num_normal == 5
samples = buffer.sample_examples(100)
env_a_count = sum(1 for p in samples if p["env_name"] == "env_a")
assert 60 <= env_a_count <= 95
def test_buffer_env_ratios_validation():
"""Validates that env ratios must be positive and all-or-nothing."""
from pydantic import ValidationError
from prime_rl.configs.orchestrator import TrainConfig, TrainEnvConfig
with pytest.raises(ValidationError):
EnvConfig(id="env_a", ratio=-0.3)
with pytest.raises(ValidationError, match="mix of set and unset"):
TrainConfig(env=[TrainEnvConfig(id="a", ratio=0.5), TrainEnvConfig(id="b")])
def test_buffer_no_cross_env_pool_assignment(mock_openai_client, tmp_path):
"""Pool assignments don't transfer if example_id exists but env changed."""
original_dataset = Dataset.from_dict({"question": ["q0"], "answer": ["a0"]})
original_env = vf.SingleTurnEnv(
client=mock_openai_client,
model="test-model",
dataset=original_dataset,
rubric=vf.Rubric(),
)
original_env_set = make_envs({"env_a": make_env("env_a", original_env)})
buffer = Buffer(original_env_set, BufferConfig(easy_threshold=1.0))
eb = buffer.env_buffers["env_a"]
example_id = list(eb.examples.keys())[0]
example = eb.examples.pop(example_id)
eb.easy_examples.append(example)
buffer.save(tmp_path / "buffer")
new_dataset = Dataset.from_dict({"question": ["different_q"], "answer": ["different_a"]})
new_env = vf.SingleTurnEnv(
client=mock_openai_client,
model="test-model",
dataset=new_dataset,
rubric=vf.Rubric(),
)
new_env_set = make_envs({"env_b": make_env("env_b", new_env)})
new_buffer = Buffer(new_env_set, BufferConfig())
new_buffer.load(tmp_path / "buffer")
assert len(new_buffer.env_buffers["env_b"].easy_examples) == 0
assert new_buffer.env_buffers["env_b"].num_normal == 1
+60 -42
View File
@@ -1,4 +1,5 @@
import math
import uuid
from prime_rl.configs.orchestrator import GibberishFilterConfig, RepetitionFilterConfig
from prime_rl.orchestrator.filters import (
@@ -8,10 +9,19 @@ from prime_rl.orchestrator.filters import (
setup_filter,
setup_filters,
)
from prime_rl.orchestrator.types import TrainRollout
def _make_rollout(completion_ids, completion_logprobs, reward=1.0, multi_step=False):
"""Create a minimal rollout dict matching the verifiers RolloutOutput structure."""
def _make_rollout(
completion_ids: list[int],
completion_logprobs: list[float],
*,
reward: float = 1.0,
multi_step: bool = False,
) -> TrainRollout:
"""Build a ``TrainRollout`` with a minimal ``vf.RolloutOutput``-shaped
raw payload — enough for the filters to inspect ``trajectory`` /
``stop_condition`` / etc."""
if multi_step:
mid = len(completion_ids) // 2
trajectory = [
@@ -40,12 +50,20 @@ def _make_rollout(completion_ids, completion_logprobs, reward=1.0, multi_step=Fa
}
}
]
return {
raw = {
"trajectory": trajectory,
"reward": reward,
"stop_condition": None,
"metrics": {},
}
return TrainRollout(
raw=raw,
env_name="test",
example_id=0,
group_id=uuid.uuid4(),
policy_version=0,
off_policy_steps=0,
)
def _make_gibberish_filter(vocab_size=128_000, token_id_threshold=100_000, logprob_offset=2.0, enforce=False):
@@ -209,7 +227,7 @@ def test_setup_filters_multiple():
GibberishFilterConfig(),
RepetitionFilterConfig(),
]
filters = setup_filters(configs, vocab_size=128_000)
filters = setup_filters(configs, vocab_size=128_000, kind="post-batch")
assert len(filters) == 2
assert filters[0].name == "gibberish"
assert filters[1].name == "repetition"
@@ -229,12 +247,12 @@ def test_apply_filters_enforced_flags_rollout():
apply_filters([gibberish_filter], [rollout])
assert rollout["reward"] == 1.0
assert rollout["trajectory"][0]["tokens"]["completion_ids"] == [120_000]
assert rollout["trajectory"][0]["tokens"]["completion_mask"] == [1]
assert rollout["stop_condition"] is None
assert rollout["filters"] == {"gibberish": True}
assert rollout["is_filtered"] is True
assert rollout.reward == 1.0
assert rollout.raw["trajectory"][0]["tokens"]["completion_ids"] == [120_000]
assert rollout.raw["trajectory"][0]["tokens"]["completion_mask"] == [1]
assert rollout.raw["stop_condition"] is None
assert rollout.filter_results == {"gibberish": True}
assert rollout.is_filtered is True
def test_apply_filters_preserves_clean_rollouts():
@@ -248,12 +266,12 @@ def test_apply_filters_preserves_clean_rollouts():
apply_filters([gibberish_filter], [rollout])
assert rollout["reward"] == 1.0
assert rollout["trajectory"][0]["tokens"]["completion_ids"] == [50, 60, 70]
assert all(m == 1 for m in rollout["trajectory"][0]["tokens"]["completion_mask"])
assert rollout["stop_condition"] is None
assert rollout["filters"] == {"gibberish": False}
assert rollout["is_filtered"] is False
assert rollout.reward == 1.0
assert rollout.raw["trajectory"][0]["tokens"]["completion_ids"] == [50, 60, 70]
assert all(m == 1 for m in rollout.raw["trajectory"][0]["tokens"]["completion_mask"])
assert rollout.raw["stop_condition"] is None
assert rollout.filter_results == {"gibberish": False}
assert rollout.is_filtered is False
def test_apply_filters_first_filter_wins():
@@ -268,9 +286,9 @@ def test_apply_filters_first_filter_wins():
apply_filters([gibberish_filter, repetition_filter], [rollout])
assert rollout["stop_condition"] is None
assert rollout["filters"] == {"gibberish": True, "repetition": False}
assert rollout["is_filtered"] is True
assert rollout.raw["stop_condition"] is None
assert rollout.filter_results == {"gibberish": True, "repetition": False}
assert rollout.is_filtered is True
def test_apply_filters_empty_list():
@@ -279,9 +297,9 @@ def test_apply_filters_empty_list():
completion_logprobs=[-1.0, -1.0, -1.0],
)
apply_filters([], [rollout])
assert rollout["filters"] == {}
assert rollout["is_filtered"] is False
assert rollout["reward"] == 1.0
assert rollout.filter_results == {}
assert rollout.is_filtered is False
assert rollout.reward == 1.0
def test_apply_filters_mixed_batch():
@@ -294,10 +312,10 @@ def test_apply_filters_mixed_batch():
apply_filters([gibberish_filter], [clean, dirty])
assert clean["reward"] == 1.0
assert dirty["reward"] == 1.0
assert clean["is_filtered"] is False
assert dirty["is_filtered"] is True
assert clean.reward == 1.0
assert dirty.reward == 1.0
assert clean.is_filtered is False
assert dirty.is_filtered is True
def test_apply_filters_enforced_preserves_rollout_tokens():
@@ -311,14 +329,14 @@ def test_apply_filters_enforced_preserves_rollout_tokens():
apply_filters([gibberish_filter], [rollout])
assert rollout["trajectory"][0]["tokens"]["completion_ids"] == [10, 120_000, 30]
assert rollout["trajectory"][0]["tokens"]["completion_logprobs"] == [
assert rollout.raw["trajectory"][0]["tokens"]["completion_ids"] == [10, 120_000, 30]
assert rollout.raw["trajectory"][0]["tokens"]["completion_logprobs"] == [
-1.0,
gibberish_filter.logprob_threshold - 1.0,
-0.5,
]
assert rollout["trajectory"][0]["tokens"]["completion_mask"] == [1, 1, 1]
assert rollout["is_filtered"] is True
assert rollout.raw["trajectory"][0]["tokens"]["completion_mask"] == [1, 1, 1]
assert rollout.is_filtered is True
def test_apply_filters_preserves_existing_stop_condition():
@@ -329,12 +347,12 @@ def test_apply_filters_preserves_existing_stop_condition():
completion_logprobs=[gibberish_filter.logprob_threshold - 1.0],
reward=1.0,
)
rollout["stop_condition"] = "generation_truncated"
rollout.raw["stop_condition"] = "generation_truncated"
apply_filters([gibberish_filter], [rollout])
assert rollout["stop_condition"] == "generation_truncated"
assert rollout["is_filtered"] is True
assert rollout.raw["stop_condition"] == "generation_truncated"
assert rollout.is_filtered is True
# --- apply_filters tests (monitor-only, enforce=False) ---
@@ -351,11 +369,11 @@ def test_apply_filters_monitor_only_tracks_detection():
apply_filters([gibberish_filter], [rollout])
assert rollout["reward"] == 1.0
assert all(m == 1 for m in rollout["trajectory"][0]["tokens"]["completion_mask"])
assert rollout["stop_condition"] is None
assert rollout["filters"] == {"gibberish": True}
assert rollout["is_filtered"] is False
assert rollout.reward == 1.0
assert all(m == 1 for m in rollout.raw["trajectory"][0]["tokens"]["completion_mask"])
assert rollout.raw["stop_condition"] is None
assert rollout.filter_results == {"gibberish": True}
assert rollout.is_filtered is False
def test_apply_filters_monitor_only_mixed_batch():
@@ -368,7 +386,7 @@ def test_apply_filters_monitor_only_mixed_batch():
apply_filters([gibberish_filter], [clean, dirty])
assert clean["reward"] == 1.0
assert dirty["reward"] == 1.0
assert clean["is_filtered"] is False
assert dirty["is_filtered"] is False
assert clean.reward == 1.0
assert dirty.reward == 1.0
assert clean.is_filtered is False
assert dirty.is_filtered is False

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