2224 Commits
Author SHA1 Message Date
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
v0.5.1.dev282
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
v0.5.1.dev281
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
v0.5.1.dev280
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.
v0.5.1.dev279
2026-06-04 18:41:03 +08:00
samsjaandGitHub 5b5f234053 add worlde (#2704)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
v0.5.1.dev278
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>
v0.5.1.dev277
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
v0.5.1.dev276
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>
v0.5.1.dev275
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>
v0.5.1.dev274
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>
v0.5.1.dev273
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
v0.5.1.dev272
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>
v0.5.1.dev271
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
v0.5.1.dev270
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>
v0.5.1.dev269
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>
v0.5.1.dev268
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>
v0.5.1.dev267
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
v0.5.1.dev266
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>
v0.5.1.dev265
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>
v0.5.1.dev264
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>
v0.5.1.dev263
2026-06-01 12:03:19 -07:00
JannikStandGitHub 543e37eb3a Disable vLLM DeepGEMM by default (#2678)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
v0.5.1.dev262
2026-06-01 16:48:08 +02:00
Matej SirovatkaandGitHub 618de8a511 Feat: retry/logging (#2673)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
v0.5.1.dev261
2026-05-30 19:52:27 -07:00
eead822cb3 chore(security): extend cooldown exempt list with first-party deps (#2668)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
prime-rl already had exclude-newer = "7 days" and a partial exempt list
for prime/prime-sandboxes/prime-tunnel/prime-evals. This PR extends the
exempt list with the other PrimeIntellect packages now in prime-rl's
`uv tree` closure: verifiers, renderers, prime-pydantic-config.

The exempt entries are scoped to packages actually in this project's
dep graph — the resolver ignores entries for packages it never sees.

Pins `required-version = ">=0.11.1"` so older uvs fail loudly instead
of silently parsing "7 days" as an RFC 3339 date and proceeding
*without* the cooldown — see uv#17908.

Lock regenerated. Five third-party env packages were rolled back by the
existing cooldown (opencode-cp/math/science/swe and mini-swe-agent-plus
each released in the past 7 days), confirming the cooldown is doing
real protection work, not just sitting as config.

Part 1 of 3 in a coordinated supply-chain hardening across PI repos.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
v0.5.1.dev260
2026-05-31 00:27:36 +02:00
Matej SirovatkaandGitHub aeaf4c44f1 Update BUGBOT.md with custom model requirements (#2672)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Added requirements for new custom models in PRs.

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
v0.5.1.dev259
2026-05-30 00:58:24 +02:00
241d8e931e feat: configurable grace period for SLURM multinode (#2670)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: configurable grace period for SLURM cleanup

Add slurm.cleanup_grace_period_seconds (default 3600) so that when a
component exits — completion, crash, or SIGTERM — the multi-node RL and
inference sbatch teardown sends SIGTERM and then waits up to the grace
period for the remaining processes to exit before force-killing and
releasing the allocation. This gives in-flight work, notably trainer
checkpoint writes, a bounded window to flush. The wait ends as soon as
all processes exit, so it is only an upper bound; set to 0 for the
previous immediate force-kill behavior.

Closes #2664

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

* refactor: rename cleanup_grace_period_seconds to cleanup_grace_period

Drop the _seconds suffix; the unit is documented in the field docstring.

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

* chore: drop CHANGELOG entry for cleanup_grace_period

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

* fix: make cleanup grace actually cover cross-node teardown

The previous SIGTERM-then-wait approach didn't help the target case
(inference dies while the trainer is mid-checkpoint on another node):
that teardown is driven by `srun --kill-on-bad-exit=1`, which reaps the
trainer task via SLURM's own KillWait path and never runs our in-task
grace loop.

Instead, on a non-zero exit the failing node now stays alive (signalling
nothing) for the grace period before propagating the exit. Because
--kill-on-bad-exit only fires when a task exits, holding the failing
task keeps peer nodes' checkpointing trainers running untouched until
they flush. Clean (zero-exit) completion is unaffected.

Scope to multi_node_rl only; the inference-only template has no trainer
checkpoints to protect, so it reverts to immediate teardown.

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

* docs: note cleanup_grace_period is multi-node RL only

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

* docs: minimize cleanup_grace_period docstring

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

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
v0.5.1.dev258
2026-05-29 15:15:32 -07:00
rasdaniandGitHub f510ef62cb Fix multi-run checkpoint dispatch (#2661)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
v0.5.1.dev257
2026-05-28 14:27:10 -07:00
26cdf2ee1d chore(deps): bump renderers (offset-tokenizer config-build fallback for Laguna) (#2663)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Bumps the deps/renderers submodule 89ab3f0 (v0.1.8.dev35) -> 35c2407
(v0.1.8.dev37), pulling in PrimeIntellect-ai/renderers#75: apply the
config-build fallback to ``_get_offset_tokenizer`` too.

#72 only wired the fallback into ``load_tokenizer``;
``_get_offset_tokenizer`` still called ``AutoTokenizer.from_pretrained``
directly to avoid the fastokens shim and so kept hitting HF's RoPE
validator on Laguna-family models. Every rollout through a hand-coded
renderer (LagunaXS2, Qwen35, ...) crashed with the same KeyError #72
was supposed to fix.

Verified end-to-end against poolside/Laguna-XS.2 with reverse-text:
two RL steps complete cleanly (reward 0.36 / 0.31, ~100 tok/sample);
the run then hits an unrelated single-GPU FSDP OOM on the 256-expert
trainer, which is a config-sizing issue, not the renderers bug.

Also pulls in renderers#74 (``message_tool_names`` field for per-message
tool attribution).

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
v0.5.1.dev256
2026-05-28 13:05:51 -07:00
Matej SirovatkaandGitHub ae748fd69d Support delta-only routed experts replay (#2632)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* Support delta-only routed experts replay

* Pin routed experts replay dependencies

* fix(orchestrator): match longest active prefix in interleave_rollout
v0.5.1.dev255
2026-05-28 03:00:20 +02:00
083127fe32 chore(config): remove unused sampling args (min_tokens, repetition_penalty, seed) (#2656)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Drop `min_tokens`, `repetition_penalty`, and `seed` from `TrainSamplingConfig`
and `EvalSamplingConfig`. They distorted the on-policy sampling distribution
(min_tokens suppressed natural EOS, repetition_penalty introduced
train/serve mismatch) or weren't pulling their weight (seed). Hard
deprecation — no migration window.

Closes #2655

Co-authored-by: Cursor <cursoragent@cursor.com>
v0.5.1.dev254
2026-05-27 16:50:50 -07:00
Varun SinghandGitHub b90aca4221 prevent path where expert biases are not loaded for afmoe (#2658)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* prevent path where expert biases are not loaded

* address bugbot
v0.5.1.dev253
2026-05-27 16:11:45 -07:00
d3727060cb chore(deps): bump renderers (tokenizer config-build fallback for Laguna) (#2657)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Bumps the deps/renderers submodule 2ec28a8 (v0.1.8.dev28) -> 89ab3f0
(v0.1.8.dev35), pulling in PrimeIntellect-ai/renderers#72: when
AutoTokenizer.from_pretrained fails while building the model config
(e.g. HF RoPE validation rejecting nested rope_parameters for
poolside/Laguna-XS.2), fall back to loading the repo's self-contained
tokenizer.json directly. Fixes the tokenizer load crash for the Laguna
model series; loads under the fastokens fast path.

Re-locks uv.lock: renderers now floors openai-harmony at >=0.0.4 (renderers#69).

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
v0.5.1.dev252
2026-05-28 00:44:47 +02:00
1891771201 chore(config): remove wandb.shared shim; fix --no-wandb / --no-ckpt (#2654)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* 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>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
v0.5.1.dev251
2026-05-27 10:23:18 -07:00
10bc02c6dc fix(config): round-trip materialized RLConfig; deprecate wandb.shared (#2649)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(rl-config): accept matching shared/sub duplicates so materialized config round-trips

The single-node SLURM launcher (``rl_slurm`` for
``deployment.type == "single_node"``) dumps the fully-resolved ``RLConfig`` to
``<output_dir>/configs/rl.toml`` and the sbatch script re-runs
``uv run rl @ rl.toml``. ``propagate_shared_fields`` writes both shared keys
(``output_dir``, ``wandb.project``, ...) *and* the matching sub-config keys
(``trainer.output_dir``, ``orchestrator.wandb.project``, ...) during the
first-load propagation; ``model_dump`` preserves both. On re-load the
``if sub_set: conflict`` check fired even though both keys had the same
value — treating a no-op round-trip as ambiguity.

Tighten the check to ``if sub_set and sub != shared_value``: genuine
conflicts still raise (a CLI-shared override silently no-opping against
an inconsistent sub-config value still surfaces), but matching values are
accepted so the materialized config re-loads cleanly. ``output_dir`` and
``wandb.name`` compare against their *transformed* sub-config values
(``output_dir → /run_default`` and ``-trainer``/``-orchestrator``
suffixes in non-shared mode).

Verified end-to-end on the hendrycks-sanity example for all three RL
deployments: local dry-run, single-node SLURM (submitted job 21902 from the
materialized rl.toml — config re-loaded, all three subprocesses spawned,
wandb shared run id preserved across trainer + orchestrator), multi-node
SLURM dry-run (write_subconfigs path).

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

* chore(rl): deprecate wandb.shared, hardcode shared W&B mode

Shared W&B mode (single run for trainer + orchestrator) has been the default
on the rl entrypoint since #1330 and is the only mode anyone uses. The
non-shared mode — two separate runs suffixed ``-trainer`` /
``-orchestrator``, gated on ``wandb.shared = false`` — was kept around as
the legacy fallback and as the reason the validator's ``wandb.name``
propagation needed custom asymmetric ``expected``/conflict logic.

Drop the non-shared path:

* ``SharedWandbConfig.shared`` is removed from the schema. A
  ``mode="before"`` validator pops the field from input dicts with a
  ``FutureWarning`` so existing configs that still set ``shared = true``
  (or ``false``) keep loading.
* ``validate_shared_not_offline`` becomes ``validate_not_offline``:
  ``wandb.offline = true`` at the shared level is rejected because shared
  mode is always on and needs server connectivity. The escape hatch is to
  set ``offline`` per sub-config (``[trainer.wandb] offline = true``,
  ``[orchestrator.wandb] offline = true``).
* ``propagate_shared_fields`` collapses the ``wandb.name`` block into a
  plain ``propagate("wandb.name", "trainer.wandb.name",
  "orchestrator.wandb.name")``. The ``expected``/conflict-against-
  transformed-value machinery is gone; only ``output_dir`` still needs the
  custom block because of its asymmetric ``/run_default`` suffix.
* ``rl_local`` always sets ``WANDB_SHARED_MODE`` / ``WANDB_SHARED_RUN_ID``
  for subprocesses (no ``if config.wandb and config.wandb.shared`` gate).
* The multi-node SLURM template (``multi_node_rl.sbatch.j2``) drops the
  ``{% if wandb_shared %}`` gates and always exports the shared env vars
  + ``WANDB_SHARED_LABEL``. The ``wandb_shared`` template variable is
  removed from both call sites in ``rl_slurm``.
* Configs that still set ``shared = true`` (``configs/nemotron_debug``,
  ``configs/nemotron_4node``) are cleaned up.
* Docs + the runtime info log are updated.

Verified end-to-end on hendrycks-sanity (job 21919, single-node SLURM): the
materialized rl.toml round-trips through the validator, both trainer and
orchestrator log ``Using shared W&B mode (label=…, primary=…)``, and the
W&B run name is the verbatim shared name (no ``-trainer``/``-orchestrator``
suffix). 234 config-related unit tests pass.

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

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
v0.5.1.dev250
2026-05-26 22:18:26 -07:00
samsjaandGitHub dbe4d1f351 Handle token export mkdir race (#2628)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Ignore FileExistsError from mkdir when the token export step path is already a directory.

(cherry picked from 5ee18c884bec295c77bfe6d9d276197985b01a38)
v0.5.1.dev249
2026-05-26 22:07:58 -07:00
JannikStandGitHub 4ecb92b534 Add ModelExpress to CUDA image (#2621)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* add ModelExpress to CUDA image

* add UCX runtime library to CUDA image

* build CUDA-enabled UCX for ModelExpress

* Keep protobuf 6 for ModelExpress image

* Scope ModelExpress protobuf metadata override

* Avoid empty UCX library path segment

* Cap ModelExpress protobuf metadata override
v0.5.1.dev248
2026-05-27 01:59:26 +02:00
6d17559422 Consume the typed RendererConfig surface (#2635)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* Consume the typed RendererConfig surface

Reshapes the orchestrator / SFT renderer plumbing around
``renderers.RendererConfig`` (the typed discriminated union) instead of
flat strings + booleans.

- ``configs.shared.RendererConfig`` now composes ``renderers.RendererConfig``
  as a single ``settings`` field; ``pool_size`` stays as a separate
  prime-rl-side concern. The flat ``name`` / ``tool_parser`` /
  ``reasoning_parser`` / ``preserve_*`` fields are gone.
- ``setup_inference_pool`` / ``setup_clients`` / ``StaticInferencePool``
  / ``ElasticInferencePool`` collapse their six-arg renderer surface to
  a single ``renderer_config: RendererConfig | None`` plus the orthogonal
  ``renderer_model_name`` / ``renderer_pool_size`` fields.
- Orchestrator + SFT trainer call sites pass the typed config straight
  through to ``create_renderer(tokenizer, config.renderer.settings)``.
- Cross-env / unmapped-model validators rewritten to inspect
  ``renderer.settings`` (discriminated-union shape) instead of the flat
  field names.
- Tests updated to construct typed configs (``Qwen3VLRendererConfig()``,
  etc.) and assert against the new call shapes.

Pins ``deps/renderers`` and the ``prime-rl-configs`` ``renderers`` dep to
the renderers PR's tip
(``4c9099debbc9bc4fcc3eb6a118bbfa5c364ec395``) until it merges and a dev
release ships.

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

* Bump renderers pin to the merged v0.1.8.dev27

The typed-config refactor landed on renderers main as ``c86c50b``
(tag ``renderers-v0.1.8.dev27``). Switching:

- ``deps/renderers`` submodule pointer → ``c86c50b``
- ``prime-rl-configs`` git URL pin → ``@renderers-v0.1.8.dev27``

Same commit, more readable, and stable to anyone reading the diff
after the feature branch is deleted. PyPI dev release for the same
version is pending a publisher-config fix; once it lands the git URL
pin can collapse to a plain ``renderers>=0.1.8.dev27`` PyPI pin.

* Migrate in-repo TOMLs to the typed renderer schema

The new RendererConfig accepts only `settings` (typed
`renderers.RendererConfig` discriminated union) and `pool_size`, so
flat `name`/`reasoning_parser`/`preserve_*` keys under
`[orchestrator.renderer]` now fail pydantic validation. Move those
keys under `[orchestrator.renderer.settings]`. `pool_size` stays in
the outer block. Two configs that only set `preserve_all_thinking`
gain an explicit `name = "auto"` since the discriminator is required.

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

* Use renderers.RendererConfig directly; None means MITO

Per Mika's review: drop prime-rl's RendererConfig wrapper that nested
the renderers' discriminated union under a ``.settings`` field. The
wrapper bought a parallel ``pool_size`` attribute but cost a clunky
two-level TOML layout and made every call site dereference ``.settings``.

Use ``renderers.RendererConfig`` (the typed discriminated union) as
the field type directly. Pool size moves up one level to
``orchestrator.renderer_pool_size``. ``use_renderer: bool`` is gone —
``renderer: RendererConfig | None`` with ``None`` for MITO replaces it
(consistent with how SFT, optimizer, and other optional sub-configs
express absence). TOML callers spell MITO with ``renderer = "None"``,
which ``prime_pydantic_config.BaseConfig._none_str_to_none`` coerces
back to Python None.

Net effect on TOMLs is a wash with the previous commit: 26 in-repo
configs lose the ``.settings`` indirection they gained yesterday, and
one (multimodal) splits ``pool_size`` out of the renderer block.

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

* Pin renderers via PyPI now that 0.1.8.dev27 is published

The slim ``prime-rl-configs`` wheel (installed standalone, outside the
workspace) now resolves ``renderers`` from PyPI instead of the git tag
URL it used while the dev release was waiting on PyPI trusted-publisher
config. The full ``prime-rl`` workspace still pulls renderers from the
``deps/renderers`` submodule, so this only affects downstream slim
consumers.

Re-locks to refresh the lockfile against the same workspace state.

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

* Lazy-import renderers in the typed config schema

The slim ``prime-rl-configs`` install path (configs only, no GPU
deps) asserts that importing the config classes doesn't pull in
``transformers``. ``from renderers import RendererConfig`` at the top
of ``orchestrator.py`` / ``sft.py`` broke that: ``renderers/__init__``
eagerly imports every concrete renderer module (DefaultRenderer,
Qwen3Renderer, …), each of which imports
``transformers.tokenization_utils.PreTrainedTokenizer``.

Defer the renderers import via:
  - ``TYPE_CHECKING``-guarded ``from renderers import RendererConfig``
    so static type checkers still see the typed discriminated union.
  - ``renderer: Any`` field annotation at runtime, so no resolution
    happens at class definition.
  - ``model_validator(mode="before") _resolve_renderer`` that
    lazy-imports ``renderers``, fills the orchestrator default
    (``AutoRendererConfig()``), and coerces dict input through the
    typed union via ``TypeAdapter``. SFT's default stays ``None``.

End-user semantics unchanged; class import is now transformers-free.

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

* Restore typed renderer field; pin renderers to dev28

dev28 lazy-loads concrete renderer classes via PEP 562
``__getattr__`` (renderers#64), so ``from renderers import
RendererConfig`` no longer drags ``transformers`` into ``sys.modules``.
The slim-install CI gate is satisfied without the prior workaround.

Drop the ``Any`` annotation and the ``_resolve_renderer``
model-validator that lazy-resolved the discriminated union from
``OrchestratorConfig`` and ``SFTConfig``. The fields are typed
``RendererConfig | None`` again, and pydantic does the full
discriminator validation at class definition.

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

* Bump deps/renderers (dev28) and deps/verifiers (typed ClientConfig)

- deps/renderers c86c50b -> 2ec28a8 — picks up the PEP 562
  ``__getattr__`` so the workspace install path also lazy-loads
  concrete renderer classes.
- deps/verifiers 04651be -> d107442 — adds the typed
  ``ClientConfig.renderer_config`` field that ``setup_clients``
  forwards. Fixes the unit-test
  ``test_setup_clients_assigns_renderer_and_dp_rank_headers``
  AttributeError on ``renderer_config``.

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

* Preserve MITO across orch.toml round-trip; drop RendererConfig alias

Two cleanups on the typed renderer surface:

1. Per Samsja: drop the ``RendererConfig as RendererSettings`` alias
   in ``client.py`` / ``elastic.py``. The alias was a workaround for the
   former local ``RendererConfig`` wrapper class; with that gone, we
   just import ``RendererConfig`` from renderers directly.

2. Per Cursor bugbot: ``OrchestratorConfig.renderer = None`` (MITO) was
   silently dropped by ``model_dump(exclude_none=True)``, so any saved
   ``control/orch.toml`` would reload as the default
   ``AutoRendererConfig()`` (TITO). Add a wrapping ``model_serializer``
   that re-injects ``renderer = "None"`` (string) when the field is
   ``None``, matching what ``BaseConfig._none_str_to_none`` accepts on
   reload. MITO and TITO now round-trip through TOML.

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

* Address mika review on #2635: rename pool_size, drop factory, trim docstring

- renderer field uses direct AutoRendererConfig() default (frozen, no
  factory needed)
- renderer_pool_size -> pool_size on OrchestratorConfig; cascade through
  client.py, elastic.py, orchestrator.py call sites and the test;
  vf.ClientConfig kwarg name (verifiers-side) stays renderer_pool_size
- shorter docstring on the renderer field

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

* Bump deps/verifiers to f9c68eb2 (both renderer PRs merged to main)

Picks up verifiers main with PR #1463 (surface every parsed tool_call,
drop status filter) and PR #1468 (pipe chat_template_kwargs into typed
RendererConfig) now that both are merged. verifiers 0.1.15.dev11.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Eli Gottlieb <eli@primeintellect.ai>
v0.5.1.dev247
2026-05-26 12:43:26 -07:00
c1f6fbdd3b docs: big revamp (#2602)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* docs: rewrite into 8 task-oriented pages with auto-generated reference

Replaces 22 small/uneven docs files with 8 longer pages modeled on the
verifiers docs: each page opens with a TOC, content is grouped by task
(configure, train, scale, …) instead of by feature, and a single
auto-generated reference page covers every config field.

New pages: overview, configuration, training, scaling, algorithms,
advanced, faqs, reference. reference.md is generated by
scripts/generate_docs_reference.py from the Pydantic config models;
regenerate with `uv run python scripts/generate_docs_reference.py`.

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

* docs: fix stale claims found in source verification pass

- algorithms.md: max_async_level default is 1 (not 2); default loss
  includes the Kimi-K2.5 KL regularizer (was wrongly claimed to drop
  it); update the formula to show the full L = -PG + tau_KL * KL form;
  filter table is `[[orchestrator.filters]]` (plural)
- training.md: checkpoint paths nest under `checkpoints/step_N/{trainer,
  orchestrator}/` rather than separate hierarchies; --inference-gpu-ids
  / --trainer-gpu-ids don't exist — use --deployment.num-{infer,train}-
  gpus and pin physical GPUs via CUDA_VISIBLE_DEVICES; update
  max_async_level prose to match the new default
- scaling.md: same GPU-flag fix throughout the single/multi-GPU
  examples; correct the claim that Muon + optim_cpu_offload is
  unsupported (only fsdp_cpu_offload is blocked)
- configuration.md: there is no generic PRIME_* env var override
  mechanism in pydantic-config — rewrite the env vars section to list
  the specific named vars that individual fields read as defaults
- advanced.md: add the qwen3_vl_moe entry to the VLM registry table;
  the small-scale MoE RL config lives at
  configs/ci/integration/reverse_text_moe/start.toml, not .../rl/
- faqs.md: update the max_async_level Q&A to match the new default

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

* ci: enforce docs/reference.md stays in sync with configs

Adds two safety nets so the auto-generated reference can't silently
drift from the Pydantic config models:

- Pre-commit hook (local): re-runs scripts/generate_docs_reference.py
  whenever a config class or the generator itself is staged. If the
  generated file changes, pre-commit fails the commit so the contributor
  re-stages the regenerated reference.
- GitHub Actions (CI): a small workflow runs the generator and
  `git diff --exit-code docs/reference.md`. Catches anyone who bypassed
  the pre-commit hook.

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

* chore: rename pre-commit hook id to docs-reference

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

* docs(overview): tighten landing page

- Quick run now uses examples/reverse_text/rl.toml; the env is bundled
  with the verifiers submodule so no prime env install is needed, and
  the tmux helper is documented elsewhere instead of duplicated here
- Architecture bullets advertise the SOTA features per process: vLLM
  multi-node + FP8 + P/D disaggregation for inference; FSDP2 + EP
  (incl. DeepEP) + CP + selective AC + FP8 + LoRA + multi-run for the
  trainer
- Drop the "Use prime-rl when you want to" bullets and the CPU-only
  SFT smoke check — the landing page reads cleaner without them

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

* docs(configuration): trim and reorganize

- Drop the env-vars section entirely (and the precedence callout that
  referenced it) — the page is now strictly TOML + CLI. The few named
  env vars that individual fields read as defaults are out of scope for
  the config docs and stay in the per-feature pages (training.md, etc.)
- Drop the entrypoint enumeration and the W&B/output-dir recommendation
  blurb in the intro
- Reword "@ introduces a TOML file" so the sentence doesn't lead with
  an inline code token; convert the "Mind the space" hint to a
  blockquote
- Drop --output-dir from the convenience-flag list (it's just another
  override, not a special flag)
- Note that --dry-run is available on rl, sft, and inference only —
  the standalone trainer and orchestrator configs don't have a dry_run
  field
- Split "Booleans, None, and lists" into one section each, matching
  the pydantic-config README style; add a Dicts section
- Drop the "Prefer --ckpt" convention bullet — checkpointing is
  covered in training.md and didn't belong in the config conventions

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

* docs(training): drop redundant OpenAI-compatible prefix on vLLM server

vLLM is an OpenAI-compatible server by default; the prefix in the
entrypoints table was just noise. Other mentions of "OpenAI-compatible"
describe the API surface or third-party endpoints and stay.

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

* docs(training): trim and restructure per review

- Quick-start now uses examples/reverse_text/rl.toml; drop the prime
  env install and tmux preamble (covered elsewhere)
- Add a "Useful CLI flags" subsection: --ckpt, --wandb, --orchestrator.
  prime-monitor (Prime Lab), --clean-output-dir, --output-dir,
  --max-steps, --dry-run
- Mention the env-server / env-worker fan-out in the orchestrator
  bullet under "What each process does at runtime"
- Restrict the Key knobs table to orchestrator-only args; drop
  max_async_level, max_completion_tokens, inference, trainer rows;
  rename rollouts_per_example row to lead with "Group size"
- SFT Launch now uses examples/reverse_text/sft.toml; drop the CPU
  fake-data smoke alternative
- "two distillation modes" -> "three training modes" (rl/opd/sft)
- Drop the long-run checkpoint-combo recommendation
- Drop the trainer+orchestrator lockstep note from Resuming a run
- Swap order: Platform monitoring now appears before Prometheus +
  BetterStack under Observability; show --orchestrator.prime-monitor
  CLI invocation
- Rename "Metrics that matter" -> "Important metrics"; drop the live
  vLLM curl snippet
- Drop "Eyeball the reward distribution", "Match inference.parallel.tp",
  and "Set max_async_level deliberately" rules of thumb
- Add new rules of thumb: batch size >= 64; group size >= 8 with the
  reasoning that all-succeed / all-fail groups give the trainer no
  signal because the within-group advantage collapses
- Drop the Common Issues section entirely

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

* docs: trim scaling layout table and move multi-node logs to training

- scaling.md: drop the 1-GPU row and the "Production MoE with long
  contexts" row from the "Choosing a layout" table; the disaggregated
  prefill/decode page section is still findable via its own H2
- scaling.md: drop the trailing "Multi-node logs" section (heading +
  TOC entry); the content now lives next to single-node log layout
- training.md: fold the multi-node tree into "Log files" with the
  single-node skip note inlined; add live-tail recipes and the
  per-rank torchrun debug note; mention the tmux helper works on a
  SLURM head node

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

* docs(algorithms): add Renderers section, trim renderer prose

- New Renderers section explains why best-effort interleaving works:
  the renderer guarantees the exact-prefix invariant by construction
  via bridge_to_next_turn. Lists the renderer API surface and the
  hand-coded model coverage
- Drop the verifiers trajectories-design-note link from Discontinuous
  trajectories and the --trajectory-strategy branching deprecation
- Drop preserve_all_thinking workaround mentions from algorithms.md
  and faqs.md (reference.md still documents the fields)
- Leave a TODO(blog-post-url) for the PI site writeup

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

* docs: refresh FAQ + training W&B claim + recommend prime eval

faqs.md:
- Drop the "override an env var in TOML" Q&A (matches the configuration
  page where env vars are no longer documented as a generic override)
- Drop the "max_async_level" Q&A; replace with a max_off_policy_steps
  Q&A — the more impactful knob to tune on long agentic rollouts
- Drop the outdated "two W&B runs per RL job" Q&A; default is shared
  now (wandb.shared = true)
- Drop the SFT-section Q&As that referenced preserve_all_thinking or
  were too thin to keep
- Switch the "evaluate without training" recipe from vf-eval to prime
  eval run (the Prime CLI is the recommended entrypoint)

training.md:
- Fix the W&B section to describe the new default: shared single run
  (wandb.shared = true), with the legacy split as opt-out
- Add max_off_policy_steps to the Key knobs table
- Switch the eval example from vf-eval to prime eval run

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

* docs(faqs): drop the CP <= 8 recommendation

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

* docs(faqs): drop the vLLM log-quieting and KV-cache pressure Q&As

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

* docs(faqs): drop the Environments Hub install Q&A

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

* docs(faqs): drop the Models and environments section

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

* docs(overview): second tightening pass

- Inference bullet now leads with the local default (token-in
  /v1/generate via renderers; OpenAI-compatible routes called out
  as the external-client path) and adds DP/TP/EP with deepep +
  flashinfer all-to-all backends + EPLB, P/D disaggregation behind
  vllm-router, CPU KV-cache offload, and router replay (FP8 MoE
  numerical-parity feature). Weight broadcast is filesystem or NCCL.
- Orchestrator bullet now leads with "owns the data plane across
  many verifiers training and eval environments" plus the per-env
  isolated subprocess + variable-size env-worker pool.
- Trainer bullet drops "torchrun-launched" and surfaces the custom
  modeling code as the enabler for advanced trainer parallelism
  (EP with DeepEP, CP for long sequences).
- Drop the [AIPO] link in the async paragraph (off-policy-aware PG
  + KL regularizer, no paper handle); also drop the "AIPO loss"
  mention from the Algorithms blurb in "Where to go next" so the
  page is internally consistent.
- Quick-run command is now bare: uv run rl @ examples/reverse_text/rl.toml
  (no --wandb.* / --ckpt).
- Drop the trailing scaling pointer (Scaling is already linked in
  "Where to go next").

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

* docs(configuration): second tightening pass

- Drop the entrypoint-splitting paragraph ([trainer] / [orchestrator]
  / [inference] table lifting); covered elsewhere.
- Rename "TOML files and composition" -> "TOML composition", and
  "Special syntax" -> "Syntax".
- Open "Sources and precedence" by naming the three sources (Pydantic
  defaults, TOML files, CLI flags) up front, then layering them.
- Drop the "(-- is a kebab-case marker)" parenthetical from CLI
  overrides; turn the snake/kebab note into a callout.
- Drop the --help / --dry-run convenience-flag block and the
  "--dry-run is the single most useful debugging tool" prose; the
  bash example is enough.
- Reorder Syntax subsections to mirror the pydantic-config README:
  Booleans -> Lists -> Dicts -> Optional sub-configs -> None ->
  Discriminated unions -> Environments. None moves down and is
  cross-linked from "disabling an optional sub-config".
- Booleans example swapped from --ckpt (which is itself an optional
  sub-config) to --clean-output-dir (a real bool = False field),
  showing both --flag and --no-flag forms.
- Lists / Dicts now show TOML and CLI on the *same* field name so
  the mapping is obvious (target_modules for lists, env.0.args for
  dicts), and add the "lists are replaced wholesale" overlay note
  + "dicts deep-merge across sources" detail.
- Add a callout on validation aliases (rollouts_per_example still
  works after the rename to group_size) — only material gap vs the
  pydantic-config README that's relevant to end users.
- Worked example: --dry-run is now the final flag.
- Drop the Conventions section.

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

* docs(training): second tightening pass

- Rename "RL training" -> "RL trainer" and "SFT training" -> "SFT
  trainer" (and update the page intro accordingly).
- Entrypoints table: clarify that `uv run rl` wraps the trainer,
  orchestrator, and inference server in one launch — runs locally
  for single-node experiments and submits to SLURM for single- or
  multi-node when [slurm] is set. Drop the trailing "rl is a
  convenience wrapper" paragraph.
- RL trainer Launch: minimal command is now bare
  `uv run rl @ examples/reverse_text/rl.toml` (no flags). Drop the
  GPU-placement paragraph + multi-GPU example (covered in scaling.md).
- Replace "Useful CLI flags" + "Key knobs" + "What each process does
  at runtime" with one consolidated "Useful knobs" section split into
  three sub-tables: data-and-algorithm, monitoring, run management.
  - Add training environments ([[orchestrator.train.env]] for
    multi-env training)
  - Add eval environments ([[orchestrator.eval.env]] +
    orchestrator.eval.interval)
  - Add monitoring entries: orchestrator.log.vf_level, --wandb,
    --orchestrator.prime-monitor
- Move Training modes from a top-level section into RL trainer as
  a subsection (it's RL-entrypoint-specific).
- Drop the standalone Evaluations section — eval syntax is covered
  in configuration.md and the eval-knobs row in Useful knobs links
  to `prime eval` for one-off evals.
- Drop the optimization_dtype / reduce_dtype rule of thumb.

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

* docs(training): SFT trainer metrics + tools column + minor renames

- Drop "-via-orchestrator" from the Training modes heading and the
  internal/cross-doc anchors. The mode value is just `sft` and the
  short title reads cleaner.
- Drop "and the tmux helper" from the Console output subsection
  title; the tmux helper is still documented in the section body.
- Important metrics is now split into RL trainer and SFT trainer
  subsections so the SFT-only metrics (loss/mean, val/loss,
  progress/{epoch,num_samples,num_tokens}, optim/zero_grad_ratio,
  per-subset mixing ratios, MoE max_vio + routing_confidence,
  perf/peak_memory + the time/* breakdown) are documented.
- SFT Dataset format gains a Tool definitions paragraph: rows can
  carry a `tools` column (OAI function-calling format) or
  `tool_defs` (verifiers rollout format), as either a list of dicts
  or a JSON-encoded string. `tool_defs` is auto-converted to OAI
  shape before being passed into the chat template's `tools=...`
  argument. `chat_template_kwargs` rows pass through verbatim.

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

* docs(training): rename 'Saving HF weights for serving' -> 'Serving checkpoints'

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

* docs: cross-link the agent skills from training + configuration

Adds a callout under the intro of training.md and configuration.md
pointing at the equivalent skill files for AI agents working in
this repo:

- training.md -> skills/training/SKILL.md (top-level routing) +
  skills/training/start-run/SKILL.md (launch details) +
  skills/training/monitor-run/SKILL.md (check-in / restart).
- configuration.md -> skills/configs/SKILL.md.

The skills aren't part of the published Mintlify nav, so the links
go to GitHub blob URLs.

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

* docs(training): fold Important metrics into RL + SFT trainer sections

The standalone "## Important metrics" section is gone. Each
trainer subsection now ends with its own "### Important metrics"
covering only the metrics relevant to that flow:

- RL trainer / Important metrics: reward + rollout signals from the
  orchestrator, mismatch_kl + entropy + grad_norm from the trainer,
  and the trainer/orchestrator/vLLM performance grid.
- SFT trainer / Important metrics: loss/mean, val/loss, progress
  counters, optim signals, MoE max_vio + routing_confidence, and
  the perf/{throughput,mfu,peak_memory} + time/* breakdown.

TOC updated to point at #important-metrics (RL) and
#important-metrics-1 (SFT) — Mintlify de-duplicates with the same
-N suffix scheme it already uses for the two Launch subsections.

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

* docs(training): drop Prometheus and BetterStack subsection

Not ready for end-user docs yet. Both knobs (trainer.metrics_server.port,
trainer.heartbeat.url) are still in reference.md for anyone who needs
them, just no narrative coverage.

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

* docs(training): tighten Useful knobs language

- Use "task" not "prompt" for the conceptual unit ingested by the
  orchestrator (rows for batch_size and group_size, plus the matching
  Rules of thumb wording).
- group_size: drop the "Used for advantage normalization and pass@k
  estimation" trailer; the row name is enough.
- max_off_policy_steps: rename "throughput-vs-noise dial" to just
  "off-policy dial".
- eval row: drop the "Scores land in trainer logs and W&B as
  eval/{env}/{avg@k,pass@k}" + `prime eval` trailer; keep the row
  scoped to what the knob does.
- Add log.level to the Monitoring table (trainer/orchestrator process
  log level, $PRIME_LOG_LEVEL fallback, per-process or global on rl).
- Drop --ckpt from Run management; checkpointing has its own section.

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

* docs(training): trim RL Performance table to the bottleneck signals

Drop the throughput/MFU/async-lag/KV-cache rows from the RL trainer
Performance table — they're either generic perf metrics already
covered by the SFT trainer's perf table or vLLM-internal. The two
remaining rows (time/wait_for_batch, time/wait_for_ckpt) are the
useful diagnostic — they tell you which side is the bottleneck.

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

* docs(training): refresh chat-template prefix-property paragraph

The old wording recommended only patched checkpoints / a custom
chat template as the fix for position-dependent templates. The
renderer-based path landed in SFT (use_renderer flag) and is now
the primary recommended fix, but it's still off by default
(use_renderer: bool = False on SFTConfig), so the patched-
checkpoint path also still works — and is what
examples/reverse_text/sft.toml uses today via PrimeIntellect/
Qwen3-0.6B.

Rewrite the paragraph to cover both fixes:
- Renderer path: use_renderer = true, lists the hand-coded
  renderers, calls out the VLM unsupported case.
- Patched template path: the prime-rl-patched checkpoint or a
  user-supplied template that preserves thinking.

Cross-link both to Algorithms § Renderers and § Multi-turn
trajectories.

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

* docs(training): fix SFT data row (data.name, drop default data.type)

- data.type = "sft" is the discriminated-union default for
  SFTConfig.data, so users don't need to spell it out.
- The dataset path field is data.name, not data.path. Confirmed
  against SFTDataConfig.name in packages/prime-rl-configs/src/
  prime_rl/configs/sft.py.

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

* docs(training): drop loss/nan_count from SFT trainer metrics

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

* docs(advanced): drop the Environments section

Environment installation, authoring, and multi-env mixing are
already covered concisely in configuration.md (Environments syntax)
and training.md (Useful knobs row pointing at the same). The
advanced.md duplicate just spread the same material across three
subsections without adding anything material.

- Drop the section + its TOC entries.
- Update the page intro and overview.md "Where to go next" to stop
  advertising "environments deep-dive" / "environments installation
  and authoring".

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

* docs(advanced): rename "MoE models" -> "Custom modeling" + "LoRA" -> "LoRA training"

The first section was conceptually about our custom modeling stack
(model.impl = "custom"/"auto", the family registry, EP backends),
not about MoE specifically — even though the supported families
happen to be MoE-heavy. Rename so the section title matches the
defining feature.

Bump LoRA to "LoRA training" for parity with the trainer-oriented
section names elsewhere on the page.

Update the page intro and TOC entries to match. No external doc
links to the renamed anchors (#moe-models, #lora) so nothing else
to fix.

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

* docs(advanced): drop 'Poolside' prefix from Laguna family row

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

* docs: rename Vision-language models -> Multimodal training

Standardize on "multimodal training" as the section title:

- advanced.md: "## Vision-language models" -> "## Multimodal training"
  + "### Multi-turn VLM training" -> "### Multi-turn training" (the
  parent context is already multimodal). "### Enabling VLM mode" stays
  because it's literally enabling the [model.vlm] config block.
- advanced.md page intro: "vision-language models" -> "multimodal
  training".
- advanced.md custom-modeling cross-link to (#vision-language-models)
  -> (#multimodal-training).
- overview.md "Where to go next" blurb: align the Advanced bullet's
  language ("MoE training" + "VLMs") with the destination's section
  titles ("Custom modeling" + "multimodal training").

reference.md still mentions "vision-language model" in auto-generated
descriptions sourced from Pydantic field docstrings. Those are
out-of-scope for this rename; would need a config docstring change.

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

* docs(advanced): drop the DeepEP grad-clip-disable tradeoff aside

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

* docs(advanced): fix the freeze_vision_encoder + LoRA claim

The bullet said the combo "has no effect under LoRA (LoRA freezes
everything non-adapter regardless)". Source check:
packages/prime-rl-configs/.../trainer.py:591-597 now contains a
vlm_freeze_incompatible_with_lora validator that explicitly
*rejects* the combo with an error. So the user-facing behavior is
not silent-no-op, it's a config validation failure.

Other bullets in the Limitations list verified against source and
are correct as written:

- "No multimodal-safe truncation": confirmed in trainer/batch.py
  (input_ids / mm_token_type_ids truncated to seq_len; mm_kwargs
  passes through unchanged).
- "bfloat16 mandatory": confirmed by the vlms_require_bfloat16
  validator in trainer.py.
- "Images aren't logged to monitors": confirmed — no image / pixel
  handling in src/prime_rl/utils/monitor/.

The "Higher KL mismatch with multi-image inputs" bullet is left
unchanged for now — flagged for review separately because the cited
rationale ("minor numerical differences between trainer and vLLM
image processing") no longer matches reality after the renderer-
only multimodal path landed (#2473): the renderer now owns image
processing end-to-end and both sides consume the same pre-processed
pixel_values / image_grid_thw. The empirical observation may still
hold but the reason given would be stale.

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

* docs(advanced): drop the Multi-turn training subsection

The render/pack/forward rendition lived close to internal code and
felt out of scope for the user-facing Advanced page; the spawn-method
hint that ended it can move elsewhere if needed.

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

* docs(advanced): rename Multi-run manager -> Multi-tenant training

User-facing framing now leads with the actual use case: many
concurrent LoRA tenants sharing a single trainer + inference
deployment, which is the topology behind hosted training on the
Prime Intellect platform (Lab). The MultiRunManager class still
exists in code and is name-checked in the section body — only the
section title and surrounding prose change.

- advanced.md: rename TOC entry + H2 + open paragraph; drop the now-
  redundant "primary use case today" trailer (Lab is in the intro).
- advanced.md LoRA section: reword the cross-link.
- overview.md: trainer description bullet now says "multi-tenant
  training" instead of "multi-run manager"; "Where to go next"
  Advanced bullet renamed similarly.
- scaling.md: parenthetical aside on optim_cpu_offload incompatibility
  updated for consistency.

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

* docs(advanced): trim multi-tenant training to user-facing surface only

Drop the per-run filesystem layout, Run discovery / Eviction / Hooks
subsections — these are MultiRunManager internals (run_* dir
discovery, evicted.txt protocol, hook lifecycle) that don't belong
in a user-facing Advanced page. The pointer to
src/prime_rl/trainer/runs/ still tells anyone who needs the API
where to look.

The remaining section is one paragraph: what multi-tenant training
buys you, that Lab is the production user, and the
trainer.max_concurrent_runs entry point.

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

* docs: add a Development page; move "Testing MoE at small scale" off Advanced

Advanced was mixing user-facing features (custom modeling, multimodal,
LoRA, multi-tenant training) with developer-facing workflows
(building a tiny MoE for modeling-code iteration, adding a new
architecture). Split the latter into a new Development page so each
audience reads only what's relevant.

- New page: docs/development.md, scoped to "developing on prime-rl
  itself". Contains the unchanged Testing MoE at small scale recipe
  (build/verify mini model, SFT warmup, RL on reverse-text) and the
  Adding a new architecture how-to.
- advanced.md: drop the section + TOC entry; rewrite the page intro
  to point at Development for developer-side workflows.
- mint.json: insert "development" in the nav between "advanced" and
  "faqs".
- overview.md "Where to go next": add the Development bullet, drop
  "small-scale MoE testing" from the Advanced bullet.
- README.md docs index: same split (Advanced + Development as two
  separate bullets).

No external links to the moved anchors needed updating; the only
existing cross-link was the relocated TOC entry in development.md
itself.

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

* docs(algorithms): fold Renderers into Multi-turn trajectories

Renderers existed as a top-level section because they were added in
a follow-up, but conceptually they're the mechanism that makes
best-effort interleaving safe — splitting them apart forced a
forward-reference and duplicated the "exact-prefix invariant" framing.

- Demote "## Renderers" to "### Renderers" inside "## Multi-turn
  trajectories", placed between Best-effort interleaving and
  Discontinuous trajectories.
- Move the Qwen3 thinking-stripping example from Best-effort
  interleaving into Renderers — it's the failure case the renderer
  fixes, so it reads better adjacent to the family list / config
  block.
- Drop the "Workaround: use a chat template that preserves thinking"
  trailer; the patched-checkpoint workaround for SFT is already
  documented in training.md and isn't relevant in the orchestrator
  context (use_renderer defaults to true).
- Open Multi-turn trajectories with a forward-link to Renderers so
  the reader knows the safety mechanism is coming.
- TOC updated; both #multi-turn-trajectories and #renderers anchors
  preserved (only their nesting changes), so the existing cross-
  links from training.md and faqs.md keep working.

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

* docs(algorithms): drop max_async_level tuning + reframe as fixed one-step

max_async_level is being deprecated as a user-facing knob (hardcoded
to 1; matching reframe in docs/async.md on feat/deprecate-max-async-
level). Update algorithms.md so the long-form treatment matches.

- Drop the "### Tuning max_async_level" subsection (the k=0/1/2/>=3
  table) and the NCCL-needs-max_async_level=1 line that follows it
  — both become vacuous when k is fixed at 1.
- Reword the Async / off-policy training intro to describe the
  one-step overlap directly instead of "up to k steps where
  k = max_async_level".
- Step semantics: rho_inference is now pi_{max(0, n-1)}, with prose
  "inference is exactly one step behind the trainer" replacing the
  generic "gap is at most k steps".
- Drop the Tuning entry from the page TOC.

Other docs (overview.md intro, training.md rule of thumb, faqs.md
two entries, scaling.md NCCL-example comment) still mention
max_async_level and are now stale; will clean those up in the next
turn unless flagged otherwise.

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

* docs(development): add Test suite + Pre-commit hooks sections

Pull in the testing- and contributor-workflow content from README and
the GitHub Actions configs so contributors don't have to dig through
.github/workflows/ to figure out what runs where.

New sections in development.md:

- Test suite
  - Layout: tests/unit/, tests/integration/, tests/nightly/ — what
    each tier is for, with the actual file names contributors will
    encounter.
  - Running tests locally: pytest one-liners (everything, unit-only,
    integration-only, -m "not gpu", -m gpu, single file).
  - CI workflows: a 3-row table covering cpu_tests.yaml,
    gpu_tests.yaml (matrix list pulled verbatim from the workflow),
    and nightly_tests.yaml — including the trigger conditions
    (cpu = always, gpu = non-draft, nightly = scheduled +
    workflow_dispatch) and the runners (ubuntu-latest, vm/4xa6000,
    research-cluster).
  - Markers: gpu + slow, both declared with --strict-markers in
    pyproject.toml.
- Pre-commit hooks
  - uv run pre-commit install
  - Currently configured hooks: ruff check/format and
    docs-reference (regenerator that fails the commit if
    docs/reference.md would drift).

Plus update the Development pitch in overview.md "Where to go next"
and README.md docs index to mention the new scope.

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

* docs(algorithms): fold Length penalties into Default advantage

Length penalties are configured under [orchestrator.length_penalty]
and layer on top of *any* advantage function — they're conceptually
not a standalone advantage variant. Move them into Default advantage
where readers will see the option while reading about advantages.

Drive-by: clean up the parenthetical hint in Default advantage. The
old version listed "length penalties tied to turn count" as a reason
to write a custom advantage, which conflicts with the actual
turn-count length penalty being a built-in. New wording points
length-penalty users at the now-adjacent built-in section, and
points custom-advantage users at trajectory-metadata-driven shaping
(sub-agents, relative-rank, …).

TOC entry for #length-penalties dropped; no external doc links to
that anchor.

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

* docs(advanced): add Difficulty pools + Online difficulty filtering

Covers the two complementary buffer-side mechanisms for keeping the
trainer batch high-signal. Verified each claim against
src/prime_rl/orchestrator/buffer.py and packages/prime-rl-configs/
src/prime_rl/configs/orchestrator.py.

- Difficulty pools (buffer.easy_threshold / hard_threshold +
  easy_fraction / hard_fraction): per-problem running-average reward
  is compared to the thresholds; problems hitting either bound move
  to easy/hard pool and stop being sampled. Pool assignments persist
  across checkpoints (easy_examples.jsonl / hard_examples.jsonl);
  *_fraction lifts a fraction of pooled problems back into normal on
  resume / start.
- Online difficulty filtering (buffer.online_difficulty_filtering
  bool): groups whose avg reward is exactly 0.0 or 1.0 are dropped
  from the buffer because their within-group advantage is zero
  (DR-GRPO produces no signal). Counted under filtered_rollouts/
  {env}/{easy,hard} for visibility.
- The tradeoff bit the user asked for explicitly: with ODF on each
  trainer step's effective batch is dense + predictable, but the
  orchestrator pays for the throw-away rollouts and may need a
  higher oversampling_factor; if time/wait_for_batch is already
  high on the trainer, ODF can starve the loop.
- ODF is orthogonal to the pools — ODF reacts to the current
  group's reward distribution, pools track the running per-problem
  average. Configs often use both.

Plus a one-line page-intro update + TOC entries.

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

* docs: relocate Difficulty pools + ODF from Advanced to Algorithms

Both are buffer-side controls over what reaches the trainer — same
conceptual category as Filters and the loss/advantage knobs.
Algorithms is the right home; Advanced is for orthogonal feature
sets (LoRA, multi-tenant, custom modeling, multimodal). Promote each
to its own top-level section.

- algorithms.md: new "## Difficulty pools" and "## Online difficulty
  filtering" sections, inserted between Filters and Multi-turn
  trajectories. TOC updated.
- advanced.md: section + TOC entries + page-intro mention removed.

Content unchanged from the previous commit on Advanced — same
threshold / fraction / persistence claims, same ODF tradeoff
explanation, same cross-link to oversampling_factor. ODF section
back-links to Difficulty pools for the orthogonality note.

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

* docs(development): split MoE-debug recipe; promote "Adding a new architecture"

- "Adding a new architecture" promoted to its own top-level section,
  placed *before* the renamed Debugging MoE recipe so the natural
  reading order is "here's how to wire up a new arch -> here's how
  to smoke-test it". Step 3 of the recipe now forward-links to
  Debugging MoE instead of "the three steps above".
- "Testing MoE at small scale" -> "Debugging MoE". The page is
  already titled Development, so the qualifier was redundant.
- Subsection titles drop the "Step N:" prefixes (the page-level TOC
  already implies sequence) and switch to sentence case for
  consistency with the rest of the docs:
  - Step 1: build and verify a mini model -> Build and verify a mini model
  - Step 2: SFT warmup -> SFT warmup (already correct)
  - Step 3: RL on reverse-text -> RL on reverse-text (already correct)
- TOC updated; README docs index pitch swaps "small-scale MoE
  testing" -> "debugging MoE" to match the new section title.

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

* docs(development): tighten Debugging MoE subsections

- "### Build and verify a mini model" -> "### Create mini model".
  The roundtrip-verify body covers the "and verify" half; the
  shorter title is enough.
- Merge "### SFT warmup" + "### RL on reverse-text" into one
  "### Smoketest training" subsection. The two were always run
  together as a single end-to-end smoke test (warmup so KL is
  meaningful, then RL stack), so a single subsection with two code
  blocks reads better than two artificially-split ones.
- TOC updated. No external doc links to the old sub-anchors.

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

* docs: rename Worked example -> Examples; update reference generator

User-facing docs no longer reference configs/ directly — examples/
is the only "we keep this up to date" surface, the rest is CI- and
debug-internal:

- configuration.md: launch line + worked-example switched to
  examples/reverse_text/rl.toml. Section renamed "Worked example"
  -> "Examples" with a curated tour of the 10 README examples
  (basic 1-8 GPU + advanced SLURM tiers); the compose / override /
  dry-run walkthrough lives as a "### Worked example" subsection.
- training.md: drop the "Debug configs for all variants ship under
  configs/debug/training_modes/" pointer in the Training modes
  section. The prose already explains how to set the mode.
- scaling.md: P/D inference now points at examples/glm5_pd_disag/
  rl.toml (with a link to its README) instead of the configs/-side
  inference-only TOML.
- faqs.md: install-verify and smoke-test recipes both switch from
  configs/debug/sft and configs/gsm8k to examples/reverse_text.

Reference generator (scripts/generate_docs_reference.py):
- Drop "from the Pydantic config models" from the page header.
- Move the regenerate command + structural notes from the header to
  a new "## About this page" footer.
- Wrap the Type column in code spans so list[int], int | None, etc.
  render as code instead of plain text. fmt_type now emits literal
  `|` (GFM accepts pipes inside code spans inside table cells; no
  escaping needed).
- Walk list-of-BaseModel fields. Previously orchestrator.train.env
  / orchestrator.eval.env / orchestrator.filters were rendered as
  one row showing the default repr; their leaf fields never showed
  up. New _list_inner_models() detects both list[X] (single model)
  and list[Annotated[Union[A | B], discriminator]] (discriminated
  union of list items, e.g. filters: list[FilterConfig]). Index
  placeholder rendered as <n> to match the CLI form
  (--orchestrator.train.env.0.id ...).

Regenerate reference.md: +5k chars, mostly the new env/filter
list-item subsections that were missing before.

development.md still references two CI-tested configs/ paths
(configs/debug/moe/sft/train.toml, configs/ci/integration/
reverse_text_moe/start.toml) — those are validated by the
reverse_text_moe GPU integration test on every PR, so they don't
risk drifting. Flagging in case the user wants those swapped too.

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

* docs(training): correct batch-size rule of thumb

128-512 is the range for quick ablations, not production. Production
RL often runs at 1024+.

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

* docs: relocate "Disaggregated prefill/decode inference" to Advanced

P/D disaggregation is a feature you opt into for large-MoE serving,
not a step on the single-GPU -> 1000-GPU scaling ladder. It pairs
naturally with Custom modeling / multi-tenant / multimodal as a
specialized inference topology, so Advanced is the right home.

- scaling.md: drop the section + TOC entry + "disaggregated
  prefill/decode inference" from the page intro. Page intro now
  forward-links to Advanced for users who came in for P/D.
- advanced.md: append the section after Multi-tenant training,
  unchanged content (P:D ratio table, glm5_pd_disag example link,
  queue-depth monitoring snippet, UCX 1.19 build-from-source note).
  TOC + page-intro list updated.
- overview.md "Where to go next": drop disagg from the Scaling
  bullet, add to the Advanced bullet.

Anchor preserved (#disaggregated-prefilldecode-inference) — no
external doc links to it survived the move check.

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

* docs(scaling): correct the Single GPU section

The previous claim "trainer and inference server can share a GPU"
via the rl launcher was wrong. Verified against
src/prime_rl/entrypoints/rl.py:86-99: the launcher partitions
visible GPUs strictly (inference 0..N-1, trainer N..N+M-1) and
raises ValueError when total_requested_gpus > len(physical_gpu_ids).
Setting CUDA_VISIBLE_DEVICES=0 + --num-infer-gpus 1 +
--num-train-gpus 1 makes total=2, visible=1, validation fails
before anything launches.

What actually works for single-GPU RL is the manual three-pane
launch: each of uv run {inference,orchestrator,trainer} is an
independent process with no cross-process GPU validation, so
pinning CUDA_VISIBLE_DEVICES=0 on inference *and* trainer lets
them share the same physical GPU.

- Drop the misleading `uv run rl` recipe.
- Promote the manual three-pane recipe to the canonical single-GPU
  path, with CUDA_VISIBLE_DEVICES=0 spelled out on both the
  inference and trainer panes.
- Lead with SFT (where single-GPU is the default and just works).
- Add an explicit "single-GPU RL is for debugging only" caveat.

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

* docs(scaling): collapse Single GPU / multi-GPU / Multi-node manual into one umbrella

- New umbrella section "## Single-node vs. multi-node deployment"
  framing the [deployment] discriminated union as the user-facing
  knob: single_node runs locally; multi_node currently goes through
  SLURM. Subsections nest beneath:
  - ### Single GPU (unchanged content from "## Single GPU")
  - ### Single-node multi-GPU (unchanged from "## Single-node multi-GPU")
    - #### RL placement
    - #### SFT and torchrun
  - ### Multi-node (new short pointer to ## SLURM with two cross-
    links to the existing RL / SFT-and-inference examples)
- The umbrella section opens with a callout that manual multi-node
  launches are technically possible but reimplement what the SLURM
  launcher does — the user's preferred framing.
- Drop "## Choosing a layout" entirely (the new umbrella section
  conveys the same routing more naturally + the layout table was
  going stale).
- Drop "## Multi-node (manual)" entirely (RL training, SFT training,
  Multi-node inference subsections all gone). Anyone who needs the
  manual recipe can replicate what the SLURM templates do.

Cross-link fixes:

- training.md SFT § Launch line previously pointed at
  scaling.md#sft-training (under "## Multi-node (manual)"). Now
  points at scaling.md#sft-and-torchrun for non-default single-node
  layouts and scaling.md#slurm for multi-node.
- faqs.md "Multi-node without SLURM or K8s?" answer updated: from
  "yes, see [Scaling § Multi-node (manual)]" to "not currently
  documented; technically possible but reimplements the SLURM
  launcher".

Page intro adjusted to match the new structure ("multi-node SLURM
and Kubernetes deployments" -> "single-node and multi-node
deployments").

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

* docs: drop Kubernetes coverage for now

The K8s Helm chart at k8s/prime-rl/ still ships, but the user-facing
docs are dropping coverage until the chart and the matching guide
are re-validated together.

- scaling.md: drop the "## Kubernetes" section + TOC entry. Page
  intro already covered (was reworded earlier in the restructure).
- overview.md "Where to go next": drop "Kubernetes guides" from
  the Scaling bullet.
- README.md docs index: drop "Kubernetes" from the Scaling bullet.

The two passing-mention "k8s" / "Kubernetes" lines in README
(Overview features list, Advanced Training Examples adaptability
note) are left as-is — they describe codebase capability, not docs
coverage. Reference.md still mentions Kubernetes liveness probes in
an auto-generated field docstring; that's source-side, out of scope
for this pass.

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

* docs(development): tighten test-suite layout bullets

- Drop the example test filenames from the tests/integration/
  bullet — they're a moving list and not the point.
- Reframe the tests/nightly/ bullet around what it does (runs the
  examples/ configs to catch regressions) instead of listing the
  individual nightly tests by name.

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

* docs(development): drop the nightly 24h-timeout / research-cluster aside

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

* docs(development): polish 'Adding a new architecture' prose

- Replace the bare 'To add (e.g.) Kimi 2.5:' opener with a one-line
  framing of the two-step contract: implement modeling code,
  register a mini preset for smoke-testing.
- Bold the leading verb on each numbered step so the structure
  reads as a checklist.
- Step 1 now nudges readers at glm4_moe/ and qwen3_moe/ as
  templates for the modeling code.
- Step 2 explains *what* the preset is for ('build a ~0.5B test
  model in your architecture') rather than just listing fields.
  Path now links to scripts/mini_moe.py.
- Step 3 says what the smoke-test actually exercises (roundtrip +
  SFT + RL stack) so users know what 'smoke-test' means here.

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

* ci(docs-reference): add minimal GITHUB_TOKEN permissions

CodeQL alert actions/missing-workflow-permissions
(security/code-scanning/19) flagged the new workflow for relying on
the repo's default GITHUB_TOKEN permissions.

The workflow only checks out code (contents: read), syncs deps via
uv, runs the doc generator, and runs git diff. None of that needs
write scope on any resource type. Pin to contents: read at the
workflow level — explicit minimum that satisfies the rule.

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

* docs: refresh architecture + async diagrams

- assets/architecture.png: replace with the new diagram (trainer
  + orchestrator + inference deployment, GPU layout per process,
  data + scheduling + weight-broadcast arrows). Was 511k 96dpi,
  now 111k @ 200dpi from architecture.pdf.
- assets/two-step-off-policy.png removed; assets/async-pipeline.png
  replaces it with the cleaner one-step-overlap diagram (trainer
  steps g_0..g_n above, inference samples with theta_{n-1} below).
  algorithms.md image reference + alt text updated to match the
  post-deprecation "one-step overlap" framing.
- assets/rollout-timeline.png added but not yet referenced. It's a
  continuous-time view showing rollouts spanning policy boundaries
  (policies pi_{i-2}, pi_{i-1}, pi_i on the x-axis with rollout
  bars crossing the boundaries) — that's the picture behind
  max_off_policy_steps, not max_async_level. Want me to drop it
  into algorithms.md (e.g. above the off-policy / max_off_policy
  discussion) or save it for later?

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

* docs: normalize package mentions to [\`pkg\`](github-url)

User-facing prose mentions of verifiers / renderers / research-
environments / pydantic-config now consistently render as code-spans
with a github link to the package. Affected lines:

- overview.md: orchestrator-bullet [verifiers](url) (dropped the
  bare-text variant), install paragraph (linked all three submodules
  individually), quick-run paragraph.
- algorithms.md: "Since [\`verifiers\` v0.1.8]..." (added backticks
  around the package name in the release-tag link).
- training.md: SFT \"verifiers submodule\" launch line, useful-knobs
  vf_level row, tool-defs paragraph.

Intentionally left alone:
- algorithms.md \`verifiers.RolloutOutput\` (dotted-path code ref;
  whole expression already in code).
- algorithms.md / training.md [renderers](#renderers) / [Renderers]
  (#renderers) (internal anchors to the in-page section, more useful
  than the github repo for a reader inside the doc).
- algorithms.md "Hand-coded renderers ship for ..." and "the
  renderers writeup on the PI blog" — generic prose, not a package
  mention.
- reference.md docstring-sourced mentions ("verifiers package",
  "renderers package", etc.) — those come from Pydantic field
  docstrings; would need source-side edits + regen.

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

* docs(overview): drop the async-by-default + loss summary paragraph

Out of date with the max_async_level deprecation and duplicates
content already covered properly in algorithms.md (one-step overlap
framing + the AIPO/KL loss math). Architecture bullets above
already mention async semantics where relevant.

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

* docs(overview): tighten 'Where to go next' to one-line pitches

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

* docs(readme): collapse test-suite commands into one code block

Was four separate code blocks separated by one-line prose; now a
single bash block with inline-comment annotations for each variant.
Reads cleaner and matches the test-suite block in development.md.

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

* docs: review-pass cleanups (max_async_level fallout, anchor fix, smoke-test)

Self-review found a handful of small inconsistencies and stale claims
that survived earlier passes.

Stale max_async_level references (now hardcoded to 1, so any prose
that treats it as tunable is wrong):

- faqs.md: "If growing, drop max_async_level or LR" -> drop
  max_off_policy_steps. NCCL FAQ no longer says "requires
  max_async_level=1" — that constraint is vacuous.
- training.md Rules of thumb: NCCL/max_async_level=1 dropped from
  the dry-run validator example; CP / flash-attention example
  stays.
- scaling.md NCCL example: drop the trailing
  "# synchronous; max_async_level forced to 1" comment.

Other accuracy / consistency fixes:

- faqs.md hardware FAQ: drop "you can co-locate both on a single
  GPU" — verified earlier that the rl launcher rejects this; the
  manual three-pane recipe is the actual single-GPU path. Cross-
  link to Scaling § Single GPU.
- faqs.md max_off_policy_steps wording: "throughput-vs-noise knob"
  -> "off-policy dial" to match algorithms.md / training.md.
- training.md sft.data.loss_mask cross-link: anchor was
  reference.md#sft-data (the discriminated-union heading); the
  loss_mask sub-table actually lives at #sft-data-sft-loss-mask.
- development.md "Smoketest training" -> "Smoke-test training" in
  the section title and TOC anchor, matching the hyphenated verb
  form ("smoke-test the new architecture") used in the page body.

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

* docs: review-pass cleanup (drop FAQs, Title Case, smell fixes)

Four asks rolled in:

1. **Drop docs/faqs.md entirely.** Removed the file plus all its
   cross-references: docs/mint.json nav, README.md docs index, and
   docs/overview.md "Documentation" list. The standalone Q&A page
   wasn't pulling its weight against the verifiers tone reference.

2. **Title Case all headings** across the user-facing pages so the
   visual style matches deps/verifiers/docs/* (which uses
   "Hosted Training" / "Performance Trade-offs" etc., not sentence
   case). Anchors are slug-based (lowercase + hyphen), so internal
   #links survive the case flip — only the link text in cross-doc
   "§ Section" references needed updating (training.md → Algorithms
   § Multi-Turn Trajectories, training.md → Scaling § SFT and
   Torchrun, scaling.md → Configuration § TOML Composition,
   scaling.md → SLURM § RL Example / SFT and Inference Examples).

3. **Rename overview.md "Where to go next" → "Documentation"** for
   symmetry with the verifiers landing page.

4. **Smell fixes**:
   a. algorithms.md had two near-identically-named subsections ("###
      The default loss" under Async with the loss math, and "###
      Default loss" under Loss with the mode dispatch). Collapse:
      the loss math now lives under "## Loss > ### Default Loss"
      together with the rl/opd/sft mode-dispatch bullets; the Async
      section is just intro + step semantics. One source of truth.
   b. reference.md auto-generated docstring mentions of "verifiers
      package" / "renderers package" / "renderers library" /
      "renderers.parsers" / "Registered verifiers environment ID"
      now render as [`pkg`](github-url) links. Source-side edits in
      packages/prime-rl-configs/src/prime_rl/configs/{shared,
      orchestrator,sft}.py, then regenerated reference.md.

Net: faqs.md deletion (-198) dominates; everything else is small
churn for case + anchor consistency.

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

* docs: tightening pass after main merge

Restructure + accuracy fixes that were piled up locally during the
SSH-signing block earlier today.

- configuration.md: note that reusing an env id requires a unique
  name; drop the "See each environment's README on the Hub" tail.
- development.md: collapse "Adding a New Architecture" + "Debugging
  MoE" (with its Create Mini Model + Smoke-Test Training subsections)
  into a single "## Adding a New Model" with three subsections —
  Implement the Modeling Code, Register a Mini Preset, Run the
  Smoke Test. Page intro updated.
- scaling.md: drop "## Single GPU" subsection; rename "## Single-Node
  Multi-GPU" -> "## Single-Node" so "Single-Node vs. Multi-Node
  Deployment" has just two clean children. Drop the manual-multi-
  node prose. Drop the [slurm] field reference table; rename the
  section to "## [deployment] Block" and link to reference.md.
  Collapse the two example subsections into one "## Examples" with
  pointers to examples/multinode/{rl,sft}.toml. Rename "## CPU
  Optimizer Offload" -> "## Optimizer Offloading". Add new "## LM
  Head Chunking" subsection covering the fused_lm_head_token_chunk_
  size knob. Drop torchrun phrasing in the SFT scaling subsection,
  the CP recommendation paragraph, "(offloads checkpoints to CPU)"
  parenthetical, "RL gradient-accumulation amortization" line,
  attn = "flash_attention_2" from the memory-tight recipe, dry-run
  invaluable line.
- algorithms.md: drop the Step Semantics subsection heading (body
  stays); replace the AIPO link with a plain "DPPO + KL similar to
  Kimi-K2.5" framing.
- advanced.md: drop the "## Custom vs HF Implementations"
  subsection heading; the body becomes the lead content under
  "## Custom Modeling".
- overview.md + README.md: pitch updates ("adding a new
  architecture" -> "adding a new model"; FAQs row already gone).

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

* docs: drop the auto-generated reference page and its tooling

Removes everything in the reference-generation pipeline:

- docs/reference.md — the 197k-char auto-generated field reference.
- scripts/generate_docs_reference.py — the generator that walks
  Pydantic config trees, discriminated unions, list-of-models, etc.
- .github/workflows/docs-reference.yaml — the CI guard that ran the
  generator and failed on git diff drift.
- .pre-commit-config.yaml — drops the local docs-reference hook
  that re-ran the generator on staged config-class edits.

Knock-on cleanup of cross-references:

- mint.json: drop the "reference" page from nav.
- overview.md / README.md: drop the Reference bullet from the
  Documentation list / docs index.
- configuration.md: drop the two trailing "See [Reference] ..."
  pointers (under Discriminated Unions and at the end of the
  Examples section).
- training.md: drop the "for the full field reference see
  [Reference]" tail in Useful Knobs; the loss_mask row no longer
  cross-links and just lists the four roles.
- scaling.md: drop the [Reference § trainer.model] DeepEP pointer
  and the [Reference § slurm] pointer in the [deployment] block.
- algorithms.md: drop the [Reference § orchestrator length
  penalties] line.
- development.md: simplify the Pre-Commit Hooks section — only the
  ruff hook remains, so the configured-hooks bullet list goes away.

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

* revert: drop github-url docstrings on config fields

The earlier edits added [\`verifiers\`](github-url) / [\`renderers\`]
(github-url) markdown to a handful of Pydantic field docstrings so
the auto-generated docs/reference.md rendered them as code-spans
with links. With reference.md now removed, those annotations are
inert clutter inside the runtime config classes — they don't render
anywhere user-facing. Restore the three affected files to their
state on main:

- packages/prime-rl-configs/src/prime_rl/configs/orchestrator.py
- packages/prime-rl-configs/src/prime_rl/configs/sft.py
- packages/prime-rl-configs/src/prime_rl/configs/shared.py

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
v0.5.1.dev246
2026-05-26 11:09:38 -07:00
Matej SirovatkaandGitHub b8a2205389 feat: split wandb inference metrics by role (#2642)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
v0.5.1.dev245
2026-05-26 19:55:16 +02:00
3f5ee350f6 fix(sft): sync validation iteration to prevent FSDP deadlock (#2636)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(sft): sync validation iteration to prevent FSDP deadlock

Variable-length packing yields different per-rank batch counts in the
validation dataloader. Under FSDP every forward is a collective, so the
first rank to exit run_eval_loop deadlocks the rest in the next
all-gather. Sync a has_data flag per batch and exit together as soon as
any rank exhausts its iterator.

Fixes #2515.

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

* refactor(sft): inline has_data tensor in eval sync loop

Drop the preallocated tensor + fill_; constructing a 0-d cuda tensor
per iteration is effectively free and reads more directly.

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

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
v0.5.1.dev244
2026-05-25 16:38:35 -07:00
a73fa39f2f chore: gitignore .claude/worktrees/ (#2633)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Cursor <cursoragent@cursor.com>
v0.5.1.dev243
2026-05-25 13:59:30 -07:00
0057f3bb91 exp: general-agent (#2525)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* exp: general-agent

* docs: update PR description guidance

* Revert "docs: update PR description guidance"

This reverts commit b8c33de68b7a2b924b43d8cbb508afef8571091c.

* feat(general-agent): add RLM behavior learning configs

* feat(general-agent): tune behavior reward shaping

* feat(general-agent): log behavior judge state for audits

* feat(general-agent): document split behavior rewards

* feat(general-agent): document pruned behavior metrics

* docs(general-agent): record behavior judge calibration runs

* feat(general-agent): define behavior learning ablations

* chore(general-agent): move behavior learning configs

* exp(behavior-learning): add labels, prime monitor, remove cp from ablation configs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* exp(behavior-learning): source ~/.env before run to fix auth

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(slurm): source ~/.env before uv run in single-node RL template

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* exp(behavior-learning): rename prefix, pin rlm_ref, prime sandbox kill in pre-run

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

* revert(slurm): drop source ~/.env from single-node RL template

Source ~/.env directly in the shell before uv run rl instead; env vars
propagate to sbatch via --export=ALL.

Reverts 3703dc05f.

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

* chore(deps): bump verifiers submodule to main (dd89b5e9)

Picks up #1395 which fixes the ParsedToolCall subscription bug in
renderer_client.from_native_response — previously raised
'ParsedToolCall' object is not subscriptable on every rollout.

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

* exp(behavior-learning): switch model to Qwen3-4B-Thinking-2507

4B-Instruct hallucinated tool names and gave up after a few errors
(reward ~0.4% at step 2). Try the thinking variant which is better
at structured tool-use.

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

* exp(behavior-learning): log behavior metrics in baseline without affecting reward

Set behavior_judge_model + behavior_reward_alpha=0.0 so the judge runs
and behavior_<key> metrics get logged, but final_reward stays equal to
task_reward.

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

* exp(behavior-learning): log behavior metrics in prompt run without affecting reward

Same change as baseline: enable judge for metrics but alpha=0.0.

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

* exp(behavior-learning): cap ablations at 200 steps, log behavior metrics in prompt run

- prompt run: enable judge with alpha=0.0 so behavior_<key> metrics
  get logged but final_reward stays equal to task_reward (same setup
  as baseline)
- all four configs: max_steps 1000 → 200 to keep ablations bounded

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

* chore(deps): bump research-environments to include behavior-judge team-id fix

Picks up PrimeIntellect-ai/research-environments@769298b1 which forwards
PRIME_TEAM_ID as X-Prime-Team-ID on behavior judge requests, so the judge
bills the team balance instead of the user's personal balance.

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

* chore(deps): bump research-environments to include final_reward fix

Picks up eaaabf3c which makes final_reward use state.get() so judge
failures don't zero out task_reward.

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

* exp(behavior-learning): bump context to 65K with cp=2 on all configs

Previous runs (cp=1, 32K) saw 6-9% truncation rate and output_tokens
hitting the 32K cap on long trajectories. Double the seq_len and
max_model_len; cp=2 keeps per-rank activation memory flat under the
2x context.

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

* chore(deps): bump research-environments to log un-gated behavior_reward

Picks up fdca6d76 which logs behavior_reward as the raw judge mean
(independent of task_reward) and moves the solution gate into
final_reward.

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

* exp(behavior-learning): extend max_steps to 400 for phase-3 continuation

All 4 phase-2 runs completed step 200 with promising trajectories.
Extend max_steps to 400 to continue training from the step_200
checkpoints.

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

* exp: move general-agent and behavior-learning configs into private submodule

The general-agent + behavior-learning configs are not meant for the public
prime-rl repo. Move them into the research-configs submodule mounted at
configs/private/ so they share access controls with the rest of our
internal experiment configs.

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

* chore(deps): bump configs/private to include phase-3 behavior-learning RESULTS.md

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

* exp(general-agent): bump research-envs, add public RLM configs, rename eval-config helper

- Bump deps/research-environments to origin/main HEAD (general-agent 0.1.4)
- Add configs/general_agent/{rl_qwen3_0p6b_debug,rl_qwen3_4b,rl_qwen3_30b_a3b}.toml
  using the general-agent-solver-rlm env
- Rename is_vf_eval_config -> is_eval_config in tests/unit/test_configs.py

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

* exp(general-agent): rename 0p6b config, point all configs at general-agent-debug wandb project

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

* chore(deps): bump configs/private to expand behavior-learning RESULTS

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

* chore(deps): bump configs/private for tightened behavior-learning RESULTS

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

* exp(general-agent): drop num_workers/max_retries/tool_call_parser, set step counts

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
v0.5.1.dev242
2026-05-25 13:43:16 -07:00
e792f9cf88 chore(orchestrator): hardcode async-barrier semantics, drop max_async_level + strict_async_level (#2631)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: deprecate user-facing max_async_level, hardcode to 1

Removes `max_async_level` as a user-configurable knob on `OrchestratorConfig`,
`TrainerConfig`, and the shared `RLConfig`, and replaces internal usage with a
constant `MAX_ASYNC_LEVEL = 1` in `prime_rl.utils.utils`. This was the only
value compatible with NCCL weight broadcast, and exposing it invited
misconfiguration (the trainer/orchestrator values had to match, and bench mode
+ a few configs overrode it ad-hoc).

Drops the now-redundant NCCL validators on both sub-configs and the
shared-field propagation/validator for `max_async_level`. Also removes the
bench-mode `max_async_level = int(1e9)` workaround (no replacement flag).

Closes #2630.

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

* docs(async): drop MAX_ASYNC_LEVEL mention, describe as one-step overlap

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

* refactor: simplify step logic now that async lag is fixed at one

Now that the trainer/orchestrator always run with a one-step async barrier,
inline the value where it actually appears (scheduler ckpt math, trainer
broadcast skip, filesystem cleanup) and drop the indirection through a
``MAX_ASYNC_LEVEL`` constant — the value is a design invariant, not a
configuration knob, and naming it as a constant just made it look tunable.

- scheduler: factor out ``_async_away_ckpt_step()`` so both ``_compute_next_ckpt_step``
  and ``_apply_policy_update`` share a single source of truth, skip the
  ``get_latest_ckpt_step`` filesystem read entirely in strict mode, and clean
  up the awkward ``>1 step(s) ahead`` log line.
- trainer: replace ``last_async_level_steps`` with a ``nccl_broadcast_unused``
  flag that names the actual reason the broadcast is skipped (NCCL receivers
  have torn down). Filesystem broadcast still writes through to the final step
  for resume support.
- ``maybe_clean``: drop the ``async_level`` parameter (only one caller, fixed
  value) and document why we delete the dir from two trainer steps ago.

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

* refactor(scheduler): drop _async_away_ckpt_step helper, inline step math

The helper wrapped a single ``max(self.step - 1, 0)`` and was being called
three times across two methods, adding indirection without saving anything.
Inline it with a localized comment explaining the one-step lag invariant in
each method, and flatten ``_compute_next_ckpt_step`` so the strict path is a
guard around the latest-ckpt lookup rather than a separate early return.

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

* chore: deprecate user-facing strict_async_level

The strict-mode branch existed to support an "always exactly one step
behind" reproducibility/ablation knob, but it's never been the default and
exposing it just complicated the scheduler. Drop the field on
``OrchestratorConfig``, the constructor parameter on ``Scheduler``, and
collapse ``_compute_next_ckpt_step`` to the single non-strict path
(``max(step - 1, 0, latest_ckpt)``).

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

* refactor(scheduler): drop redundant 0 clamp in _compute_next_ckpt_step

``latest_ckpt_step`` already falls back to 0 (via ``... or 0``), so it
dominates the explicit ``0`` argument in every case — including
``self.step == 0`` startup, where ``latest_ckpt_step`` is also 0. Dropping
it makes the intent clearer: advance to at least step - 1, or to whatever
the trainer has broadcast if that's newer.

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

* docs(changelog): note max_async_level / strict_async_level removal as breaking

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

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
v0.5.1.dev241
2026-05-25 13:41:06 -07:00
Mika SenghaasandGitHub a36151c951 fix(logger): preserve traceback in JSON sink (#2594)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(logger): preserve traceback in JSON sink with enqueue=True

loguru's RecordException.__reduce__ unconditionally drops the
traceback object before pickling, so records dequeued by the
enqueue=True worker have exc.traceback=None and the JSON sink
emits only the exception type + message - no frames.

Pre-format the traceback into extra["_traceback"] via a loguru
patcher that runs at log time, while the live traceback is still
attached. The string survives pickling, and build_log_entry reads
it back into the "exception" field.

enqueue=True is kept because the trainer's torchrun workers all
write JSON lines to a shared inherited stdout, and loguru's docs
flag this as the case where the multiprocessing-safe queue is
required to avoid interleaved/corrupt output.

* refactor(logger): drop underscore prefix from traceback patcher/key

* chore(logger): tighten traceback patcher comments
v0.5.1.dev240
2026-05-25 13:41:01 -07:00
c5559033bd Add indexCache training support (#2541)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* Add indexCache training support

* fix glm moe dsa index cache threading

Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>

* Delete tests/unit/train/models/test_glm_moe_dsa_index_cache.py

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>

* fix

* refactor: group IndexCache knobs into IndexCacheConfig sub-config

Replaces the three flat ModelConfig fields (use_index_cache,
index_topk_freq, index_topk_pattern) with a single
index_cache: IndexCacheConfig | None = None sub-config.

None signals "disabled" explicitly, so the brittle model_fields_set
check in get_model goes away. HF/vLLM-side flat fields stay flat —
they're written from the sub-config only when it's set.

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

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
Co-authored-by: samsja <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
v0.5.1.dev239
2026-05-25 11:55:07 -07:00
25d4b1dcc8 fix(orchestrator): trigger evals on orchestrator step (#2626)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: trigger evals from orchestrator step

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

* refactor: simplify eval scheduling

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

* refactor: inline resume eval skip

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

* refactor: clarify resume eval skip

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

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
v0.5.1.dev238
2026-05-25 11:12:33 -07:00
3b386a4489 chore: drop teacher_inference from rl entrypoint (#2629)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The `rl` entrypoint now only manages student-policy inference. External
teachers (OPD, local-vLLM SFT) must be started manually and pointed at
via `[orchestrator.teacher.client]`.

Removed:
- `[teacher_inference]` block from `RLConfig`
- `deployment.num_teacher_gpus` (`SingleNodeDeploymentConfig`)
- `deployment.num_teacher_nodes` (`MultiNodeDeploymentConfig`)
- launcher code that spawned/monitored the teacher inference subprocess
- related validators (`auto_setup_teacher_inference`,
  `_stub_orchestrator_teacher_for_auto_setup`,
  `validate_no_teacher_in_multinode`,
  `teacher_inference_not_supported`)

Fixes #2627

Co-authored-by: Cursor <cursoragent@cursor.com>
v0.5.1.dev237
2026-05-25 10:56:19 -07:00
faresobeidandGitHub 38303f82d4 add routing confidence metric (#2545)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
v0.5.1.dev236
2026-05-25 10:21:32 -07:00
JannikStandGitHub f5e8113420 chore: drop environment gate on manifest job (#2624)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Each job referencing environment: ghcr-publish requires its own admin approval. manifest only combines arch-suffixed tags that build already pushed (and build was already approved), so a second approval doesn't add meaningful security but adds friction. Keep the gate on build.
v0.5.1.dev235
2026-05-25 04:47:38 +02:00
ef773f1cee chore: add manual ghcr image build workflow (#2385)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: also publish image to ghcr + add manual trigger

* chore: drop push/tag triggers, keep manual dispatch only

* chore: revert release.yaml, add manual ghcr build workflow

* fix: avoid script injection by passing inputs via env

* fix: trim trailing dash after tag truncation

* chore: dispatch build_image after creating dev tag

* multi platform builds (am64 and arm64)

* OCI metadata

* remove temporary push trigger

* trigger image builds when gh releases are published

* add step to init public submodules

* add pydantic-config to submodules

* should fail on failed image builds

* chore: gate ghcr publish on environment + ref/tag allowlist

- Require ghcr-publish environment for build and manifest jobs (admin approval)
- Reject refs other than main, v*, or *.dev*
- Disallow custom tag input unless ref=main, so a feature branch can't overwrite v1.2.3

* chore: allow tag input when it matches ref

Release events and the dev-tag auto-dispatch always pass ref==tag (e.g. v1.2.3/v1.2.3); the previous guard rejected those because tag was set and ref was not main. Only block when tag and ref diverge.

* chore: serialize same-tag builds and skip manifest job when single-arch

- Add concurrency group keyed on resolved tag so two runs for the same image queue rather than interleave (would otherwise mix arch digests in the unsuffixed manifest).
- Skip the manifest job when platforms != 'both' so a single-arch dispatch can't replace an existing multi-arch :tag with a single-arch index. The suffixed :tag-amd64 / :tag-arm64 are still pushed by build.

---------

Co-authored-by: eexwhyzee <13672394+eexwhyzee@users.noreply.github.com>
v0.5.1.dev234
2026-05-25 03:15:55 +02:00
84f072bc99 chore(deps): bump pydantic-config for dict[str, str] coercion fix (#2618)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Pulls in PrimeIntellect-ai/pydantic-config#14, which stops
`BaseConfig._coerce_dict_str_values` from rewriting string values in
`dict[str, str]` fields. Configs like
`configs/private/rlm5/glm5-swe.toml` that set
`prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0"}` previously
failed validation because "0" was coerced to int(0); they now load.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
v0.5.1.dev233
2026-05-23 19:58:54 -07:00