Compare commits

...
Author SHA1 Message Date
e466d233e9 fix(slurm): portable GLOO/UCX NIC selection in sbatch templates (#2760)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
GLOO_SOCKET_IFNAME was hardcoded to bond0 and UCX_NET_DEVICES to all,
both of which break on clusters with different NIC naming or with RDMA
devices UCX cannot open (e.g. a non-functional Ethernet bond, which
fails NIXL backend creation with NIXL_ERR_BACKEND). Derive the gloo
interface from LOCAL_IP and enumerate RDMA ports from sysfs (ibv_devices
is not on the job PATH), preferring InfiniBand, falling back to RoCE,
and keeping "all" on hosts without RDMA devices.

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

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

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

* Update README.md

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

---------

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

* update deps

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

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

* fixes
2026-06-09 01:48:12 +01:00
samsjaandGitHub 53b22b55c8 fix: add prime-pydantic-config as direct dep so uv uses editable path source (#2733)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The [tool.uv.sources] override for prime-pydantic-config was being ignored
because it was only a transitive dependency (via prime-rl-configs). uv only
applies source overrides for packages that appear in project.dependencies.
Adding it as a direct dependency makes uv resolve from the local editable
path (deps/pydantic-config) instead of PyPI.
2026-06-08 16:34:24 -07:00
minh hoangandGitHub c2a5fa466c chore(renderers): bump to submodule to renderers-v0.1.8.dev41 (#2732)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-08 15:16:58 -07:00
Matej SirovatkaandGitHub 90b074492e Feat: fix weight reload to cpu optim (#2729)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-08 17:58:23 +02:00
766e36f000 Feat/fp8 fused transpose cast (#2724)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(fp8): fuse transpose into the dX block-fp8 weight cast

The dX backward built `weight.transpose(0, 1).contiguous()` and re-cast it to
fp8 every step, materializing a full bf16 transpose buffer plus an extra
read/write pass. Add `per_block_cast_to_fp8_tp_triton`, which produces the
block-fp8 of `weight.T` directly by reusing the existing per-block kernel with
swapped output/scale strides — no intermediate buffer.

128x128 block quantization is transpose-symmetric, so the result is
bit-identical to casting the materialized transpose; DeepGEMM receives an
identical B tensor. Verified byte-for-byte across shapes; ~14x faster on a
4096x4096 weight (373 -> 27 us).

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

* deslopified

* also add fused implementation for per-token

* Fix: skip tests on <Hopper

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
2026-06-07 17:51:36 +02:00
209f76eb52 fix(install): support aarch64 hosts with any compute capability (#2587)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The aarch64 host install path was broken: `uv sync` installs flash-attn
from PyPI source but pyproject sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE,
so the compiled extension never builds. `scripts/docker-arm64-post-install.sh`
fixed it for Docker GB200 builds but hardcoded sm_100 and /app/.venv,
leaving Hopper hosts (H100/H200/GH200) without a recipe.

Changes:
- `scripts/docker-arm64-post-install.sh`: auto-detect compute capability
  via nvidia-smi when available; parameterize venv path. Preserves the
  sm_100 default when no GPU is visible (Docker buildx).
- `scripts/install.sh`: call the post-install for aarch64 hosts after
  `uv sync --all-extras`. Previously the script ran uv sync and exited,
  leaving aarch64 users with a broken venv.
- `README.md`: document the aarch64 post-install step (mirrors the
  existing 3.1 Flash Attention 3 pattern).

Validated on GH200 (sm_90, aarch64):
- forward + backward parity vs torch SDPA (max diff < 0.05 / 0.25)
- 383/384 unit tests pass (the 1 failure is unrelated TileLang/MoE)
- SFT trainer smoke test (5 steps, Qwen3-0.6B) runs with flash_attention_2

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

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

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

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

* chore: ruff format

* fix: force VLLM_CONFIGURE_LOGGING=1 when setting LOGGING_CONFIG_PATH

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

* fix: emit tz-aware UTC timestamps in JsonFormatter

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

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

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

* fix: guard None inference in auto_setup_logs

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

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

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

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

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

* fix: route transformers logs through JSON handler

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

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

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

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

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

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

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

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

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

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

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

* exp: lower qwen35 wordle kl drift

* fix: preserve qwen3.5 broadcast weight names

* chore: keep qwen35 debug configs local

* chore: clarify qwen3.5 weight naming bypass

* fix: use upstream qwen3.5 conversion mapping

* chore: use released transformers package

* chore: drop qwen3.5 cp patch

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

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

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

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

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

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

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

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

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

Two correctness fixes for the external-LB paths:

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

* exp: reverse_text v1 smoke config

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

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

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

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

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

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

---------

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

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

* fix: regenerate uv.lock against merged verifiers submodule

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

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

---------

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

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

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

* Fix: development

* Fix: overview

* Fix: scaling

* Fix: inference

---------

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

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

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

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

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

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

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

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

* refactor(orchestrator_v2): address review feedback

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

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

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

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

New module layout:

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

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

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

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

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

Also:

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

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

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

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

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

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

Dispatcher changes:

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

Orchestrator changes:

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

Removed:

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

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

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

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

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

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

Dispatcher Rollout dataclass:

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

TrainSink:

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

EvalSink:

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

Orchestrator:

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

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

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

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

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

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

Orchestrator main loop:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* chore(configs): drop max_completion_tokens cap from orch_v2_demo

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* revert: restore validation.py to main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Docs and CHANGELOG updated.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* chore(agents): trim docs rule

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

* refactor(eval_sink): drop redundant batch_arrivals counter

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Two parallel typed metric dataclasses, one per sink:

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

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

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

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

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

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

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

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

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

W&B handling tightens:

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

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

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

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

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

Changes:

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

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

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

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

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

API rename + co-location:

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

Config collapse:

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

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

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

Dead-state removal:

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

API symmetry:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Functional:

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

Log format:

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

Smaller log demotions / renames:

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

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

* refactor(eval_source): unify trigger + trigger_at_start

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

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

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

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

Five small follow-ups bundled together:

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

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

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

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

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

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

Log polish:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Two related bugs in the eval-side pipeline view:

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

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

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

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

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

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

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

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

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

* refactor(eval_sink): rename epoch_progress → batch_progress

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

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

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

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

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

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

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

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

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

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

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

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

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

Step progress leads:

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

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

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

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

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

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

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

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

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

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

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

* chore(configs): drop verbose docstring on OrchestratorExperimentalConfig

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

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

* chore(configs): generic LogConfig.interval docstring

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

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

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

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

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

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

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

Knock-on changes:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Three legit bugs from the recent audit:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* chore: trim excessive code comments + docstrings

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

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

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

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

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

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

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

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

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

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

Remove four config surfaces that the new orchestrator never reads:

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

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

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

## Breaking

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

CPU unit suite: 76 passed in the orchestrator subset.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* chore(orchestrator): remove dead print_benchmark from utils

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-01 12:03:19 -07:00
JannikStandGitHub 543e37eb3a Disable vLLM DeepGEMM by default (#2678)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
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
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>
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>
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>
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
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>
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
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>
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
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>
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>
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>
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)
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
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>
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>
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
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>
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>
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>
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>
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
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>
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>
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>
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
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.
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>
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>
2026-05-23 19:58:54 -07:00
JannikStandGitHub 4df5b6229f fix: probe github ssh auth directly in install.sh (#2613)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: probe github ssh auth directly in install.sh

The previous `has_ssh_access` probe ran `git ls-remote` against the
public prime-rl repo, which can return success under SSH connection
multiplexing, cached creds, or other states without the local key
actually being registered with a GitHub user. When that happens, the
HTTPS `insteadOf` rewrite is never applied and private-submodule
clones fail with "Permission denied (publickey)".

Use `ssh -T git@github.com` and grep for the canonical
"successfully authenticated" string instead. This is a direct check
of the precondition (your key is registered with a GitHub user) and
matches the pattern git itself recommends.

* fix: capture ssh output to var so pipefail doesn't mask success

`ssh -T git@github.com` always exits 1 (GitHub denies shell access
after authenticating), and install.sh has `set -o pipefail` at the
top, so the previous pipeline made has_ssh_access return failure even
for developers with valid keys. Capture stdout/stderr into a variable
first, then grep — keeps pipefail intact for the rest of the script.

* fix: use universal ssh options in github auth probe

`StrictHostKeyChecking=accept-new` requires OpenSSH 7.6+ (Sep 2017).
On older systems ssh errors with 'Bad configuration option' and the
probe wrongly reports no SSH auth, forcing HTTPS even when SSH would
have worked.

Use `StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null`
instead, which works on all OpenSSH versions. Safe for a probe-only
flow: no key material is exchanged, and a hostile MITM at worst
makes the probe wrongly report 'no SSH', causing HTTPS fallback for
public repos.

* fix: rely on ensure_known_hosts and default ssh host key checking

Previous commit disabled `StrictHostKeyChecking` and `UserKnownHostsFile`
to side-step OpenSSH version requirements, but that made the auth probe
trust any host that returns the "successfully authenticated" string —
a MITM could steer the script into using their SSH for submodule
clones.

`ensure_known_hosts` already runs (line 116) before any
`has_ssh_access` call and populates github.com via ssh-keyscan, so
default host key checking is both safe and sufficient. Drop the
options entirely; keep `BatchMode=yes` to suppress prompts.

* fix: propagate insteadOf to submodule clones via GIT_CONFIG_* env

`git submodule--helper clone` spawns fresh `git clone` processes
that read only ~/.gitconfig and env vars — not the parent repo's
local .git/config. So setting `url..insteadOf` locally never reached
the submodule clones, and they kept attempting SSH despite the probe
correctly reporting no auth.

Use `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_0`/`GIT_CONFIG_VALUE_0` which
propagate the rewrite to every child git process for the duration of
this script, with no persistent state in ~/.gitconfig.
2026-05-24 04:58:21 +02:00
Mika SenghaasandGitHub ae1461e7a1 docs: fix stale slurm config examples and references (#2619)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The docs and a couple of example READMEs described slurm usage that
no longer matches the real config system - users following them would
hit validation errors.

- docs/slurm.md: drop bogus `toml_files = [...]` (not a pydantic-config
  feature) and document the real `@ base.toml @ overlay.toml` compose
  syntax. Rename `[orchestrator.sampling]` and `[[orchestrator.env]]`
  to the current `train`-scoped paths, swap `max_tokens` for
  `max_completion_tokens`, repoint dead `examples/hendrycks_math/`
  links to `examples/multinode/`, fix the inference example filename
  and `--dry-run` flag usage
- examples/hendrycks_sanity/README.md: the slurm command was invoking
  the overlay alone (which fails validation), compose base + overlay
- examples/wiki_search/README.md: stale `[[orchestrator.env]]` path
2026-05-23 19:56:41 -07:00
7e8355003a chore(orchestrator): backfill rollout tokens only when needed (#2610)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(orchestrator): gate pretokenize_rollout_trajectory on SFT mode

Only call the pretokenize fallback in sft mode. The renderer-backed and
MITO rollout clients populate step["tokens"] from vLLM's prompt_token_ids
and token_ids extensions, so the call is a no-op there. sft from an
external teacher (e.g. openai/gpt-5-mini via PI inference) does still
need the fallback because external APIs return no token IDs.

Verified on examples/reverse_text/rl.toml @ 5 steps:
- renderer (default):                  reward 0.11 → 0.24
- MITO (--no-orchestrator.use-renderer): reward 0.11 → 0.20
- sft external (configs/debug/training_modes/sft_external.toml): reward ~0.92, all 5 steps complete

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

* chore(orchestrator): gate pretokenize on tokens-missing, log when it runs

Replace the training_mode == "sft" gate with a behavioral check on
step["tokens"] is None. This skips the 256-way to_thread fanout for
SFT against a local vLLM teacher too (vLLM populates tokens via
prompt_token_ids/token_ids), not just RL/OPD. Only the external teacher
API path (OpenAI/etc.) actually needs the fallback. Log inside the
guard so it's visible when the work runs.

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

* refactor(orchestrator): rename pretokenize_rollout_trajectory -> backfill_rollout_tokens

"Pretokenize" was misleading - the function is a backfill that fills in
step["tokens"] for any step where it's None, run only when the rollout
source (e.g. external teacher API) didn't return token IDs.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 19:18:14 -07:00
81822debb6 feat(orchestrator): default X-Session-ID header to trajectory_id (#2615)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): default X-Session-ID header to trajectory_id

Switch the auto-injected `X-Session-ID` sticky-routing header from
`example_id` to `trajectory_id` so each rollout (rather than each
dataset example) pins to a single inference engine.

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

* chore: bump configs/private submodule

Pin to the research-configs branch dropping the explicit
`X-Session-ID = example_id` override on `rlm5/{prod,glm5-swe}`
so they pick up the new `trajectory_id` default.

See: PrimeIntellect-ai/research-configs#2

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 19:18:07 -07:00
8e978063b4 perf(orchestrator): reduce event-loop lag (#2609)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* perf(transport): offload TrainingBatch send to a worker thread

Make FileSystemTrainingBatchSender.send async and run the msgspec encode
+ disk write in asyncio.to_thread. Keeps the orch event loop responsive
during step transitions when the batch payload is large.

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

* perf(orchestrator): await async sender; to_thread advantages+filters+uvloop

- await training_batch_sender.send(training_batch) since sender is async (O1+O2)
- compute_advantages and apply_filters wrapped in asyncio.to_thread (O3+O4):
  both iterate ~2k rollouts in pure Python and release the GIL on every
  bytecode tick, so threading actually helps unlike the C-extension encode
- main() installs uvloop (O7) — lower scheduler overhead matters when the
  orchestrator is juggling many concurrent rollouts + the HTTP client to
  inference; measurably reduces tail latency.

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

* perf(orchestrator): log p99 event-loop lag in metrics + busy-loop warning

p90 alone undersells the long tail we see at step boundaries. p99 is the
metric we actually compare across runs, so surface it in the wandb dict
(`event_loop_lag/p99`) and in the busy-loop warning line.

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

* perf(orchestrator): defer routed_experts concat in interleave_rollout

extend_sample's previous implementation unpacked the accumulated
routed_experts bytes, mutated one boundary entry, np.concatenated the new
step's routings, then re-packed to bytes — every extension. For an N-turn
rollout reaching seq_len 60k, the accumulated buffer reached ~23 MB and was
fully read+written N times, giving O(N²) byte work (~2.3 GB of memcpy per
rollout). At 256 rollouts/step this dominated the orch's step-boundary
event-loop stalls more than the encode path we'd already fixed.

Defer the concat: track per-sample `chunks: list[np.ndarray]` during the
extension loop and finalize once at the end. The "boundary token" entry
that vLLM omits for each request is appended as its own one-entry chunk
between consecutive steps' contributions, so the final concat is a
straight join — no destructive writes to prior chunks.

Verified byte-exact against the old implementation on a 50-step extension
chain. Per-rollout work drops from O(N²) → O(N): ~100× less memcpy in the
realistic regime.

This makes use_process_pool unnecessary for the residual orch lag: each
rollout's process_rollout cost drops below the IPC pickle cost, so the
threaded path is strictly better.

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

* perf(orchestrator): orjson save_rollouts + dedup bool conversion

- save_rollouts: json.dump -> orjson.dumps + bytes write. The pure-Python
  serializer held the GIL for the whole save phase (multi-second spikes
  on big steps); orjson serializes in C and releases the GIL.
- prepare/make/extend mask handling: [bool(i) for i in mask] was the
  remaining per-turn GIL-held Python loop. make_sample/extend_sample
  swapped to list(...) / direct extend; prepare_step_tokens uses
  list(map(bool, ...)). Together drops gather wallclock 5-10% on
  long-tail rollouts.

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

* perf(orchestrator): skip pretokenize fanout when nothing needs work; 10Hz lag monitor

- Pretokenize was a no-op for router-replay (every step already has
  tokens populated by the renderer client), but the 256-way to_thread
  fanout starved the loop for ~2 s per step. Short-circuit when no
  rollout's trajectory has unpopulated tokens. Offline attribution:
  pretokenize lag drops 2050 ms → 11 ms.
- EventLoopLagMonitor sampling 1 Hz → 10 Hz (mirrors verifiers'
  monitor). 1 Hz was missing sub-second spikes that show up clearly
  at 10 Hz.

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

* chore(deps): bump verifiers submodule to a930f2e5 (post-1453 main)

Pulls in the env_worker / env_router event-loop lag fixes that just
landed on verifiers main via PR 1453 — required for the orch-side
gains in this PR to surface under realistic 256-rollout concurrency.

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

---------

Co-authored-by: Sami <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 18:34:42 -07:00
Matej SirovatkaandGitHub 934c014bec Pin CUDA 12 routed experts vLLM wheel (#2611)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-24 02:56:02 +02:00
20f6449e1f refactor: rename rollouts_per_example to group_size (#2599)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Renames the orchestrator-level, [orchestrator.eval] group-level, and per-env
[[orchestrator.eval.env]] fields. The old name still parses as a validation
alias in both TOML and CLI, so existing configs keep working unchanged.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 16:47:02 -07:00
1e0fe9637d [R3]: Move to new vLLM routed experts format (#2487)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: wire r3 v3 routed experts stack

* feat: reset routing caches on policy update

* fix: rely on native vllm routed experts

* fix: pin routed experts dependencies for ci

* fix: update scheduler tests for prefix reset

* fix: clean routed experts replay integration

* fix: keep routed experts transport first class

* fix: keep routed experts on samples

* fix: use upstream vllm nightly wheel

* fix: pin latest routed experts verifiers

* fix: pin routed experts dependencies

* fix: allow routed experts with nixl

* style: format nixl patch

* Use raw uint8 routed experts payloads

* Remove unrelated rlm-swe dependency

* Pin vllm-router 0.1.25 wheel

* Keep verifiers routed experts opaque

* Forward renderer thinking preservation config

* Avoid duplicate routed experts in token responses

* [codex] Guard checkpoint disk metrics mkdir (#2523)

* Guard checkpoint disk metrics mkdir

* Remove test_trainer_utils.py per review feedback

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

* Simplify ckpt disk metrics guard

Drop the rank-0 gate and the disk_usage path fallback per review feedback.
Catching FileExistsError on mkdir is sufficient: every rank that races on
mkdir either wins or harmlessly catches the BeegFS race, and shutil.disk_usage
can then operate on the now-existing ckpt_dir.

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

---------

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

* Pin verifiers routed experts sidecar

* Pin cleaned verifiers routed experts handling

* Pin rebased verifiers routed experts handling

* fix: remove unrelated prime-rl changes

* fix: pack routed experts as typed payloads

* refactor: inline routed experts trajectory packing

* fix: restore trajectory tokenization helpers

* refactor: simplify routed experts packing

* chore: pin vllm router wheel

* chore: update renderers and verifiers

* Pin vLLM PR39568 backport wheel

* Pin vLLM revert42434 PR39568 wheel

---------

Co-authored-by: Sami <sami@primeintellect.ai>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:39:40 +02:00
samsjaandGitHub badd2b0fe2 feat: write token exports per step (#2596)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-21 21:09:57 -07:00
samsjaandGitHub e971d905a2 Add trainer token JSONL export (#2592)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: add trainer token jsonl export

* chore: use docstrings for token export config
2026-05-21 20:31:03 -07:00
Matej SirovatkaandGitHub 710e11912f fix: set deepgemm moe env for inference (#2591)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-22 03:46:08 +02:00
c95a943c39 feat(scheduler): train on partial groups instead of dropping on rollout error (#2590)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(scheduler): train on partial groups instead of dropping on rollout error

When an individual-scoring env returns N rollouts for a single example and one
errors out, scrap only the failed rollout — keep the survivors and ship the
group through as soon as every dispatched rollout has come back (success or
failure). Group-scoring envs still drop the whole group on any failure because
their per-rollout scores are computed against the now-missing rollouts.

To make variable-size groups round-trip through advantage computation, group
rollouts by (env_name, example_id) instead of positional slicing, and bucket
groups by size so each advantage_fn call still sees a uniform 2D rewards
tensor. Singleton groups produce zero advantage and get filtered out by the
existing zero-advantage filter — no special-casing.

Closes #2585.

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

* refactor(advantage): make advantage_fn per-group

Drop the bucket-by-size workaround in compute_advantages by changing the
advantage_fn contract: AdvantageInputs.rollouts is now a single group
(list[RolloutOutput]) and AdvantageOutputs.advantages is 1D. The framework
calls advantage_fn once per group, which works cleanly for variable-size
groups (partial-group training).

BREAKING: second change to this public API in three weeks. Custom advantage
functions must drop the outer list dim. Migration documented in CHANGELOG.md
and docs/bring-your-own-algorithms.md.

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

* refactor(advantage): return list[float] from advantage_fn

Drops the torch tensor from the public AdvantageOutputs contract; internal
math stays in torch and converts via .tolist() at the boundary. Same partial-
group support, simpler downstream consumers (no more .tolist() / no shape
gymnastics in custom advantages).

BREAKING (folds into the per-group change in the previous commit): custom
advantage functions must return AdvantageOutputs(advantages=[...]) rather
than a tensor. CHANGELOG entry and docs example updated.

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

* refactor(scheduler): log each rollout failure inline, drop GroupState.last_failure_reason

The reason is now logged at the moment the failure is observed (one warning
per failed rollout) instead of being stashed on the group and replayed at
finalization. Removes the per-group field entirely and avoids the "first vs
latest wins" semantic question that came up in review - each log line carries
its own actual reason. Finalization warnings only carry counts now.

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

* chore(scheduler): drop verbose comment on GroupState.failed_rollouts

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:40:34 -07:00
ca03d89fad feat(orchestrator): per-env state_columns for extra rollout fields (#2589)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): per-env state_columns for extra rollout fields

Adds `state_columns: list[str] = []` to `EnvConfig` so each env can
persist additional `State` fields into the saved JSONL rollouts on top
of the always-saved `trajectory` and `sampling_args`. Merged at the
call site (required first, deduped).

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

* refactor: drop seen set from state_columns dedup

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:23:30 -07:00
Matej SirovatkaandGitHub e6e814697a fix: patch deepgemm silu quant addressing (#2582)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-21 15:57:53 -07:00
f9cebaa19c fix(slurm): stop cleanup srun from self-killing (#2586)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The pre-launch cleanup block runs `pkill -9 -f "[v]llm"` to mop up
orphans from prior jobs. The `[v]llm` regex-trick relies on no literal
`vllm` appearing in the matching cmdline, but the surviving lines in the
same block do — `pkill -9 "vllm"`, `pkill -9 "vllm::.*"`, the
`/tmp/vllm-*` glob, and the closing `grep -E "...vllm..."`. With
`srun bash -c '<script>'` the entire script body lives in both srun's and
the inner bash's argv, so `[v]llm` matches them and SIGKILLs the cleanup
processes mid-flight. `set -e` then bubbles it up and the batch dies
before any component starts.

Switch to `srun bash -s <<'CLEANUP_SH' ... CLEANUP_SH`. The heredoc goes
over stdin, so the cmdline of srun and bash on every task is just
`srun bash -s` / `bash -s`. `pkill -f "[v]llm"` no longer self-matches
and the cleanup completes normally on every node.

Verified on cluster (multinode RL example): pre-fix the cleanup step
died with `9:0` in 6 s; post-fix the cleanup step exits `0:0` and the
log shows `[node-cleanup] <host> procs=1 gpu_mem=0MiB` from both nodes.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 13:45:00 -07:00
c656d2f8f2 fix(orchestrator): deep-merge legacy model/client aliases; switch multinode template to canonical CLI path (#2584)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(orchestrator): deep-merge legacy model/client aliases; switch multinode template to canonical CLI path

`fold_student_shortcuts` previously skipped re-nesting top-level `client`
into `student.client` when the latter was already populated (and used
`setdefault` for `model`, so existing keys won). That meant a CLI override
like `--client.base-url URL` could never reach `student.client.base_url`
once the TOML provided `[student.client]` — pydantic's `extra="forbid"`
rejected the leftover top-level `client` with `Extra inputs are not
permitted`. Same shape for `--model.<k>` against TOML `[student.model]`.

Deep-merge with the legacy (top-level / CLI) side winning at the leaf.
TOML values that the CLI doesn't touch are preserved.

Also update `multi_node_rl.sbatch.j2` to use the canonical
`--student.client.{base-url,admin-base-url}` instead of the legacy alias.
The new path is a known leaf in pydantic-config, so single-value args
get list-wrapped correctly (the legacy alias goes through the unknown-leaf
branch and would still produce a raw string).

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

* nit: rename _deep_merge_into -> deep_merge, drop redundant comment

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 12:17:10 -07:00
9ef2705898 fix(scheduler): drop group on rollout error instead of rescheduling (#2581)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(scheduler): drop group on rollout error instead of rescheduling

Raise per-env max_retries default from 0 to 3 so transient infra failures
are absorbed inside the env server. Drop any group whose rollout bubbles
up with an error or empty trajectory, log it, and let the rest of the
batch proceed — no in-orchestrator reschedule, no partial-group salvage.

Removes max_error_reschedule_attempts and the GroupState round/attempt
tracking. Closes #2475.

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

* fix(scheduler): count every failed rollout in error metrics

Iterating over the rollouts and breaking on the first failure undercounted
errored_rollouts/empty_rollouts for group-scoring envs (which return N
rollouts per task), deflating the reported error rate.

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

* feat(scheduler): emit error/<type>/count metric per step

Adds errors_by_type tracking keyed by ErrorInfo["error"] (the outermost
exception class name from the verifiers error chain), surfaced to wandb
as error/<type>/count. Lets dashboards see which failure mode (e.g.
OverlongPromptError vs InterceptionError vs SandboxError) is driving
dropped groups, instead of one opaque errored_rollouts rate.

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 12:16:54 -07:00
1d9ca92551 fix(rl): normalize loss by global token count across dp_cp (#2562)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Each DP rank was dividing its summed token loss by its own local
loss_scale, then FSDP averaged the resulting gradients. Because ranks
process different sequence lengths, that mean is not the true per-token
mean over the global batch — ranks with fewer loss tokens get implicitly
upweighted.

Mirror the SFT trainer fix (src/prime_rl/trainer/sft/train.py:416-427):
all-reduce the local token count across dp_cp, divide by that global
denominator on every rank, and multiply grads by fsdp_gradient_divide_factor
after the microbatch loop so FSDP's per-rank averaging is undone and the
final gradient is the per-token mean over the global batch.

Closes #2358. Adapted from #2359, which first diagnosed the bias and
proposed the all-reduce-then-rescale approach.

Co-authored-by: irfanjamil <irfanjamil9@gmail.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 20:12:08 -07:00
ea2f390045 feat: renderer-only multimodal path — rip MITO branch, pack pixel_values from renderer (#2473)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: drop use_renderer=True VLM skip; pack pixel_values from renderer

interleave_rollout now consumes renderer-emitted multi_modal_data on each
trajectory step (when present), packs the per-image pixel_values and
image_grid_thw onto the TrainingSample, and computes mm_token_type_ids —
no VLMImageCache lookup required when the rollout went through a
multimodal renderer. VLMImageCache stays as the fallback for
MITO/chat-completions rollouts.

build_trajectory_step (renderers package) was updated separately to
surface mm_data on its output, so the pretokenize-fallback path also
carries images through correctly.

Other changes:
- orchestrator config: removed validate_renderer_vs_vlm validator that
  previously rejected use_renderer=True for VLMs (it's now supported).
- e2e test: a real Qwen3VLRenderer + RendererClient -> /inference/v1/generate
  mock POST, plus a roundtrip through vllm's GenerateRequest pydantic
  model and decode_mm_kwargs_item. Strongest end-to-end check we can
  run without a GPU.
- 20-step A/B configs for color-codeword (feat-renderer vs main-mito),
  both logging to W&B project 'multimodal-renderer'.

126 orchestrator unit tests pass (+2 new for renderer-mm packing).

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

* refactor(orchestrator): rip MITO multimodal path, renderer-only for VLMs

Delete the MITO chat-completions multimodal branch from the orchestrator
and the ~370 lines of image-cache/preprocess machinery in trajectories.py
that supported it. VLM training now goes through the renderer path
exclusively — the renderer owns the processor, ships byte-identical
pixel_values to both vLLM (via /inference/v1/generate features) and the
trainer (via mm_kwargs).

Renderer-shipped mm_token_type_ids: the orchestrator reads the renderer's
`mm_token_type_id_map` property (1=image_pad, 2=video_pad) and stamps a
per-token list onto each TrainingSample. Trainer's `_get_qwen3_vl_mm_token_type_ids`
auto-path remains as a fallback but the renderer is now the source of truth.

forward() now takes a generic `mm_kwargs: dict` (e.g. {pixel_values,
image_grid_thw}) instead of the Qwen3-VL-specific (pixel_values, image_grid_thw)
keyword pair, so adding new VLM families (Gemma3, LLaVA, etc.) doesn't
require touching forward.

Config validator: orchestrator.use_renderer must be true when model.vlm is
set — fail at config-load instead of producing cryptic runtime errors.

Test cleanup: drop 25 tests for removed helpers (VLMImageCache, _extract_images,
etc.); update the one remaining renderer-mm trajectory test to pass
`mm_token_type_ids_mapping` directly.

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

* fix: align with renderer-multimodal PR surface (configs + deps + tests)

CI was failing for three reasons after the cherry-pick of the renderer
multimodal commits onto current origin/main. Three fixes:

1. Multimodal configs missing the renderer flag pair. The orchestrator
   config validator (added in the same PR) requires
   ``use_renderer = true`` when ``model.vlm`` is set, AND it's mutually
   exclusive with ``use_token_client`` (default ``true``). Three configs
   (``rl_color_codeword_test.toml``, ``rl_color_codeword.toml``,
   ``ci/nightly/multimodal_color_codeword.toml``) needed both flags set
   explicitly in ``[orchestrator]``. Delete
   ``rl_color_codeword_main_mito.toml`` — that was the A/B reference for
   the legacy MITO path, which this PR rips out. With MITO gone the
   config is no longer runnable; the ``rl_color_codeword_feat_renderer``
   counterpart already covers the new renderer-driven path.

2. ``test_model_forward.py`` was still calling ``forward(...,
   pixel_values=..., image_grid_thw=...)``. ``forward()`` now takes a
   generic ``mm_kwargs: dict`` (so adding new VLM families doesn't
   require touching the trainer signature) — update both tests to pass
   ``mm_kwargs={"pixel_values": ..., "image_grid_thw": ...}`` instead.

3. ``renderers`` / ``verifiers`` deps stale. The orchestrator imports
   ``MultiModalData`` from ``renderers.base`` (introduced in the
   companion renderers PR) and threads ``multi_modal_data`` end-to-end
   via the verifiers ``RendererClient`` changes. Pin both to their
   feature branches until the upstream PRs merge and PyPI / git
   rev-pins are bumped:

     - renderers @ feat/multimodal-vlm
     - verifiers @ feat/renderer-multimodal-passthrough

   Drops the ``renderers==0.1.6`` PyPI pin (the new symbols are post-0.1.6).

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

* chore: bump renderers + verifiers to latest feature-branch commits

Picks up:
- renderers c3feaa5: RendererPool implements Renderer protocol structurally
  (callers can drop pool unwrap + isinstance branching), size=1 fast path,
  is_multimodal helper with per-type cache.
- verifiers 64f2555a: bugbot pass — multimodal dispatch fix (was broken
  for pooled renderers), tighter is_json_serializable, response-tokens
  mm_data strip on intermediate steps.

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

* chore: bump renderers + verifiers to pick up isinstance dispatch fix

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

* chore: drop renderers git source, pin to released 0.1.7

renderers v0.1.7 is now on PyPI with the multimodal feature set this
branch consumes (RenderedTokens, MultiModalData, MultimodalRenderer
protocol, mm_token_type_id_map, RendererPool delegation).

verifiers still pinned to feat/renderer-multimodal-passthrough until
that companion PR merges.

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

* chore: repin verifiers to main + bump renderers to 0.1.8.dev2

The multimodal renderer-passthrough work has merged on verifiers
(verifiers#1346 → c7731bbb, on main since 2026-05-12), so we no longer
need the feature-branch pin. Switching to a `rev =` pin on main
(f633365f) — consistent with how every other git source in this file
is pinned — and bumping renderers to 0.1.8.dev2 to match what verifiers
main now requires.

Pin updates:
- verifiers: branch `feat/renderer-multimodal-passthrough`
  (0.1.14 @ 397b8aa5)  ->  rev `f633365f` (0.1.15.dev7)
- renderers: `>=0.1.7` -> `>=0.1.8.dev2`
- prime-sandboxes: 0.2.22 -> 0.2.26 (transitive from verifiers main)
- fastokens added (transitive from renderers 0.1.8.dev1+; renderers
  routes `load_tokenizer` through fastokens by default)

What's in the verifiers delta (397b8aa5..f633365f) that touches our
surface:
- `RendererClient.from_native_response` migrated to renderers'
  `ParsedToolCall` dataclass shape and filters non-OK parse attempts
  (verifiers#1366 / renderers#22). Internal — the Response we consume
  is unchanged.
- Routed-experts payloads now flow as opaque bytes through the chat
  completions clients (verifiers PRs around the `routed_experts`
  changes). Prime-rl consumes the surface that emits these; no caller
  change needed.

Test plan:
- [x] `uv run pytest tests/unit/orchestrator` — 101 passed against the
  new pins, including `test_qwen3_vl_e2e` which exercises the renderer
  -> RendererClient -> /inference/v1/generate roundtrip path.

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

* chore: drop renderers version pin, defer to verifiers' transitive constraint

We import directly from `renderers` (orchestrator + tests), so the dep
needs to be declared — but pinning a floor here is just second-guessing
verifiers, which already requires `renderers>=0.1.8.dev2`. Let verifiers
be the source of truth for the version.

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

* fix(trainer): drop mm_token_type_ids auto-compute, trust renderer

The auto-compute path (`_get_qwen3_vl_mm_token_type_ids`) was preferred
over the renderer-shipped `mm_token_type_ids` in `forward()`. For
Qwen3-VL the auto function never returns `None` (allocates
`torch.zeros_like(input_ids)` then masked_fills), so the explicit
orchestrator-shipped list was silently discarded — contradicting both
the "renderer is source of truth" design and the trajectories.py
comment noting the explicit list produces ~30x lower mismatch KL.

The new `vlm_requires_renderer` validator (this PR) mandates the
renderer for every VLM config, so the auto path is no longer reachable
as a real fallback. Deleting it. The renderer's `mm_token_type_id_map`
is now the sole source of truth, exactly as advertised.

Also adding the CHANGELOG entry the validator missed — removing the
`[model.vlm]` + `use_renderer = false` combo is a breaking config
change per CHANGELOG.md's stated policy.

The remaining `if "image_grid_thw" not in mm_kwargs` branch is *not*
renderer-replaceable: it skips `position_ids` for MRoPE families
because HF's Qwen-VL `forward()` internally recomputes 3D positions
from `image_grid_thw` and breaks if given the trainer's pre-computed
1D `position_ids`. Duck-typed against the kwargs schema so any future
MRoPE family that ships `image_grid_thw` is handled without a
`model_type` enumeration.

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

* fix(orchestrator): union per-step delta mm_data across sample's step range

verifiers ≥ c7731bbb (PR #1346 merge) replaced ``_strip_intermediate_mm_data``
with ``_delta_intermediate_mm_data`` (commit 9aafa659): each trajectory
step now carries only the items whose ``mm_hash`` was NOT in the prior
step's cumulative set, with multiset-aware semantics. The intended
contract is that per-window assemblers union deltas to recover the
per-sample cumulative.

Prime-rl's ``interleave_rollout`` was that assembler but still read
``prepared_steps[last_step_idx].get("multi_modal_data")`` alone,
assuming the last step held the cumulative set. With the new delta
encoding, the last step often holds **0 items** (everything was a
duplicate of step 0's cumulative set) — so the trainer was given
pixel_values for only the first turn's images. For ``color-codeword``
with ``max_turns=2, images_per_turn=2`` (4 images total), the trainer
saw a subset → wildly wrong attention → mismatch KL jumped from
~0.04 to ~7 (>100× regression). On Qwen3-VL the model raised
``ValueError: Image features and image tokens do not match`` when the
delta drop left the trainer with fewer feature blocks than placeholder
runs.

Fix: track ``start_step_idx`` per active sample and concatenate
``mm_items`` / ``mm_hashes`` across ``[start_step_idx, last_step_idx]``
in step order. No dedup here — verifiers' delta already handled
cross-step dedup with multiset semantics (legitimate duplicate
placeholders, where the same image appears in two turns' separate
placeholder runs, are preserved).

Test plan:
- ``uv run pytest tests/unit/orchestrator/test_trajectories.py`` — 20 passed
- ``uv run pytest tests/unit/orchestrator tests/unit/train`` — 216 passed, 6 skipped, 1 xfailed
- ``uv run rl @ configs/multimodal/rl_color_codeword_feat_renderer.toml``
  on 2× RTX PRO 6000: Step 0 KL **0.020** (was 7.0), Step 1 **0.090**,
  Step 2 **0.253** — all within the baseline range published in #2473
  (max 0.487 across 20 steps).

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

* fix(orchestrator): track explicit step indices per sample for mm union

interleave_rollout used (start_step_idx, last_step_idx) to bound the
mm_data union per sample. When agents interleave (e.g. agent1 at steps
0,1,3 and agent2 at step 2), the range [0,3] over-collects step 2 and
agent2's delta mm_items leak into agent1's sample.mm_kwargs — placeholder
count vs. patch count mismatches at the VLM forward.

Replace the (start, last) pair with the explicit list of prepared_steps
positions merged into the sample. _union_step_mm_data iterates the list
directly, so non-owned steps are skipped by construction.

Non-interleaved trajectories produce step_indices = [0..N], iterating
identically to the old range — bit-for-bit unchanged for the common path.

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: eligotts <78387377+eligotts@users.noreply.github.com>
2026-05-20 19:00:55 -07:00
44dcc5ab40 fix(slurm): release allocation when any component crashes (#2577)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Previously a trainer/inference/orchestrator/router crash left surviving
components running, holding the SLURM allocation until walltime. The
sbatch script propagates the failure now:

- srun uses --kill-on-bad-exit=1 so a non-zero exit on any task kills
  tasks on the other nodes.
- All per-node components run in the background; `wait -n` turns the
  first exit (success or crash) into the task exit code, surfacing
  background crashes (router, orchestrator) that the previous foreground
  layout silently ignored.
- `set -o pipefail` inside the task and `set -e` in the outer sbatch
  keep failures from being swallowed by `| tee` or by setup commands.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 17:04:39 -07:00
271801bd4d fix(wandb): handle shared mode breakage from wandb v0.26.1 (#2578)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(wandb): handle shared mode breakage from wandb v0.26.1

wandb v0.26.1 (PR #11759) changed `inform_init` to propagate
duplicate stream ID errors as `ServerResponseError` instead of
silently swallowing them. This breaks shared mode where multiple
processes intentionally call `wandb.init(id=same_run_id)`.

- Add `resume="allow"` when a run ID is provided so wandb attaches
  to the existing run instead of rejecting it
- Catch `ServerResponseError` (alongside `CommError`) for non-primary
  shared-mode processes to handle transient init races

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

* fix(wandb): teardown wandb-core between init retries

A failed wandb.init leaves the run_id registered in the local
wandb-core StreamMux. The next retry hits the same wandb-core,
finds the stream still there, and raises ServerResponseError
("run ID ... is in use") regardless of resume="allow" — the check
fires before reaching the server.

Tearing down the service before sleeping clears the StreamMux so
the retry starts fresh. Also catch ServerResponseError on the
primary side, since the race is symmetric: either side can win
the upsertBucket and the other can hit this path.

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 17:00:04 -07:00
851233e5de feat(release): automated tagging + release flow (#2573)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(release): add tag-and-release workflow, backfill release notes, expand release skill

Port the verifiers tag-and-release pattern: on version bump in pyproject.toml,
auto-tag main and create the GitHub Release using assets/release/RELEASE_v{tag}.md
as the body. Skip the PyPI publish steps since prime-rl is not on PyPI.

Backfill release-note files for v0.1 through v0.5.0 by copying each existing
GitHub Release body so the workflow has historical artifacts to compare against.

Expand skills/release/SKILL.md so an agent can prepare the full release PR
(version bump, release notes file, draft PR) — merging the PR is then enough
to publish the release.

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

* chore(release): rename v0.1/v0.2 notes to v0.1.0/v0.2.0 for consistency

Aligns all backfilled release note filenames on a MAJOR.MINOR.PATCH suffix.
The historical GitHub tags (v0.1, v0.2) keep their original names; this only
touches the on-disk filenames.

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

* chore(ci): rename release.yaml to docker-push.yaml; exclude dev tags from tag-and-release

The old release.yaml only builds and pushes the Docker image; the new
tag-and-release.yaml is now the canonical "release" workflow. Renaming
removes the ambiguity.

Add a trigger filter to tag-and-release so '*dev*' tags do not flow through
the release path. devx_tag.yaml creates dev tags via GITHUB_TOKEN, which
already does not retrigger workflows; this exclusion is defensive for any
manual dev-tag pushes. Skill note updated to clarify the two workflows
coexist.

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

* fix(ci): check release notes before tagging, and retry on tag-without-release

Two bugbot fixes in tag-and-release.yaml:

1. Move the assets/release/RELEASE_*.md presence check into auto-tag-on-main,
   before the tag is created and pushed. Missing notes used to fail in
   release-from-auto-tag, but only after the tag was already on the remote,
   blocking a clean retry.

2. If the target tag already exists (locally or on origin) but no GitHub
   Release exists for it yet, still emit created=true so release-from-auto-tag
   runs against the existing tag. This unblocks recovery from a partial
   failure (e.g. the release step crashed after the tag push) without
   requiring manual cleanup or workflow_dispatch.

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

* refactor(release): drop in-repo release notes; promote pre-existing draft release on tag

Pivot the release flow:
- Release notes live as a draft GitHub Release created via `gh release create
  --draft` (no longer tracked in the repo). Removed assets/release/*.
- The release skill instructs an agent to (1) draft the release on GitHub
  with the notes inline and (2) open a draft PR that only bumps `version` in
  pyproject.toml.
- On merge, tag-and-release verifies the draft release exists for the new
  tag, pushes the tag, then promotes the draft via `gh release edit
  --draft=false --latest`. Recovery path: if the tag exists with a draft,
  the next main push (or workflow_dispatch) re-promotes it.

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 14:43:06 -07:00
7f7ce8a0f4 chore(skills): slim skills, rename, regroup under training/ (#2576)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore(skills): slim skills, rename, regroup under training/

Rename `config` -> `configs`, `installation` -> `install`. Move
`entrypoints` (as `start-run`) and `monitor-run` under a new
`training/` skill. Slim each skill (~37% fewer lines overall) and
fact-check paths/commands against the current codebase — most
notably the config-class paths now live under
`packages/prime-rl-configs/`, and rollouts are saved to
`{output_dir}/rollouts/step_N/` (no `run_default` prefix).

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

* chore(skills): drop tyro mention in configs skill

pydantic-config is now Pydantic-only (TOML + CLI), no tyro dependency.

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

* chore(skills): drop unsupported `@ toml --help` example

`pydantic-config` doesn't merge TOML into `--help` output; only the
class-level defaults are shown either way. Keep the plain `--help`
and `--dry-run` examples instead.

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

* chore(skills): summarize pydantic-config features in start-run; trim configs

- start-run: add a brief feature summary of `pydantic-config` so the
  config primitives are visible alongside the launch commands.
- configs: drop the SFT/RL domain notes (they belong with the
  respective training docs, not the config primer) and collapse the
  two config-package paths in "Key files" into one line.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 14:27:48 -07:00
09e2977437 feat(config): regex-based auto-resolution of tool-call & reasoning parsers (#2569)
Release / Push CUDA image to Docker (push) Canceled after 0s
Replace the ~100-entry MODEL_TOOL_CALL_PARSER dict + runtime resolver in
server.py with regex patterns in utils/parsers.py — new model variants
match automatically without a dict entry per checkpoint. Reasoning parser
gets the same treatment (previously only the tool-call side auto-resolved).

Resolution moves to a ModelConfig after-validator (auto_resolve_parsers),
not the entrypoint. It piggybacks on RLConfig's before-validator
propagation: the shared [model] name lands in inference.model.name BEFORE
ModelConfig is constructed, so the after-validator sees the resolved name.
Testable without a running server.

Also fixes INTELLECT-3 / Qwen3-Coder mapping from hermes to qwen3_coder,
which matches the upstream HF model docs.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 10:57:33 -07:00
fa191e589b refactor(config): propagate shared RL fields via before-validator (#2565)
Release / Push CUDA image to Docker (push) Canceled after 0s
pydantic-config 0.3 (drop-tyro, #2564) removed the typed-default mirror
that previously round-tripped CLI args through tyro. With that gone, a
``mode="before"`` validator on RLConfig now sees a clean dict-of-dicts and
can propagate shared top-level fields into the right sub-config keys
*before* sub-configs are constructed. Sub-configs' own ``mode="after"``
validators then see the resolved values (e.g. ``OrchestratorConfig.auto_setup_tokenizer``
sees the propagated ``student.model.name`` at the moment it derives
``tokenizer.name``, instead of running with the stale class default and
then being patched up by a load-bearing RL-level re-derive).

Replaces eight per-field ``auto_setup_*`` ``mode="after"`` validators with
a single ``auto_setup_shared_configs`` ``mode="before"`` validator using a
``fill``-if-absent helper. The previous fix-up at the RL level
(``auto_setup_tokenizer``'s "no shared tokenizer: re-derive from
(now-correct) model names") silently overrode explicit
``[orchestrator.tokenizer] name = ...`` values; with the before-validator,
explicit sub-config values survive untouched.

Also:
  - keep per-field mutex ``validate_no_shared_field_conflicts`` —
    duplicating a field in shared + sub-config is still ambiguous and the
    mutex catches it explicitly.
  - drop ``RLConfig.max_model_len`` — declared but never wired to a
    validator. Users set ``inference.model.max_model_len`` directly.
  - move ``auto_setup_session_headers`` from RLConfig onto
    ``OrchestratorConfig`` (now ``self.student.client``), so the hosted
    orchestrator entrypoint also enforces it when loading standalone.
  - collapse the per-field ``validate_shared_*`` calls into a single
    ``validate_shared_configs`` ``mode="after"`` validator that runs the
    full consistency suite post-construction.
  - add ``validate_shared_seq_len`` to ``utils.validation`` and the
    propagation map; ``seq_len`` now also goes through the same flow.

Tests (``tests/unit/test_configs.py``): 24 new cases covering propagation
of ``model.name`` / ``tokenizer`` / ``seq_len`` / ``max_steps`` /
``output_dir`` / ``[ckpt]`` / ``[wandb]``, the per-field mutex on every
shared key, the "empty shared block coexists with sub-block" rule, the
"disjoint shared + sub fields coexist" rule, and end-to-end CLI override
of ``--seq-len`` propagating through TOML.

Crucially, ``test_explicit_subconfig_tokenizer_name_survives_shared_model_propagation``
regression-tests the case that the old RL-level fix-up silently broke:
shared ``[model] name`` propagates everywhere it should, but an explicit
``[orchestrator.tokenizer] name`` is left alone.

Three in-repo configs were tripping the new mutex; same fixes:
  - configs/hendrycks_math/sanity.toml: drop redundant ``[trainer.model] name``
  - examples/hendrycks_sanity/rl.toml: drop redundant ``[trainer.model] name``,
    move shared ``seq_len = 8192`` under ``[orchestrator]`` so the trainer
    keeps its longer 16384 context
  - examples/glm5_pd_disag/rl.toml: split shared ``[model] name`` into
    per-component names (trainer = GLM-5 BF16, orchestrator + inference =
    GLM-5-FP8 to satisfy ``validate_shared_model_name``).

Closes #2430. Supersedes #2517 — the same approach, rebased onto
post-tyro pydantic-config which removes the need for the
``_dump_preserving_discriminators`` workaround the original PR carried.

CPU suite (matches cpu_tests.yaml): 374 passed.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 09:36:57 -07:00
d718fddaa4 chore: bump version to 0.5.0 (#2571)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 22:47:40 -07:00
1f26eeeb52 feat: convert config field descriptions to docstrings + config simplification (#2567)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore(configs): convert field descriptions to PEP 224 docstrings

Now that the pydantic-config bump supports attribute docstrings, switch
every config field from ``Annotated[T, Field(description=...)]`` to a
plain typed assignment plus a single-line docstring on the next line.
``Field(...)`` is kept only where it carries other metadata
(``ge=``/``gt=``, ``validation_alias=``, ``default_factory=``).

Descriptions are tightened: dropped redundant restatements of the field
name, dropped mentions of defaults and aliases (the help renderer shows
those automatically), and dropped pydantic model docstrings (mostly
redundant). Net change is ~1.4k fewer lines across the seven config
modules.

Bumps the pydantic-config submodule to pick up MRO-aware docstring
extraction (so inherited fields keep their description) and
``default_factory`` rendering in --help.

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

* chore(configs): drop trivial sub-config docstrings, base DUV variants on BaseConfig

- Drop sub-config field docstrings that just restated the field name
  (e.g. ``"""Logger configuration."""`` on ``log: LogConfig``). Without
  the docstring the help renderer falls back to ``<path> options`` for
  the panel title, which is just as readable. Keep docstrings that carry
  real info (gating semantics, propagation, side-effects, etc.).
- Switch every discriminated-union variant (and standalone ``BaseModel``
  configs like ``KVCacheOffloadConfig``) from ``BaseModel`` to
  ``BaseConfig`` and drop the per-class
  ``model_config = ConfigDict(extra="forbid")`` line — ``BaseConfig``
  already bakes in ``extra="forbid"`` and the TOML ``"None"`` →
  ``None`` coercion, so this is both leaner and more consistent (some
  variants previously had ``extra="forbid"``, others did not).
- Fix typo in ``examples/wordle/sft.toml`` (``micro-batch-size`` →
  ``micro_batch_size``) that was silently dropped under the old
  ``extra="ignore"`` and would now be rejected.
- Bump pydantic-config submodule to the merged upstream commit
  (PrimeIntellect-ai/pydantic-config#12) for MRO-aware docstring
  extraction and ``default_factory`` rendering in ``--help``.

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

* chore(deps): bump pydantic-config to merged help-rendering fixes

Picks up PrimeIntellect-ai/pydantic-config#13: per-panel flag column
widths, 60-char cap on the flag column with oversize flags rendered on
their own line, inline ``(default: X)`` in place of the right-aligned
annotation column, and title/flag wrapping so the box always fits the
terminal width.

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

* chore(deps): bump slim-wheel pydantic-config floor to 0.3.0.dev82

The PyPI floor on ``prime-pydantic-config`` only matters for the slim
wheel install (plain ``pip install prime-rl-configs`` outside the uv
workspace). Bump it to ``0.3.0.dev82``, the dev release auto-published
when PrimeIntellect-ai/pydantic-config#13 merged — the help-rendering
fixes prime-rl now relies on for clean ``--help`` output.

Workspace installs are unaffected; they keep resolving
``prime-pydantic-config`` editable from ``deps/pydantic-config`` via
the root ``[tool.uv.sources]`` override.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 22:11:58 -07:00
90e9ae98bf fix(tests): bump benchmark regression METRIC_TOLERANCE to 15% (#2570)
Release / Push CUDA image to Docker (push) Canceled after 0s
The 4-GPU step time test flaked at 55.50 vs an upper bound of 55.44 (10.13%
measured deviation) on run 26141695659. Slight bump to 15% to absorb runner
variance between hyperstack (baseline) and massed compute A6000s.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 22:11:02 -07:00
67cdc55521 perf(cli): defer heavy imports so --help short-circuits in cli() (#2566)
Release / Push CUDA image to Docker (push) Canceled after 0s
* perf(cli): defer heavy ML imports so --help short-circuits in cli()

The rl/sft/trainer/orchestrator entrypoints loaded torch, transformers,
torchtitan and friends at module top — so `--help` blocked on ~10s of
import work before cli() got a chance to exit. Mirror the inference
entrypoint pattern: keep module top light, push heavy imports into the
function body that actually uses them.

For `trainer` and `orchestrator`, add lightweight shim entrypoints under
src/prime_rl/entrypoints/ (the heavy implementation modules stay
runnable via `python -m` for torchrun).

--help timings:
  inference   0.35s -> 0.14s
  rl          9.96s -> 0.42s  (24x)
  trainer    10.21s -> 0.20s  (51x)
  sft        10.42s -> 0.20s  (52x)
  orchestrator 9.20s -> 0.24s (38x)

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

* perf(cli): drop redundant _compat import from rl/sft entrypoints

`prime_rl._compat` is already imported at the only two files that
directly pull in ring_flash_attn (`utils/cp.py:4` and
`trainer/models/layers/ring_attn.py:4`, both with ruff:noqa: I001 to
lock the order). Any transitive import path reaches one of those before
ring_flash_attn loads, so the entrypoint-level import is redundant.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:16:48 -07:00
d3e478d732 chore(deps): bump pydantic-config (drop tyro) (#2564)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore(deps): bump pydantic-config to refactor/drop-tyro tip (1659db2)

Point both the submodule and the pyproject.toml source at
PrimeIntellect-ai/pydantic-config @ 1659db2, the latest commit on
refactor/drop-tyro. The package is renamed to prime-pydantic-config,
so update prime-rl-configs and tool.uv.{sources,exclude-newer-package}
accordingly.

Brings in the legacy key remapping (via before-validators), so e.g.
`uv run orchestrator --model.name <name>` now routes to
`student.model.name`.

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

* chore(deps): wire pydantic-config submodule as editable workspace member

Add deps/pydantic-config to [tool.uv.workspace] members and switch the
source from a pinned git rev to { workspace = true }. uv now installs
prime-pydantic-config editable from the submodule on disk, so local
edits propagate to .venv without re-syncing a wheel.

Drop the [tool.uv.exclude-newer-package] entry — that knob only matters
for non-workspace pins.

Bumps the submodule pointer to df5b38e to pick up the upstream ruff
bump (==0.5.0 -> >=0.12.1), which is required so prime-pydantic-config's
dev group unifies with prime-rl's (ruff>=0.12.1).

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

* chore(deps): pin slim-wheel prime-pydantic-config dep to a git rev

The slim wheel CI installs prime-rl-configs in a venv with no workspace
context, so it has to resolve prime-pydantic-config from somewhere
reachable. PyPI only has older 0.3.0.dev* wheels that pre-date the new
RLConfig schema, so the slim parse test was tripping on them.

Embed the git URL directly in the dep string (same pattern as before
the rename, just pointed at PrimeIntellect-ai's repo + the rev we
already track via submodule). In-workspace builds keep using the
editable submodule via the root [tool.uv.sources] override.

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

* chore(deps): bump pydantic-config to 7481096

Pulls in fix for --no-optional.field negation, "did you mean" hints,
and stale tyro refs.

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

* chore(deps): bump pydantic-config submodule to main (ab3a8e7), pin slim wheel to PyPI 0.3.0.dev80

refactor/drop-tyro merged into pydantic-config's main as ab3a8e7. Bump
the submodule to that tip and switch the slim-wheel dep from a git URL
to the PyPI release (`prime-pydantic-config>=0.3.0.dev80`, auto-published
on the merge). uv workspace install still uses the editable submodule
via the root [tool.uv.sources] override.

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

* fix(ci): use [model] alias on CLI for multi_run orchestrator overrides

The orchestrator TOML uses the legacy `[model]` shortcut (which
`fold_student_shortcuts` re-routes to `student.model`). Pairing that with
`--student.X` CLI overrides triggers an alias-collision in the bumped
pydantic-config's `_normalize_alias_keys`: both `model` (from TOML) and
`student` (from CLI) survive the deep-merge, and the canonical-key pass
overwrites instead of merging — silently resetting `student.model.name`
to the default. Inference servers serve the wrong model and the
orchestrator times out before reaching Step 11.

Keep all layers on the `model` alias by using `--model.lora.name` and
`--model.client.base-url`. Pydantic-config side fix lands separately.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:02:34 -07:00
d8698f4e53 test(ci): add reverse-text smoke tests for RL OPD + SFT training modes (#2563)
Release / Push CUDA image to Docker (push) Canceled after 0s
* test(ci): add reverse-text smoke tests for RL OPD + SFT training modes

Covers the rl-entrypoint training_mode = "opd" / "sft" paths on the
existing `vm` integration runner. The student inference deployment is
launched by the rl entrypoint; the teacher is started as a dedicated
`uv run inference` process by the test fixture (low gpu_memory_utilization
on GPU 0 so the student still fits), with orchestrator.teacher.client
pointing at it.

Both tests pass locally on 2× Blackwell GPUs in ~1m40s each.

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

* test(ci): match reverse_text training config + symmetric 0.4 gpu util

Aligns max_steps / seq_len / batch_size / rollouts_per_example / max_completion_tokens
with the existing reverse_text smoke test, and switches the student+teacher
overlap from asymmetric (0.85 + 0.1) to symmetric 0.4 + 0.4 — both fit on one
Blackwell GPU with the small Qwen3-0.6B models. Both tests still pass locally
(~2m10s each).

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

* test(ci): drop to 5 steps and remove [ckpt] for the OPD/SFT smoke tests

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

* test(ci): drop [deployment] and enforce_eager from OPD/SFT configs

Matches the rest of `configs/ci/integration/` — the default
SingleNodeDeploymentConfig (1 train + 1 infer GPU, gpus_per_node=8)
works on the 2-GPU vm runner, and no other CI config sets
enforce_eager. OPD test still passes locally (2m18s).

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

* test(ci): assert eval reward goes up instead of loss goes down

Loss going down is a weak signal for distillation training modes — both OPD
(KL-style) and SFT (teacher-token CE) loss curves are noisy across the 5
smoke steps. Switch to checking that the per-step eval reward on the same
reverse-text env actually improves end-to-end.

- Add [orchestrator.eval] (interval=1, num_examples=16) to both configs.
- New `check_eval_avg_goes_up` helper greps the orchestrator log for
  "Evaluated <env> ... Avg@K=X.XXXX" and asserts last > first.

Both tests pass locally (OPD 1m52s, SFT 1m42s).

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

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 15:30:44 -07:00
rasdaniandGitHub 845eb6e6f2 Scrub padded vLLM model inputs (#2506)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Scrub padded vLLM model inputs

* Fix padded input scrub vLLM wrapper

* Document vLLM patch removal points
2026-05-19 21:31:23 +02:00
eaf95997f7 feat: first-class sft+opd training modes (#2546)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: add student eval inference pool for SFT hard distillation

When teacher_rollout_model is configured for SFT distillation, the
orchestrator now supports a separate student inference pool for online
evals and weight sync. Previously, configuring [inference] alongside
teacher_rollout_model was forbidden — evals either ran on the teacher
or were skipped entirely.

Changes:
- Relax RLConfig validator to allow [inference] + teacher_rollout_model
- Create eval_inference_pool from config.client when teacher_rollout_model
  is set, pointing at the student vLLM server
- Route eval calls and weight updates to the student pool
- Add eval_inference_pool param to Scheduler for weight sync targeting
- All existing RL/soft-distill paths are unchanged (eval_inference_pool
  defaults to inference_pool when no teacher_rollout_model is configured)

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

* fix: keep hard distill student eval pool optional

* fix: scope teacher rollout routing

* fix: address teacher rollout review comments

* fix: clarify teacher rollout client routing

* fix: honor teacher rollout client type

* refactor(orchestrator): rename model/teacher_model to student/teacher

Consolidates 3 training modes (rl, opd, sft) under a unified config
structure: `student` (always present) and `teacher` (optional, role
determined by `training_mode`). Removes scattered flags (`use_sft_loss`,
`update_student_inference_weights`) in favour of a single discriminator.

Backward-compat aliases (`model` → `student`, `teacher_model` → `teacher`)
keep existing TOML configs parsing without changes.

Also adds `configs/reverse_text/debug_{rl,opd,sft}.toml` for local
mode debugging.

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

* chore(configs): cap reverse-text debug eval at 64 examples

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

* chore(configs): cap reverse-text debug eval completion tokens at 128

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

* fix(configs): use correct PI inference teacher model name

qwen/qwen3-4b-instruct doesn't exist on PI inference;
use Qwen/Qwen3-4B-Instruct-2507 instead.

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

* fix(configs): use qwen3-30b-a3b-instruct as debug teacher model

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

* fix(configs): correct teacher model name to qwen3-30b-a3b-instruct-2507

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

* feat(client): add headers_from_env to ClientConfig

Maps header names to env var names, resolved at client setup time.
Analogous to api_key_var but for arbitrary headers. Useful for e.g.
X-Prime-Team-ID when hitting the PI inference API.

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

* feat(client): auto-inject X-Prime-Team-ID header for PI inference

When ClientConfig.base_url targets pinference.ai, auto-add a
headers_from_env mapping for X-Prime-Team-ID -> PRIME_TEAM_ID so team
billing works without each config repeating the boilerplate.

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

* chore(configs): set debug eval to 256 rollouts (64 examples x 4)

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

* fix(configs): use local vLLM teacher for debug OPD instead of PI inference

PI inference is OpenAI-compatible but doesn't expose vLLM's
/inference/v1/generate prefill endpoint that compute_teacher_logprobs
needs - so OPD against PI inference 404s. SFT mode kept working
because that path only hits /chat/completions.

Switch debug_opd.toml to use the existing teacher_inference auto-setup:
set num_teacher_gpus = 1, and an empty [orchestrator.teacher] block to
satisfy the orchestrator validator (which runs before
auto_setup_teacher_inference can populate it). The validator chain
spins up a local vLLM teacher on port 8001 using the same reverse-text
student model.

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

* docs+validate: training modes grid + cross-config constraints

- Add docs/training_modes.md with the rl/opd/sft role grid, implications
  (e.g. OPD needs local vLLM teacher, SFT teacher is any OAI-compatible
  endpoint), and minimal config per mode. Linked from mint.json nav.
- Add validate_training_mode_loss_consistency on RLConfig enforcing:
  sft mode <-> sft loss type, opd mode requires teacher_tau > 0,
  non-sft modes forbid sft loss type. These cross orchestrator and
  trainer fields so they live on RLConfig (per-component validators in
  OrchestratorConfig already cover the within-orchestrator constraints).
- Fix debug_sft.toml to set trainer.loss.type = "sft" (was relying on
  default loss which is now explicitly rejected).
- Make training_mode explicit in debug_rl.toml and debug_opd.toml.

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

* feat(configs): lift training_mode to RLConfig + point debug teacher at local vLLM

- Add shared training_mode field to RLConfig (rl | opd | sft). A mode="before"
  validator propagates it into orchestrator.training_mode and (for sft)
  trainer.loss.type before nested validation runs. Must be a before-validator
  because OrchestratorConfig.validate_training_mode would otherwise reject
  configs like training_mode = "opd" + [orchestrator.teacher] - the
  orchestrator-level default of "rl" would conflict with the teacher block
  before the after-validator could propagate the shared value.

- Point debug_opd and debug_sft at a manually-deployed teacher vLLM
  (Qwen3-0.6B-Reverse-Text-RL on localhost:8001). Add a comment with the
  exact teacher start command at the top of each config. Drop the
  num_teacher_gpus auto-launch from debug_opd since we now use the
  external teacher.

- Set student inference gpu_memory_utilization = 0.5 in all three debug
  configs (matches the teacher's mem budget, leaves room when both are
  co-located).

- Add configs/reverse_text/README.md with the start commands.

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

* chore: drop GPU-occupancy runtime check; teacher uses uv run inference

- Remove check_gpus_available in rl entrypoint - it raised RuntimeError
  when other processes held GPUs, which blocked iterating with a
  long-lived teacher inference server on a sibling GPU.
- Update debug_opd / debug_sft / README to start the teacher via
  uv run inference (the prime-rl variant) instead of raw vllm serve.
  Same port (8001), same model, same flags.

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

* fix(configs): accept legacy flat [orchestrator.model.lora] layout

Pre-refactor, orchestrator.model was a ModelConfig directly (name, lora,
trust_remote_code, vlm). After the student/teacher rename it's a
RolloutModelConfig wrapping ModelConfig + ClientConfig, so existing
[orchestrator.model.lora] TOML sections stopped parsing because they
landed on the wrong nesting level.

Add a mode="before" validator on RolloutModelConfig that detects a flat
ModelConfig dict (any of {name, trust_remote_code, vlm, lora} at the top
level, no nested model/client keys) and re-nests it under "model". This
lets the three existing LoRA configs revert to their original syntax.

Also fix examples/alphabet_sort/sft_distill_hard.toml: hoist training_mode
to the top-level shared field so trainer.loss.type = "sft" gets auto-set
(previously the orchestrator-only flag triggered the new sft/loss
consistency validator).

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

* refactor(orchestrator): split into student_inference + teacher_inference pools

Replace the "one pool plus optional teacher-client overlay" model with two
explicit pools:

- student_inference: InferencePool | None
  - Required for rl/opd, optional for sft (set iff [inference] is configured)
  - Target for evals, weight broadcast, and inference metrics
  - When None, online evals and policy updates are skipped automatically
- teacher_inference: InferencePool | None
  - Set whenever orchestrator.teacher is configured (opd or sft)
  - Source of teacher logprobs in opd
  - Source of train rollouts in sft
  - Always MITO (chat completions) for simplicity; external OAI-compatible
    teachers (PI inference, OpenAI) work as drop-in endpoints

Scheduler now takes both pools and resolves the rollout target internally
(rollout_inference = teacher_inference if sft else student_inference).
The old _resolve_rollout_request_target overlay is gone - the rollout pool
serves rollouts directly. Fixes a latent bug where SFT-mode LoRA updates
would overwrite scheduler.model_name and route subsequent teacher requests
with the student's LoRA name.

Also:
- Drop setup_external_rollout_model (logic is now inline + clearer)
- Rename setup_rollout_inference_pool -> setup_student_inference_pool;
  always handles only the student pool, teacher is plain setup_inference_pool
- Log the resolved training_mode + one-line description at orchestrator start
- Update tests: cover both sft (rollout != student) and rl (rollout = student)
  LoRA paths; drop the now-obsolete teacher-overlay scheduler test

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

* docs+configs: legacy [orchestrator.client] shim + merge OPD doc into training_modes

- Add _accept_top_level_client validator on OrchestratorConfig: legacy
  [orchestrator.client...] re-nests under [orchestrator.student.client...]
  matching the existing _accept_flat_model_layout shim pattern. Revert
  configs/elastic/rl.toml back to the original [orchestrator.client.elastic]
  syntax.
- Revert configs/ci/integration/reverse_text_multi_run/orchestrator.toml
  [model.model] -> [model]; the flat-layout shim on RolloutModelConfig
  already handles it (verified).
- Merge docs/on_policy_distillation.md into docs/training_modes.md. The
  training_modes page is now the single entry point; OPD-specific details
  (external teacher, pure distillation, monitoring, VLM, params) live as
  subsections. Delete the standalone OPD page.
- Drop the redundant "Initializing static inference pool" / WandbMonitor /
  PrimeMonitor init logs - they duplicate the immediately-preceding
  per-pool init line.

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

* feat(orchestrator): probe teacher for prompt_logprobs before training

In OPD mode, send a tiny probe request to the teacher's /inference/v1/generate
endpoint after the pool is ready. If the endpoint 404s or doesn't return
prompt_logprobs, raise an informative error pointing at docs/training_modes.md
instead of crashing mid-training with a 404.

Verified that PI inference fails this probe on all three plausible routes:
- /inference/v1/generate -> 404
- /v1/chat/completions with logprobs=true -> logprobs:null in response
- /v1/completions with echo=true,logprobs=1 -> 404

Also add configs/reverse_text/debug_sft_thinking.toml: SFT from
qwen3-30b-a3b-thinking-2507 via PI inference (sft path needs only
chat completions, so PI inference is fine here).

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

* chore(orchestrator): deprecate use_token_client (server-tokenized TITO)

Drop the server-tokenized TITO path (``openai_chat_completions_token`` /
``/v1/chat/completions/tokens``). The orchestrator now picks between
renderer-backed TITO (``use_renderer = true``, default) and MITO
(``use_renderer = false``, fallback for VLMs and external teacher rollouts).

- Remove ``OrchestratorConfig.use_token_client`` field and its validators
- Drop the TITO branch in ``setup_rollout_inference_pool``
- Drop the obsolete TITO warning in ``setup_inference_pool`` and flip the
  default ``train_client_type`` to ``openai_chat_completions`` in
  ``StaticInferencePool`` / ``ElasticInferencePool``
- Strip ``use_token_client = false`` from configs/examples/docs that
  carried the no-op fallback line
- CHANGELOG entry documenting the breaking removal

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

* chore(inference): remove server-side TITO route

Drop the ``/v1/chat/completions/tokens`` endpoint and the
``OpenAIServingChatWithTokens`` / ``ChatCompletionRequestWithTokens``
wrappers now that no client routes to them. Also drop the obsolete
``base()`` helper and unused imports from ``server.py``.

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

* refactor: require student_inference in all training modes

Student inference was already required for rl/opd and optional for sft;
making it required everywhere simplifies the orchestrator + scheduler:

- Drop has_student_inference / enable_policy_updates gating
- student_inference: InferencePool (no longer Optional) in Scheduler.__init__
- Weight broadcast init, weight sync, metrics collector, eval routing, and
  shutdown all unconditionally use student_inference
- Drop the now-stale OPD probe (will revisit in a follow-up PR)
- Add is_vlm property on BaseModelConfig; replace local is_vlm vars in the
  orchestrator with config.student.model.is_vlm
- Merge the two legacy student-layout shims on OrchestratorConfig into one
  before-validator (_accept_legacy_student_layout) covering both
  [orchestrator.client.*] and flat [orchestrator.model.<k>] paths
- Drop redundant pool / WandbMonitor / PrimeMonitor init log lines
- Reorder OrchestratorConfig fields: training_mode > student > teacher
- Drop "OAI" from RolloutModelConfig.client description
- Update docs/training_modes.md: SFT student inference is now required;
  evals and weight sync are unconditional

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

* feat(configs): default OPD to pure distillation (teacher_tau=1, adv_tau=0)

auto_setup_training_mode now seeds trainer.loss defaults when training_mode
is opd: teacher_tau=1.0 and adv_tau=0.0 (pure distillation: drop the reward
signal, full weight on the teacher KL). User-provided values still win via
setdefault. Also accept training_mode set only inside [orchestrator] - same
auto-setup applies for both the shared top-level and orchestrator-local
forms.

Drop the redundant [trainer.loss] teacher_tau = 0.5 block from
configs/reverse_text/debug_opd.toml; verified the auto-setup applies
end-to-end (3 train steps, teacher logprobs computed each step, clean exit).

Also drop the now-redundant InferencePool type annotation on
self.rollout_inference - both branches assign a definite InferencePool now
that student_inference is non-Optional.

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

* chore(configs): rename debug_sft_thinking -> debug_sft_external; drop examples/alphabet_sort/sft_distill_hard.toml

debug_sft_external describes the role better - external SFT teacher via
OAI-compatible endpoint (PI inference). The "thinking" label was about the
specific model the config picks (qwen3-30b-a3b-thinking-2507), not about
what the config demonstrates.

Drop examples/alphabet_sort/sft_distill_hard.toml: configs/reverse_text/
debug_sft* are the canonical SFT examples now.

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

* fix(tests): unbreak CPU tests after student/teacher rename + headers_from_env

- tests/unit/train/test_runs.py: orchestrator config attribute access
  changed from config.model.name to config.student.model.name after the
  RolloutModelConfig rename.
- tests/unit/utils/test_elastic.py: MagicMock client_config needs
  headers_from_env set to {} - the field was added in this PR and the
  test's hand-built mock missed it (pydantic rejects MagicMock as a dict).

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

* feat(orchestrator): strip logprobs from train sampling in sft mode

The trainer in sft mode reconstructs teacher tokens via the student
tokenizer - it never reads inference-side logprobs from the teacher
endpoint. Stripping logprobs at runtime lets external reasoning-model
endpoints (openai/gpt-5*, etc.) accept the rollout request - they
reject logprobs with 400 invalid_request "logprobs are not supported
with reasoning models".

Done at orchestrator-startup time on each TrainEnv's sampling_args
rather than as a public config field, since this is a mode-specific
runtime concern.

Also: bump configs/reverse_text/debug_sft_external.toml to use
openai/gpt-5-mini (faster than qwen3-30b-a3b-thinking-2507).

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

* chore(configs): bump debug_sft_external for gpt-5-mini reasoning budget

gpt-5-mini's max_completion_tokens budget includes reasoning tokens.
At 128 the model burned the whole budget on internal CoT before
producing the final answer, returning empty content. Raise to 2048
and set reasoning_effort=minimal so the chat-completions response
includes the actual output.

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

* docs: fix stale SFT references after the student/teacher refactor

- skills/config/SKILL.md: update the SFT hard distill section -
  orchestrator.teacher_model -> orchestrator.teacher, drop the
  "student inference is optional" guidance (the orchestrator now
  unconditionally sets up student_inference), and add a note that
  shared training_mode auto-propagates to trainer.loss.type.
- rl.py: auto_setup_inference_client docstring referenced the deleted
  setup_external_rollout_model function. Rewrite to explain what the
  validator actually does for each mode.

Also note the behavior change in the PR description: SFT now requires
[inference] (was previously optional).

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

* feat(loss): batch-driven loss dispatch via TrainingSample.training_mode

Replace TrainingSample/MicroBatch.sft_loss bool with training_mode literal
(rl|opd|sft). The trainer's compute_loss reads training_mode from the
micro batch and dispatches:

- "sft"     -> sft_loss_fn (masked NLL on teacher tokens)
- "rl"      -> default_loss_fn with (adv_tau=1.0, teacher_tau=0.0)
- "opd"     -> default_loss_fn with (adv_tau=0.0, teacher_tau=1.0)

Taus move from trainer.loss config to compute_loss's mode->tau table and
flow into LossInputs per batch; DefaultLossConfig drops the teacher_tau /
adv_tau fields. The orchestrator stamps each sample with
config.training_mode at the same point it used to set sft_loss.

Packer enforces same-mode packing (samples with different training_mode
cannot share a micro batch). RLConfig drops the OPD tau auto-setup +
"opd requires teacher_tau > 0" validator + the validate_teacher_model
teacher_tau gate (all redundant under batch-driven dispatch).

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

* refactor(loss): dedicated opd_loss_fn instead of routing taus through inputs

Replace the per-batch adv_tau/teacher_tau routing through LossInputs with a
dedicated opd_loss_fn that lives alongside default_loss_fn and sft_loss_fn.
A bit of code dup in opd_loss_fn (clone of default's DPPO math) makes the
two paths read as separate losses rather than the same function with magic
multipliers.

- setup_loss_fn -> setup_loss_fns: returns a dict {training_mode: LossFn}.
  rl uses the configured loss (default/custom). opd uses opd_loss_fn (only
  available when loss_config is DefaultLossConfig). sft is always available.
- compute_loss takes loss_fns + training_mode, looks up the right fn.
- opd_loss_fn requires teacher_logprobs (raises otherwise).
- LossInputs no longer carries adv_tau/teacher_tau - those values are baked
  into each loss fn.
- Add validator: opd mode requires trainer.loss.type = "default".

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

* refactor(loss): drop trainer.loss type discriminator + shared training_mode

Now that loss dispatch is fully batch-driven (TrainingSample.training_mode),
the trainer.loss type union and the shared RLConfig.training_mode propagator
are redundant. Flatten:

- Delete SFTLossConfig (the mode implies it; no fields).
- trainer.loss: DefaultLossConfig = DefaultLossConfig() (flat, not a union).
- trainer.custom_loss: CustomLossConfig | None = None - optional override
  for rl-mode loss only; opd and sft always use opd_loss_fn / sft_loss_fn.
- setup_loss_fns(loss_config, custom_loss) always returns all three keys -
  mixed-mode batches dispatch correctly at the trainer level (orchestrator
  still stamps a single mode per run; that's a separate concern).
- Drop RLConfig.training_mode shared field, the auto_setup_training_mode
  before-validator, and validate_training_mode_loss_consistency. The
  orchestrator-level [orchestrator] training_mode is the single source.

Move training_mode = "sft" out of top-level into [orchestrator] in the
three SFT debug configs.

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

* fix(rl entrypoint): warn for missing [inference] in all modes (incl. sft)

After the always-require-student refactor, sft runs need a student
inference pool too (orchestrator unconditionally creates it for evals +
weight sync). The old "sft mode, using teacher for rollouts" info log
was correct under the old semantics but now silently puts the user on a
path where the orchestrator hangs waiting for a non-existent student
server at the default localhost:8000. Replace with a single warning
that prints the configured student base_url and flags the hang risk.

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

* refactor(loss): make opd_loss_fn's tau values explicit (adv_tau=0, teacher_tau=1)

Mirror default_loss_fn's structure literally: declare the two tau locals at
the top, then use them in the same `adv_tau * advantages + teacher_tau *
teacher_kl.detach()` expression. The "this is the default loss with those
specific knobs baked in" relationship is now visible in the code rather than
hidden in a substituted expression.

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

* refactor(loss): restore DefaultLossConfig.adv_tau + LossConfig union (rl-only)

- DefaultLossConfig regains adv_tau (= 1.0). default_loss_fn reads it.
- trainer.loss is back to a discriminated union of DefaultLossConfig |
  CustomLossConfig (drop SFTLossConfig stays dropped). type discriminator
  restored.
- trainer.loss only applies to rl-mode batches. opd and sft batches dispatch
  unconditionally to opd_loss_fn / sft_loss_fn - they don't read trainer.loss.
- opd_loss_fn is self-contained: the DPPO/KL knobs (dppo_mask_*, kl_tau)
  are baked in as module-level _OPD_* constants matching DefaultLossConfig's
  defaults. No loss_config parameter.
- Drop the trainer.custom_loss sibling field (subsumed by the union).

Also add debug_opd_lora.toml + bump lr to 1e-4 in both lora debug configs.

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

* refactor(loss): inline opd_loss_fn knobs (no named locals/constants)

Drop the module-level _OPD_* constants and the local adv_tau/teacher_tau
bindings - inline the literal values into the math. Keeps the parallel
structure to default_loss_fn visible: `0.0 * advantages + 1.0 * teacher_kl`
in the same place default_loss_fn has `loss_config.adv_tau * advantages`.

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

* docs(loss): trim opd_loss_fn docstring

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

* docs: update reverse_text README — add lora configs

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

* polish: auto-disable renderer in sft + CHANGELOG + log/shim cleanup

- OrchestratorConfig auto-sets use_renderer=False when training_mode='sft'
  via an after-validator placed before the renderer validators in
  declaration order, so the user doesn't have to set it. Drop the rejecting
  branch in validate_training_mode + the explicit use_renderer=false lines
  in the three sft debug configs.
- CHANGELOG: add a "first-class training_mode + batch-driven loss dispatch"
  entry covering the breaking removals (orchestrator.use_sft_loss,
  orchestrator.teacher_rollout_model, trainer.loss.type='sft' /
  SFTLossConfig, trainer.loss.teacher_tau) with migration notes.
- _accept_legacy_student_layout: use set(ModelConfig.model_fields) instead
  of hardcoding the field list, so new ModelConfig fields are picked up
  automatically.
- Trim the orchestrator startup log to just '(<training_mode>)'; the
  prose description was redundant with docs/training_modes.md.

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

* fix(configs): unbreak OPD auto-wiring when num_teacher_gpus is set

Add a mode="before" validator on RLConfig that stubs an empty
[orchestrator.teacher] block when deployment.num_teacher_gpus is set and
the user didn't write one. Without this, OrchestratorConfig.validate_training_mode
("opd requires orchestrator.teacher") fires during nested validation - before
auto_setup_teacher_inference can wire the teacher from teacher_inference.

Repro that now passes:

  RLConfig.model_validate({
      "deployment": {"num_teacher_gpus": 1},
      "trainer": {},
      "orchestrator": {"training_mode": "opd"},
      "inference": {},
  })

-> auto_setup_teacher_inference fills in orchestrator.teacher.client.base_url
   = ["http://localhost:8001/v1"] and model.name from teacher_inference.

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

* docs(training_modes): shrink mode-comparison table + add sft/opd teacher note

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

* chore(configs): move training-mode debug configs to configs/debug/training_modes/

The reverse-text debug configs are about exercising the training modes, not
about reverse-text specifically. Move to configs/debug/training_modes/ and
drop the debug_ prefix from each filename (the directory name carries it).

  configs/reverse_text/debug_rl.toml          -> configs/debug/training_modes/rl.toml
  configs/reverse_text/debug_opd.toml         -> configs/debug/training_modes/opd.toml
  configs/reverse_text/debug_opd_lora.toml    -> configs/debug/training_modes/opd_lora.toml
  configs/reverse_text/debug_sft.toml         -> configs/debug/training_modes/sft.toml
  configs/reverse_text/debug_sft_lora.toml    -> configs/debug/training_modes/sft_lora.toml
  configs/reverse_text/debug_sft_external.toml -> configs/debug/training_modes/sft_external.toml
  configs/reverse_text/README.md              -> configs/debug/training_modes/README.md

Update path references in each TOML's header comment, the README, and
docs/training_modes.md.

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

* refactor(configs): drop auto pinference team-id, rename student-shortcut shim

- ClientConfig.auto_setup_pinference_team_header dropped. The hostname-sniff
  was implicit magic. Configs that need the X-Prime-Team-ID header against
  PI inference set it explicitly under [...client.headers_from_env] now.
  Update configs/debug/training_modes/sft_external.toml accordingly and
  drop the auto-injection note from the file header.
- Rename OrchestratorConfig._accept_legacy_student_layout (with leading
  underscore + "backward-compat" framing) to fold_student_shortcuts. The
  shim is more than a back-compat: it's the ergonomic path for rl configs
  too, letting users write [orchestrator.model.name] / [orchestrator.client]
  rather than [orchestrator.student.model.name] / [orchestrator.student.client].
  Docstring reframed accordingly. Teacher has no equivalent shortcut on
  purpose: rl mode forbids teacher, so the same shortcut routing to two
  roles would be ambiguous.

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

* fix(tests): update multi_run CLI args after student rename

test_reverse_text_multi_run.start_orchestrator passes --client.base-url
and --model.lora.name as CLI flags to `uv run orchestrator`. After the
student rename, those tyro args don't exist anymore (they're now
--student.client.base-url and --student.model.lora.name). tyro rejects
them before the fold_student_shortcuts before-validator can re-nest the
dict, so the orchestrator process exits immediately and the test times
out waiting for "Step 11" to appear in the log.

Rename both CLI args to their new student-scoped form.

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

---------

Co-authored-by: Timothy Kostolansky <39891386+tim0120@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-19 10:39:58 -07:00
09e11c7527 fix(benchmarks): refresh a6000 rl baselines after lm_head speedup (#2558)
Release / Push CUDA image to Docker (push) Canceled after 0s
#2547 cut step time ~27% (1-GPU: 65.87s -> 48.29s, 4-GPU: 68.34s -> 50.40s)
and peak memory (1-GPU: 31.81 GiB -> 24.25 GiB), pushing the regression tests
above the 10% tolerance. Refresh baselines from CI run 26067881101.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 23:21:38 -07:00
samsjaandGitHub 03f7feff14 Add pydantic-config submodule (#2556)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-18 21:46:40 -07:00
87ab84b666 chore(orchestrator): deprecate use_token_client (#2549)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore(orchestrator): deprecate use_token_client (server-tokenized TITO)

Drop the server-tokenized TITO path (``openai_chat_completions_token`` /
``/v1/chat/completions/tokens``). The orchestrator now picks between
renderer-backed TITO (``use_renderer = true``, default) and MITO
(``use_renderer = false``, fallback for VLMs and external teacher rollouts).

- Remove ``OrchestratorConfig.use_token_client`` field and its validators
- Drop the TITO branch in ``setup_rollout_inference_pool``
- Drop the obsolete TITO warning in ``setup_inference_pool`` and flip the
  default ``train_client_type`` to ``openai_chat_completions`` in
  ``StaticInferencePool`` / ``ElasticInferencePool``
- Strip ``use_token_client = false`` from configs/examples/docs that
  carried the no-op fallback line
- CHANGELOG entry documenting the breaking removal

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

* chore(inference): remove server-side TITO route

Drop the ``/v1/chat/completions/tokens`` endpoint and the
``OpenAIServingChatWithTokens`` / ``ChatCompletionRequestWithTokens``
wrappers now that no client routes to them. Also drop the obsolete
``base()`` helper and unused imports from ``server.py``.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:22:07 -07:00
halleriteandGitHub 0b37bc923e fix(tests): inject prime lm_head + complete ring-attn restore (#2547)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-19 02:08:06 +02:00
halleriteandGitHub 6591943919 feat(orchestrator): validate renderer auto-resolution at config time (#2537) (#2540)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-19 01:06:07 +02:00
alelpoanandGitHub 4748472b9f docs: add testing-moe-at-small-scale to mint.json navigation (#2542)
Release / Push CUDA image to Docker (push) Canceled after 0s
Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>
2026-05-18 15:31:27 -07:00
samsjaandGitHub 8106bf0a02 [codex] add custom qwen3 dense model (#2505)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add custom qwen3 dense model

* format qwen3 model files

* remove qwen3 unit test
2026-05-18 15:30:47 -07:00
46653c1d70 [codex] add per-env trainer metrics (#2478)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add per-env trainer metrics

* require env names for trainer batches

* address per-env metric review feedback

* reuse tensor stats for env metrics

* fix sft trajectory env-name fixture

* address trainer metric naming comments

* fix: reuse trainer ratio tensors for env metrics

* fix: derive dppo mask from shared ratio

* address PR review: drop precomputed loss inputs, use {all,env} keys

- compute importance-ratio / mismatch_kl inside the loss functions instead of
  passing them in via LossInputs (per Mika)
- compute mismatch_kl inline in train.py only for per-env logging
- rename trainer aggregate keys to entropy/all and mismatch_kl/all to match the
  orchestrator {all,env}/{mean,std,max} convention; drop the leftover bare
  entropy/* and mismatch_kl/* keys
- drop the overly defensive env_names length check in DataLoader

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

* guard mismatch_kl logging behind sft_loss flag

SFT batches don't have meaningful inference_logprobs (sft_loss_fn ignores
them), so computing and logging mismatch_kl for those microbatches is wasted
work and produces misleading numbers. Skip the inline mismatch_kl compute and
the per-env / debug-log emissions when sft_loss is True.

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

* address review: simplify probs_diff and move mismatch_kl/all to trainer loop

* reserve env_name='all' for aggregate metric keys

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 15:19:52 -07:00
samsjaandGitHub c5fb9591b2 feat(orchestrator): default max_error_reschedule_attempts to 3 (#2484)
Release / Push CUDA image to Docker (push) Canceled after 0s
Follow-up to #2459. Switches the default from `None` (retry indefinitely)
to `3`, so single-example hangs in agent envs no longer block step progress
out of the box. Users who want the legacy infinite-retry behavior can still
set `None` explicitly.
2026-05-18 14:51:13 -07:00
alelpoanandGitHub b22e768fc4 docs: fix typos and grammar errors in documentation (#2544)
Release / Push CUDA image to Docker (push) Canceled after 0s
* docs: fix "seemless" typo

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

* docs: fix model name Qwen-4B to Qwen3-4B

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

* docs: fix "violation to" grammar error

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

* docs: fix "asynchronoously" typo

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

* docs: fix duplicate "the the"

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

---------

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>
2026-05-18 14:34:27 -07:00
faresobeidandGitHub ef8f459ca0 clean quack norm (#2543)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-18 14:28:54 -07:00
c3c6b70f11 [codex] chore: bump vllm to 0.21.0 (#2519)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore: bump vllm

* fix: adapt dp pause patch for vllm 0.21

* Drop deep_gemm ep_scatter and silu_mul_quant int64 monkey patches

Both int64-addressing carries are fixed upstream in vLLM 0.21.0.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 13:55:08 -07:00
f18297fd7d chore(verifiers): bump submodule to main (dd89b5e9) (#2534)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 20:18:58 -07:00
HubertandGitHub 6d80c412b6 Allow capped inflight rollout capacity (#2533)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-17 20:08:31 -07:00
a166a8b8df fix(orchestrator): trim glibc heap after each step to prevent RSS growth (#2527)
Release / Push CUDA image to Docker (push) Canceled after 0s
numpy/pandas allocate array data via malloc() (outside Python's allocator),
so gc.collect() alone doesn't reclaim RSS after per-step DataFrames are freed.
glibc retains freed pages in its internal pool, causing ~+6 MB/step monotonic
RssAnon growth on the orchestrator process.

malloc_trim(0) forces glibc to return freed heap pages to the OS, producing
a stable sawtooth pattern (peak during rollout generation, drops after trim)
with no upward trend.

Verified on alphabet-sort (512 rollouts/step, 20 steps, no wandb):
- Without fix: 941 MB → 973 MB by step 3 (+6 MB/step, unbounded)
- With fix:    941 MB → 942 MB by step 5 (flat, sawtooth only)

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 15:57:34 -07:00
samsjaandGitHub 66ff00d117 make renderers default for rollouts (#2521)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-17 12:58:38 +02:00
ae610d9dd8 feat(renderer): expose preserve_*_thinking flags in RendererConfig (#2436)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(renderer): expose preserve_*_thinking flags in RendererConfig

Adds two new fields to RendererConfig:
  - preserve_all_thinking
  - preserve_thinking_between_tool_calls

The orchestrator forwards them in two places so train and infer stay
consistent:

  1. create_renderer() — bound at construction on the training-side
     renderer used by build_trajectory_step / render_ids.
  2. setup_inference_pool() → setup_clients() → vf.ClientConfig — the
     verifiers RendererClient picks them up and forwards to its
     create_renderer_pool, so every inference render carries the same
     thinking-preservation behaviour.

Both flags are off by default → zero behaviour change for existing
configs. Setting either without orchestrator.use_renderer=True is
rejected by validate_renderer_args, matching the existing renderer
knobs.

Bumps source pins:
  - verifiers 3b77145 → a7516a1 (PR #1298: ClientConfig propagation)
  - renderers (now a separate repo): pinned to fe67f9f (PR #4:
    construction-time preserve flags)

Re-applies #2433, which was merged into feat/unify-inference-generate
by mistake.

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

* fix(sft): forward preserve_*_thinking flags through SFT renderer path

The flags were added to the shared RendererConfig but only wired up
in the orchestrator. SFT also constructs a renderer via create_renderer
for training-side tokenization, so it must forward both flags or
silently ignore them.

Also tighten validate_renderer_args to reject either flag when
use_renderer=False, matching the orchestrator validator.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 17:38:53 -07:00
254 changed files with 15860 additions and 15377 deletions
+2
View File
@@ -15,3 +15,5 @@ Config files live in:
- `src/prime_rl/configs/`
If breaking changes are detected without a corresponding `CHANGELOG.md` update, request that the author add an entry.
Any PR that introduces a new custom model must also provide a table showing mean KL mismatch across 20 steps on math environment on this new model with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not present, request the author to add such a table.
+262
View File
@@ -0,0 +1,262 @@
name: Build Image (ghcr)
on:
release:
types: [published]
workflow_dispatch:
inputs:
ref:
description: "Branch, tag, or commit to build"
required: false
default: "main"
type: string
tag:
description: "Image tag (defaults to sanitized ref)"
required: false
type: string
platforms:
description: "Target platforms to build"
required: false
default: "both"
type: choice
options:
- amd64-only
- arm64-only
- both
env:
REGISTRY: ghcr.io
IMAGE_NAME: primeintellect-ai/prime-rl
BUILD_REF: ${{ github.event.release.tag_name || inputs.ref || github.ref_name }}
BUILD_TAG: ${{ github.event.release.tag_name || inputs.tag || '' }}
BUILD_PLATFORMS: ${{ inputs.platforms || 'both' }}
concurrency:
group: build-image-${{ github.event.release.tag_name || inputs.tag || inputs.ref || github.ref_name }}
cancel-in-progress: false
jobs:
prepare:
name: Prepare build
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
matrix: ${{ steps.matrix.outputs.matrix }}
ref: ${{ steps.vars.outputs.ref }}
tag: ${{ steps.vars.outputs.tag }}
sha: ${{ steps.vars.outputs.sha }}
full_sha: ${{ steps.vars.outputs.full_sha }}
platforms: ${{ steps.vars.outputs.platforms }}
steps:
- name: Set build matrix
id: matrix
env:
PLATFORMS: ${{ env.BUILD_PLATFORMS }}
run: |
case "$PLATFORMS" in
arm64-only)
echo 'matrix={"include":[{"runner":"image-builder-arm-2204","platform":"linux/arm64","suffix":"arm64"}]}' >> "$GITHUB_OUTPUT"
;;
both)
echo 'matrix={"include":[{"runner":"image-builder","platform":"linux/amd64","suffix":"amd64"},{"runner":"image-builder-arm-2204","platform":"linux/arm64","suffix":"arm64"}]}' >> "$GITHUB_OUTPUT"
;;
amd64-only)
echo 'matrix={"include":[{"runner":"image-builder","platform":"linux/amd64","suffix":"amd64"}]}' >> "$GITHUB_OUTPUT"
;;
*)
echo "Unsupported platforms value: ${PLATFORMS}" >&2
exit 1
;;
esac
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ env.BUILD_REF }}
fetch-depth: 0
- name: Resolve image vars
id: vars
env:
INPUT_REF: ${{ env.BUILD_REF }}
INPUT_TAG: ${{ env.BUILD_TAG }}
PLATFORMS: ${{ env.BUILD_PLATFORMS }}
run: |
case "$INPUT_REF" in
main|v[0-9]*|*.dev[0-9]*) ;;
*)
echo "ref '${INPUT_REF}' not allowed for ghcr publish (must be main, v*, or *.dev*)" >&2
exit 1
;;
esac
if [ -n "$INPUT_TAG" ] && [ "$INPUT_TAG" != "$INPUT_REF" ] && [ "$INPUT_REF" != "main" ]; then
echo "custom 'tag' that differs from 'ref' is only allowed when ref=main; got ref='${INPUT_REF}' tag='${INPUT_TAG}'" >&2
exit 1
fi
raw_tag="$INPUT_TAG"
if [ -z "$raw_tag" ]; then
raw_tag="$INPUT_REF"
fi
tag=$(echo "$raw_tag" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | cut -c1-50 | sed 's/^-//;s/-$//')
if [ -z "$tag" ]; then
echo "Could not derive a valid image tag from '${raw_tag}'." >&2
exit 1
fi
echo "ref=${INPUT_REF}" >> "$GITHUB_OUTPUT"
echo "tag=${tag}" >> "$GITHUB_OUTPUT"
echo "sha=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT"
echo "full_sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
echo "platforms=${PLATFORMS}" >> "$GITHUB_OUTPUT"
build:
name: Build and push (${{ matrix.suffix }})
needs: prepare
environment: ghcr-publish
strategy:
fail-fast: true
matrix: ${{ fromJson(needs.prepare.outputs.matrix) }}
runs-on: ${{ matrix.runner }}
permissions:
contents: read
packages: write
steps:
- name: Remove unnecessary packages
run: |
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ needs.prepare.outputs.ref }}
fetch-depth: 0
submodules: false
- name: Init public submodules
run: |
if [ -f .gitmodules ]; then
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/pydantic-config deps/verifiers deps/renderers deps/research-environments
fi
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push
id: build
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile.cuda
push: true
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:commit-${{ needs.prepare.outputs.sha }}-${{ matrix.suffix }}
labels: |
org.opencontainers.image.revision=${{ needs.prepare.outputs.full_sha }}
org.opencontainers.image.version=${{ needs.prepare.outputs.tag }}
org.opencontainers.image.source=https://github.com/${{ github.repository }}
- name: Summary
env:
INPUT_REF: ${{ needs.prepare.outputs.ref }}
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
PLATFORM: ${{ matrix.platform }}
SUFFIX: ${{ matrix.suffix }}
run: |
{
echo "## Build Summary (${SUFFIX})"
echo ""
echo "| Property | Value |"
echo "|----------|-------|"
echo "| **Ref** | \`${INPUT_REF}\` |"
echo "| **Platform** | \`${PLATFORM}\` |"
echo "| **Image** | \`${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}-${SUFFIX}\` |"
echo "| **Commit** | \`${IMAGE_SHA}\` |"
echo "| **Digest** | \`${IMAGE_DIGEST}\` |"
} >> "$GITHUB_STEP_SUMMARY"
manifest:
name: Create multi-arch manifest
needs: [prepare, build]
if: needs.prepare.outputs.platforms == 'both'
runs-on: ubuntu-latest
permissions:
packages: write
steps:
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Create and push manifests
env:
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
IMAGE_FULL_SHA: ${{ needs.prepare.outputs.full_sha }}
PLATFORMS: ${{ needs.prepare.outputs.platforms }}
SOURCE_URL: https://github.com/${{ github.repository }}
run: |
set -euo pipefail
image="${REGISTRY}/${IMAGE_NAME}"
tag_sources=()
sha_sources=()
if [ "$PLATFORMS" != "arm64-only" ]; then
tag_sources+=("${image}:${IMAGE_TAG}-amd64")
sha_sources+=("${image}:commit-${IMAGE_SHA}-amd64")
fi
if [ "$PLATFORMS" != "amd64-only" ]; then
tag_sources+=("${image}:${IMAGE_TAG}-arm64")
sha_sources+=("${image}:commit-${IMAGE_SHA}-arm64")
fi
docker buildx imagetools create \
--annotation "index:org.opencontainers.image.revision=${IMAGE_FULL_SHA}" \
--annotation "index:org.opencontainers.image.version=${IMAGE_TAG}" \
--annotation "index:org.opencontainers.image.source=${SOURCE_URL}" \
-t "${image}:${IMAGE_TAG}" \
"${tag_sources[@]}"
docker buildx imagetools create \
--annotation "index:org.opencontainers.image.revision=${IMAGE_FULL_SHA}" \
--annotation "index:org.opencontainers.image.version=${IMAGE_TAG}" \
--annotation "index:org.opencontainers.image.source=${SOURCE_URL}" \
-t "${image}:commit-${IMAGE_SHA}" \
"${sha_sources[@]}"
- name: Summary
env:
INPUT_REF: ${{ needs.prepare.outputs.ref }}
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
PLATFORMS: ${{ needs.prepare.outputs.platforms }}
run: |
{
echo "## Manifest Summary"
echo ""
echo "| Property | Value |"
echo "|----------|-------|"
echo "| **Ref** | \`${INPUT_REF}\` |"
echo "| **Platforms** | \`${PLATFORMS}\` |"
echo "| **Image** | \`${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}\` |"
echo "| **Commit Image** | \`${REGISTRY}/${IMAGE_NAME}:commit-${IMAGE_SHA}\` |"
} >> "$GITHUB_STEP_SUMMARY"
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
+15 -1
View File
@@ -7,6 +7,7 @@ on:
permissions:
contents: write
actions: write
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -81,7 +82,6 @@ jobs:
sha,
});
core.notice(`Created tag ${tag} at ${sha}`);
return;
} catch (error) {
if (error.status === 422) {
core.warning(`Tag ${tag} already exists, retrying...`);
@@ -89,6 +89,20 @@ jobs:
}
throw error;
}
try {
await github.rest.actions.createWorkflowDispatch({
owner,
repo,
workflow_id: "build_image.yaml",
ref: "main",
inputs: { ref: tag, tag, platforms: "both" },
});
core.notice(`Dispatched build_image.yaml for ${tag}`);
} catch (error) {
core.setFailed(`Failed to dispatch build_image.yaml: ${error.message}`);
}
return;
}
core.setFailed("Could not create a unique .dev tag after retries.");
@@ -1,4 +1,4 @@
name: Release
name: Docker Push
on:
push:
@@ -29,7 +29,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Docker meta
id: meta
uses: crazy-max/ghaction-docker-meta@v2
+8 -2
View File
@@ -32,7 +32,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v5
- name: Install dependencies
@@ -69,6 +69,12 @@ jobs:
- test: reverse_text
runner: vm
pytest_args: "tests/integration/test_reverse_text.py"
- test: reverse_text_rl_opd
runner: vm
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
- test: reverse_text_rl_sft
runner: vm
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
- test: alphabet_sort
runner: vm
pytest_args: "tests/integration/test_alphabet_sort.py"
@@ -97,7 +103,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v5
- name: Install dependencies
+1 -1
View File
@@ -79,7 +79,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
+212
View File
@@ -0,0 +1,212 @@
name: Tag and Release
on:
push:
branches:
- main
tags:
# Stable release tags only. `.dev` tags are created by `devx_tag.yaml`
# via GITHUB_TOKEN (which does not retrigger workflows), so they would
# not arrive here anyway — this exclusion is defensive for manual pushes.
- 'v*'
- '!v*dev*'
workflow_dispatch:
inputs:
tag:
description: 'Existing tag to release (e.g. v0.6.0)'
required: true
type: string
jobs:
auto-tag-on-main:
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
permissions:
contents: write
outputs:
created: ${{ steps.tag.outputs.created }}
tag: ${{ steps.tag.outputs.tag }}
version: ${{ steps.tag.outputs.version }}
steps:
- name: Checkout main
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Detect version bump and create tag
id: tag
env:
BEFORE_SHA: ${{ github.event.before }}
GH_TOKEN: ${{ github.token }}
run: |
echo "created=false" >> "$GITHUB_OUTPUT"
if [ "$BEFORE_SHA" = "0000000000000000000000000000000000000000" ]; then
echo "No valid base commit available; skipping auto-tag."
exit 0
fi
OLD_VERSION=$(git show "$BEFORE_SHA:pyproject.toml" | sed -n 's/^version = "\([^"]*\)"$/\1/p' | head -n1)
if [ -z "$OLD_VERSION" ]; then
echo "Could not find version in previous pyproject.toml" >&2
exit 1
fi
NEW_VERSION=$(python - <<'PY'
from pathlib import Path
import re
import sys
match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', Path("pyproject.toml").read_text())
if not match:
sys.exit("Could not find version in current pyproject.toml")
print(match.group(1))
PY
)
if [ "$OLD_VERSION" = "$NEW_VERSION" ]; then
echo "No version change detected in pyproject.toml; skipping auto-tag."
exit 0
fi
TAG="v${NEW_VERSION}"
# A draft GitHub Release must already exist for this tag before we
# bump the version on main. The release skill creates it via
# `gh release create --draft` ahead of the PR merge.
STATE=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft --jq '.isDraft' 2>/dev/null || echo "missing")
if [ "$STATE" = "missing" ]; then
echo "No GitHub Release found for $TAG." >&2
echo "Create a draft release first: gh release create --draft $TAG --title $TAG --notes-file <notes>.md" >&2
exit 1
fi
if [ "$STATE" = "false" ]; then
echo "Release $TAG is already published; skipping auto-tag."
exit 0
fi
TAG_EXISTS_LOCAL=false
TAG_EXISTS_REMOTE=false
if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then
TAG_EXISTS_LOCAL=true
fi
if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null 2>&1; then
TAG_EXISTS_REMOTE=true
fi
if [ "$TAG_EXISTS_LOCAL" = "true" ] || [ "$TAG_EXISTS_REMOTE" = "true" ]; then
# Tag exists but draft hasn't been published — proceed to publish
# (covers retries after the release-from-auto-tag step failed).
echo "Tag ${TAG} already exists with a draft release; will publish."
echo "created=true" >> "$GITHUB_OUTPUT"
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -a "$TAG" -m "Release $TAG"
git push origin "$TAG"
echo "created=true" >> "$GITHUB_OUTPUT"
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
release-from-auto-tag:
needs: auto-tag-on-main
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Publish draft release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.auto-tag-on-main.outputs.tag }}
run: |
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
tag-and-release:
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout tagged release (dispatch)
if: github.event_name == 'workflow_dispatch'
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: refs/tags/${{ inputs.tag }}
- name: Checkout tagged release (push)
if: github.event_name != 'workflow_dispatch'
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Resolve release version
id: release
env:
EVENT_NAME: ${{ github.event_name }}
PUSHED_REF: ${{ github.ref_name }}
INPUT_TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || '' }}
run: |
if [ "$EVENT_NAME" = "workflow_dispatch" ]; then
TAG="$INPUT_TAG"
else
TAG="$PUSHED_REF"
fi
if [ -z "$TAG" ]; then
echo "Unable to determine release tag" >&2
exit 1
fi
case "$TAG" in
v*)
;;
*)
echo "Release tags must be prefixed with 'v' (received '$TAG')" >&2
exit 1
;;
esac
VERSION="${TAG#v}"
FILE_VERSION=$(python - <<'PY'
from pathlib import Path
import re
import sys
match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', Path("pyproject.toml").read_text())
if not match:
sys.exit("Could not find version in pyproject.toml")
print(match.group(1))
PY
)
if [ "$FILE_VERSION" != "$VERSION" ]; then
echo "Version mismatch: tag requests '$VERSION' but pyproject.toml defines '$FILE_VERSION'" >&2
exit 1
fi
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Publish draft release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
run: |
STATE=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft --jq '.isDraft' 2>/dev/null || echo "missing")
if [ "$STATE" = "missing" ]; then
echo "No GitHub Release found for $TAG." >&2
echo "Create a draft release first: gh release create --draft $TAG --title $TAG --notes-file <notes>.md" >&2
exit 1
fi
if [ "$STATE" = "false" ]; then
echo "Release $TAG is already published; nothing to do."
exit 0
fi
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
+1
View File
@@ -1,5 +1,6 @@
.vscode/*
.claude/scheduled_tasks.lock
.claude/worktrees/
*.ipynb
*.jsonl
configs/endpoints.py
+3 -3
View File
@@ -7,6 +7,6 @@
[submodule "research-environments"]
path = deps/research-environments
url = git@github.com:PrimeIntellect-ai/research-environments.git
[submodule "configs/private"]
path = configs/private
url = git@github.com:PrimeIntellect-ai/research-configs.git
[submodule "pydantic-config"]
path = deps/pydantic-config
url = https://github.com/PrimeIntellect-ai/pydantic-config
+5 -2
View File
@@ -35,6 +35,10 @@ Namespaces are one honking great idea -- let's do more of those!
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
## Docs
- **Docs reflect `main`, not history**: `docs/` describes the current state of the codebase only. Don't mention removed/legacy fields, migration paths, or "this used to be X" anecdotes.
## Skills
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs). When you make changes to the codebase, check if any skills need to be updated to stay accurate.
@@ -50,11 +54,10 @@ Write tests as plain functions with pytest fixtures. Don't use class-based tests
## Git
- **Branch prefixes**: use the following prefixes for branches: `feat/`, `fix/`, `chore/`
- **Branch prefixes**: use `feat/`, `fix/`, `chore/`; use `exp/` for experiment branches (configs, run summaries, pins, notes).
## GitHub
- **Draft PRs**: always create PRs as drafts (`gh pr create --draft`) to avoid triggering CI unnecessarily.
- **Pull requests**: do not include a "test plan" section in PR descriptions unless you actually ran tests to verify the changes or the user explicitly asked for one.
- **Keep PR descriptions in sync**: every time you push commits to a PR, also update the PR description (`gh pr edit <num> --body-file ...`) so it reflects the current state of the branch — not just what was true when the PR was opened. Preserve any auto-generated blocks (e.g. `<!-- CURSOR_SUMMARY -->`).
+25
View File
@@ -2,6 +2,31 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
- **`orchestrator.eval.eval_base_model` → `orchestrator.eval.skip_first_step`** (semantics inverted): `eval_base_model = true` becomes `skip_first_step = false` (the default — run the step-0 eval before any train rollouts). No alias; configs setting `eval_base_model` must rename.
- **`orchestrator.eval.skip_eval_on_resume` (and its alias `skip_eval_on_restart`) removed**: folded into `skip_first_step`. Resume no longer re-fires an already-completed eval (deduped via per-env last-eval-step tracking in the checkpointed progress).
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval` removed**: the drain-switch overlap (stop scheduling new train, let in-flight train drain while eval queues) is now the only eval transition mode.
- **`ckpt.skip_buffer` removed**: there is no buffer to skip.
- **`[orchestrator.buffer]` removed** (difficulty pools): the whole block and every key (`seed`, `easy_threshold`, `hard_threshold`, `easy_fraction`, `hard_fraction`, `online_difficulty_filtering`, `hash_keys`) are gone, with no alias — `extra="forbid"` rejects the block, so existing configs must delete it. To preserve `online_difficulty_filtering = true`, enforce the zero-advantage pre-batch filter: `[[orchestrator.pre_batch_filters]]\ntype = "zero_advantage"\nenforce = true`.
- **`orchestrator.filters` → `orchestrator.post_batch_filters`** (renamed, no alias): existing configs setting `[[orchestrator.filters]]` must rename to `[[orchestrator.post_batch_filters]]` (`extra="forbid"` rejects the old key). A new `pre_batch_filters` list is also available. Filters are **train-only** now — eval rollouts are no longer filtered.
- **`orchestrator.max_off_policy_steps` now also applies to eval** (behavior change, field unchanged): eval rollouts that fall more than `max_off_policy_steps` versions behind the policy are cancelled, same as train. (2026-05-29)
- **`sampling.min_tokens`, `sampling.repetition_penalty`, `sampling.seed` removed**: Dropped from both `TrainSamplingConfig` and `EvalSamplingConfig` (group-level `[orchestrator.train.sampling]` / `[orchestrator.eval.sampling]` and per-env `[[orchestrator.train.env.sampling]]` / `[[orchestrator.eval.env.sampling]]`). `min_tokens` suppressed natural EOS, `repetition_penalty` distorts the on-policy sampling distribution, and `seed` wasn't pulling its weight — none belonged on the supported config surface. Existing configs setting any of these must delete the field. Hard-deprecation, no migration window. (2026-05-27)
- **`wandb.shared` removed**: The deprecation shim that popped `wandb.shared` from input dicts with a `FutureWarning` (introduced in #2649) is gone. The `rl` entrypoint always uses shared W&B mode now, and existing configs that still set `wandb.shared = true` (or `false`) will fail validation. Drop the field from your config. (2026-05-27)
- **`max_async_level` and `strict_async_level` removed**: The async-execution semantics between trainer and orchestrator are now design invariants, not config knobs. The trainer always runs exactly one step ahead of inference, and the orchestrator always adopts the freshest checkpoint that doesn't violate the one-step barrier. The shared top-level `max_async_level`, the per-sub-config `trainer.max_async_level` / `orchestrator.max_async_level`, and `orchestrator.strict_async_level` have all been removed. Existing configs setting any of these must drop the field; the previous defaults (`max_async_level = 1`, `strict_async_level = false`) match the new hardcoded behavior. Bench mode no longer bypasses the weight-ckpt wait (the `int(1e9)` workaround is gone) and `multimodal/rl_color_codeword_feat_renderer.toml`'s prior `max_async_level = 0` (fully synchronous on-policy) is no longer expressible. (2026-05-25)
- **`teacher_inference` removed from RL entrypoint**: The `[teacher_inference]` config block and the `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` fields have been removed. The `rl` entrypoint now only manages the student-policy inference server. External teachers (used by OPD and local-vLLM SFT) must be started manually (e.g. `CUDA_VISIBLE_DEVICES=1 uv run inference --model.name <teacher> --server.port 8001 ...`) and pointed at via `[orchestrator.teacher.client]`. Existing configs using `[teacher_inference]` or `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` must drop those fields and bring up the teacher out-of-band. (2026-05-25)
- **`rollouts_per_example` → `group_size`**: The orchestrator-level field, the group-level `[orchestrator.eval]` field, and the per-env `[[orchestrator.eval.env]]` field have all been renamed. The old name still parses as a validation alias (in both TOML and CLI), so existing configs keep working without changes; new configs should prefer `group_size`. (2026-05-22)
- **`AdvantageInputs` / `AdvantageOutputs` are now per-group, and `AdvantageOutputs.advantages` is a plain `list[float]`** (second breaking change to this API in three weeks). `AdvantageInputs.rollouts` is now `list[vf.RolloutOutput]` (a single group) instead of `list[list[vf.RolloutOutput]]`, and `AdvantageOutputs.advantages` is now `list[float]` instead of a 2D `Float[Tensor, "num_examples rollouts_per_example"]`. `compute_advantages` calls `advantage_fn` once per group, which lets partial-group training (groups smaller than `rollouts_per_example` after rollout errors) round-trip without the previous bucket-by-size workaround. Custom advantage functions must drop the outer list dimension and return a list of floats — e.g. `AdvantageOutputs(advantages=(rewards - rewards.mean(dim=1, keepdim=True)).tolist())` becomes `AdvantageOutputs(advantages=[r - mean for r in rewards])` (or `.tolist()` if you keep torch internally). (2026-05-22)
- **`[model.vlm]` requires `orchestrator.use_renderer = true`**: VLMs must go through the renderer path; the `vlm_requires_renderer` validator rejects `use_renderer = false` when `[model.vlm]` is set. The renderer owns the HF processor per-slot and ships generic `mm_kwargs` keyed by the model's forward signature. Since `use_renderer` already defaults to `true`, most VLM configs need no change. (2026-05-19)
- **First-class `training_mode` + batch-driven loss dispatch** (collection of removals/renames). Loss selection is now driven by `TrainingSample.training_mode` (`rl` / `opd` / `sft`), set under `[orchestrator]`. The trainer is mode-agnostic and dispatches per batch.
- **`orchestrator.use_sft_loss` removed**: replaced by `[orchestrator] training_mode = "sft"`. The orchestrator stamps each sample's `training_mode` and the trainer dispatches to `sft_loss_fn` per batch.
- **`orchestrator.teacher_rollout_model` removed (no alias)**: configs must rename to `[orchestrator.teacher]` (`teacher_model` is also accepted as a back-compat alias for `teacher`). Used in both opd and sft modes; the role is determined by `training_mode`.
- **`orchestrator.model` → `orchestrator.student`**: renamed for symmetry with `orchestrator.teacher`. Legacy `[orchestrator.model]` and a flat `[orchestrator.model.lora]`-style layout are aliased via a back-compat shim, so most existing configs still parse. New code should use `[orchestrator.student.*]`.
- **`trainer.loss.type = "sft"` removed (`SFTLossConfig` deleted)**: zero-field discriminator that is now implied by `training_mode = "sft"`. `trainer.loss` collapsed to a `DefaultLossConfig | CustomLossConfig` union. Existing configs setting `[trainer.loss] type = "sft"` must remove that line; the orchestrator-level `training_mode = "sft"` is enough.
- **`trainer.loss.teacher_tau` removed from `DefaultLossConfig`**: the teacher-KL term is now exclusive to `opd_loss_fn` (which inlines `teacher_tau = 1.0`). `default_loss_fn` only handles reward-driven RL and no longer accepts a `teacher_tau`. Configs that set `teacher_tau` on `[trainer.loss]` will fail validation — switch to `[orchestrator] training_mode = "opd"` (which uses `opd_loss_fn` with the value baked in).
- **`trainer.loss` only applies to rl-mode batches**: opd and sft don't read `trainer.loss`. `opd_loss_fn`'s knobs (dppo_mask_*, kl_tau) are inlined as literals; tweak them by editing the function. `CustomLossConfig` overrides the rl-mode loss only — opd and sft always use their dedicated fns. (2026-05-19)
- **`orchestrator.use_token_client` removed**: The server-tokenized TITO path has been deprecated end-to-end. The orchestrator-side config flag (`use_token_client`), the verifiers client_type (`openai_chat_completions_token`), and the inference server's `/v1/chat/completions/tokens` route (along with the `OpenAIServingChatWithTokens` wrapper) are all gone. The orchestrator now picks between renderer-backed TITO (`use_renderer = true`, default) and MITO (`use_renderer = false`, fallback). Existing configs with `use_token_client = true` must migrate to `use_renderer = true` (or `use_renderer = false` for MITO); configs with `use_token_client = false` can simply drop the field. (2026-05-19)
- **`orchestrator.advantage.length_penalty` → discriminated sub-config**: The scalar `length_penalty: Literal["tokens","turns"] | None` is replaced by a `LengthPenaltyConfig | None` discriminated on `type`. Token shaping now takes weighted completion + tool-response token costs. Migration: `length_penalty = "tokens"` becomes `[orchestrator.advantage.length_penalty]\ntype = "tokens"` (default weights `completion_weight = 1.0`, `tool_response_weight = 1.0` — total context). `length_penalty = "turns"` becomes `[orchestrator.advantage.length_penalty]\ntype = "turns"`. (2026-05-06)
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
+39 -2
View File
@@ -1,7 +1,7 @@
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
# Build stage - multi-arch base (supports amd64 + arm64)
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu22.04 AS builder
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 AS builder
LABEL maintainer="prime intellect"
LABEL repository="prime-rl"
@@ -18,12 +18,42 @@ ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Etc/UTC
RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
build-essential \
autoconf \
automake \
libtool \
pkg-config \
ca-certificates \
curl \
sudo \
git \
ninja-build \
libnuma-dev \
libnl-3-dev \
libnl-route-3-dev \
libibverbs-dev \
librdmacm-dev \
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
ARG UCX_VERSION=1.19.1
RUN git clone --depth 1 --branch v${UCX_VERSION} https://github.com/openucx/ucx.git /tmp/ucx \
&& cd /tmp/ucx \
&& ./autogen.sh \
&& ./configure \
--prefix=/opt/ucx \
--enable-shared \
--disable-static \
--disable-doxygen-doc \
--enable-optimizations \
--enable-cma \
--enable-devel-headers \
--enable-mt \
--with-verbs \
--with-cuda=/usr/local/cuda \
--with-ze=no \
&& make -j"$(nproc)" \
&& make install \
&& rm -rf /tmp/ucx
# Download the latest installer
ADD https://astral.sh/uv/install.sh /uv-installer.sh
@@ -49,7 +79,7 @@ COPY examples /app/examples
COPY benchmarks/scripts /app/benchmarks/scripts
RUN --mount=type=cache,target=/app/.cache/uv \
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --group mamba-ssm --locked --no-dev
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress --group mamba-ssm --locked --no-dev
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
ARG TARGETARCH
@@ -74,8 +104,12 @@ RUN apt-get update && apt-get install -y \
net-tools \
curl \
vim \
libnuma1 \
libnl-3-200 \
libnl-route-3-200 \
libibverbs1 \
ibverbs-providers \
librdmacm1 \
&& apt-get clean autoclean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
@@ -96,6 +130,7 @@ ENV PATH="/usr/local/bin:$PATH"
WORKDIR /app
# Copy the application from the builder
COPY --from=builder --chown=appuser:appuser /app /app
COPY --from=builder /opt/ucx /opt/ucx
# Copy and set up entrypoint script
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
@@ -107,6 +142,8 @@ RUN rm /app/.venv/bin/python3.12 && ln -s /usr/local/bin/python /app/.venv/bin/p
# Place executables in the environment at the front of the path
ENV PATH="/app/.venv/bin:$PATH"
ENV UCX_HOME=/opt/ucx
ENV LD_LIBRARY_PATH="/opt/ucx/lib:/opt/ucx/lib/ucx${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"
# HuggingFace Hub timeouts (defaults are 10s which causes issues on slow networks)
ENV HF_HUB_ETAG_TIMEOUT=500
+24 -36
View File
@@ -52,13 +52,13 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | yes | ✅ | ✅ |
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | [multimodal.md](docs/multimodal.md) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#vision-language-models) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ❌ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
| GLM-4 · GLM-4.5 MoE · INTELLECT-3 (`glm4_moe`) | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5-Air`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | yes | ✅ | ✅ |
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ❌ | ✅ |
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ✅ | ✅ |
| Other HF causal LMs | Qwen3 dense, Mistral, … (`impl = "hf"`) | varies | ❌ | ✅ |
@@ -94,7 +94,7 @@ cd prime-rl
2. Initialize submodules
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
```
3. Install [uv](https://docs.astral.sh/uv/)
@@ -110,6 +110,15 @@ source $HOME/.local/bin/env
uv sync --all-extras
```
4.1. On aarch64 hosts: build flash-attn from source for your GPU
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`.
```bash
bash scripts/docker-arm64-post-install.sh
```
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
@@ -217,17 +226,13 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
Check out the [docs](docs) directory for in-depth guides on how to use PRIME-RL.
- [**Entrypoints**](docs/entrypoints.md) - Overview of the main components (orchestrator, trainer, inference) and how to run SFT, RL, and evals
- [**Configs**](docs/configs.md) - Configuration system using TOML files, CLI arguments, and environment variables
- [**Environments**](docs/environments.md) - Installing and using verifiers environments from the Environments Hub
- [**Async Training**](docs/async.md) - Understanding asynchronous off-policy training and step semantics
- [**Logging**](docs/logging.md) - Logging with loguru, torchrun, and Weights & Biases
- [**Checkpointing**](docs/checkpointing.md) - Saving and resuming training from checkpoints
- [**Benchmarking**](docs/benchmarking.md) - Performance benchmarking and throughput measurement
- [**Deployment**](docs/deployment.md) - Training deployment on single-GPU, multi-GPU, and multi-node clusters
- [**Memory Usage**](docs/memory_usage.md) - Techniques for reducing memory usage (activation checkpointing, offloading, EP, CP, LoRA, etc.)
- [**Troubleshooting**](docs/troubleshooting.md) - Common issues and their solutions
- [**Multimodal**](docs/multimodal.md) - Training VLMs like Qwen3-VL
- [**Overview**](docs/overview.md) - Architecture, install, and a copy-pasteable end-to-end RL run
- [**Configuration**](docs/configuration.md) - TOML composition, CLI overrides, env vars, validation
- [**Training**](docs/training.md) - RL, SFT, evals, checkpointing, observability, rules of thumb
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA, multi-tenant training
- [**Development**](docs/development.md) - Test suite, pre-commit hooks, adding a new model
## Contributing
@@ -249,28 +254,11 @@ uv run pre-commit install
### Tests
Run the full test suite
```bash
uv run pytest -v
```
To run unit tests, run
```bash
uv run pytest tests/unit -v
```
To run integration tests, run
```bash
uv run pytest tests/integration -v
```
To run CPU-only tests, use the inverse of the `gpu` marker:
```bash
uv run pytest -v -m "not gpu"
uv run pytest -v # everything
uv run pytest tests/unit -v # unit only
uv run pytest tests/integration -v # integration only
uv run pytest -v -m "not gpu" # CPU-only (inverse of the gpu marker)
```
## License
@@ -15,34 +15,34 @@
"cp": 1,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "83c21ddac",
"timestamp": "2026-02-26T02:07:06+00:00",
"commit_sha": "0b37bc923",
"timestamp": "2026-05-19T01:28:25+00:00",
"success": true,
"error_reason": null,
"time_taken": 276.12556480802596
},
"metrics": {
"mfu": {
"mean": 16.41977165630161,
"std": 0.010586646038388221,
"min": 16.407648988464405,
"max": 16.42719598975201
"mean": 22.77046832707997,
"std": 0.03172890658906481,
"min": 22.750797215697055,
"max": 22.80707156937409
},
"throughput": {
"mean": 1960.9836648020673,
"std": 1.2643440104327244,
"min": 1959.5358764831926,
"max": 1961.8703395331793
"mean": 2719.4358949662887,
"std": 3.7893259921987053,
"min": 2717.086609671837,
"max": 2723.8073540657224
},
"step_time": {
"mean": 65.87,
"std": 0.13,
"min": 65.74,
"max": 66.0
"mean": 48.285218452724315,
"std": 0.06726350421944344,
"min": 48.207625919021666,
"max": 48.327002701349556
},
"peak_memory": {
"gib": 31.806640625,
"pct": 67.03
"gib": 24.248046875,
"pct": 51.15428047554115
}
}
}
@@ -15,34 +15,34 @@
"cp": 1,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "83c21ddac",
"timestamp": "2026-02-26T02:07:06+00:00",
"commit_sha": "0b37bc923",
"timestamp": "2026-05-19T01:32:27+00:00",
"success": true,
"error_reason": null,
"time_taken": 291.91085167229176
},
"metrics": {
"mfu": {
"mean": 15.634260517326164,
"std": 0.009817863071768202,
"min": 15.622927380137481,
"max": 15.640172924064188
"mean": 21.824271379711288,
"std": 0.07444985226850119,
"min": 21.739369034306105,
"max": 21.878404774433935
},
"throughput": {
"mean": 7468.685954343421,
"std": 4.690118598479809,
"min": 7463.271969943842,
"max": 7471.510386564679
"mean": 10425.733211800512,
"std": 35.565645418564436,
"min": 10385.174276894972,
"max": 10451.593425935866
},
"step_time": {
"mean": 68.34095695288852,
"std": 0.16054587555887065,
"min": 68.16114284005016,
"max": 68.46991707291454
"mean": 50.39627862814814,
"std": 0.1756523472528039,
"min": 50.26670710090548,
"max": 50.59620195720345
},
"peak_memory": {
"gib": 23.25390625,
"pct": 49.05701678145735
"gib": 17.490234375,
"pct": 36.897831788841806
}
}
}
}
+10 -5
View File
@@ -17,7 +17,7 @@ name = "stage1"
[orchestrator]
batch_size = 1024
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
@@ -32,17 +32,22 @@ interval = 50
[[orchestrator.eval.env]]
id = "math500"
rollouts_per_example = 1
group_size = 1
[[orchestrator.eval.env]]
id = "aime2024"
rollouts_per_example = 32
group_size = 32
[[orchestrator.eval.env]]
id = "aime2025"
rollouts_per_example = 32
group_size = 32
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+10 -5
View File
@@ -18,7 +18,7 @@ name = "stage2"
[orchestrator]
batch_size = 2048
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
temperature = 0.6
@@ -33,17 +33,22 @@ interval = 50
[[orchestrator.eval.env]]
id = "math500"
rollouts_per_example = 1
group_size = 1
[[orchestrator.eval.env]]
id = "aime2024"
rollouts_per_example = 32
group_size = 32
[[orchestrator.eval.env]]
id = "aime2025"
rollouts_per_example = 32
group_size = 32
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+2 -2
View File
@@ -11,7 +11,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 512
@@ -28,7 +28,7 @@ interval = 50
id = "alphabet-sort"
name = "alphabet-sort"
num_examples = 50
rollouts_per_example = 4
group_size = 4
args = { min_turns = 2, max_turns = 2 }
[trainer]
+9 -3
View File
@@ -1,17 +1,17 @@
max_steps = 5
max_steps = 10
seq_len = 2048
[ckpt]
[model]
name = "PrimeIntellect/Qwen3-0.6B"
name = "Qwen/Qwen3-0.6B"
[trainer.optim]
lr = 1e-5
[orchestrator]
batch_size = 128
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 384
@@ -22,3 +22,9 @@ name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
[inference]
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
[orchestrator.renderer]
name = "auto"
preserve_all_thinking = true
@@ -12,7 +12,7 @@ lr = 3e-6
[orchestrator]
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -20,4 +20,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -11,7 +11,7 @@ lr = 3e-6
[orchestrator]
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -19,4 +19,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -18,7 +18,7 @@ save_adapter_separately = true
[orchestrator]
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.model.lora]
name = "r8-1e-4"
@@ -31,4 +31,8 @@ id = "reverse-text"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
gpu_memory_utilization = 0.7
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -17,7 +17,7 @@ save_adapter_separately = true
[orchestrator]
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.model.lora]
name = "r8-1e-4"
@@ -30,4 +30,8 @@ id = "reverse-text"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
gpu_memory_utilization = 0.7
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -14,7 +14,7 @@ impl = "custom"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -27,3 +27,7 @@ gpu_memory_utilization = 0.7
[inference.model]
max_model_len = 2048
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -1,7 +1,7 @@
# Orchestrator config for multi-run RL integration test
# model.lora.name and output_dir are set via CLI
batch_size = 128
rollouts_per_example = 16
group_size = 16
seq_len = 2048
max_steps = 20
@@ -20,3 +20,7 @@ id = "reverse-text"
[ckpt]
interval = 10
resume_step = -1
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[renderer]
name = "default"
@@ -1,6 +1,5 @@
# Trainer config for multi-run RL integration test
max_concurrent_runs = 2
max_async_level = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -0,0 +1,51 @@
# Smoke test for the RL-entrypoint OPD (on-policy distillation) training mode.
# The student inference deployment is launched by the rl entrypoint on GPU 0;
# the teacher inference server is started externally by the test fixture (see
# tests/integration/test_reverse_text_rl_opd.py) on the same GPU. Trainer
# takes GPU 1. Training config mirrors `reverse_text/start.toml`.
max_steps = 5
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-ci"
name = "ci-rl-opd"
[orchestrator]
training_mode = "opd"
batch_size = 128
group_size = 16
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
[inference]
gpu_memory_utilization = 0.4
@@ -0,0 +1,48 @@
# Smoke test for the RL-entrypoint SFT (on-policy hard distillation) training
# mode. The student inference deployment is launched by the rl entrypoint on
# GPU 0; the teacher inference server is started externally by the test
# fixture (see tests/integration/test_reverse_text_rl_sft.py) on the same GPU.
# Trainer takes GPU 1. Training config mirrors `reverse_text/start.toml`.
max_steps = 5
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-ci"
name = "ci-rl-sft"
[orchestrator]
training_mode = "sft"
batch_size = 128
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
[inference]
gpu_memory_utilization = 0.4
+7 -2
View File
@@ -15,7 +15,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[orchestrator]
batch_size = 1024
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
@@ -28,4 +28,9 @@ args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", que
[trainer]
[inference]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
@@ -15,7 +15,7 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 64
@@ -1,5 +1,5 @@
max_steps = 3000
seq_len = 8192
seq_len = 4096
[wandb]
project = "hendrycks-math-debug"
@@ -9,8 +9,9 @@ name = "hendrycks-math-sanity"
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
rollouts_per_example = 8
batch_size = 256
max_inflight_rollouts = 512
group_size = 8
[[orchestrator.train.env]]
id = "math-env"
@@ -23,17 +24,19 @@ interval = 50
[[orchestrator.eval.env]]
id = "aime2024"
name = "aime2024"
rollouts_per_example = 16
[trainer.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
group_size = 16
[trainer.model.ac]
[trainer.model.compile]
[inference.model]
max_model_len = 8192
max_model_len = 4096
[log]
level = "debug"
level = "debug"
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+52
View File
@@ -0,0 +1,52 @@
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-multi-env"
[orchestrator]
training_mode = "rl"
batch_size = 128
group_size = 16
[orchestrator.renderer]
name = "qwen3"
# -- multi train envs --
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-train-1"
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-train-2"
# -- multi eval envs --
[orchestrator.eval]
interval = 10
num_examples = 16
group_size = 4
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text-eval-1"
[[orchestrator.eval.env]]
id = "reverse-text"
name = "reverse-text-eval-2"
interval = 5
[trainer.optim]
lr = 3e-6
[inference]
gpu_memory_utilization = 0.5
[inference.model]
max_model_len = 128
+75
View File
@@ -0,0 +1,75 @@
# 2-GPU debug RL run for the multimodal (renderer) path: Qwen3-VL-4B on
# color-codeword. Sized to actually learn (reward should trend up) while
# staying 2-GPU friendly. Exercises RendererClient + Qwen3VLRenderer end-to-end.
max_steps = 15
seq_len = 4096
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
gpus_per_node = 2
[orchestrator]
batch_size = 256
group_size = 16
# Image processor is CPU-bound and dominates for VLMs; returns diminish past 4.
pool_size = 4
# Step 0 on Qwen3-VL-4B vs color-codeword can be uniform (all-correct or
# all-wrong), so don't enforce zero-advantage dropping or training would crash
# before any progress.
[[orchestrator.post_batch_filters]]
type = "gibberish"
[[orchestrator.post_batch_filters]]
type = "repetition"
[[orchestrator.post_batch_filters]]
type = "zero_advantage"
enforce = false
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
# MODEL_RENDERER_MAP to Qwen3VLRenderer at runtime; no explicit name needed.
[trainer]
[trainer.model]
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[trainer.optim]
lr = 3e-6
[inference]
[inference.model]
# Workaround for vLLM 0.20.1 Qwen3-VL deepstack buffer bug: when num_scheduled_tokens
# (188) gets padded up to the next cudagraph_capture_size (192), the model's
# _set_deepstack_input_embeds sizes the buffer to 188 but forward() runs with 192,
# triggering "Requested more deepstack tokens than available in buffer". Eager mode
# skips the padding so num_input_tokens == num_scheduled_tokens.
enforce_eager = true
[inference.parallel]
dp = 1
tp = 1
[wandb]
project = "debug"
name = "multimodal"
tags = ["qwen3vl-4b", "color-codeword", "renderer"]
-1
View File
@@ -1,5 +1,4 @@
max_steps = 5
max_async_level = 5
batch_size = 16
[train.sampling]
+31
View File
@@ -0,0 +1,31 @@
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text"
name = "reverse-text-v1"
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
args = { v1 = true }
[trainer.optim]
lr = 3e-6
[ckpt] # Checkpoint at the end of training
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
-1
View File
@@ -1,5 +1,4 @@
max_steps = 5
max_async_level = 5
[data.fake]
batch_size = 2
+47
View File
@@ -0,0 +1,47 @@
# Training Mode — Debug Configs
Minimal end-to-end configs for the three training modes (`rl` / `opd` / `sft`) against the `reverse-text` env, using `PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT` as the student.
| Config | Mode | Teacher | Notes |
|---|---|---|---|
| `rl.toml` | `rl` | none | |
| `opd.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `opd_lora.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
| `sft.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `sft_lora.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
| `sft_external.toml` | `sft` | PI inference (`openai/gpt-5-mini`) | external OAI endpoint; no local teacher |
The student inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local teacher (used by everything except `rl.toml` and `sft_external.toml`) is **not** auto-launched — start it manually on GPU 1.
## Start the local teacher
Needed for `opd*.toml` and `sft.toml` / `sft_lora.toml`:
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--server.port 8001 \
--gpu-memory-utilization 0.5 \
--model.enforce-eager
```
## Run the debug configs
```bash
# RL (no teacher)
uv run rl @ configs/debug/training_modes/rl.toml
# OPD (needs teacher on port 8001)
uv run rl @ configs/debug/training_modes/opd.toml
uv run rl @ configs/debug/training_modes/opd_lora.toml
# SFT hard distill (needs teacher on port 8001)
uv run rl @ configs/debug/training_modes/sft.toml
uv run rl @ configs/debug/training_modes/sft_lora.toml
# SFT hard distill from openai/gpt-5-mini via PI inference
# (requires PRIME_API_KEY + PRIME_TEAM_ID in env; no local teacher needed)
uv run rl @ configs/debug/training_modes/sft_external.toml
```
See [docs/training.md](../../docs/training.md#training-modes-rl--opd--sft-via-orchestrator) for what each mode does.
+54
View File
@@ -0,0 +1,54 @@
# Start the teacher inference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/opd.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-opd"
[orchestrator]
training_mode = "opd"
batch_size = 128
group_size = 16
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -0,0 +1,60 @@
# Start the teacher inference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/opd_lora.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-opd-lora"
[orchestrator]
training_mode = "opd"
batch_size = 128
group_size = 16
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
gpu_memory_utilization = 0.5
+41
View File
@@ -0,0 +1,41 @@
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-rl"
[orchestrator]
training_mode = "rl"
batch_size = 128
group_size = 16
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
+51
View File
@@ -0,0 +1,51 @@
# Start the teacher inference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/sft.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-sft"
[orchestrator]
training_mode = "sft"
batch_size = 128
group_size = 4
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -0,0 +1,55 @@
# SFT from openai/gpt-5-mini via PI inference.
# Requires PRIME_API_KEY + PRIME_TEAM_ID in the environment.
#
# Run with:
# uv run rl @ configs/debug/training_modes/sft_external.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-sft-external"
[orchestrator]
training_mode = "sft"
batch_size = 128
group_size = 4
[orchestrator.train.sampling]
max_completion_tokens = 2048
extra_body = { reasoning_effort = "minimal" }
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "openai/gpt-5-mini"
[orchestrator.teacher.client]
base_url = ["https://api.pinference.ai/api/v1"]
api_key_var = "PRIME_API_KEY"
[orchestrator.teacher.client.headers_from_env]
X-Prime-Team-ID = "PRIME_TEAM_ID"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -0,0 +1,57 @@
# Start the teacher inference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/sft_lora.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-sft-lora"
[orchestrator]
training_mode = "sft"
batch_size = 128
group_size = 4
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
gpu_memory_utilization = 0.5
+7 -2
View File
@@ -17,7 +17,7 @@ interval = 100
[orchestrator]
batch_size = 1024
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
@@ -31,4 +31,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+7 -2
View File
@@ -18,7 +18,7 @@ resume_step = 500
[orchestrator]
batch_size = 1024
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
@@ -32,4 +32,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+7 -2
View File
@@ -18,7 +18,7 @@ resume_step = 1000
[orchestrator]
batch_size = 1024
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
@@ -32,4 +32,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+1 -1
View File
@@ -30,7 +30,7 @@ lr = 1e-5
[orchestrator]
batch_size = 512
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 768
+1 -1
View File
@@ -14,7 +14,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[[orchestrator.train.env]]
id = "math-env"
+29
View File
@@ -0,0 +1,29 @@
max_steps = 5
seq_len = 8192
[wandb]
project = "general-agent-debug"
name = "qwen3-0p6b-rlm"
[model]
name = "Qwen/Qwen3-0.6B"
[orchestrator]
batch_size = 16
rollouts_per_example = 4
[orchestrator.train.sampling]
max_completion_tokens = 4096
[[orchestrator.train.env]]
id = "general-agent-solver-rlm"
[trainer]
[inference]
[inference.model]
max_model_len = 8192
[inference.parallel]
dp = 1
@@ -0,0 +1,52 @@
max_steps = 400
seq_len = 32768
[slurm]
job_name = "general-agent-qwen3-30b-a3b-rlm"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[wandb]
project = "general-agent-debug"
name = "qwen3-30b-a3b-rlm"
[ckpt]
interval = 50
keep_last = 1
[model]
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
[trainer]
[trainer.model]
cp = 2
[trainer.model.ac]
freq = 1
[trainer.model.compile]
[orchestrator]
batch_size = 512
rollouts_per_example = 16
max_off_policy_steps = 32
[[orchestrator.train.env]]
id = "general-agent-solver-rlm"
[orchestrator.train.env.args]
min_tier = 1
[inference]
gpu_memory_utilization = 0.85
[inference.model]
max_model_len = 32768
[inference.parallel]
dp = 2
tp = 4
+44
View File
@@ -0,0 +1,44 @@
max_steps = 200
seq_len = 32768
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "general-agent-debug"
name = "qwen3-4b-rlm"
[ckpt]
interval = 100
keep_last = 1
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[trainer]
[trainer.model]
cp = 2
[trainer.model.ac]
freq = 1
[trainer.model.compile]
[orchestrator]
batch_size = 512
rollouts_per_example = 8
max_off_policy_steps = 32
[[orchestrator.train.env]]
id = "general-agent-solver-rlm"
[inference]
gpu_memory_utilization = 0.85
[inference.model]
max_model_len = 32768
[inference.parallel]
dp = 4
+9 -3
View File
@@ -6,11 +6,11 @@ project = "gsm8k-debug"
name = "gsm8k"
[model]
name = "PrimeIntellect/Qwen3-0.6B"
name = "Qwen/Qwen3-0.6B"
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 2048
@@ -22,4 +22,10 @@ args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max
[trainer] # Default trainer config
[inference] # Default inference config
[inference] # Default inference config
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
[orchestrator.renderer]
name = "auto"
preserve_all_thinking = true
+2 -6
View File
@@ -10,7 +10,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 2048
@@ -20,10 +20,6 @@ id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[orchestrator.eval]
interval = 10
@@ -33,7 +29,7 @@ max_completion_tokens = 2048
[[orchestrator.eval.env]]
id = "math500"
num_examples = 30
rollouts_per_example = 4
group_size = 4
[trainer] # Default trainer config
+2 -6
View File
@@ -9,7 +9,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 256
rollouts_per_example = 8
group_size = 8
[[orchestrator.train.env]]
id = "math-env"
@@ -23,10 +23,6 @@ name = "acereason-math"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
ratio = 0.5
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[orchestrator.eval]
interval = 50
@@ -34,7 +30,7 @@ interval = 50
id = "aime2024"
name = "aime2024"
num_examples = 30
rollouts_per_example = 4
group_size = 4
[trainer.model]
seq_len = 4096
+1 -1
View File
@@ -10,7 +10,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 512
-55
View File
@@ -1,55 +0,0 @@
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
# -- train envs --
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-1"
[orchestrator.train.env.sampling]
max_completion_tokens = 127
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-2"
# -- eval envs --
[orchestrator.eval]
interval = 5
[orchestrator.eval.sampling]
max_completion_tokens = 512
[[orchestrator.eval.env]]
id = "reverse-text"
name = "eval-default"
num_examples = 32
rollouts_per_example = 4
[[orchestrator.eval.env]]
id = "reverse-text"
name = "eval-custom"
num_examples = 16
rollouts_per_example = 2
interval = 10
[orchestrator.eval.env.sampling]
max_completion_tokens = 256
temperature = 0.5
[trainer.optim]
lr = 3e-6
[inference] # Default inference config
-35
View File
@@ -1,35 +0,0 @@
max_steps = 15
seq_len = 4096
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
[trainer]
[trainer.model]
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[trainer.optim]
lr = 3e-6
[inference]
[inference.parallel]
dp = 1
@@ -1,35 +0,0 @@
max_steps = 3
seq_len = 2048
output_dir = "outputs/rl_color_codeword_test"
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
[orchestrator]
batch_size = 16
rollouts_per_example = 2
[orchestrator.train.sampling]
max_completion_tokens = 32
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 2, num_examples = 100, seed = 42 }
[trainer]
[trainer.model]
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[trainer.optim]
lr = 3e-6
[inference]
[inference.parallel]
dp = 1
+2 -7
View File
@@ -18,7 +18,6 @@ level = "debug"
[wandb]
project = "sami_debug_nemotron"
name = "nemotron-120b-math"
shared = true
[weight_broadcast]
type = "nccl"
@@ -46,7 +45,7 @@ max_inflight_activations = 5
[orchestrator]
batch_size = 128
rollouts_per_example = 8
group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 2048
@@ -56,10 +55,6 @@ id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[orchestrator.eval]
interval = 10
@@ -69,7 +64,7 @@ max_completion_tokens = 2048
[[orchestrator.eval.env]]
id = "math500"
num_examples = 30
rollouts_per_example = 4
group_size = 4
[inference.parallel]
tp = 8
+2 -7
View File
@@ -17,7 +17,6 @@ level = "debug"
[wandb]
project = "nemotron_sami_debug"
name = "nemotron-120b-math"
shared = true
[weight_broadcast]
type = "nccl"
@@ -45,7 +44,7 @@ freq = 1
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 4096
@@ -55,10 +54,6 @@ id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[orchestrator.eval]
interval = 10
@@ -68,7 +63,7 @@ max_completion_tokens = 4096
[[orchestrator.eval.env]]
id = "math500"
num_examples = 30
rollouts_per_example = 4
group_size = 4
[inference.parallel]
tp = 4
Submodule configs/private deleted from 74c1330008
+99
View File
@@ -0,0 +1,99 @@
output_dir = "/beegfs/mika/rlm-swe-qwen35-4b"
max_steps = 400
seq_len = 65536
[slurm]
job_name = "rlm-swe-qwen35-4b"
project_dir = "."
pre_run_command = "prime sandbox delete --label rlm-swe-qwen35-4b -y --plain || true"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
num_infer_replicas = 2
[wandb]
project = "rlm-swe-debug"
name = "qwen35-4b"
[weight_broadcast]
type = "nccl"
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[model]
name = "Qwen/Qwen3.5-4B"
# --- Trainer ---
[trainer]
[trainer.model]
cp = 4
cp_style = "ulysses"
[trainer.model.ac]
freq = 1
[trainer.model.compile]
# --- Orchestrator ---
[orchestrator]
batch_size = 256
group_size = 8
max_inflight_rollouts = 512
max_off_policy_steps = 16
# Thinking enabled for the Qwen3.5 renderer.
[orchestrator.renderer]
name = "qwen3.5"
enable_thinking = true
[orchestrator.train.sampling]
temperature = 1.0
[[orchestrator.train.env]]
id = "rlm_swe"
name = "rlm-swe-r2e"
num_workers = 4
[orchestrator.train.env.args]
labels = ["rlm-swe-qwen35-4b"]
[orchestrator.prime_monitor]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
id = "rlm_swe"
name = "rlm-swe-swebench-verified-quick"
num_workers = 4
timeout = 3600
[orchestrator.eval.env.args]
task_type = "swebench"
dataset_name = "PrimeIntellect/SWE-Bench-Verified-Quick"
labels = ["rlm-swe-qwen35-4b"]
# --- Inference ---
[inference]
gpu_memory_utilization = 0.85
enable_prefix_caching = true
[inference.model]
max_model_len = 65536
[inference.parallel]
dp = 8
# Qwen3.5-4B is a VL model; skip the vision tower for text-only SWE.
# `language_model_only` is a vLLM MultiModalConfig arg (no prime-rl field) → pass via vllm_extra.
[inference.vllm_extra]
language_model_only = true
+1 -4
View File
@@ -27,15 +27,12 @@ target_modules = [
[orchestrator]
batch_size = 512
rollouts_per_example = 16
group_size = 16
oversampling_factor = 2.0
[orchestrator.train.sampling]
max_completion_tokens = 512
[orchestrator.buffer]
online_difficulty_filtering = true
[[orchestrator.train.env]]
id = "wiki-search"
Vendored Submodule
+1
Submodule deps/pydantic-config added at 896ade4e69
+1 -1
+1 -1
+145
View File
@@ -0,0 +1,145 @@
# Advanced
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, multi-tenant training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
## Table of Contents
- [Custom Modeling](#custom-modeling)
- [Expert Parallelism Backends](#expert-parallelism-backends)
- [Multimodal Training](#multimodal-training)
- [Supported Families](#supported-families)
- [Enabling VLM Mode](#enabling-vlm-mode)
- [Limitations](#limitations)
- [LoRA Training](#lora-training)
- [Multi-Tenant Training](#multi-tenant-training)
- [Disaggregated Prefill/Decode Inference](#disaggregated-prefilldecode-inference)
## Custom Modeling
`prime-rl` ships custom optimized model implementations for several MoE families. With `model.impl = "auto"` (default) the trainer picks the custom path when the HF config type is registered, falling back to plain HF otherwise. To force one:
```toml
[trainer.model]
impl = "custom" # or "hf" to force the HF path
```
| Family | HF config types | EP | CP |
|---|---|---|---|
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | ✅ | ✅ |
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
| Laguna | `poolside/Laguna-XS.2` | ✅ | ✅ |
| MiniMax M2 | `MiniMax/MiniMax-M2` | ✅ | ✅ |
| Nemotron H | `nvidia/Nemotron-3-Nano-30B-A3B`, … | ✅ | ❌ |
| Trinity (AFMoE) | `arcee-ai/Trinity-Mini`, … | ✅ | ✅ |
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
The custom path enables you to set EP, CP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
### Expert Parallelism Backends
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
- **`torch`** (default): TorchTitan's all-to-all collective. Works everywhere, no extra install.
- **`deepep`**: Utilizes DeepEP's custom all-to-all collectives. This provides better performance if EP dimension spans multiple nodes. We provide pre-built binaries for H100/H200 with cuda runtime 12.9 installed, you can install them by running `uv sync --all-extras`.
DeepEP requires some careful tuning to achieve optimal performance, tuning parameters are `deepep_num_sms` and `deepep_token_chunk_size`.
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
## Multimodal Training
### Supported Families
The built-in VLM registry covers:
| Family | `model_type` | Vision attr | LM attr |
|---|---|---|---|
| Qwen3-VL | `qwen3_vl` | `model.visual` | `model.language_model` |
| Qwen3-VL MoE | `qwen3_vl_moe` | `model.visual` | `model.language_model` |
| Qwen3.5 | `qwen3_5` | `model.visual` | `model.language_model` |
| Qwen3.5-MoE | `qwen3_5_moe` | `model.visual` | `model.language_model` |
For a model not in the table, look up the attribute paths on the loaded HF model with `model.named_children()` and set them under `[model.vlm]` directly.
### Enabling VLM Mode
Add `[model.vlm]` and bfloat16 dtypes:
```toml
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
# freeze_vision_encoder = true # default; set false to fine-tune the encoder
```
The weight-broadcast key prefix is derived as `{language_model_attr}.layers.` automatically.
To add a new model family permanently, append an entry to `VLM_REGISTRY` in `src/prime_rl/utils/vlm.py`.
### Limitations
- **Vision encoder frozen by default.** Set `freeze_vision_encoder = false` to fine-tune it; in that case it's FSDP-sharded per block. The combination `freeze_vision_encoder = false` + LoRA is rejected by a config validator — LoRA freezes everything non-adapter, so unfreezing the encoder under LoRA would be a silent no-op.
- **No multimodal-safe truncation.** Token sequences are truncated to `seq_len`, but `pixel_values` and `image_grid_thw` pass through unchanged. If a sample's tokens overflow, image tokens may get dropped while image tensors still describe the full image set. Set `seq_len` to cover your longest sample.
- **bfloat16 mandatory.** The trainer config validator refuses any other `optimization_dtype` / `reduce_dtype` for VLMs — vLLM serves VLMs in bfloat16 and a mismatch breaks the importance ratio.
- **Higher KL mismatch with multi-image inputs.** Expect noisier `mismatch_kl` than text-only; this is from minor numerical differences between the trainer's and vLLM's image processing.
- **Images aren't logged to monitors.** Sample logging captures the prompt text but not the actual images.
## LoRA Training
LoRA is enabled by adding `[model.lora]`:
```toml
[model.lora]
rank = 16
alpha = 32
dropout = 0.0
```
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
LoRA is supported across SFT and RL. For RL, `weight_broadcast.type = "nccl"` is **not** supported with LoRA — use the default filesystem transport. To save the raw adapter alongside the merged HF weights:
```toml
[ckpt.weights]
save_adapter_separately = true
```
LoRA pairs naturally with [multi-tenant training](#multi-tenant-training) — each tenant gets its own adapter and the backbone is shared across all of them in trainer memory.
## Multi-Tenant Training
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/src/prime_rl/trainer/runs.py).
## Disaggregated Prefill/Decode Inference
For large MoE serving, splitting prefill and decode onto separate vLLM groups can substantially improve throughput. Pick the prefill:decode ratio based on workload shape:
| Workload | P:D ratio | Why |
|---|---|---|
| Agentic (SWE, Lean) | 3:1 | Long growing contexts → prefill-heavy |
| Non-agentic (math, chat) | 1:2 | Short prompts, long generations → decode-heavy |
Example config: [`examples/glm5_pd_disag/rl.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/glm5_pd_disag/rl.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast (see the [README](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/glm5_pd_disag) for the launch story).
Monitor live queue depths to detect imbalance:
```bash
curl -s http://<prefill_node>:8100/metrics | grep num_requests_waiting
curl -s http://<decode_node>:8200/metrics | grep num_requests_waiting
```
If prefill queues and decode is idle, add prefill nodes (and vice versa).
**UCX 1.19 requirement.** NVSHMEM needs UCX ≥ 1.19 for multi-GPU CUDA. If your cluster doesn't ship with UCX >=1.19, you can build it from source with the following command:
```bash
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
```
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version.
+320
View File
@@ -0,0 +1,320 @@
# Algorithms
This page covers the math and the configurable algorithmic components: how off-policy training works, the default loss and advantage functions, how to plug in your own, the filters applied between rollout and training, and how multi-turn rollouts get merged into training samples.
## Table of Contents
- [Async / Off-Policy Training](#async--off-policy-training)
- [Loss](#loss)
- [Default Loss](#default-loss)
- [Custom Loss](#custom-loss)
- [Advantage](#advantage)
- [Default Advantage](#default-advantage)
- [Custom Advantage](#custom-advantage)
- [Filters](#filters)
- [Difficulty Pools](#difficulty-pools)
- [Online Difficulty Filtering](#online-difficulty-filtering)
- [Multi-Turn Trajectories](#multi-turn-trajectories)
- [Extension Property](#extension-property)
- [Best-Effort Interleaving](#best-effort-interleaving)
- [Renderers](#renderers)
- [Discontinuous Trajectories](#discontinuous-trajectories)
## Async / Off-Policy Training
`prime-rl` is asynchronous by default. The trainer and inference always run one step overlapped: while the trainer is producing $\pi_n$ from rollouts at step $n$, inference is already generating the rollouts for step $n+1$ using $\pi_{n-1}$. With matched trainer and inference step times this produces fully-overlapped pipeline parallelism — neither side ever idles.
![Async pipeline: trainer step n produces $\theta_n$, inference at step n samples with $\theta_{n-1}$](assets/async-pipeline.png)
At step $n = 1, 2, 3, \dots$:
- **Trainer** produces policy $\pi_n$ with weights $\theta_n$ from rollouts $(x_n, y_n)$.
- **Inference** produces rollouts $(x_n, y_n)$ from policy $\pi_{\max(0,\,n-1)}$.
Step indices are 0-indexed so the gap holds at startup — inference is exactly one step behind the trainer.
## Loss
### Default Loss
The default RL loss is a DPPO policy-gradient term combined with a KL regularizer similar to Kimi-K2.5. For each prompt $x_j$ we sample a group of $G$ rollouts $\{y_i\}_{i=1}^G$, score them to get $s_i$, then optimize:
$$
\mathcal{L}(\theta) = -\,\mathcal{J}_{\text{PG}}(\theta) \;+\; \tau_{KL}\,\mathcal{L}_{KL}(\theta)
$$
where the policy-gradient term is
$$
\mathcal{J}_{\text{PG}}(\theta)
= \frac{1}{\sum_{j,i} |y_i^{(j)}|}
\sum_{j,i,t}
\min\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}, \delta\right) \hat{A}^{(j)}_{i,t}
$$
and the KL regularizer penalizes drift between trainer and inference policies via the squared log importance ratio:
$$
\mathcal{L}_{KL}(\theta) = \frac{1}{\sum_{j,i} |y_i^{(j)}|}
\sum_{j,i,t} \log^2\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}\right).
$$
$\mu$ is the policy that generated the rollout (inference), $\pi$ is the current policy (trainer), $\hat{A}_{i,t}$ is the token-level advantage, $\delta$ is the importance-sampling clipping ratio, and $\tau_{KL}$ is the KL temperature. The `min` clamps the importance ratio from above so a stale rollout assigning very low probability to a high-reward token doesn't produce a runaway gradient.
The knobs (under `[trainer.loss]` with `type = "default"`):
| Knob | Default | What it does |
|---|---|---|
| `dppo_mask_low` / `dppo_mask_high` | 0.2 / 0.2 | Lower / upper thresholds for DPPO-style token-level masking. |
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 for pure distillation (no RL signal). |
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
The trainer dispatches automatically based on the batch's training mode (set by the orchestrator via `orchestrator.training_mode`):
- `rl` mode → DPPO + KL with the advantage signal.
- `opd` mode → KL distillation against the teacher's per-token logprobs. The teacher must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
- `sft` mode → standard token-level NLL on teacher-generated rollouts.
Set `[trainer.loss] type = "default"` and configure via the knobs above. SFT and OPD modes ignore the policy-gradient–specific fields.
### Custom Loss
The loss is computed **per sequence**: you write a function that takes one sequence's tensors and returns a scalar loss. The trainer iterates and aggregates.
```python
# my_module.py
import torch
from prime_rl.trainer.rl.loss import LossInputs, LossOutputs
def ppo_clip_loss(inputs: LossInputs, clip_eps: float = 0.2) -> LossOutputs:
ratio = torch.exp(inputs.trainer_logprobs - inputs.inference_logprobs)
clipped = torch.clamp(ratio, 1 - clip_eps, 1 + clip_eps)
surr1 = ratio * inputs.advantages
surr2 = clipped * inputs.advantages
loss = -torch.min(surr1, surr2)[inputs.loss_mask].sum()
return LossOutputs(
loss=loss,
metrics={
"clip_frac": (ratio != clipped)[inputs.loss_mask].float().mean(),
},
)
```
Wire it up:
```toml
[trainer.loss]
type = "custom"
import_path = "my_module.ppo_clip_loss"
kwargs = { clip_eps = 0.2 }
```
The dataclasses:
```python
@dataclass
class LossInputs:
trainer_logprobs: Float[Tensor, "seq"] # current policy
inference_logprobs: Float[Tensor, "seq"] # rollout-time policy
teacher_logprobs: Float[Tensor, "seq"] | None # only set in OPD mode
advantages: Float[Tensor, "seq"]
loss_mask: Bool[Tensor, "seq"]
@dataclass
class LossOutputs:
loss: Float[Tensor, ""]
metrics: dict[str, Tensor]
```
Anything you put in `metrics` is averaged across sequences and logged with the other trainer metrics.
## Advantage
### Default Advantage
The default advantage is per-group reward minus per-group baseline (DR-GRPO without std normalization). For each prompt's group of `group_size` rollouts, every token in rollout $i$ receives advantage $s_i - \bar{s}$ where $\bar{s}$ is the group mean.
This is intentionally simple — it does the right thing for most envs. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
Two built-in **length penalties** can be layered on top of any advantage to discourage rambling:
- `[orchestrator.length_penalty] type = "tokens"` — penalizes long completions in tokens, with configurable target and slope.
- `[orchestrator.length_penalty] type = "turns"` — penalizes long multi-turn rollouts by turn count.
### Custom Advantage
Advantages are computed **per group**. You write a function that takes one group of rollouts and returns one advantage scalar per rollout. The orchestrator handles groups of varying size automatically — partial-group training kicks in when some rollouts in a group errored.
```python
# my_module.py
import statistics
from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
rewards = [r["reward"] for r in inputs.rollouts]
mean = statistics.fmean(rewards)
std = statistics.pstdev(rewards) if len(rewards) > 1 else 0.0
return AdvantageOutputs(advantages=[(r - mean) / (std + eps) for r in rewards])
```
```toml
[orchestrator.advantage]
type = "custom"
import_path = "my_module.normalized_advantage"
kwargs = { eps = 1e-8 }
```
`AdvantageInputs.rollouts` is a list of `verifiers.RolloutOutput`, so you have access to the full rollout (turns, tool calls, custom metadata) — not just the reward. Use this for anything reward-shaping-like that needs trajectory context.
### Per-Env Advantage
`advantage` can be set per training environment. Each env inherits the top-level `[orchestrator.advantage]` when it doesn't set its own, so mixed-env runs can give each env its own advantage computation:
```toml
[orchestrator.advantage]
type = "default" # the default every env inherits unless it overrides
[[orchestrator.train.env]]
id = "math-env" # inherits the default above
[[orchestrator.train.env]]
id = "agent-env"
advantage = { type = "custom", import_path = "my_module.normalized_advantage" }
```
## Filters
Filters drop rollouts between scoring and training. Built-ins (composable):
| Filter | Effect |
|---|---|
| `gibberish` | Drops rollouts whose mean log-prob fall below a threshold — usually a sign of degenerate output. |
| `repetition` | Drops rollouts with high n-gram repetition. |
| `zero_advantage` | Drops rollouts whose advantage is zero, so the trainer doesn't waste tokens on them. |
The default `[orchestrator]` config already includes all three filters with their defaults. To override, set `filters` explicitly — the list replaces the defaults wholesale:
```toml
[[orchestrator.filters]]
type = "zero_advantage"
[[orchestrator.filters]]
type = "repetition"
threshold = 0.4
```
Filtered rollouts still appear in W&B distributions, just not in the trainer batch — useful for spotting whether filtering is doing its job.
## Difficulty Pools
Difficulty pools gradually retire problems the model has solved or never solves. After each rollout, the average reward across a problem's group is compared to two thresholds:
- `buffer.easy_threshold` — at or above this, the problem moves into the `easy` pool and is no longer sampled.
- `buffer.hard_threshold` — at or below this, the problem moves into the `hard` pool and is no longer sampled.
- Otherwise the problem stays in `normal` and remains in the sampling rotation.
Pool assignments persist across checkpoints (`easy_examples.jsonl` / `hard_examples.jsonl` under each step's orchestrator checkpoint). When you resume — or want to broaden the curriculum mid-run — `buffer.easy_fraction` / `buffer.hard_fraction` randomly lift that fraction of pooled problems back into `normal` so they re-enter sampling.
```toml
[orchestrator.buffer]
easy_threshold = 0.95
hard_threshold = 0.05
easy_fraction = 0.0 # default; bump on resume to bring some easy problems back
hard_fraction = 0.0 # default; bump on resume to bring some hard problems back
```
Watch `pool/{env}/{easy,normal,hard}` (current pool ratios) and `evicted_examples/{env}/{easy,hard}` (per-step eviction rate).
## Online Difficulty Filtering
Online difficulty filtering (ODF) drops collapsed-advantage groups on the way *into* the buffer. Set `buffer.online_difficulty_filtering = true` (default `false`) to enable:
- Average reward across the group is **0.0** (every rollout failed) → drop the group, count under `filtered_rollouts/{env}/hard`.
- Average reward **1.0** (every rollout succeeded) → drop, count under `filtered_rollouts/{env}/easy`.
- Otherwise → into the buffer.
These are exactly the groups whose within-group advantage collapses to zero — DR-GRPO produces no gradient signal for them, so the trainer would burn step time on tokens it can't learn from.
```toml
[orchestrator.buffer]
online_difficulty_filtering = true
```
**Tradeoff: trainer stability vs. inference speed.** With ODF on, every rollout that reaches the trainer carries non-zero advantage — each trainer step's effective batch is predictable and the gradient signal is denser. The cost is paid on the inference side: rollouts get produced and then thrown away, so the orchestrator has to oversample to keep the trainer fed. If the orchestrator is your bottleneck (`time/wait_for_batch` high on the trainer), ODF can starve the loop. Bump `orchestrator.oversampling_factor` so inference produces enough groups per step to absorb the drops.
ODF is orthogonal to the [pools](#difficulty-pools): ODF reacts to the *current* group's reward distribution, the pools track the *running* per-problem average. Many configs use both — ODF for per-step density, pools for long-horizon curriculum cleanup.
## Multi-Turn Trajectories
Multi-turn rollouts (tool use, browser environments, long conversations) used to be stitched into a single fake "single-turn" sample, which silently corrupted the importance ratio when chat templates didn't roundtrip. Since [`verifiers` v0.1.8](https://github.com/PrimeIntellect-ai/verifiers/releases/tag/v0.1.8), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
### Extension Property
A sequence of trajectory steps has the **extension property** when each successive step's prompt contains all previous prompts and completions as an exact prefix. The trainer relies on this property — when it holds:
- Multiple steps merge into one training sample.
- Compute scales as $O(T)$ in the trajectory length.
When it breaks (chat template strips past thinking, environment compacts context, an agent hands off to a sub-agent, etc.), the trainer starts a new training sample from that step:
- Graceful fallback to multiple samples — no corrupted data.
- Worst case (every step breaks extension) is $O(T^2)$.
### Best-Effort Interleaving
Concretely:
```
5-step trajectory where extension breaks at step 4:
steps 1–3: extension holds → merged into Sample 1
step 4: extension breaks (e.g. thinking stripped from history)
steps 4–5: extension holds → merged into Sample 2
result: 2 training samples instead of 5
```
The orchestrator enforces an **exact prefix invariant**: the prompt at turn $t$ must be the exact concatenation of prior messages exactly as the LLM originally generated them. If turn 2's prompt is `U1, A1', U2` while `A1' ≠ A1`, the orchestrator can't safely merge — either choice produces logprob drift between trainer and inference. Starting a fresh sample is the only correct behavior, so that's what happens.
### Renderers
Best-effort interleaving works because the renderer guarantees the exact-prefix invariant *by construction* — it never re-renders prior turns, so it can't lose tokens to chat-template normalization, BPE retokenization drift, or thinking stripping. A renderer turns a model's chat template into a Python object that can:
- `render_ids(messages)` — tokenize messages to ids the inference engine accepts.
- `parse_response(completion_ids)` — recover structured `(content, reasoning_content, tool_calls)` from sampled ids.
- `bridge_to_next_turn(prev_prompt_ids, prev_completion_ids, new_messages)` — extend the previous turn's tokens verbatim with the new environment turn, instead of re-rendering history.
When `bridge_to_next_turn` succeeds, the trainer sees the exact token stream the sampler produced; when it can't be proven safe (e.g. the renderer is `DefaultRenderer` and the template's stop sequence is unknown), it returns `None` and the orchestrator falls back to a full re-render — which triggers the new-sample fallback above.
A common source of breakage in the absence of a hand-coded renderer is models like Qwen3 whose chat templates strip past `<think>` blocks across user turns:
```python
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
messages = [
{"role": "user", "content": "U1"},
{"role": "assistant", "content": "<think>R1</think>A1"},
{"role": "user", "content": "U2"},
]
tok.apply_chat_template(messages[:1], tokenize=False)
# <|im_start|>user
# U1<|im_end|>
tok.apply_chat_template(messages, tokenize=False)
# <|im_start|>user\nU1<|im_end|>\n<|im_start|>assistant\nA1<|im_end|>\n<|im_start|>user\nU2<|im_end|>
# (the <think>R1</think> from turn 2 is gone)
```
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `glm5`, `glm4.5`, `minimax-m2`, `deepseek-v3`, `kimi-k2`, `kimi-k2.5`, `nemotron-3`, `gpt-oss`; anything else falls back to `DefaultRenderer` (a generic `apply_chat_template` wrapper). Pick one via:
```toml
[orchestrator.renderer]
name = "auto" # detect from tokenizer; pass an explicit name for fine-tunes
```
For the full design rationale (failure modes ruled out, empirical token-identity comparison against `apply_chat_template`, when to write a hand-coded renderer), see [the renderers writeup on the Prime Intellect blog](https://www.primeintellect.ai/blog/renderers) — the canonical reference.
### Discontinuous Trajectories
Some envs are discontinuous by design — e.g. a main agent delegating to a sub-agent and getting back only a summarized result, not the sub-agent's whole conversation. Best-effort interleaving handles this naturally: each agent's contiguous turns merge, the handoff starts a new sample. The trainer never sees fabricated extension where there is none.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 500 KiB

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 440 KiB

-39
View File
@@ -1,39 +0,0 @@
# Asynchronous Training
PRIME-RL implements asynchronous off-policy training, instead of the traditional synchronous on-policy training. This means that we allow inference to generate rollouts from a stale policy up to $k$ (in the code we call this `max_async_level`) steps ahead of the trainer. With `k=1` and trainer and inference step timings being equal, this allows to run without any idle time on either the trainer or inference. By default, we set `k=2` to allow overlap with a weight broadcast over the Internet, which is needed for decentralized training.
![Two-Step Off-Policy Training](assets/two-step-off-policy.png)
## Loss Objective
We adopt a loss objective capable of handling the natural distribution shift caused by the off-policy nature of the training. By default, we use a token-level loss variant of the [AIPO](https://arxiv.org/abs/2505.24034) training objective introduced in Llama-RL,
but omit the entropy and KL loss terms.
At each step, we sample $N$ prompts from our dataset. For
each prompt $x$, we sample a group of rollouts $\{y_i\}^G_{i=1}$
and use a verifier to assign scores $s_i$ to each $y_i$.
Then, the optimization objective is given by
$$
\mathcal{J}_{\text{AIPO}}(\theta)
= \frac{1}{\sum_{j=1}^N \sum_{i=1}^G |y_i^{(j)}|}
\sum_{j=1}^N
\sum_{i=1}^G
\sum_{t=1}^{|y_i^{(j)}|}
\min\left(
\frac{\pi(y^{(j)}_{i,t}\mid x_j, y^{(j)}_{i,<t})}{\mu(y^{(j)}_{i,t}\mid x_j, y^{(j)}_{i,<t})},
\delta
\right)\hat{A}^{(j)}_{i,t}
$$
where $\mu$ refers to the policy that generated the rollout, $\pi$ refers to the current policy, $\hat{A}_{i,t}$ is the token-level advantage, and $\delta$ is the importance sampling clipping ratio.
## Step Semantics
PRIME-RL uses a global training step $n=1,2,3,\dots$ that is used to tag artifacts:
- **Trainer**: Produces policy $\pi_n$ with weights $\theta_n$ from rollouts $(x_n, y_n)$
- **Inference**: Produces rollouts $(x_n, y_n)$ from policy $\pi_{max(0, n-k)}$
Here, $k$ is the `max_async_level` parameter, which defaults to 2. Note that we use 0-indexed steps to cleanly indicate that at each step, the divergence off-policy gap is at most $k$ steps.
-79
View File
@@ -1,79 +0,0 @@
# Benchmarking
We provide a convenient way to benchmark the performance, mainly measured in throughput and MFU, of the inference engine and trainer using the `--bench` flag. It will run each module in isolation for a few steps and log performance benchmark results in a rich table to the console.
## SFT
Benchmark on the default fake data configuration
```bash
uv run sft ... --data.type fake --bench
```
Benchmark with variable-length, instead of fixed-length, fake data to more closely simulate real data.
```bash
uv run sft ... --data.type fake --data.length variable --bench
```
Benchmark different batch configurations, i.e. the (micro) batch size and sequence length
```bash
uv run sft ... --data.type fake --data.seq-len 4096 --data.batch-size 64 --data.micro-batch-size 2 --bench
```
Benchmark against a real dataset
```bash
uv run sft ... --data.name PrimeIntellect/Reverse-Text-SFT --bench
```
Benchmark against a training configuration
```bash
uv run sft @ path/to/config.toml --bench
```
## RL
### Trainer
Benchmark on a fake data loader
```bash
uv run trainer ... --data.fake --bench
```
Benchmark different batch configurations, i.e. the (micro) batch size and sequence length
```bash
uv run trainer ... --model.seq-len 4096 --data.fake.batch-size 64 --data.fake.micro-batch-size 2 --bench
```
*Note, that it is not yet possible to benchmark the RL trainer against real data when benchmarking the RL trainer in isolation.*
### Inference
To benchmark the inference engine in isolation, start the inference server with the correct configuration file and run the orchestrator with the `--bench` flag.
```bash
uv run inference @ path/to/config.toml
```
```bash
uv run orchestrator @ path/to/config.toml --bench
```
*Note, that it is not yet possible to benchmark the inference engine against fake data.*
## Trainer + Inference
To benchmark the full RL training, you can add the `--bench` flag to your RL entrypoint. This will benchmark the RL trainer against fake data and the inference engine against real data from the orchestrator.
```bash
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--inference @ path/to/infer.toml \
--bench
```
-143
View File
@@ -1,143 +0,0 @@
# Bring Your Own Algorithms
Prime-RL supports custom implementations for key algorithmic components, allowing you to experiment with different RL objectives and techniques.
## 1. Custom Loss Functions
The loss is computed **per-sequence** (per-sample). You provide a function that computes the loss for a single sequence, and the framework handles iteration and aggregation.
### Interface
```python
from prime_rl.trainer.rl.loss import LossInputs, LossOutputs
def my_custom_loss(inputs: LossInputs, **kwargs) -> LossOutputs:
...
```
#### LossInputs
```python
@dataclass
class LossInputs:
trainer_logprobs: Float[Tensor, "seq"] # Log probs from current policy
inference_logprobs: Float[Tensor, "seq"] # Log probs from reference policy
teacher_logprobs: Float[Tensor, "seq"] | None # Optional teacher log probs
advantages: Float[Tensor, "seq"] # Per-token advantages
loss_mask: Bool[Tensor, "seq"] # Mask for valid tokens
```
#### LossOutputs
```python
@dataclass
class LossOutputs:
loss: Float[Tensor, ""] # Scalar loss for this sequence
metrics: dict[str, Tensor] # Metrics to log
```
### Example: PPO Clipped Loss
```python
import torch
from prime_rl.trainer.rl.loss import LossInputs, LossOutputs
def ppo_clip_loss(inputs: LossInputs, clip_eps: float = 0.2) -> LossOutputs:
ratio = torch.exp(inputs.trainer_logprobs - inputs.inference_logprobs)
clipped_ratio = torch.clamp(ratio, 1 - clip_eps, 1 + clip_eps)
surr1 = ratio * inputs.advantages
surr2 = clipped_ratio * inputs.advantages
loss = -torch.min(surr1, surr2)[inputs.loss_mask].sum()
return LossOutputs(
loss=loss,
metrics={"clip_frac": (ratio != clipped_ratio)[inputs.loss_mask].float().mean()},
)
```
### Configuration
```toml
[loss]
type = "custom"
import_path = "my_module.ppo_clip_loss"
kwargs = { clip_eps = 0.2 }
```
---
## 2. Custom Advantage Functions
Advantages are computed **per-example** (grouped by `rollouts_per_example`). You provide a function that computes advantages for a batch of examples.
### Interface
```python
from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
def my_custom_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
...
```
#### AdvantageInputs
```python
@dataclass
class AdvantageInputs:
# Rollouts grouped by problem: rollouts[i][j] is the j-th rollout for problem i.
rollouts: list[list[vf.RolloutOutput]]
```
Each `vf.RolloutOutput` carries the full rollout (`reward`, `trajectory`, etc.), so custom advantages can read any metadata they need (e.g. completion-token counts, turn counts, tool calls).
#### AdvantageOutputs
```python
@dataclass
class AdvantageOutputs:
advantages: Float[Tensor, "num_examples rollouts_per_example"]
```
### Example: Normalized Advantage
```python
import torch
from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
"""Normalize advantages to zero mean and unit variance per example."""
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
mean = rewards.mean(dim=1, keepdim=True)
std = rewards.std(dim=1, keepdim=True)
advantages = (rewards - mean) / (std + eps)
return AdvantageOutputs(advantages=advantages)
```
### Configuration
```toml
[advantage]
type = "custom"
import_path = "my_module.normalized_advantage"
kwargs = { eps = 1e-8 }
```
---
## Default Implementations
If no custom function is specified:
- **Loss**: Uses `default_loss_fn` (masked importance sampling with KL against the inference policy, and optional masking strategies)
- **Advantage**: Uses `default_advantage_fn` (reward minus per-example baseline, a.k.a. DR-GRPO without std normalization)
See `LossConfig` and `AdvantageConfig` for available parameters.
## Tips
- Your functions receive structured inputs via dataclasses with jaxtyping annotations
- Return metrics as scalars or 1D tensors - they'll be aggregated automatically
- Use the `loss_mask` / tensor shapes to handle variable-length sequences
- Test your custom functions with the provided test patterns before training
-57
View File
@@ -1,57 +0,0 @@
# Checkpointing
Checkpointing is non-standard due to trainer/orchestrator separation and natural asynchrony.
- SFT+RL Trainer: Checkpoints FSDP model shard (using DCP), optimizer and scheduler state, and progress (training step, total samples, total tokens)
- Orchestrator: Checkpoints orchestrator progress (training step, total tokens, total samples, total problems)
- Inference: Inference is stateless. Upon restart, the orchestrator will reload the correct weights into the inference engine. No checkpointing is required.
The default checkpoint directory is `checkpoints` and each checkpoint step will live in a step subdirectory, i.e. `checkpoints/step_{step}`.
Checkpointing is configured with the config key `--ckpt`. One can specify the interval (`--ckpt.interval`), whether to save checkpoints asynchronoously (`--ckpt.save-async`), how many recent step checkpoints to keep on disk (`--ckpt.keep-last`), and keep checkpoints at every N steps permanently (`--ckpt.keep-interval`). By default, we do not checkpoint to save disk space.
## SFT
Let's split the reverse text training SFT example, which does 40 steps by default, into two runs of 20 steps each.
First, run the first 20 steps and append `--ckpt` flag will enable the default checkpoint configuration which will only write the final checkpoint to disk, but no intermediate checkpoints.
```bash
uv run sft ... --max-steps 20 --ckpt
```
Then, to resume the training from step 20, run the following command
```bash
uv run sft ... --max-steps 40 --ckpt.resume-step 20
```
## RL
Similarly, let's split the reverse text training RL example, which does 20 steps by default, into two runs of 10 steps each.
First, start the inference server. It can stay running across restarts as the orchestrator will automatically send the right checkpoint to the inference server when resuming.
```bash
uv run inference ...
```
Then, run the first 20 steps and write the final checkpoint to disk
```bash
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--max-steps 10 \
--ckpt
```
And finally, resume the training to do the remaining 10 steps
```bash
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--max-steps 20 \
--ckpt.resume-step 10
```
-33
View File
@@ -1,33 +0,0 @@
# Configs
We use `pydantic-settings` with some custom functionality for configuring runs. We support the following sources, in this order of precedence:
1. **Command-line arguments**: Pass (nested) arguments as `--key.subkey value` to the script. For example, to set the model name, set `--model.name <model-name>`
2. **Config files**: You can pass TOML config files using the `@` prefix. For example, to set a config, run `uv run inference @ path/to/config.toml`. (*You have to leave a space between the `@` and the config file*)
3. **Environment variables**: You can set environment variables to override the config values. All environment variables must be prefixed with `PRIME_` and use the `__` delimiter to nest the keys. For example, to set the model name you can run `export PRIME_MODEL__NAME=Qwen/Qwen3-0.6B`.
4. **Defaults**: For almost all config arguments, we have a default value which will be used if no other source is provided.
In general we recommend setting configurations via config files to define reproducible experiments and use command-line arguments to override the config values to run variants of the same experiment. Environment variables are usually only used in production settings to communicate with the [Prime Protocol](https://github.com/PrimeIntellect-ai/protocol) worker. In most cases, you should not need to use environment variables.
The precedence order will be important if multiple sources try to configure the same argument. For example, in the following command, all sources will define a model name
```toml
# qwen8b.toml
[model]
name = "Qwen/Qwen3-8B"
```
```toml
# qwen14b.toml
[model]
name = "Qwen/Qwen-14B"
```
```bash
PRIME_MODEL__NAME=Qwen/Qwen3-4B uv run ... @ qwen8b.toml @ qwen14b.toml --model.name Qwen/Qwen3-32B
```
In this example, the CLI argument `--model.name Qwen/Qwen3-32B` will take precedence and the script will use `Qwen/Qwen3-32B` as the model name. If the CLI argument wasn't set, then the second config file would take precedence and the script would use `Qwen/Qwen-14B` as the model name. If the second config file wasn't set, then the first config file would take precedence and the script would use `Qwen/Qwen3-8B` as the model name. Finally, if the first config file wasn't set, then the environment variable would take precedence and the script would use `Qwen/Qwen-4B` as the model name. If the environment variable wasn't set, then the default value would be used and the script would use `Qwen/Qwen3-0.6B` as the model name.
+207
View File
@@ -0,0 +1,207 @@
# Configuration
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `token_export` flag) that aren't surfaced here.
## Table of Contents
- [Sources and Precedence](#sources-and-precedence)
- [TOML Composition](#toml-composition)
- [CLI Overrides](#cli-overrides)
- [Inspecting and Validating](#inspecting-and-validating)
- [Syntax](#syntax)
- [Booleans](#booleans)
- [Lists](#lists)
- [Dicts](#dicts)
- [Optional Sub-Configs](#optional-sub-configs)
- [None](#none)
- [Discriminated Unions](#discriminated-unions)
- [Environments (`[[orchestrator.train.env]]`)](#environments-orchestratortrainenv)
- [Examples](#examples)
## Sources and Precedence
Field values come from three sources — Pydantic defaults, TOML files (passed with `@`), and CLI flags. They're layered in this order, with later sources winning:
1. **Defaults** declared on the Pydantic model.
2. **TOML files** passed with `@`, left to right — later files override earlier ones.
3. **CLI flags** in dotted, kebab-case form (`--model.name`).
## TOML Composition
The `@` token introduces a TOML file. Multiple `@` arguments compose left-to-right, deep-merged — unset fields in an overlay keep the base value:
```bash
uv run rl @ examples/reverse_text/rl.toml # one file
uv run rl @ base.toml @ overlay.toml # left to right
uv run rl --trainer @ trainer.toml --orchestrator @ orch.toml # per-section
uv run rl @ base.toml --trainer @ trainer.toml # mixed
```
> Mind the space: `@ path/to/x.toml`, not `@path/to/x.toml`.
## CLI Overrides
CLI flags mirror the TOML tree using dots:
```bash
--max-steps 50 # top-level
--model.name Qwen/Qwen3-4B # nested
--trainer.optim.lr 1e-5 # double-nested
--inference.parallel.tp 4
```
> Field names are snake_case in TOML (`max_model_len`) and kebab-case on the CLI (`--max-model-len`).
> Renamed fields keep their old name as a validation alias — e.g. `rollouts_per_example` is still accepted in TOML and CLI after being renamed to `group_size`. Mixing the two names across sources is safe.
## Inspecting and Validating
```bash
uv run rl --help # full schema
uv run rl @ rl.toml --dry-run --output-dir /tmp/check # write resolved configs
```
## Syntax
### Booleans
CLI uses paired flags: bare `--flag` sets `True`, `--no-flag` sets `False`. TOML must be explicit:
```bash
uv run rl @ rl.toml --clean-output-dir # True
uv run rl @ rl.toml --no-clean-output-dir # False
```
```toml
clean_output_dir = true
```
### Lists
CLI accepts space-separated values or a JSON literal. TOML uses an array literal. Both forms target the same field:
```bash
uv run rl @ rl.toml --trainer.model.lora.target-modules q_proj k_proj v_proj
uv run rl @ rl.toml --trainer.model.lora.target-modules '["q_proj", "k_proj", "v_proj"]'
```
```toml
[trainer.model.lora]
target_modules = ["q_proj", "k_proj", "v_proj"]
```
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables (e.g. environments), see [Environments](#environments-orchestratortrainenv).
### Dicts
CLI takes a JSON literal. TOML uses a table or inline-table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
```bash
uv run rl @ rl.toml --orchestrator.train.env.0.args \
'{"dataset_name": "openai/gsm8k", "dataset_subset": "main"}'
```
```toml
[[orchestrator.train.env]]
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
```
### Optional Sub-Configs
Many sub-configs are typed `SomeConfig | None`. Two patterns enable them:
- **Bare flag with defaults**: `--model.compile` or, in TOML, an empty section `[model.compile]`. The sub-config materializes with all-default values.
- **Enable and set fields together**: `--model.compile.fullgraph` (CLI) or any populated `[model.compile]` table (TOML).
To **disable** a sub-config that's on by default, use `--no-<name>` on the CLI or assign the string `"None"` in TOML (see [None](#none)). This is how `[ckpt]`, `[model.lora]`, `[model.compile]`, `[trainer.wandb]`, etc. are turned on and off.
### None
TOML has no `null`. Use the string `"None"`, which the loader coerces:
```toml
[inference.model]
max_model_len = "None"
```
On the CLI: `--inference.model.max-model-len None`.
### Discriminated Unions
Loss, advantage, optimizer, scheduler, weight broadcast transport, and several others are discriminated unions. Set the `type` field to pick a variant:
```toml
[trainer.optim]
type = "muon"
lr = 1e-5
mu = 0.95
```
Omit `type` to keep the default variant.
### Environments (`[[orchestrator.train.env]]`)
Training environments are an array of tables — set one per env, optionally with sampling weights:
```toml
[[orchestrator.train.env]]
id = "math-env"
name = "gsm8k"
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
[[orchestrator.train.env]]
id = "reverse-text"
ratio = 0.25 # 25% of batches; remaining 75% goes to math-env
[[orchestrator.eval.env]]
id = "math-env"
name = "gsm8k-eval"
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
```
`args` is forwarded verbatim to the environment's `load_environment(**args)`.
The same `id` can appear multiple times across train and eval (or with different `args`) — useful for evaluating on a held-out split of the env you're training on, or comparing two configurations of the same env side by side. When `id` is reused, set a distinct `name` on each entry; `name` defaults to `id` and must be unique across all envs in the same group.
## Examples
The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples) are the canonical, kept-up-to-date references — the rest of the repo's TOMLs (under `configs/`) are CI- and debug-internal and may drift. Each example directory has its own README with the full launch story.
**Basic** (1–8 GPUs):
- [**Reverse Text**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/reverse_text) — `Qwen3-0.6B` reversing a chunk of text. Tiny single-turn SFT + RL; runs on a single consumer GPU in minutes.
- [**Wordle**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/wordle) — `Qwen3-1.7B` playing Wordle. Multi-turn SFT + RL; 2–4 H100s.
- [**Alphabet Sort**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/alphabet_sort) — `Qwen3-4B-Instruct-2507` sorting names alphabetically. Multi-turn LoRA RL without SFT warmup; one H100.
- [**Wiki Search**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/wiki_search) — `Qwen3-4B-Instruct-2507` answering trivia by web-searching Wikipedia. Multi-turn with tool use.
- [**Hendrycks Sanity**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/hendrycks_sanity) — `DeepSeek-R1-Distill-Qwen-1.5B` on a filtered MATH subset. Useful for algorithm ablations.
**Advanced** (32–2048 GPUs, SLURM):
- [**Qwen 3 30B – A3B Math**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/qwen30b_math) — `Qwen3-30B-A3B` on hard math.
- [**Qwen 3 30B – A3B SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/qwen30b_swe) — `Qwen3-30B-A3B` on hard SWE.
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/Intellect-3.1) — reproduces our INTELLECT-3.1 training run.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/minimax_m2.5_swe) — `MiniMax-M2.5` on agentic SWE.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/glm5_pd_disag) — `GLM-5` with P/D disaggregation and FP8 inference.
### Worked Example: Compose, Override, Dry-Run
Start from a shipped base config, override two fields on the CLI, and dry-run:
```bash
uv run rl @ examples/reverse_text/rl.toml \
--wandb.name my-experiment \
--trainer.optim.lr 5e-6 \
--output-dir /tmp/reverse-dry \
--dry-run
```
Then inspect the resolved config:
```bash
ls /tmp/reverse-dry/configs/
# rl.toml trainer.toml orchestrator.toml inference.toml
```
Each per-process TOML reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/configs/trainer.toml`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
-299
View File
@@ -1,299 +0,0 @@
# Deployment
You can deploy PRIME-RL on a single GPU and larger multi-node clusters.
## SFT
### Single-GPU
For training on a single GPU, no communication orchestration is required and you can choose whether to start your trainer using our trainer entrypoint or using `torchrun`.
To start with our `sft` entrypoint
```bash
uv run sft ...
```
To do the same thing, but using `torchrun`
```bash
uv run torchrun src/prime_rl/trainer/sft/train.py ...
```
### Multi-GPU
For training on multiple GPUs, use `torchrun` with the `--nproc-per-node` flag.
```bash
uv run torchrun \
--local-rank-filter 0 \
--nproc-per-node 8 \
src/prime_rl/trainer/sft/train.py ...
```
*The `--local-rank-filter` flag is used to only log the logs from the master rank, as detailed in [logging](logging.md).*
### Multi-Node
For training on multiple nodes, use `torchrun` with the `--nnodes`, `--node-rank`, and `--rdzv-endpoint` flags.
First, decide which node will be your head node and find a reachable private IP address for it. If your nodes are not colocated, you will likely need to setup VPN (e.g. [Tailscale](https://tailscale.com)) for the nodes to reach each other.
(*Skip this step if the default network interface is sufficient.*) Make sure to set the network interface for GLOO and NCCL to one that allows all nodes to reach each other.
```bash
# On both nodes
export GLOO_SOCKET_IFNAME=...
export NCCL_SOCKET_IFNAME=...
```
Then, configure the rendezvous endpoint to allow the nodes to find each other. Here, `MASTER_ADDR` is the private IP address of the head node and `MASTER_PORT` is a free port on the head node, typically port 29500 for `torchrun`.
```bash
# On both nodes
export MASTER_ADDR=...
export MASTER_PORT=...
```
Then, on the head node, run
```bash
# On node 0
uv run torchrun \
--nnodes 2 \
--node-rank 0 \
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
--local-rank-filter 0 \
--nproc-per-node 8 \
src/prime_rl/trainer/sft/train.py ...
```
And on the second node, run
```bash
# On node 1
uv run torchrun \
--nnodes 2 \
--node-rank 1 \
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
--local-rank-filter 0 \
--nproc-per-node 8 \
src/prime_rl/trainer/sft/train.py ...
```
### SLURM
See the dedicated [SLURM guide](slurm.md).
## Inference
For SLURM-based inference deployment, see the [SLURM guide](slurm.md#inference-examples). Each node runs an independent vLLM replica — no manual coordination needed.
For manual multi-node deployment without SLURM, we rely on vLLM's multi-node data parallel deployment primitives ([docs](https://docs.vllm.ai/en/v0.10.0/serving/data_parallel_deployment.html)).
First, decide which node will be your head node and find a reachable private IP address for it. If your nodes are not colocated, you will likely need to setup VPN (e.g. [Tailscale](https://tailscale.com)) for the nodes to reach each other.
(*Skip this step if the default network interface is sufficient.*) Make sure to set the network interface for GLOO and NCCL to one that allows all nodes to reach each other.
```bash
# On both nodes
export GLOO_SOCKET_IFNAME=...
export NCCL_SOCKET_IFNAME=...
```
Then, configure the data parallel address as the private IP address of the head node.
```bash
# On both nodes
export DATA_PARALLEL_ADDRESS=...
export DATA_PARALLEL_RPC_PORT=...
```
To run TP=4 and DP=4 with DP ranks 0 and 1 on the head node and DP ranks 2 and 3 on the second node, run
```bash
# On node 0
uv run inference \
--data-parallel-size 4 \
--tensor-parallel-size 4 \
--data-parallel-size-local 2 \
--data-parallel-address $DATA_PARALLEL_ADDRESS \
--data-parallel-rpc-port $DATA_PARALLEL_RPC_PORT
```
```bash
# On node 1
uv run inference \
--data-parallel-size 4 \
--tensor-parallel-size 4 \
--data-parallel-size-local 2 \
--data-parallel-address $DATA_PARALLEL_ADDRESS \
--data-parallel-rpc-port $DATA_PARALLEL_RPC_PORT \
--data-parallel-start-rank 2 \
--headless
```
## RL
### Single-GPU Training
If you only have access to a single GPU, you may still be able to run small RL experiments. To do so, configure your inference server to use only a fraction of the available memory to leave some space for the trainer.
For example, to run an RL training on a single GPU while using 50% of the available memory for the inference server, run
```bash
bash scripts/tmux.sh
```
```bash
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--inference @ path/to/infer.toml \
--trainer-gpu-ids 0 \
--inference-gpu-ids 0 \
--inference.gpu-memory-utilization 0.5
```
*Make sure to tune the `--gpu-memory-utilization` value such that you have enough GPU memory for the RL trainer.*
You can also set this up by starting each submodule manually.
```bash
# Run this in the `Inference` pane
uv run inference @ path/to/infer.toml --gpu-memory-utilization 0.5
```
```bash
# Run this in the `Orchestrator` pane
uv run orchestrator @ path/to/orch.toml
```
```bash
# Run this in the `Trainer` pane
uv run trainer @ path/to/train.toml
```
### Multi-GPU Training
For single-node training, we recommend using the `rl` entrypoint to conveniently start all components, i.e. the inference server, the orchestrator, and the trainer.
By default, the inference server starts on GPU ID 0 and the trainer on GPU ID 1.
```bash
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--inference @ path/to/infer.toml \
```
You can configure the GPU IDs to use for the inference server and the trainer. For example, to run the inference server on GPUs IDs 0-5 with data parallelism and the trainer on GPUs IDs 6-7
```bash
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--inference @ path/to/infer.toml \
--inference-gpu-ids 0,1,2,3,4,5 \
--trainer-gpu-ids 6,7 \
--inference.parallel.dp 6
```
### Parallel Experiments
For quick ablations, it can be more efficient to parallelize experiments within a node (e.g. split your GPUs to run two experiments in parallel). For example, if you have access to 4 GPUs and your experiment fits on 2 GPUs, you can parallelize two experiments as follows:
Start the first experiment in a tmux session `exp1` with outputs directory `outputs1`. Specify it both in the tmux script, as well as in the start command (*will use the first 2 GPUs*)
```bash
bash scripts/tmux.sh -s exp1 -o outputs1
```
```bash
# Run this in the `Trainer` pane
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--inference @ path/to/infer.toml \
--output-dir outputs1
```
For the second experiment, start a second tmux session named `exp2` with outputs directory `outputs2`. In addition, specify a new server port for the inference engine and orchestrator (*will use the last 2 GPUs*)
```bash
bash scripts/tmux.sh -s exp-2 -o outputs2
```
```bash
# Run this in the `Trainer` pane
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--inference @ path/to/infer.toml \
--inference-gpu-ids 2 \
--trainer-gpu-ids 3 \
--inference.server.port 8001 \
--orchestrator.client.base-url http://localhost:8001/v1 \
--output-dir outputs2
```
### Multi-Node Training
> We currently require a shared file system for multi-node RL training.
To facilitate multi-node RL training, ensure that all nodes have access to a shared file system and that the node that will run the inference server is reachable from the orchestrator via a private or public IP address. Then, set the following environment variables on all nodes:
```bash
# On all nodes
export OUTPUT_DIR=... # Path to directory in shared file system
export INFERENCE_SERVER_IP=... # Reachable IP address of the inference node
export INFERENCE_SERVER_API_KEY=... # API key for the inference server
```
Then, start the inference server on one node.
```bash
# On one node
uv run inference ... \
--api-key $INFERENCE_SERVER_API_KEY --parallel ...
```
Then, start a single orchestrator
```bash
# On either node
uv run orchestrator ... \
--client.base-url http://$INFERENCE_SERVER_IP:8000/v1 \
--client.api-key-var INFERENCE_SERVER_API_KEY \
--output-dir $OUTPUT_DIR
```
Finally, start the trainer on one as described in the [Trainer](#trainer) section.
```bash
# On other node
uv run torchrun \
--nproc-per-node 8 \
--local-rank-filter 0 \
src/prime_rl/trainer/rl/train.py ... \
--output-dir $OUTPUT_DIR
```
Of course, you can further scale up the number of nodes used by the trainer and inference server, as described in the sections above. However, make sure that there is only a single orchestrator instance.
### SLURM
See the dedicated [SLURM guide](slurm.md).
## Kubernetes
For deployments on Kubernetes clusters, PRIME-RL provides a Helm chart that manages the entire training infrastructure including orchestrator, trainer, and inference components with automatic pod scheduling, GPU allocation, and shared storage.
See the dedicated [Kubernetes guide](kubernetes.md) for complete documentation including:
- Prerequisites and setup
- Quick start examples
- Component architecture
- Scaling and distributed training
- Configuration options
- Troubleshooting
+140
View File
@@ -0,0 +1,140 @@
# Development
This page covers workflows for developing on `prime-rl` itself — running the test suite, contributing changes, and adding new model architectures with the small-scale tooling we use to iterate on MoE families without booting up a 100B+ run.
## Table of Contents
- [Test Suite](#test-suite)
- [Layout](#layout)
- [Running Tests Locally](#running-tests-locally)
- [CI Workflows](#ci-workflows)
- [Markers](#markers)
- [Pre-Commit Hooks](#pre-commit-hooks)
- [Adding a New Model](#adding-a-new-model)
- [Implement the Modeling Code](#implement-the-modeling-code)
- [Register a Mini Preset](#register-a-mini-preset)
- [Run the Smoke Test](#run-the-smoke-test)
## Test Suite
The test suite is split into three tiers, each with its own CI workflow.
### Layout
- **`tests/unit/`** — fast-running, hermetic tests for isolated logic: config parsing and validation, advantage / loss / scheduler / packer math, individual dataset paths, model-conversion roundtrips, etc. Tests that need a GPU are tagged with the `gpu` marker.
- **`tests/integration/`** — full-stack RL/SFT runs on a tiny model end-to-end through inference + orchestrator + trainer.
- **`tests/nightly/`** — runs the configs in [`examples/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples) every night to catch regressions in the shipped examples.
### Running Tests Locally
```bash
uv run pytest -v # everything
uv run pytest tests/unit -v # unit only
uv run pytest tests/integration -v # integration only
uv run pytest -v -m "not gpu" # CPU-only subset (mirrors CPU CI)
uv run pytest -v -m gpu # GPU-only subset
uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenario
```
### CI Workflows
| Workflow | Trigger | What runs | Where |
|---|---|---|---|
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_multi_run`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
### Markers
Two pytest markers are declared in `pyproject.toml` (`addopts = "--strict-markers"`):
- `gpu` — gate a test that needs CUDA. CPU CI uses `-m "not gpu"`; the GPU unit job uses `-m gpu`.
- `slow` — gate a test that's expensive enough you'd usually skip it locally. Deselect with `-m "not slow"`.
## Pre-Commit Hooks
Install the [pre-commit](https://pre-commit.com) hooks before your first commit so ruff check + format run on staged Python files automatically:
```bash
uv run pre-commit install
```
## Adding a New Model
Bringing up a new model family is three steps: implement the modeling code, register a mini preset, and run the smoke test. The preset and smoke test let you iterate on the modeling code at ~0.5B scale on 1–2 GPUs instead of paying the cost of the full-size model — useful for catching bugs in modeling code, state-dict conversions, and pipeline integration before scaling.
### Implement the Modeling Code
Drop the modeling code under `src/prime_rl/trainer/models/<arch>/` (HF-compatible config, modeling, and weight conversion). Mirror the layout of an existing family — `glm4_moe/` or `qwen3_moe/` are good starting points.
### Register a Mini Preset
Add an entry to [`scripts/mini_moe.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/scripts/mini_moe.py) so the smoke-test workflow can build a ~0.5B test model in your architecture. The preset names the config class, picks small dimensions, and wires up the HF + PrimeRL model classes plus a tokenizer source:
```python
ARCH_PRESETS = {
"glm4_moe": {
"config_class": Glm4MoeConfig,
"config_kwargs": dict(hidden_size=1024, num_hidden_layers=24, n_routed_experts=8, ...),
"hf_model_class": HFGlm4MoeForCausalLM,
"prime_model_class": PrimeRLGlm4MoeForCausalLM,
"tokenizer_source": "THUDM/GLM-4-9B-0414",
},
# add your arch here
}
```
### Run the Smoke Test
Build the mini model. This creates a ~543M-parameter GLM-4 MoE (1024 hidden, 24 layers, 8 experts) with random weights, copies the tokenizer from the original GLM-4 model, and verifies the HF↔PrimeRL roundtrip is lossless:
```bash
uv run python scripts/mini_moe.py --arch glm4_moe --output-dir ./mini-glm-moe
```
To re-verify the roundtrip after a modeling-code change without re-creating the model:
```bash
uv run python scripts/mini_moe.py --arch glm4_moe --output-dir ./mini-glm-moe --verify-only
```
Warm up the random-weight mini model with SFT on reverse-text so KL divergence becomes meaningful in the RL phase. Loss drops from ~12 to ~2.5 — the output won't be coherent, but the distribution is non-trivial. A pre-built SFT'd checkpoint lives at [samsja/mini-glm-moe](https://huggingface.co/samsja/mini-glm-moe) if you want to skip this step:
```bash
uv run sft @ configs/debug/moe/sft/train.toml \
--model.name ./mini-glm-moe \
--data.name PrimeIntellect/Reverse-Text-SFT \
--data.type null \
--max_steps 200 \
--optim.lr 1e-4 \
--ckpt.weights
```
Then run the full RL stack on reverse-text:
```bash
uv run rl @ configs/ci/integration/reverse_text_moe/start.toml \
--model.name samsja/mini-glm-moe \
--trainer.model.impl custom \
--inference.gpu-memory-utilization 0.7 \
--inference.model.max-model-len 2048
```
What to look for:
- **No crashes.** Validates the full inference + orchestrator + trainer pipeline end-to-end.
- **Finite, non-zero KL.** Confirms the reference distribution is meaningful.
- **Loss reasonable.** Not NaN, not stuck.
Don't expect reward to climb meaningfully in 20 steps on a random model.
### Requirements for merging a new model
Before merging a new model, you need to ensure the following:
- The model is correctly registered and defines and all the required methods - such as `convert_hf_layer_to_tt` and `convert_tt_layer_to_hf`.
- The small smoke test passes.
In the PR that adds the new model, you also need to provide a table covering the KL mismatch across 20 steps on `math` environment with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not met, the PR will not be merged (unless reasonable justification is provided). This is to ensure all our models are consistent and their implementations match the implementations in the inference framework.
-91
View File
@@ -1,91 +0,0 @@
# Disaggregated Prefill/Decode Inference
Run MoE models with separate prefill and decode node groups for higher throughput.
## Quick Start
See [`configs/glm5_disagg_inference/inference.toml`](../configs/glm5_disagg_inference/inference.toml) for an example config.
```bash
uv run inference @ configs/glm5_disagg_inference/inference.toml --output-dir /data/$USER/outputs
```
## Prefill/Decode Ratio
| Workload | Recommended ratio (P:D) | Why |
|---|---|---|
| Agentic (SWE, Lean) | **3:1** | Long growing contexts → prefill-heavy |
| Non-agentic (math, chat) | **1:2** | Short prompts, long generations → decode-heavy |
Monitor live queue depths:
```bash
curl -s http://<prefill_node>:8100/metrics | grep num_requests_waiting
curl -s http://<decode_node>:8200/metrics | grep num_requests_waiting
```
If prefill has queued requests and decode has zero, add more prefill nodes (and vice versa).
For historical averages (cumulative over the entire run), query the histogram metrics:
```bash
# Average queue time per request (seconds)
curl -s http://<node>:<port>/metrics | awk '
/request_queue_time_seconds_sum\{/ { sum += $2 }
/request_queue_time_seconds_count\{/ { count += $2 }
END { if (count > 0) printf "avg queue: %.2fs (%d requests)\n", sum/count, count }
'
# Average prefill/decode compute time
curl -s http://<node>:<port>/metrics | awk '
/request_prefill_time_seconds_sum\{/ { ps += $2 }
/request_prefill_time_seconds_count\{/ { pc += $2 }
/request_decode_time_seconds_sum\{/ { ds += $2 }
/request_decode_time_seconds_count\{/ { dc += $2 }
END {
if (pc > 0) printf "avg prefill: %.2fs\n", ps/pc
if (dc > 0) printf "avg decode: %.2fs\n", ds/dc
}
'
```
Other useful metrics on the `/metrics` endpoint:
- `vllm:e2e_request_latency_seconds` — end-to-end latency
- `vllm:kv_cache_usage_perc` — KV cache memory pressure
- `vllm:nixl_xfer_time_seconds` — NIXL KV transfer duration
- `vllm:nixl_bytes_transferred` — bytes per KV transfer
## UCX 1.19
NVSHMEM requires UCX >= 1.19 for multi-GPU CUDA support. Most clusters ship UCX 1.17 (via HPC-X), which causes `cuStreamCreate: invalid device context` errors during DeepEP internode dispatch.
**Check your version:**
```bash
/opt/hpcx/ucx/bin/ucx_info -v | head -1
# If < 1.19, you need to build from source
```
**Build UCX 1.19 (run once on a GPU node):**
```bash
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
```
This installs UCX 1.19 to `prime-rl/third_party/ucx/`. The sbatch template automatically adds it to `LD_LIBRARY_PATH`, overriding the system version.
## Troubleshooting
### `DeepEP error: timeout (dispatch CPU)`
NVSHMEM internode communication failing. Check:
1. UCX version >= 1.19? (`third_party/ucx/bin/ucx_info -v`)
2. NVSHMEM libs reachable at `/tmp/deepep_build/nvshmem/lib/`? If not:
```bash
ssh <node> 'mkdir -p /tmp/deepep_build/nvshmem && \
ln -sfn <venv>/lib/python3.12/site-packages/nvidia/nvshmem/lib \
/tmp/deepep_build/nvshmem/lib'
```
3. IBGDA driver enabled? `ssh <node> 'cat /proc/driver/nvidia/params | grep EnableStreamMemOPs'` should show `1`.
### Router healthy but requests hang
NIXL side channel not running on prefill. Check:
```bash
ssh <prefill_node> 'ss -tlnp sport ge :5600 sport le :5608 | grep -c LISTEN'
# Should show 8 (one per DP rank). If 0, check logs for UCX/NVSHMEM errors.
```
-67
View File
@@ -1,67 +0,0 @@
# Entrypoints
## RL
The main usecase of PRIME-RL is RL training. Three main abstractions facilitate RL training: the **orchestrator**, the **trainer**, and the **inference** service.
![Architecture](assets/architecture.png)
### Orchestrator
The orchestrator is a lightweight CPU process that handles the core data and scheduling logic, serving as an intermediary between the trainer and inference service with bidirectional relays. In one direction, it collects rollouts from the inference server, assembles them into packed batches, and dispatches them to the trainer; in the other direction, it relays updated model weights from the trainer to the inference service. The orchestrator utilizes `verifiers` environments to abstract multi-turn rollout generation and scoring. Each training and evaluation environment is exposed as a `vf.EnvServer` as a sidecar to the orchestrator process (default) or as a standalone process (e.g. used in hosted training to run environments in containers).
### Trainer
The trainer is responsible for producing an updated policy model given rollouts and advantages. We use FSDP2 as the backend with compatibility for any HuggingFace (HF) model. For some models we also provide custom implementations, mostly for performance reasons. FSDP shards model parameters, gradients, and optimizer states, allowing training large models with data parallelism and minimal GPU memory footprint. We support a variety of popular training objectives, such as GRPO, GSPO, OPO, RLOO and [CISPO](https://arxiv.org/abs/2506.13585). The trainer is inspired by [`torchtitan`](https://github.com/pytorch/torchtitan) and relies on native PyTorch features to implement advanced parallelism techniques, such as tensor, context or expert parallelism.
### Inference
The inference service in its simplest form is a standard OpenAI-compatible server with a vLLM backend. The API specification is extended with a custom `update_weights` endpoint to reload model weights from a HF-compatible checkpoint on disk. Otherwise, we rely on vLLM's optimized kernels, parallelism strategies, and scheduling for fast rollout generation. Given the disaggregated nature of the service architecture, it can be directly extended to include multiple engines with a shared request pool, allowing operation across multiple clusters and straightforward integration of alternative inference engines (e.g. SGLang, Tokasaurus). We also heavily rely on native data parallelism in vLLM (also available in SGLang) for orchestrating the fleet of nodes dedicated to inference.
### RL
For doing RL training all components need to be started. One can do this manually:
```bash
uv run inference ...
```
```bash
uv run orchestrator ...
```
```bash
uv run trainer ...
```
Or, alternatively on a single node, use the `rl` entrypoint to start all components.
```bash
uv run rl \
--trainer @ path/to/train.toml \
--orchestrator @ path/to/orch.toml \
--inference @ path/to/infer.toml \
...
```
For more details on multi-node deployment options, see the [deployment](deployment.md) documentation and see the [examples](examples) for concrete training configurations. To see all available configuration options, run `uv run rl --help`.
## SFT
We provide a fairly straight-forward SFT trainer which is capable of fine-tuning any conversational model on multi-turn conversation with tool calling. It shares a lot of components with the RL trainer, such as the modeling code, parallelism techniques, checkpoint format, logger, etc. which ensures a seemless post-training workflow.
To start an SFT training, you need to prepare a conversational dataset in either [prompt-completion format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion) or raw `messages` format. If `messages` is provided, the trainer interprets the full conversation as a single sample with an empty prompt and applies role-based loss masking across the whole chat. If both `messages` and `prompt` / `completion` are present, `messages` takes precedence. Single-turn fine-tuning should be compatible with the chat templates of most models. However, to properly handle loss masking, we require that the tokenizer's chat template satisfies a prefix property: the tokenization of any conversation prefix must be a prefix of the tokenization of the full conversation. For instance, tokenizing message 1 should yield a token sequence that forms a prefix of tokenizing messages 1 and 2, which in turn should be a prefix of tokenizing messages 1, 2, 3, and so forth. An example of a chat template that *does not* satisfy this property is Qwen3's chat template, as it strips away past think sections.
On a single GPU, start the training with the `sft` entrypoint
```bash
uv run sft ...
```
If you have access to multiple GPUs, use [`torchrun`](https://docs.pytorch.org/docs/stable/elastic/run.html) with `--nproc-per-node` to start the training.
```bash
uv run torchrun --nproc-per-node 8 src/prime_rl/trainer/sft/train.py ...
```
For more details on multi-node deployment options, see the [deployment](deployment.md) documentation and see the [examples](examples) for concrete training configurations. To see all available configuration options, run `uv run sft --help`.
-32
View File
@@ -1,32 +0,0 @@
# Environments
PRIME-RL can train and evaluate in any [`verifiers`](https://github.com/willccbb/verifiers) environments. To train in a new environment, simply install it from the [Environment Hub](https://app.primeintellect.ai/dashboard/environments) or install a local environment.
## Installation
You can explore the installation options using
```bash
prime env info <owner>/<name>
```
To install an environment temporarily
```bash
prime env install <owner>/<name>
# Or: uv pip install <name> --extra-index-url https://hub.primeintellect.ai/<owner>/simple/
```
To install a local environment
```bash
uv pip install -e path/to/env
```
To verify your installation
```bash
uv run python -c "import <name>"
```
For more details on environments, see our Environments Hub documentation [here](https://docs.primeintellect.ai/tutorials-environments/environments).
-16
View File
@@ -1,16 +0,0 @@
# Docs
This directory maintains the documentation for PRIME-RL. It is organized into the following sections:
- [**Entrypoints**](entrypoints.md) - Overview of the main components (orchestrator, trainer, inference) and how to run SFT, RL, and evals
- [**Configs**](configs.md) - Configuration system using TOML files, CLI arguments, and environment variables
- [**Environments**](environments.md) - Installing and using verifiers environments from the Environments Hub
- [**Async Training**](async.md) - Understanding asynchronous off-policy training and step semantics
- [**Logging**](logging.md) - Logging with loguru, torchrun, and Weights & Biases
- [**Platform Monitoring**](platform-monitoring.md) - Register runs on the Prime Intellect platform and stream training metrics
- [**MultiRunManager**](multi_run_manager.md) - Multi-run training with the MultiRunManager object for concurrent LoRA adapters
- [**Checkpointing**](checkpointing.md) - Saving and resuming training from checkpoints
- [**Benchmarking**](benchmarking.md) - Performance benchmarking and throughput measurement
- [**Deployment**](deployment.md) - Training deployment on single-GPU, multi-GPU, and multi-node clusters
- [**Kubernetes**](kubernetes.md) - Deploying PRIME-RL on Kubernetes with Helm
- [**Troubleshooting**](troubleshooting.md) - Common issues and their solutions
+269
View File
@@ -0,0 +1,269 @@
# Inference
This page covers the inference configuration and the supported features/deployment shapes. It covers how to scale the inference server from a single GPU to 1000s of GPUs that run agentic workloads at the speed of light with all the bells and whistles configured.
## Table of Contents
- [Overview](#overview)
- [Single-Node](#single-node)
- [Multi-Node](#multi-node)
- [Multi-replica](#multi-replica)
- [Wide-EP](#wide-ep)
- [P/D Dissagregation](#pd-dissagregation)
- [Router](#router)
- [Routing policies](#routing-policies)
- [Advanced Configuration](#advanced-configuration)
- [KV Cache Offload](#kv-cache-offload)
- [Optimized P/D disaggregation deployment](#optimized-pd-disaggregation-deployment)
- [Other vLLM features](#other-vllm-features)
- [Router Replay](#router-replay)
## Overview
`prime-rl` chooses to use `vLLM` as the inference engine. We aim to stay up-to-date with the latest vLLM features, being at-most 1 version behind the latest stable release. This allows us to use the latest features from vLLM as soon as they are released - such as router replay, CPU KV cache offload, and more.
We support 3 distinct deployment shapes:
- [Single-Node](#single-node) - Runs the inference server on a single node. Useful for debugging, small scale experiments or smaller models. The default deployment shape.
- [Multi-Node](#multi-node) - Runs the inference server on multiple nodes. Useful for large scale experiments or larger models, where latency is not a concern - i.e. single turn inference, long context inference, etc.
- [Disaggregated](#disaggregated) - Runs the inference server on multiple nodes, but disaggregates the prefill and decode stages. Useful for large scale experiments or larger models, where latency is a concern and multi-node deployment creates very high E2E rollout latency, such as agentic workflows.
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `router_port`, `backend_port`, etc.
```toml
[inference.deployment]
type = "single_node" # or "multi_node" or "disaggregated"
```
To configure the inference server, you can use the `InferenceConfig` field. This is a config-field that allows you to set the inference server-specific knobs. Most of these are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
```toml
[inference]
model = "PrimeIntellect/INTELLECT-3"
...
```
We will now walk through the supported features and deployment shapes in detail, starting with the single-node deployment.
## Single-Node
The single-node deployment is the default deployment shape. It runs the inference server on a single node. It is useful for debugging, small scale experiments or smaller models. You can configure the single-node deployment with the `SingleNodeInferenceDeploymentConfig` config-field.
```toml
[inference.deployment]
type = "single_node"
```
This deployment shape runs the inference server on a single node, if configured with NVLink enabled, it allows you more freedom in terms of parallelism configurations.
```toml
[inference]
enable_expert_parallel = true # defaults to False
[inference.parallel]
tp = 2
dp = 4
[inference.deployment]
type = "single_node"
```
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required `orchestrator.max_inflight_requests`. Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.enable_expert_parallel` or `inference.parallel.tp` to maximize the available GPU memory.
You can also increase the available KV cache memory by enabling `inference.kv_cache_offload`. More details in the [Advanced Configuration](#advanced-configuration) section.
## Multi-Node
This deployment shape branches into 2 sub-shapes:
- [Multi-replica](#multi-replica) - Runs the inference server on multiple nodes, but each node runs an independent vLLM replica. You can think of this as a for-loop over single-node deployments.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
### Multi-replica
This deployment shape runs the inference server on multiple nodes, but each node runs an independent vLLM replica.
Parallelism configuration is the same as the single-node deployment. The shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.deployment.num_nodes` to the number of nodes you want to run the inference server on.
```toml
[inference.deployment]
type = "multi_node"
num_nodes = 2
[inference]
model = "PrimeIntellect/INTELLECT-3"
[inference.parallel]
tp = 2
dp = 4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing will be handled by the `vllm-router` instance running on the same node as the 1st replica. We aim to support more advanced routing options, such as `llm-d` or `dynamo` in the future. You can read more about the supported routing options in the [router](#router) section.
### Wide-EP
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.enable_expert_parallel = true`.
```toml
[inference.deployment]
type = "multi_node"
num_nodes = 2
[inference]
model = "PrimeIntellect/INTELLECT-3"
enable_expert_parallel = true
[inference.parallel]
tp = 2
dp = 8
```
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tp = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
## P/D Dissagregation
This is the most advanced deployment shape. It allows you to disaggregate the prefill and decode stages, with KV cache flowing between them. This is useful for large scale deployments, where there are high requirements on latency, such as agentic workflows spanning 100s of turns.
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and `inference.deployment.num_prefill_nodes` and `inference.deployment.num_decode_nodes` to the number of nodes you want to run the prefill and decode stages on.
```toml
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 2
num_decode_nodes = 2
```
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode node groups. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of replicas you want to run.
```toml
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 2
num_decode_nodes = 2
num_prefill_replicas = 2
num_decode_replicas = 1
```
Now the total deployment will span 6 nodes - 2x2 for prefill and 1x2 for decode. 2 prefill replicas will run on 2 nodes each - total of 4 nodes for prefill. 1 decode replica will run on 2 nodes for decode.
We also allow you to configure the total amount of inference replicas - this is useful if you'd like to multiply the above configuration by a factor of `k`, each running behind a separate `vllm-router` instance.
```toml
[deployment] # this is a top-level RL deployment, not inference.deployment!!
type = "multi_node"
num_train_nodes = 4
num_infer_nodes = 6 # this is per-replica
num_infer_replicas = 3
```
This will run 3 inference replicas, each running on 6 nodes. Each replica will run on 2x2 nodes for prefill and 1x2 nodes for decode. The total deployment will span 18 nodes. This will also spin-up 3 separate `vllm-router` instances.
## Router
We use our own fork of [vllm-router](https://github.com/PrimeIntellect-ai/router) as the request handler. We plan to support more advanced proxy options in the future.
Right now, router handles 2 most important things:
- Request routing - KV cache re-use and balanced routing
- P/D disaggregation - handling the prefill and decode stages separately
### Routing policies
The 2 policies you might want to configure are:
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - this works by hashing a request header to determine where to route the request to. You can configure what to hash by setting
`orchestrator.student.client.extra_headers_from_state` to the header the `router` expects to be set.
We set it to a sensible default, that works with all verifiers environments.
```toml
[orchestrator.student.client.extra_headers_from_state]
X-Session-ID = "trajectory_id" # this is the default - each rollout has a unique trajectory_id and router expects X-Session-ID
```
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
## Advanced Configuration
### KV Cache Offload
Maximizing KV-Cache space is crucial to support high-concurrency workloads. You can offload the KV cache to CPU memory (and, behind it, disk) by setting `inference.kv_cache_offload`. It is a discriminated config with two composable tiers, `cpu` and `disk`: a `cpu` tier is always required, and an optional `disk` tier is layered behind it (GPU → DRAM → disk). Disk-only is not supported.
The `type` field selects the backend:
- `native` — vLLM's built-in offloading. CPU-only uses `OffloadingConnector`; CPU+disk uses `TieringOffloadingSpec` (a CPU primary tier with a filesystem secondary tier). Fully self-contained — no extra processes.
- `mooncake` — a [Mooncake](https://github.com/kvcache-ai/Mooncake) **shared distributed store** (SLURM only). One `mooncake_master` + metadata server runs on the head inference node; every inference node runs a `mooncake_client` that contributes its DRAM (and, with `disk`, SSD) segment to that *single* pool. Because blocks are keyed by model + parallel rank + content hash (no instance id), a prefix cached by one node/replica is reusable by all of them over RDMA — pooling every node's CPU RAM into one KV cache. Use `native` for local/single-process runs.
```toml
# Native CPU offload (reserves 128GB of CPU KV cache for this instance)
[inference.kv_cache_offload]
type = "native"
[inference.kv_cache_offload.cpu]
num_bytes = 128_000_000_000 # 128GB
# Native CPU + disk tiering (self-contained)
[inference.kv_cache_offload]
type = "native"
[inference.kv_cache_offload.cpu]
num_bytes = 128_000_000_000
[inference.kv_cache_offload.disk]
path = "/scratch/kv" # disk capacity is bounded by the filesystem
# Mooncake CPU + disk (per-node distributed store, RDMA)
[inference.kv_cache_offload]
type = "mooncake"
[inference.kv_cache_offload.cpu]
num_bytes = 128_000_000_000
[inference.kv_cache_offload.disk]
path = "/scratch/kv"
```
For `native`, `cpu.num_bytes` is the aggregate CPU KV pool for the instance (vLLM shards it across workers). For `mooncake`, `cpu.num_bytes` is the DRAM each node contributes to the shared pool (so the total pool ≈ `num_bytes × #inference-nodes`); the store uses RDMA, so it requires an RDMA-capable fabric. Enabling offload automatically enables prefix caching.
### Optimized P/D disaggregation deployment
For optimal P/D disaggregation deployment, we automatically set the decode `all2all_backend` to `deepep_low_latency` and the prefill `all2all_backend` to `deepep_high_throughput`. We currently don't support customizing all2all backends for P/D disaggragation out of the box. You can do this by overriding the slurm template only.
For KV cache transfer, we utilize the NIXL connector. This is the default and only currently supported connector. We aim to support more advanced options, such as D->P transfer, or Mooncake Connector in the future.
For configuring various knobs with environment variables, we enable you to configure prefill and decode environment variables separately. This is useful if you want to configure different environment variables for the prefill and decode stages.
```toml
[inference.deployment]
type = "disaggregated"
prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
decode_env_overrides = {"VLLM_DEEP_GEMM_WARMUP"="skip"}
```
### Other vLLM features
We support various other vLLM features. Some of those, such as `enable_dbo`, `enable_eplb` are exposed as a top-level config fields. For those that are not, you can configure them by setting `inference.vllm_extra` to the desired value.
```toml
[inference.vllm_extra]
headless = true
```
### Router Replay
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.enable_return_routed_experts = true`.
```toml
[trainer]
enable_router_replay = true # this will also auto-set the inference.enable_return_routed_experts = true
[inference]
enable_return_routed_experts = true
```
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend increasing `orchestrator.*.env.num_workers` to allow for more parallelization on the verifiers side.
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
-308
View File
@@ -1,308 +0,0 @@
# Kubernetes
This guide covers deploying PRIME-RL training infrastructure on Kubernetes clusters using the provided Helm chart.
## Prerequisites
- Kubernetes cluster with GPU nodes
- [NVIDIA GPU Operator](https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/getting-started.html) installed
- [Helm 3.x](https://helm.sh/docs/intro/install/) installed
- Storage class that supports `ReadWriteMany` (e.g., NFS, CephFS, or cloud provider storage)
### Verify Prerequisites
```bash
# Check Helm installation
helm version
# Check GPU operator
kubectl get pods -n gpu-operator
# Check available storage classes
kubectl get storageclass
```
## Quick Start
### 1. Deploy
```bash
# Deploy with a release name
helm install my-exp ./k8s/prime-rl -f ./k8s/prime-rl/examples/reverse-text.yaml
# Or with defaults (no example-specific config)
helm install my-exp ./k8s/prime-rl --set trainer.replicas=3 --set inference.replicas=2
```
### 2. Verify deployment
```bash
# Check pod status
kubectl get pods -l app.kubernetes.io/instance=my-exp
# Should show 3 pods:
# my-exp-orchestrator-0
# my-exp-inference-0
# my-exp-trainer-0
```
### 3. Run training
```bash
# Exec into trainer
kubectl exec -it my-exp-trainer-0 -- bash
# Inside the pod, run training
cd /data
uv run trainer @ /app/examples/reverse_text/configs/train.toml
```
### 4. Monitor progress
```bash
# Get logs
kubectl logs my-exp-trainer-0
# Follow logs in real-time
kubectl logs -f my-exp-trainer-0
```
## Available Examples
The chart includes pre-configured values for each example:
### reverse-text (Small - 1 GPU)
```bash
helm install my-exp ./k8s/prime-rl -f ./k8s/prime-rl/examples/reverse-text.yaml
```
- Model: Qwen3-0.6B
- GPUs: 1 per component
- Runs on consumer GPUs (RTX 3090/4090)
- **Note:** You can use any release name - the chart automatically configures service URLs
## Configuration
### Storage Configuration
By default, the chart creates a 1TB PVC with NFS storage. To customize:
```yaml
# custom-values.yaml
storage:
storageClassName: my-storage-class
size: 500Gi
```
Deploy with custom storage:
```bash
helm install my-release ./k8s/prime-rl -f custom-values.yaml
```
### GPU Configuration
Adjust GPU count per component:
```yaml
# custom-gpu.yaml
inference:
gpu:
count: 4 # Use 4 GPUs for inference
trainer:
gpu:
count: 2 # Use 2 GPUs for training
```
### Resource Limits
Customize memory and CPU:
```yaml
# custom-resources.yaml
trainer:
resources:
requests:
memory: "64Gi"
cpu: "16"
limits:
memory: "128Gi"
cpu: "32"
```
### Secrets (Optional)
For W&B and HuggingFace authentication:
```bash
# Create secret
kubectl create secret generic prime-rl-secrets \
--from-literal=wandb-api-key=YOUR_WANDB_KEY \
--from-literal=hf-token=YOUR_HF_TOKEN
# Enable in values
helm install my-release ./k8s/prime-rl \
--set config.secrets.enabled=true \
--set config.secrets.name=prime-rl-secrets
```
## Common Operations
### Deploy a new experiment
```bash
# With example config
helm install my-exp ./k8s/prime-rl -f ./k8s/prime-rl/examples/reverse-text.yaml
# With custom settings
helm install my-exp ./k8s/prime-rl --set trainer.replicas=10 --set inference.replicas=5
```
### Exec into pods
```bash
# Exec into trainer-0
kubectl exec -it my-exp-trainer-0 -- bash
# Exec into specific trainer pod
kubectl exec -it my-exp-trainer-3 -- bash
# Exec into inference
kubectl exec -it my-exp-inference-0 -- bash
```
### View logs
```bash
# Get logs from trainer-0
kubectl logs my-exp-trainer-0
# Follow logs in real-time
kubectl logs -f my-exp-trainer-2
# Get logs from all trainers
kubectl logs -l app.kubernetes.io/instance=my-exp,role=trainer
```
### List all pods
```bash
# List pods for specific experiment
kubectl get pods -l app.kubernetes.io/instance=my-exp
# List all prime-rl pods
kubectl get pods -l app=prime-rl
```
## Architecture
### Components
The chart deploys three main components (all using StatefulSets):
1. **Orchestrator** (StatefulSet) - Coordinates training workflow
- Always 1 replica: `prime-rl-orchestrator-0`
- No GPU required
- Communicates with trainer and inference
2. **Inference** (StatefulSet) - Runs vLLM inference server
- Scalable replicas with stable pod names: `prime-rl-inference-0`, `prime-rl-inference-1`, ...
- Each pod gets predictable DNS: `prime-rl-inference-0.prime-rl-inference-headless.default.svc.cluster.local`
- Requires GPU(s)
- Serves model predictions
3. **Trainer** (StatefulSet) - Runs SFT or RL training
- Scalable replicas with stable pod names: `prime-rl-trainer-0`, `prime-rl-trainer-1`, ...
- Each pod gets predictable DNS: `prime-rl-trainer-0.prime-rl-trainer-headless.default.svc.cluster.local`
- Requires GPU(s)
- Updates model weights on shared storage
**Why StatefulSets for all components?**
- **Consistent naming**: All pods have predictable names (`orchestrator-0`, `trainer-0`, `trainer-1`, ...)
- **Stable networking**: Each pod gets its own DNS hostname via headless service
- **Required for distributed training**: PyTorch/vLLM need to discover peers by stable hostname
- **Clean naming**: No random pod suffixes, easier to identify and debug
### Shared Storage
All components mount the same PVC at `/data` for:
- Model checkpoint sharing
- Training data
- Experiment outputs
This is **required** for coordinating weight updates between trainer and inference.
## Environment Variables
Each pod has these K8s environment variables set:
- `$POD_NAME` - Full pod name (e.g., `my-exp-trainer-3`)
- `$POD_IP` - Pod IP address
- `$STATEFUL_REPLICAS` - Total number of replicas for that component
- `$HEADLESS_SERVICE` - DNS name for peer discovery (e.g., `my-exp-trainer-headless.default.svc.cluster.local`)
- `$INFERENCE_URL` - Full URL to the first inference pod (available in orchestrator and trainer pods)
For distributed training, extract the rank from the pod name:
```bash
# Extract ordinal from pod name
RANK=$(echo $POD_NAME | grep -o '[0-9]*$') # e.g., "my-exp-trainer-3" -> "3"
# Use in torchrun
torchrun \
--nnodes=$STATEFUL_REPLICAS \
--node-rank=$RANK \
--nproc-per-node=8 \
--rdzv-endpoint=my-exp-trainer-0.$HEADLESS_SERVICE:29501 \
src/prime_rl/trainer/sft/train.py @ configs/train.toml
```
## Troubleshooting
### Can't access shared storage
Verify PVC is bound:
```bash
kubectl get pvc prime-rl-shared-data
# STATUS should be "Bound"
```
Check mount inside pod:
```bash
kubectl exec -it prime-rl-trainer-xxx -- df -h /data
```
### Pod stuck in Pending
Check if GPU resources are available:
```bash
kubectl describe pod my-exp-trainer-0
```
Look for events like `Insufficient nvidia.com/gpu`.
### Inference server not responding
Check if the inference pod is ready:
```bash
kubectl get pods -l role=inference
kubectl logs my-exp-inference-0
```
## Uninstalling
```bash
# Remove the Helm release
helm uninstall my-exp
# Delete PVC (data will be lost!)
kubectl delete pvc prime-rl-shared-data
```
-86
View File
@@ -1,86 +0,0 @@
# Logging
prime-rl uses [loguru](https://loguru.readthedocs.io/en/stable/) for logging with a global logger pattern. All logs are captured at the deployment level (stdout/stderr redirection for local, `tee` for SLURM) under `{output_dir}/logs/`. For RL training, we recommend streaming logs into tmux panes (as set up by `tmux.sh`).
## Logger Architecture
### `setup_logger` and `get_logger`
We use a **singleton pattern** with a module-level global logger instance (`_LOGGER`).
```python
from prime_rl.utils.logger import setup_logger, get_logger
# At entrypoint - call ONCE
logger = setup_logger("info")
# Anywhere else in codebase
logger = get_logger()
logger.info("Hello world")
```
**How it works:**
1. **`get_logger()`** - Returns the global logger instance. Always works — if `setup_logger` hasn't been called yet, it initializes a default logger automatically. Safe to call from any module at any time.
2. **`setup_logger(log_level)`** - Configures (or reconfigures) the global logger:
- Creates an isolated loguru `Logger` instance (not the default `loguru.logger`) to prevent third-party code from hijacking our logs
- Adds a stdout handler with colorized output (or JSON output if `json_logging=True`)
- Can be called multiple times — cleans up the previous logger before creating a new one
3. **`reset_logger()`** - Resets the global logger to `None`:
- Used in subprocesses that inherit parent state (e.g., env workers)
- Used in tests between test cases
## Log File Structure
Logs are captured at the deployment level — the entrypoint redirects subprocess stdout/stderr to files (local) or `tee` captures them (SLURM). The structure is consistent across deployment types: `logs/trainer.log` and `logs/inference.log` always exist, regardless of whether the run is local or multi-node SLURM.
### Local (single node)
```
{output_dir}/logs/
├── trainer.log # trainer stdout (rank 0 only)
├── orchestrator.log # orchestrator stdout
├── inference.log # vLLM inference server stdout
├── trainer/
│ └── torchrun/ # per-rank stdout/stderr (all ranks)
└── envs/
├── train/{env_name}/
│ ├── env_server.log
│ └── env_worker_{id}.log
└── eval/{env_name}/
└── ...
```
### SLURM multi-node
```
{output_dir}/logs/
├── trainer.log -> trainer/node_0.log (symlink)
├── inference.log -> inference/node_0.log (symlink)
├── orchestrator.log # orchestrator stdout
├── trainer/
│ ├── node_0.log # per-node trainer output (rank 0 only)
│ ├── node_1.log
│ └── torchrun/ # per-rank stdout/stderr (all ranks)
├── inference/
│ ├── node_0.log # per-node inference output
│ ├── node_1.log
│ └── router_0.log # vllm-router per replica
└── envs/
└── ...
```
Environment logs live under `logs/envs/train/{env_name}/` and `logs/envs/eval/{env_name}/`. Env log verbosity is controlled by `orchestrator.log.vf_level`.
Only rank 0 output is shown in `trainer.log`. Per-rank logs from all ranks are available under `logs/trainer/torchrun/{rdzv_id}/attempt_0/{rank}/{stdout,stderr}.log`, written by torchrun's `--log-dir`.
## tmux helper (`scripts/tmux.sh`)
`scripts/tmux.sh` sets up a tmux session for RL runs with **four panes**:
- **Trainer**: follows `{output_dir}/logs/trainer.log`
- **Orchestrator**: follows `{output_dir}/logs/orchestrator.log`
- **Envs**: follows `{output_dir}/logs/envs/*/*/*.log`
- **Inference**: follows `{output_dir}/logs/inference.log`
-132
View File
@@ -1,132 +0,0 @@
# Reducing memory usage
While most of our parallelism techniques in prime-rl are designed to scale training up (FSDP, EP, CP, ...), we also provide many tools to scale training down that allow training large MoE models on a limited amount of GPUs.
These techniques target the trainer part of prime-rl.
## TLDR: config to use for maximum memory usage reduction with correct throughput
```toml
[trainer.model]
impl = "custom"
attn = "flash_attention_2"
fused_lm_head_token_chunk_size = 1024
ep = 8
cp = 2
optim_cpu_offload = true
[trainer.model.compile]
[trainer.model.ac]
freq = 1
[trainer.model.ac_offloading]
max_inflight_activations = 1
```
## Activation checkpointing
Activation checkpointing discards intermediate activations during the forward pass and recomputes them during the backward pass, trading compute for memory.
To enable it, use:
```toml
[trainer.model.ac]
freq = 1
```
`freq` controls how often layers are checkpointed: every `freq` layers. Lower values yield lower memory usage (e.g. `freq = 1` checkpoints every layer).
## Activation offloading
Activation offloading offloads the activations to CPU to reduce the memory usage of the trainer. It can be used in combination with activation checkpointing.
To enable it, use:
```toml
[trainer.model.ac]
freq = 1
[trainer.model.ac_offloading]
max_inflight_activations = 5
```
## Chunk loss
Chunk loss splits the loss computation into smaller chunks to reduce the memory usage of the trainer.
To enable it, use:
```toml
[trainer.model]
fused_lm_head_token_chunk_size = auto
```
## Expert parallelism
While expert parallelism splits the weights of the experts across all GPUs like FSDP, using EP still reduces memory usage by reducing the communication size and therefore the FSDP buffer.
EP is only available for models with MoE layers using the custom model implementation.
```
[trainer.model]
impl = "custom"
ep = 8
```
## Context parallelism
Context parallelism splits the context into smaller chunks to reduce the memory usage of the activations. We don't advise using CP across multiple nodes (i.e., increasing CP beyond 8).
CP is only available for certain models and only with the custom model implementation.
```
[trainer.model]
impl = "custom"
cp = 2
```
We recommend CP 2 or CP 4 for most 128K sequence length training runs. Can be pushed to 8.
## torch compile
Enabling torch.compile can reduce the memory usage for certain model architectures, especially MoE with the custom model implementation.
```
[trainer.model.compile]
```
## CPU Optimizer offloading
Offloading the optimizer states to CPU can reduce the memory usage of the trainer significantly, especially at low GPU counts where the optimizer states take a lot of memory as they won't be sharded enough.
In RL, in contrast with pretraining, we end up with many gradient accumulation steps, so the cost of offloading the optimizer states is not as high as in pretraining, and indeed barely noticeable.
```
[trainer.optim]
optim_cpu_offload = true
```
## :warning: FSDP CPU offloading
FSDP CPU offloading offloads the parameters, gradients, and optimizer states to CPU to reduce the memory usage of the trainer.
This will make training significantly slower and is not recommended most of the time.
```
[trainer.model]
fsdp_cpu_offload = true
```
## :warning: Lora training
LoRA training significantly reduces the memory usage of the trainer at the cost of smaller gradient updates.
```
[trainer.model.lora]
rank = 8
```
-55
View File
@@ -1,55 +0,0 @@
# Metrics
## W&B
For most runs we recommend logging metrics to [W&B](https://wandb.ai). Before enabling W&B, make sure that you have an account and are logged in.
```bash
uv run wandb login
# Or set `export WANDB_API_KEY=...`
```
### SFT
Logging to W&B is disabled by default. Enable the default configuration with `--wandb`
```bash
uv run sft ... --wandb
```
This will log to the `prime-rl` project with a random run name. You can specify which project and name to log to
```bash
uv run sft ... --wandb.project my-project --wandb.name my-run
```
The same settings also work for multi-node training with `torchrun`. Note, that we only log global metrics from the master rank (e.g. the all-reduced loss)
```bash
uv run torchrun --nproc-per-node 8 ... --wandb
```
### RL
For RL training, both the trainer and orchestrator log to W&B as separate runs. Again, logging to W&B is disabled by default. Enable the default configuration with `--wandb`
```bash
uv run rl ... --wandb
```
This will log to the `prime-rl` project with a random run name. The trainer run is suffixed with `-trainer` and the orchestrator run is suffixed with `-orchestrator`. You can specify which project and name to log to using the same flags as for SFT.
```bash
uv run rl ... --wandb.project my-project --wandb.name my-run
```
For the RL trainer, we support logging samples (e.g. prompt, completion, reward, advantage for selected rollouts) and distributions (e.g. reward, advantage, entropy distributions) as W&B tables using the `wandb.log-extras` subconfig. If W&B is setup, this is enabled by default and will log for the RL trainer and orchestrator every 10 steps.
You can configure this on the trainer and orchestrator separately. For example, to only log samples on the orchestrator every 50 steps, but not distribution on either
```bash
uv run rl ... \
--no-trainer.wandb.log-extras.distributions \
--orchestrator.wandb.log-extras.interval 50
```
+9 -13
View File
@@ -4,19 +4,15 @@
{
"group": "PRIME-RL",
"pages": [
"index",
"entrypoints",
"configs",
"environments",
"async",
"logging",
"multi_run_manager",
"checkpointing",
"benchmarking",
"deployment",
"kubernetes",
"troubleshooting"
"overview",
"configuration",
"training",
"inference",
"scaling",
"algorithms",
"advanced",
"development"
]
}
]
}
}
-244
View File
@@ -1,244 +0,0 @@
# MultiRunManager
The `MultiRunManager` object is a global singleton that manages the parameters and components for multiple concurrent training runs within a single trainer process.
This allows multiple orchestrator deployments to share the same trainer.
When `max_concurrent_runs > 1`, the trainer can train multiple runs in parallel. Each run:
- Has its own LoRA adapter parameters
- Has its own optimizer and scheduler
- Saves its own checkpoints
- Tracks its own training progress (step, tokens, samples)
- Loads its own orchestrator configuration
The `MultiRunManager` object provides:
- **Bidirectional mapping** between run IDs (e.g., `run_abc123`) and run indices (0, 1, 2, ...)
- **Progress tracking** per run (step count, total tokens, total samples)
- **Configuration management** for orchestrator configs
- **Distributed synchronization** across ranks via the PyTorch distributed store
- **LoRA module registration** for multi-adapter parameter management
- **Creation hooks** for initializing per-run resources (optimizers, schedulers)
- **Run eviction** for removing runs that are misbehaving
## **Initialization and run discovery**
The `MultiRunManager` singleton is set up at the start of training:
```python
from prime_rl.trainer.runs import setup_multi_run_manager, get_multi_run_manager
# Initialize with output directory and max concurrent runs
setup_multi_run_manager(output_dir=Path("outputs/my-experiment"), max_runs=4)
# Get the singleton instance anywhere in the codebase
multi_run_manager = get_multi_run_manager()
```
Each run's directory follows this structure:
```
{output_dir}/
├── run_abc123/
│ ├── control/
│ │ ├── orch.toml # Orchestrator configuration
│ │ ├── config_validation_error.txt # Config validation errors (if any)
│ │ └── evicted.txt # Eviction reason (if evicted)
│ ├── checkpoints/
│ │ └── step_100/ # Orchestrator checkpoints
│ ├── rollouts/
│ │ └── step_100/ # Rollouts
│ └── broadcast/
│ └── step_100/ # Broadcasted weights for inference
├── run_def456/
│ └── ...
└── ...
```
Runs are discovered by scanning the output directory for the pattern `run_*`. Each run must contain a valid orchestrator config at `{run_dir}/control/orch.toml` before they are added to the active runs otherwise they are ignored. When the maximum number of runs is reached, new `run_*` directories will not be picked up until old ones are deleted.
```python
# Master rank scans for new/deleted runs
multi_run_manager.discover_runs()
# All ranks synchronize state (must be called after discover_runs)
multi_run_manager.synchronize_state()
```
The `discover_runs()` method (master only):
1. Scans the output directory for `run_*` directories
2. Filters out evicted runs (those with `control/evicted.txt`)
3. Detects new runs and deleted runs
4. Calls `forgotten_hook` for deleted runs (master only)
5. Loads and validates the orchestrator config for each new run
6. Updates internal mappings and data structures
7. Calls `discovered_hook` for new runs (master only)
The `synchronize_state()` method (all ranks):
1. Master broadcasts run state to all ranks via the distributed store
2. Non-master ranks catch up by calling internal `_delete_run_data` / `_create_run_data`
3. All ranks execute `deletion_hook` for deleted runs
4. All ranks execute `creation_hook` for new runs (e.g., optimizer setup, LoRA parameter reset)
## Run Eviction
The master proc on the trainer can evict a run using the `evict_run(idx: int, reason: str)` method.
This is useful when the trainer detects an issue with a run that requires it to be stopped (e.g., invalid data, resource constraints, or policy violations).
```python
# Evict a run by its index (master only)
multi_run_manager.evict_run(idx=0, reason="Run exceeded memory limits")
```
The `evict_run()` method (master only):
1. Writes the eviction reason to `{run_dir}/control/evicted.txt`
2. Logs a warning with the eviction details
3. The run is **not** immediately removed from the manager's data structures
The eviction takes effect through two mechanisms:
**On the trainer side:**
- The next `discover_runs()` call will filter out the evicted run (it checks for `evicted.txt`)
- The run will then be treated as deleted, triggering forgotten/deletion hooks
- The run index is returned to the unused pool
**On the orchestrator side:**
- The orchestrator checks for `evicted.txt` at the start of each iteration in its main loop
- If found, it raises a `RuntimeError` with the eviction reason, causing the orchestrator to exit
- This surfaces the eviction reason to the user
- The orchestrator also self-evicts by writing `evicted.txt` if a training batch has no learning signal (all rollouts filtered out) on `MAX_EMPTY_BATCH_ATTEMPTS` (3) consecutive attempts
## LoRA Module Registration
LoRA modules register themselves with `MultiRunManager` for parameter management:
```python
# In apply_lora_to_model()
lora_module = MultiLoRALinear(
base_layer=base_module,
rank=config.rank,
n_adapters=get_multi_run_manager().max_runs,
...
)
lora_module.register_with_runs(get_multi_run_manager(), module_name)
```
The `MultiRunManager` object then exposes:
```python
# Get parameters for a specific run (used by optimizer creation)
multi_run_manager.get_named_parameters_for_run(idx)
# Get state dict for a specific run (used by weight broadcast)
multi_run_manager.get_state_dict_for_run(idx)
# Reset parameters for a new run
multi_run_manager.reset_run_parameters(idx)
```
## Hooks
The `MultiRunManager` object supports several types of hooks for different lifecycle events.
Deletion hooks are always called before creation hooks.
```mermaid
flowchart TD
subgraph master["Rank 0 (Master)"]
discover["discover_runs()"]
forgotten["forgotten_hooks"]
validation["config_validation_hooks"]
discovered["discovered_hooks"]
discover --> forgotten
forgotten --> validation
validation --> discovered
discovered --> discover
end
subgraph rank1["Rank 1"]
wait1["waiting..."]
end
subgraph rankN["Rank N"]
waitN["waiting..."]
end
discovered --> barrier
wait1 --> barrier
waitN --> barrier
barrier[["synchronize_state()"]]
barrier --> deletion["deletion_hooks"]
deletion --> creation["creation_hooks"]
style barrier fill:#fff9c4
```
### Hook Registration
```python
# These hooks are only called on the master as only master uses `discover_runs()`
# These hooks are thus only relevant to master only components (packer)
multi_run_manager.register_discovered_hook(callback)
multi_run_manager.register_forgotten_hook(callback)
# These hooks are executed by all ranks in the order they were added during `synchronize_state()`
# This ensures DTensor creations and other distributed operations happen together
# Calling torch.dist.barrier() in a hook here should work
multi_run_manager.register_creation_hook(callback)
multi_run_manager.register_deletion_hook(callback)
# These hooks validate the orchestrator config when runs are discovered:
multi_run_manager.register_config_validation_hook(callback)
```
The callback signatures:
```python
def discovered_callback(idx: int, run_id: str, config: OrchestratorConfig) -> None:
"""Called when a new run is discovered (master only).
Args:
idx: The run's index (0 to max_runs-1)
run_id: The run's ID (e.g., "run_abc123")
config: The orchestrator config for the run
"""
# Example: Set the scaling factor for the run
multi_run_manager.scaling_factors[idx] = config.model.lora.alpha / config.model.lora.rank
def forgotten_callback(idx: int, run_id: str) -> None:
"""Called when a run is forgotten/removed (master only).
Args:
idx: The run's index (0 to max_runs-1)
run_id: The run's ID (e.g., "run_abc123")
"""
pass
def callback(idx: int, run_id: str) -> None:
"""Called when a run is created/deleted.
Args:
idx: The run's index (0 to max_runs-1)
run_id: The run's ID (e.g., "run_abc123")
"""
pass
def config_validation_callback(config: OrchestratorConfig) -> tuple[bool, str]:
"""Validate an orchestrator config.
Args:
config: The orchestrator config to validate
Returns:
(is_valid, error_message): If invalid, error_message is written to config dir
"""
return True, ""
```
-62
View File
@@ -1,62 +0,0 @@
# Multimodal (VLM) Support
Prime-RL supports training vision-language models (VLMs) like Qwen3-VL.
## VLM Configuration
### Supported Models
The built-in registry supports these model families out of the box:
| Model Family | model_type | Vision Encoder | Language Model |
|-------------|------------|---------------|----------------|
| Qwen3-VL | `qwen3_vl` | `model.visual` | `model.language_model` |
| Qwen3.5 | `qwen3_5` | `model.visual` | `model.language_model` |
| Qwen3.5-MoE | `qwen3_5_moe` | `model.visual` | `model.language_model` |
Enable VLM mode by adding a `[model.vlm]` section. Both fields are required — they tell prime-rl where the vision encoder and language model live on the model object:
```toml
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
```
For the registered models in the table above, use the attrs shown there. For custom VLMs, check your model's structure with `model.named_children()`.
Both fields are dotted attribute paths resolved on the loaded model. A bad path raises a `ValueError` immediately — there are no silent fallbacks.
The weight key prefix for NCCL broadcasting is derived automatically as `{language_model_attr}.layers.`.
To add permanent support for a new model family, add an entry to `VLM_REGISTRY` in `src/prime_rl/utils/vlm.py`.
## Current Limitations
- **Vision encoder is frozen by default**: The vision encoder is frozen during training by default. Set `freeze_vision_encoder = false` in `[model.vlm]` to make it trainable. When unfrozen, the vision encoder is FSDP-sharded per-block for proper gradient flow. Note: this has no effect when using LoRA.
- **No multimodal-safe truncation**: Token sequences are truncated to `seq_len`, but `pixel_values` and `image_grid_thw` are passed through unchanged. If a multimodal sample exceeds `seq_len`, image tokens can be dropped while image tensors still describe the full set of images. Ensure `seq_len` covers your longest VLM samples.
- **Optimization dtype must be bfloat16**: Set `optimization_dtype = "bfloat16"` and `reduce_dtype = "bfloat16"` in your trainer config.
- **Higher KL mismatch with multi-image inputs**: VLM training exhibits higher KL mismatch compared to text-only, especially with multiple images.
- **Images are not logged**: The images the VLM sees during training are not logged to monitors.
## How Multi-Turn VLM RL Training Works
VLM training uses the same `interleave_rollout` path as text-only models. Multi-turn trajectory steps are merged into a single training sample wherever the extension property holds.
Images are handled via a `VLMImageCache` built once per batch:
1. **Extract**: Base64 images are decoded from trajectory step prompts into PIL images.
2. **Preprocess**: Images are processed through the HuggingFace image processor, producing `pixel_values` and `image_grid_thw`.
3. **Attach**: Each training sample receives the cumulative `pixel_values` up to its last merged step.
Each multimodal sample becomes its own micro-batch during training (no packing) since image tensor sizes vary.
## vLLM Configuration
`VLLM_WORKER_MULTIPROC_METHOD=spawn` is required for VLM inference. This is set automatically when using `uv run rl @ ...`, but if you start the vLLM server yourself, make sure this environment variable is set.
-117
View File
@@ -1,117 +0,0 @@
# On-Policy Distillation
On-policy distillation uses a teacher model to provide dense token-level feedback during RL training. The student generates rollouts, and the teacher's logprobs guide the student to stay close to stronger behavior while still learning from rewards.
For more details, see [On-Policy Distillation](https://thinkingmachines.ai/blog/on-policy-distillation/) by Thinking Machines.
## Quick Start
Add `num_teacher_gpus` to `[deployment]` and set `teacher_tau > 0`:
```toml
[deployment]
num_teacher_gpus = 2
[trainer.loss]
teacher_tau = 0.5
```
This automatically starts a teacher inference server using the same model as inference. To use a different teacher model:
```toml
[deployment]
num_teacher_gpus = 2
[teacher_inference.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[trainer.loss]
teacher_tau = 0.5
```
## Using an External Teacher Server
If the teacher is already running elsewhere:
```toml
[trainer.loss]
teacher_tau = 0.5
[orchestrator.teacher_model.client]
base_url = ["http://teacher-server:8000/v1"]
[orchestrator.teacher_model.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
```
## Pure Distillation (No Verification)
For agentic environments where verification is expensive (code execution, tool use, multi-turn interactions), you can skip verification entirely and use only the teacher signal:
```toml
[deployment]
num_teacher_gpus = 2
[trainer.loss]
teacher_tau = 1.0
adv_tau = 0.0 # Disable reward-based learning
[orchestrator.verification]
enabled = false # Skip expensive verification
```
This runs pure on-policy distillation: the student learns to match the teacher without needing any reward signal.
## SFT Distillation ("Hard Distillation") From Teacher Rollouts
Use this mode when you want to train from teacher-generated completions directly (hard distillation), without teacher token-level logprobs.
```toml
[trainer.loss]
type = "sft"
[orchestrator]
use_token_client = false
[orchestrator.teacher_rollout_model.client]
base_url = ["https://your-openai-compatible-endpoint/v1"]
skip_model_check = true
[orchestrator.teacher_rollout_model.model]
name = "teacher-model-name"
```
In this mode:
- Rollouts are generated from `orchestrator.teacher_rollout_model`
- The orchestrator uses text-level reconstruction with the student tokenizer
- The RL trainer optimizes masked NLL (`trainer.loss.type = "sft"`)
- Omit `[inference]` (no local inference server required)
### Image Input (VLM) Support
Yes, image input is supported in SFT/hard-distillation mode when the student model is multimodal (VLM).
- Prompts can include OpenAI-style image items in `message.content`, e.g. `{"type": "image_url", "image_url": {"url": "data:image/..."}}`
- The orchestrator extracts and preprocesses images from trajectory prompts and attaches `pixel_values`/`image_grid_thw` to training samples
- No teacher token IDs/logprobs are required; reconstruction still happens from messages
Notes:
- This path currently expects `data:image/...` payloads in message content
- The teacher rollout endpoint still needs to be able to handle the same multimodal prompts during generation
Reference configs:
- `configs/alphabet_sort/sft_distill_hard_qwen4b_lora_prime_teacher.toml`
- `examples/alphabet_sort/sft_distill_hard.toml`
## Parameters
| Parameter | Default | Description |
|-----------|---------|-------------|
| `deployment.num_teacher_gpus` | `None` | Number of GPUs for teacher server. Auto-starts server when set. |
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Set `> 0` to enable. |
| `trainer.loss.adv_tau` | `1.0` | Weight for RL advantage signal. Set `0` for pure distillation. |
| `orchestrator.verification.enabled` | `true` | Enable/disable verification. Set to `false` for pure distillation with `adv_tau = 0`. |
## Monitoring
The `teacher_kl` metric shows the KL divergence from teacher to student. Lower values mean the student is closer to the teacher.
+45
View File
@@ -0,0 +1,45 @@
# Overview
`prime-rl` is a framework for large-scale, asynchronous reinforcement learning of large language models. It is designed to be easy to use and hackable, yet capable of training 1T+-parameter MoE models on 1000+ GPU clusters.
## Architecture
A `prime-rl` RL run is three cooperating processes:
![Architecture](assets/architecture.png)
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). We are trying to stay up-to-date with the latest vLLM features, you can read more about the supported features and deployment options in the dedicated [inference documentation](inference.md).
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses the filesystem (or NCCL for synchronous setups). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
## Installation
```bash
curl -sSL https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/main/scripts/install.sh | bash
```
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`research-environments`](https://github.com/PrimeIntellect-ai/research-environments) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
You need at least one NVIDIA GPU (RTX 3090/4090/5090, A100, H100, H200, or B200). Single-GPU runs are supported for debugging; production RL is typically 1× inference node + 1+ trainer nodes.
## Quick Run
Train an SFT-warmed `Qwen3-0.6B` on the `reverse-text` task — the env is bundled with the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) submodule so no separate install is needed. This config ships in the repo and runs on two GPUs (one for inference, one for the trainer):
```bash
uv run rl @ examples/reverse_text/rl.toml
```
The `rl` entrypoint reads `examples/reverse_text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into `outputs/logs/{trainer,orchestrator,inference}.log`. Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes and final HF-compatible weights land at `outputs/weights/step_20`.
## Documentation
- **[Configuration](configuration.md)** — TOML composition, CLI overrides, dry-run.
- **[Training](training.md)** — Launch and observe RL and SFT runs.
- **[Inference](inference.md)** — vLLM-backed server (or fleet) holding the current policy.
- **[Scaling](scaling.md)** — Single-GPU through multi-node clusters via FSDP / EP / CP and SLURM.
- **[Algorithms](algorithms.md)** — Async semantics, loss / advantage / filter plugins, trajectory merging.
- **[Advanced](advanced.md)** — Custom modeling, multimodal, LoRA, multi-tenant, P/D inference.
- **[Development](development.md)** — Test suite, pre-commit hooks, adding a new model.
-48
View File
@@ -1,48 +0,0 @@
# Platform Monitoring
Use `orchestrator.prime_monitor` to register a run on the Prime Intellect platform and stream training metrics, samples, and distributions.
> **Internal-only for now:** external run registration is currently only enabled for internal / allowlisted teams.
## Prerequisites
You need a Prime API key with `rft:write` scope.
Use the CLI:
```bash
prime login
```
Or set an environment variable directly:
```bash
export PRIME_API_KEY=pit_...
```
## Minimal config
```toml
[orchestrator.prime_monitor]
run_name = "my-experiment"
```
You can also override from the CLI:
```bash
uv run rl @ config.toml --orchestrator.prime_monitor.run_name "my-experiment"
```
## Troubleshooting
### `API key not found`
Set the env var from `api_key_var` or run:
```bash
prime login
```
### `External training runs are not enabled for this team`
Your team is not allowlisted yet. This feature is currently internal-only.
+275
View File
@@ -0,0 +1,275 @@
# Scaling
This page covers how to scale `prime-rl` from a single GPU to a 1000-GPU cluster: single-node and multi-node deployments, FSDP / expert parallelism / context parallelism, and throughput benchmarking. See [Training](training.md) for detailed documentation of the trainer configuration and [Inference](inference.md) for the inference configuration.
## Table of Contents
- [Single-Node vs. Multi-Node Deployment](#single-node-vs-multi-node-deployment)
- [Single-Node](#single-node)
- [RL Placement](#rl-placement)
- [SFT and Torchrun](#sft-and-torchrun)
- [Multi-Node](#multi-node)
- [Parallelism Knobs](#parallelism-knobs)
- [FSDP](#fsdp)
- [Expert Parallelism](#expert-parallelism)
- [Context Parallelism](#context-parallelism)
- [Activation Checkpointing and Offloading](#activation-checkpointing-and-offloading)
- [Optimizer Offloading](#optimizer-offloading)
- [LM Head Chunking](#lm-head-chunking)
- [Memory-Tight Recipe](#memory-tight-recipe)
- [SLURM](#slurm)
- [Activation](#activation)
- [`[deployment]` Block](#deployment-block)
- [Examples](#examples)
- [Custom Templates](#custom-templates)
- [Benchmarking](#benchmarking)
## Single-Node vs. Multi-Node Deployment
The `rl`, `sft`, and `inference` entrypoints all accept a `[deployment]` block (`type = "single_node"` or `"multi_node"`) that picks how the trainer / orchestrator / inference processes are placed across hardware. **Single-node** runs locally; **multi-node** currently goes through [SLURM](#slurm) — the launcher writes an sbatch script that places inference replicas, the orchestrator, and the trainer with the right rendezvous endpoints, IPs, ports, and shared-filesystem paths wired in.
### Single-Node
#### RL Placement
`rl` defaults to 1 trainer GPU and 1 inference GPU. To give inference 6 GPUs with data parallelism and the trainer the remaining 2 on an 8-GPU node:
```bash
uv run rl @ rl.toml \
--deployment.num-infer-gpus 6 \
--deployment.num-train-gpus 2 \
--inference.parallel.dp 6
```
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next, teacher last. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
For quick A/B ablations on the same node, run two RL instances side-by-side in separate tmux sessions, each pinned to half the GPUs and a separate inference port:
```bash
# session 1, GPUs 0–1, default port 8000
bash scripts/tmux.sh -s exp1 -o outputs/exp1
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --output-dir outputs/exp1
# session 2, GPUs 2–3, port 8001
bash scripts/tmux.sh -s exp2 -o outputs/exp2
CUDA_VISIBLE_DEVICES=2,3 uv run rl @ rl.toml \
--inference.server.port 8001 \
--orchestrator.client.base-url http://localhost:8001/v1 \
--output-dir outputs/exp2
```
#### SFT and Torchrun
`uv run sft` handles distributed launch internally. To scale from 1 to N GPUs, set the deployment GPU count (or just let it pick up `WORLD_SIZE`). For non-default layouts, the manual equivalent is:
```bash
uv run torchrun \
--nproc-per-node 8 \
--local-ranks-filter 0 \
src/prime_rl/trainer/sft/train.py @ sft.toml
```
`--local-ranks-filter 0` keeps console output to rank 0 only; per-rank stdout/stderr is still captured in `<output_dir>/logs/trainer/torchrun/`.
### Multi-Node
Multi-node deployments (RL or SFT) are launched via [SLURM](#slurm) — set `[deployment] type = "multi_node"` plus the matching `[slurm]` block, and the launcher writes the sbatch script that places inference, orchestrator, and trainer across the requested nodes with the inter-process wiring set up correctly. See [SLURM § Examples](#examples) for full configs.
## Parallelism Knobs
### FSDP
FSDP2 is the default model sharding strategy. By default the trainer fully shards parameters, gradients, and optimizer state across the data-parallel mesh. Tweakable knobs:
| Knob | Effect |
|---|---|
| `trainer.model.dp_replicate` | Number of dimensions to **replicate** instead of shard. Set to 2 to run 2-way DP replication × FSDP sharding within each replica — useful for very large clusters where pure FSDP communication dominates. |
| `trainer.model.reshard_after_forward` | If `true` (default), parameters are resharded after the forward pass to free memory; the backward pass re-gathers. Set `false` to keep params resident — faster but more memory. |
| `trainer.model.fsdp_cpu_offload` | Offload params + grads + optimizer state to CPU. Big memory win, large throughput hit. |
| `trainer.model.optim_cpu_offload` | Offload only optimizer state. Mid-ground — small throughput cost, decent memory savings, especially at low GPU count. |
### Expert Parallelism
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
```toml
[trainer.model]
impl = "custom"
ep = 8 # EP degree; must divide num_experts
ep_comm_backend = "torch" # or "deepep"
```
`ep_comm_backend = "deepep"` uses DeepEP's custom dispatch/combine kernels for speed, with two extra knobs (`deepep_num_sms`, `deepep_token_chunk_size`) — tune on your hardware.
### Context Parallelism
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
```toml
[trainer.model]
impl = "custom"
attn = "flash_attention_2" # or fa3 / fa4
cp = 2 # CP degree
cp_style = "ulysses" # "ring"
```
### Activation Checkpointing and Offloading
| Knob | Memory ↓ | Throughput ↓ |
|---|---|---|
| `trainer.model.ac` | large | ~25% |
| `trainer.model.ac.mode = "selective"` | medium | small |
| `trainer.model.ac_offloading` | extra | a bit more |
Enable selective AC (custom impl only) for the best memory/throughput tradeoff:
```toml
[trainer.model.ac]
mode = "selective"
targets = ["norm", "attn_proj"] # see Reference for the full list per architecture
```
We reccomend also using `ac_offloading` and `ac_offloading.max_inflight_activations = 5` to further reduce the memory footprint in tradeoff for some throughput. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput:
```toml
[trainer.model.ac_offloading]
max_inflight_activations = 5
```
### Optimizer Offloading
Offloading optimizer states to CPU is a near-free memory win at low GPU counts:
```toml
[trainer.optim]
# any optimizer type
type = "adamw"
[trainer.model]
optim_cpu_offload = true
```
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training). Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
### LM Head Chunking
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization:
```toml
[trainer.model]
fused_lm_head_token_chunk_size = "auto" # picks 8192 for RL
# or explicit:
# fused_lm_head_token_chunk_size = 1024 # smaller = lower memory, more launches
# fused_lm_head_token_chunk_size = "disabled" # default; vanilla LM head
```
`auto` is a safe starting point for RL. Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. Only available with `model.impl = "custom"`, and currently RL-only — the SFT trainer rejects integer values.
## Memory-Tight Recipe
The kitchen-sink config for fitting large MoE on limited GPUs at acceptable throughput:
```toml
[trainer.model]
impl = "custom"
fused_lm_head_token_chunk_size = 1024
ep = 8
cp = 2
optim_cpu_offload = true
[trainer.model.compile]
[trainer.model.ac]
freq = 1
[trainer.model.ac_offloading]
max_inflight_activations = 1
```
Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
## SLURM
The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]` table is present — there's no separate entrypoint.
### Activation
A SLURM config is usually a thin overlay that adds `[slurm]` (and `[deployment]` for multi-node) on top of a base config. Configs are composed left-to-right via the `@` CLI syntax — see [Configuration § TOML Composition](configuration.md#toml-composition):
```toml
# my_slurm.toml
output_dir = "/shared/outputs/my-rl"
[slurm]
job_name = "my-rl-run"
```
Launch:
```bash
uv run rl @ base_rl.toml @ my_slurm.toml # submits via sbatch
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script + resolved config, exits
```
### `[deployment]` Block
`[deployment]` is a discriminated union picked by `type` — `single_node` or `multi_node` for RL/SFT, with an extra disaggregated variant for inference. RL multi-node:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 1
gpus_per_node = 8 # default
nodes_per_fsdp_group = 1 # optional — controls FSDP island size
```
SFT multi-node:
```toml
[deployment]
type = "multi_node"
num_nodes = 2
gpus_per_node = 8
```
### Examples
Full multi-node configs ship in [`examples/multinode/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/multinode):
- [`rl.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/multinode/rl.toml) — two-node RL run with NCCL weight broadcast on a 30B MoE student.
- [`sft.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/multinode/sft.toml) — two-node SFT against the same model.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), and the launcher prints one URL per node. Front the URLs with a router or point clients at any of them.
### Custom Templates
For unusual partitions, module loads, or environment setup, supply your own Jinja2 template:
```bash
uv run rl @ my_config.toml --slurm.template-path path/to/my_template.sbatch.j2
```
The default templates live under [`src/prime_rl/templates/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/src/prime_rl/templates) — copy one as a starting point.
## Benchmarking
Every entrypoint supports a `--bench` flag that runs a few warm-up + measurement steps with fake data and prints a rich-formatted throughput / MFU table:
```bash
# SFT trainer alone
uv run sft @ sft.toml --bench
uv run sft ... --data.type fake --data.length variable --bench # variable-length fake data
# RL trainer alone (no inference involved)
uv run trainer @ train.toml --data.fake --bench
# Inference alone — start the server normally, then bench the orchestrator
uv run inference @ infer.toml
uv run orchestrator @ orch.toml --bench
# Full RL stack (trainer with fake data, inference with real data from orchestrator)
uv run rl @ rl.toml --bench
```
Persist results with `--bench.output-json`. Use this to compare parallelism configs before committing a multi-day run.
-298
View File
@@ -1,298 +0,0 @@
# SLURM
The `rl`, `sft`, and `inference` entrypoints all have built-in SLURM support. Adding a `[slurm]` section to your config switches from local execution to SLURM job submission — no separate entrypoint needed.
## Quick Start
```bash
# Local run
uv run rl @ examples/reverse_text/rl.toml
# SLURM run (same entrypoint, just add [slurm] to the config)
uv run rl @ examples/reverse_text/slurm_rl.toml
```
The SLURM config is a thin overlay that inherits from a base config and adds `[slurm]` + `[deployment]` sections:
```toml
# examples/reverse_text/slurm_rl.toml
toml_files = ["rl.toml"]
output_dir = "outputs/reverse-text-rl"
[slurm]
job_name = "reverse-text-rl"
```
## How it works
When `[slurm]` is present, the entrypoint:
1. Resolves the full config
2. Renders a SLURM batch script from a Jinja2 template
3. Writes the script and resolved config to `{output_dir}/`
4. Submits via `sbatch` (or prints the script with `--slurm.dry-run`)
For **single-node** jobs, the entire config is dumped to a TOML file and the template simply runs `uv run rl @` or `uv run sft @` on the allocated node.
For **multi-node** jobs, sub-configs are written separately and `srun` dispatches processes across nodes.
## Configuration
### `[slurm]` — Job submission (shared between RL and SFT)
| Field | Description | Default |
|---|---|---|
| `job_name` | SLURM job name | `"prime-rl"` |
| `project_dir` | Path to the project root on the cluster | `"."` |
| `template_path` | Path to a custom Jinja2 template | auto-selected |
| `partition` | SLURM partition | `"cluster"` |
| `nodelist` | Comma-separated list of specific nodes to run on (`--nodelist`) | `None` |
| `exclude` | Comma-separated list of nodes to exclude (`--exclude`) | `None` |
| `account` | SLURM account to charge (`--account`) | `None` |
| `time` | Maximum wall time, e.g. `"24:00:00"` (`--time`) | `None` |
| `pre_run_command` | Shell command to run on head node after env setup, before starting the job (e.g. cleanup) | `None` |
### `[deployment]` — Node and GPU allocation
**RL** uses a discriminated union with `type = "single_node"` (default) or `type = "multi_node"`:
| Field | single_node | multi_node |
|---|---|---|
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
| `num_train_gpus` | Training GPUs | — |
| `num_infer_gpus` | Inference GPUs | — |
| `num_train_nodes` | — | Training nodes |
| `num_infer_nodes` | — | Inference nodes |
| `nodes_per_fsdp_group` | — | Nodes per FSDP island (optional) |
**SFT** follows the same pattern but only has training nodes:
| Field | single_node | multi_node |
|---|---|---|
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
| `num_gpus` | Number of GPUs (default: 1) | — |
| `num_nodes` | — | Training nodes (default: 2) |
| `nodes_per_fsdp_group` | — | Nodes per FSDP island (optional) |
**Inference** runs independent vLLM replicas per node:
| Field | single_node | multi_node |
|---|---|---|
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
| `num_nodes` | — | Number of inference nodes (default: 1) |
The SLURM template is auto-selected based on `deployment.type`. You can override it with `slurm.template_path`.
### Constraints
- `output_dir` should be explicitly set when using SLURM (defaults to `"outputs"`)
- Multi-node deployment requires `[slurm]` to be set
---
## RL Examples
### Single-node SLURM
The simplest case: run on a single allocated node. No `[deployment]` needed — defaults to `single_node`.
```toml
output_dir = "/shared/outputs/my-rl-run"
[slurm]
job_name = "my-rl-run"
```
### Multi-node SLURM (Hendrycks Math)
```toml
output_dir = "outputs/rl-math-moe"
max_steps = 500
seq_len = 2048
[slurm]
job_name = "hendrycks-math-rl-moe"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[weight_broadcast]
type = "nccl"
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
optim_cpu_offload = true
[trainer.model.ac_offloading]
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[orchestrator]
batch_size = 512
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
[inference.parallel]
tp = 4
dp = 2
```
See [`examples/hendrycks_math/rl.toml`](../examples/hendrycks_math/rl.toml) for the full example.
---
## SFT Examples
### Single-node SLURM
```toml
output_dir = "/shared/outputs/my-sft-run"
[slurm]
job_name = "my-sft-run"
```
### Multi-node SLURM (MoE SFT)
```toml
output_dir = "outputs/sft-moe-math"
max_steps = 500
[slurm]
job_name = "sft-moe-math"
[deployment]
type = "multi_node"
num_nodes = 2
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
impl = "custom"
attn = "flash_attention_3"
optim_cpu_offload = true
[model.ac_offloading]
max_inflight_activations = 5
[model.ac]
freq = 1
[data]
type = "sft"
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
subsets = ["default"]
splits = ["math"]
batch_size = 128
seq_len = 8192
```
See [`examples/hendrycks_math/sft.toml`](../examples/hendrycks_math/sft.toml) for the full example.
---
## Inference Examples
### Single-node SLURM
Run a vLLM server on a single allocated node:
```toml
output_dir = "/shared/outputs/my-inference"
[model]
name = "Qwen/Qwen3-8B"
[parallel]
tp = 8
[slurm]
job_name = "my-inference"
```
```bash
uv run inference @ inference_slurm.toml
```
### Multi-node SLURM
Each node runs an independent vLLM replica. TP and DP must fit within a single node — there is no cross-node parallelism.
```toml
output_dir = "/shared/outputs/my-inference"
[model]
name = "PrimeIntellect/INTELLECT-3-RL-600"
[parallel]
tp = 4
dp = 2
[deployment]
type = "multi_node"
num_nodes = 4
[slurm]
job_name = "my-inference"
```
After submission, the SLURM template prints the inference URLs for all nodes (one per node).
### Dry run
Use `dry_run = true` to generate the sbatch script without submitting:
```bash
uv run inference @ config.toml --dry-run true
```
---
## Custom SLURM Templates
The default templates handle standard setups with InfiniBand detection, environment setup, and `srun`-based process dispatch. For advanced use cases (custom partitions, account settings, module loads, etc.), provide your own Jinja2 template:
```bash
uv run rl @ my_config.toml --slurm.template-path path/to/my_template.sbatch.j2
```
See [`src/prime_rl/templates/`](../src/prime_rl/templates/) for the default templates as a starting point.
## Monitoring
After submission, logs are available at:
```bash
# All deployment types (trainer.log and inference.log are symlinks for multi-node)
tail -F {output_dir}/logs/trainer.log
tail -F {output_dir}/logs/orchestrator.log
tail -F {output_dir}/logs/inference.log
# Multi-node: per-node logs
tail -F {output_dir}/logs/trainer/node_*.log
tail -F {output_dir}/logs/inference/node_*.log
# Multi-node inference: per-replica router logs
tail -F {output_dir}/logs/inference/router_*.log
```
For convenience, a tmux launcher sets up a session with all log streams:
```bash
bash scripts/tmux.sh my-rl-job /shared/outputs/my-rl-job
```
-113
View File
@@ -1,113 +0,0 @@
# Testing MoE at Small Scale
When working on MoE architectures (GLM-4, Kimi, etc.), you can't iterate on a 100B+ parameter model locally. This guide shows how to create a small (~0.5B) MoE model with the same architecture, run SFT to warm it up, and run RL on it — all on 1-2 GPUs.
The goal isn't performance. It's catching bugs in modeling code, state dict conversions, and training pipeline integration before running at scale.
## Overview
1. **Create + verify** a mini model with random weights and check HF <-> PrimeRL roundtrip
2. **SFT** to give it a non-trivial distribution
3. **RL** on reverse-text to validate the full pipeline
## Prerequisites
- At least 1 GPU for steps 1-2, 2 GPUs for step 3 (RL)
- Architecture presets are defined in `scripts/mini_moe.py`
## Step 1: Create and verify the mini model
```bash
uv run python scripts/mini_moe.py --arch glm4_moe --output-dir ./mini-glm-moe
```
This creates a ~543M parameter GLM-4 MoE (1024 hidden, 24 layers, 8 experts) with random weights, copies the tokenizer from the original GLM-4 model, then verifies that:
- Logits match between HF and PrimeRL implementations (`convert_to_prime`)
- The HF -> PrimeRL -> HF roundtrip is lossless (`convert_to_hf`)
To re-run verification only (e.g. after a modeling code change):
```bash
uv run python scripts/mini_moe.py --arch glm4_moe --output-dir ./mini-glm-moe --verify-only
```
## Step 2: SFT warmup
Using the existing debug MoE SFT config with overrides for real data:
```bash
uv run sft @ configs/debug/moe/sft/train.toml \
--model.name ./mini-glm-moe \
--data.name PrimeIntellect/Reverse-Text-SFT \
--data.type null \
--max_steps 200 \
--optim.lr 1e-4 \
--ckpt.weights
```
This fine-tunes on [PrimeIntellect/Reverse-Text-SFT](https://huggingface.co/datasets/PrimeIntellect/Reverse-Text-SFT) for 200 steps. Loss should drop from ~12 to ~2.5. The model won't be coherent, but it will have a non-trivial distribution so KL divergence is meaningful during RL.
The latest weight checkpoint is saved under `outputs/weights/step_<N>`. You can verify the roundtrip on it:
```bash
uv run python scripts/mini_moe.py --arch glm4_moe --output-dir outputs/weights/step_200 --verify-only
```
A pre-built SFT'd model is available at [samsja/mini-glm-moe](https://huggingface.co/samsja/mini-glm-moe).
## Step 3: RL (reverse-text)
Requires 2 GPUs (one for inference, one for training).
```bash
uv run rl @ configs/ci/integration/rl/start.toml \
--model.name samsja/mini-glm-moe \
--trainer.model.impl custom \
--inference.gpu-memory-utilization 0.7 \
--inference.model.max-model-len 2048
```
Or to use the checkpoint from step 2:
```bash
uv run rl @ configs/ci/integration/rl/start.toml \
--model.name outputs/weights/step_200 \
--trainer.model.impl custom \
--inference.gpu-memory-utilization 0.7 \
--inference.model.max-model-len 2048
```
What to look for:
- **Training runs without crashing** — validates the full pipeline (inference server, orchestrator, trainer)
- **KL divergence is non-zero and finite** — confirms the reference model distribution is working
- **Loss is reasonable** — not NaN, not stuck at a constant value
Don't expect the reward to go up meaningfully in 20 steps on a random model.
## Adding a new architecture
To test a new MoE architecture (e.g., Kimi2.5):
1. Add modeling code under `src/prime_rl/trainer/models/<arch>/`
2. Add a preset to `scripts/mini_moe.py` with the config class, small dimensions, HF model class, PrimeRL model class, and tokenizer source
3. Run steps 1-3 above with `--arch <your_arch>`
The preset defines the small config:
```python
ARCH_PRESETS = {
"glm4_moe": {
"config_class": Glm4MoeConfig,
"config_kwargs": dict(
hidden_size=1024,
num_hidden_layers=24,
n_routed_experts=8,
# ...
),
"hf_model_class": HFGlm4MoeForCausalLM,
"prime_model_class": PrimeRLGlm4MoeForCausalLM,
"tokenizer_source": "THUDM/GLM-4-9B-0414",
},
# Add your new arch here
}
```

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