The off-policy drain (cancelling rollouts past max_off_policy_steps) ran via
on_new_version *after* the inference engines resumed from the weight-update
pause. In a NIXL P/D deployment this reliably crashed the decode engines.
Aborting a rollout cancels its /generate request; vLLM marks the request
FINISHED_ABORTED and frees it, recording it in the NIXL connector's
_reqs_not_processed set so the worker suppresses its in-flight KV-transfer
completion. That suppression only propagates to the workers while the engine is
stepping. Pausing with mode="keep" (PAUSED_ALL) skips step(), so KV transfers
that complete during the pause are flushed on the first step after resume — at
the same moment the drain fires its aborts. The abort frees the request before
its suppression reaches the worker, so the flushed completion hits
`assert req_id in self.requests` in the decode scheduler's
_update_from_kv_xfer_finished, killing the engine and cascading to every DP
rank via the gloo finish-state all-reduce.
With max_off_policy_steps=8 the first mass drop lands at the 9th weight update,
which is why the run always died at step 8/9.
Move the drain to a new on_version_pending observer hook that the watcher calls
*before* update_weights (before the pause), so the aborts are processed under
normal stepping and the connector's native cleanup completes before the engine
freezes. on_new_version still runs post-update for the orchestrator's dispatch
gate, which needs the live policy version.
Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(inference): strip routed_experts from chat-completions responses
routed_experts are consumed only via the serialized /generate (serving_tokens)
path used for router-replay training, which emits them as a {data, shape, start}
object the PD router merges. The stock chat-completions path encodes them as a
base64 np.save string instead, which the PD router rejects ("prefill routed_experts
must be an object with base64 data and shape") — failing every eval rollout, since
evals go through chat completions. enable_return_routed_experts is a server-wide
model-config flag with no per-request toggle, so strip the field on the chat path.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* chore: format routed experts chat patch
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Adds MultiNodeDeploymentConfig.orchestrator_on_inference (default False). When
False, the orchestrator launches on trainer rank 0 (unchanged behavior). When
True, it launches on the last inference node (a decode node) instead — useful
when trainer nodes are host-RAM-saturated (large CPU-offloaded optimizer state)
and the orchestrator's rollout buffer + env workers would otherwise exhaust
memory there; inference nodes keep weights/KV on GPU with ample free host RAM.
The orchestrator launch is now a single top-level block in multi_node_rl.sbatch.j2
gated on a flag-selected SLURM_PROCID (NUM_INFER_NODES for trainer rank 0, or
NUM_INFER_NODES-1 for the last inference node), so both placements share one code
path. No effect when num_infer_nodes == 0.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
The coordinator child spawns on the DP-rank-0 API server while every
engine-core rank on the node is importing and loading weights, so its
spawn-time re-import can exceed 30s under that CPU/IO contention (seen
on multi-node disaggregated GLM-5.1 launches). Patch _wait_for_zmq_addrs
with a configurable timeout via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT
(default 300s).
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
The DSA sparse-attention indexer runs its forward under torch.no_grad(), so its
params (wq_b, wk, k_norm, weights_proj) never receive a gradient. They were left
with requires_grad=True and handed to AdamW, which lazily creates per-param state
only on the first step where a grad exists -- so the indexer params stayed
stateless.
This breaks strict checkpoint resume. At save time DCP's _init_optim_state
returns early (optim.state already non-empty), so the stateless indexer params
are omitted from the saved optimizer state. At load time the optimizer is fresh,
so _init_optim_state runs a zero-grad step over every requires_grad param and
materializes exp_avg/exp_avg_sq/step for the indexer too. DCP then demands those
keys, the checkpoint doesn't have them, and load dies with:
RuntimeError: Missing key in checkpoint state_dict:
app.optimizers.state.model.layers.0.self_attn.indexer.wq_b.weight.step
With resume_step=-1 every restart re-picks the same checkpoint and crashes
identically -> crash-loop.
Fix:
- freeze_sparse_indexer(): set requires_grad=False on all Indexer params, called
unconditionally in setup_model (no-op for non-DSA models). The indexer is never
trainable anyway, so this only makes save/load state symmetric.
- _create_optimizer(): hand only trainable params to AdamW/SGD/SignSGD (Muon
already filtered internally), so frozen params carry no optimizer state.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(inference): restore usage block on /inference/v1/generate response
* fix(inference): apply ruff formatting
* fix(inference): drive _FinalOutputCapture through async-for, not __anext__
* fix(inference): always emit cached_tokens, drop enable_prompt_tokens_details gate
* chore: bump verifiers to fix/hatch-vcs-fallback-version
Pin to the fallback-version fix (PrimeIntellect-ai/verifiers#1650) so the
prime-rl Docker build resolves a version without VCS metadata. Temporary
pin to the PR branch; should move to verifiers main once #1650 lands.
* fix(inference): annotate _FinalOutputCapture source as AsyncIterable
* multiplex trainer output
* update skill
* test: cover multi-run token exports
* feat: export token metrics from orchestrator
* refactor: store token export run fields on microbatch
* refactor: send microbatches without payload wrapper
* test: cover orchestrator token-export metric collection
Adds an integration test asserting the orchestrator's per-step read path
(collect_token_export_metrics) surfaces finite mismatch_kl/entropy mean/max
from real multi-run exports. Complements the file-writing coverage in
test_token_exports_are_run_local; reuses the existing fixture.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix: defer token-export STABLE until run step fully consumed
A single orchestrator run_step can span multiple trainer steps when the
packer splits its samples across packs (token budget). mark_stable() ran
every trainer step and marked any dir touched that step, so the orchestrator
could read a run step's exports as complete from only the first pack's
sequences and advance its cursor, never aggregating the remainder.
Mark a run's export dir STABLE only once that run step is fully consumed —
gated on the same ready_to_update signal that drives its optimizer step.
Dirs for runs not yet ready carry over to a later trainer step. run_id=None
(single-run export) never spans trainer steps, so it is marked immediately.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat: stamp token-export metrics with their trainer step
Token exports lag the orchestrator step they're logged under (the trainer
runs behind), so on the default W&B step axis mismatch_kl/entropy appear
shifted right. Log the run step the exports actually belong to as
`trainer/step` so the metrics can be plotted against a lag-corrected axis.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: fold token-export metrics into MetricsBuilder under trainer/
Move the token-export collection from the orchestrator mainline into
MetricsBuilder.build, which now owns the last-logged-step cursor (seeded from
the resumed step via start_step). Namespace the metrics under trainer/
(trainer/mismatch_kl/*, trainer/entropy/*) alongside trainer/step so they
group in W&B and can be plotted against a lag-corrected axis.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: drop redundant max_step from token-export reader
Exports always lag the orchestrator (the current step's batch is shipped just
before metrics are built and trained afterward), so no stable export at or
beyond the current step can exist on disk. The `step <= max_step` filter was
always satisfied; the last_logged_step cursor alone drives correctness.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: return log-ready dict from token-export reader
Drop the TokenExportMetricsResult dataclass that was unpacked into a dict one
line later. collect_next_token_export_metrics now returns the trainer/-prefixed
metrics (including trainer/step) directly, so the builder just updates the log
dict and reads trainer/step back to advance its cursor.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: guard token-export log update under the truthiness check
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: drop redundant run_idx guard in SinglePacker
The receiver always stamps batch.run_idx from used_idxs (a key of idx_2_id),
so the is-not-None/in-idx_2_id check was always true. Index directly, matching
MultiPacker.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: mark token-export STABLE with a barrier instead of all_gather
The all_gather_object did barrier + dir-union + rank-0 write. Replace it with a
plain dist.barrier() (so STABLE only lands after every rank flushed its
rank_*.jsonl), then each rank touches STABLE for the dirs it wrote. touch is
idempotent, so ranks sharing a (run, step) dir converge harmlessly, and the
union is covered without shipping dir lists.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: barrier at the call site, drop participate_in_stable_marking
The barrier lived inside the exporter, so the disabled variant needed a
participate_in_stable_marking flag to opt into it. Move the barrier to the
single train-loop call site, gated on token export being enabled (uniform
across ranks): every rank barriers together, then writers touch STABLE and
disabled ranks no-op. DisabledTokenExporter is a pure no-op again and the
exporter does no collectives.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: drop dist.is_initialized guard before token-export barrier
train() always calls setup_torch_distributed before the training loop, so dist
is initialized by the time the barrier runs.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* chore: drop redundant comments around token-export barrier
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* refactor: derive token-export root from output_dir.parent
root_output_dir was just output_dir.parent of self.output_dir and used in one
place; drop the redundant attribute.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* fix: skip malformed token-export records instead of aborting the step
Token-export metrics are best-effort monitoring read inside MetricsBuilder.build
every step. A malformed JSONL line or a loss_mask/value length mismatch raised
ValueError, which would abort the orchestrator step. Guard each record, skip and
count failures, and warn once per step dir; good records still aggregate.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* feat: drain trailing token-export metrics after max_steps
Token exports lag the orchestrator, so the last shipped steps are finalized by
the trainer after the main loop ends — and build() no longer runs to log them,
dropping the tail. Add an end-of-run drain that polls for the remaining stable
steps up to max_steps-1 and logs each under its own trainer/step (a local W&B
step axis, leaving progress.step for the final checkpoint untouched). Gated on
token export being on for the run; early-returns when build() already kept up;
bounded by a timeout. Shared collection extracted to
MetricsBuilder.next_token_export_metrics.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* make token export a top-level trainer flag
* chore: fold token export into multi-run integration config
* chore: revert multi-run trainer config override
* chore: remove token export unit tests
* docs: document token export config migration
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
UCX's --with-verbs silently disables IB when the rdma-core dev headers
are missing, producing a TCP-only build that only fails much later at
runtime with NIXL_ERR_BACKEND. On hosts with RDMA devices, require the
headers before building and verify the rc_verbs transport made it into
the built UCX. Also pass --with-rdmacm so the rdmacm connection manager
is built when available.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
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>
/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>
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
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.
* 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>
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>
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>
* 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.
* 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.
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>
* 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>
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>
`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>
* 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>
* 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>
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>
* 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>
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>
* 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>
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>
* 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>
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>
* Support delta-only routed experts replay
* Pin routed experts replay dependencies
* fix(orchestrator): match longest active prefix in interleave_rollout
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>
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>
* 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>
* 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>
Ignore FileExistsError from mkdir when the token export step path is already a directory.
(cherry picked from 5ee18c884bec295c77bfe6d9d276197985b01a38)
* 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>
* 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>
* 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>
* 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>
* 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>
* 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
* 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>
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>
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.
* 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>
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>
* 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.
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
* 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>
* 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>
* 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>
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>
* 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>
* 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>
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>
* 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>
* 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>
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>
* 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>
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>
* 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>
* 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>
* 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>
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>
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>
* 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>
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>
* 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>
* 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>
* 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>
* 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>
#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>
* 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>
* 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>
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.
* 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>
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>
* 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>
* feat: turn prime-rl into a monorepo with submodules
Add verifiers, renderers, and research-environments as git submodules and
uv workspace members. Source edits in any of them now apply to prime-rl's
venv without a re-sync. Drops the PrimeIntellect PyPI index in favor of
installing env packages editable from the submodule trees.
- envs extra expanded from ~14 curated packages to ~98 env packages across
verifiers/environments and research-environments/environments
- 11 envs excluded from the workspace due to upstream dependency conflicts
(tau2 fork divergence, openenv-core unreleased, scicode protobuf clash,
gem-wordle nltk pin, two envs with hardcoded verifiers git URLs)
- override-dependencies adds torch>=2.9.0 (to override verifiers[rl]'s
torch<2.9 pin) and openenv-core (to avoid an unreleased version pin)
- scripts/install.sh now initializes submodules per-path so a missing
private repo (e.g. configs/private) does not abort the install
- installation/config/entrypoints skills updated to mention submodules and
the configs/private path
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: scope ruff to prime-rl source only
Submodules (verifiers, renderers, research-environments) have their own
ruff configuration and style. Excluding them from prime-rl's checks avoids
spurious CI failures on third-party code that we don't own.
- pyproject.toml: extend-exclude the three submodule paths
- style.yaml: don't fetch submodules in the ruff job (nothing to lint there)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat: add configs/private submodule pointing to research-configs
The private repo holds training/eval configs not meant for the public
prime-rl tree. People without access skip the submodule init via the
install script.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: bump configs/private + lock CI to public submodules only
- configs/private: pulls in all 88 TOML configs from research-prod
- CI workflows: replace 'submodules: true' with explicit init of just
verifiers/renderers/research-environments, so no CI run ever attempts
to fetch the private configs/private submodule
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor: move submodules under packages/ + scope config tests
- packages/{verifiers,renderers,research-environments}: submodules now
live alongside packages/prime-rl-configs as workspace members
- pyproject.toml: workspace members/exclude and ruff extend-exclude
updated to the new paths
- CI workflows: revert to submodules: true (the GITHUB_TOKEN doesn't
give access to configs/private, so it can't leak); the test fix
below handles the in-tree case
- tests/unit/test_configs.py: skip configs/private/ when collecting
TOMLs so private configs aren't loaded through public schemas
- scripts/install.sh: drop redundant -c url.insteadOf on clone; the
later persistent git config line is what actually rewrites URLs
for the submodule init step
- skills/installation/SKILL.md: point to packages/<submodule>/ paths
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor: scope envs extra to union of main + research-prod
Drop the "install everything" approach. The envs extra now installs only
the union of (1) envs prime-rl main shipped before this PR and (2) envs
referenced in research-prod TOMLs. The rest of the env packages remain
workspace members (installable via `uv add <name>`), but aren't pulled
in by `--extra envs`.
This trims the install set from ~95 to 27 packages — fewer transitive
dep conflicts to keep alive, and the install set actually matches what
our active configs use.
tau2-bench is un-excluded from the workspace and added as a source so
research-prod's tau2-bench configs install cleanly. The other tau2 forks
(tau2-bench-v1, tau2-synth, tau3-bench, tau3-bench-rlm) stay excluded —
they pull tau2 from divergent forks/commits that can't coexist in a
single venv.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor: scope workspace members to installed envs only
The previous setup pulled every env subdir under packages/verifiers
and packages/research-environments into the workspace via globs, then
maintained an exclude list for envs that couldn't co-resolve. With the
envs extra now narrowed to the union of (prime-rl main + research-prod),
the workspace can list exactly those env packages and skip the rest —
no exclude list needed.
Also: extend-exclude in ruff config simplified to ["packages"] so
prime-rl's checks ignore anything under packages/. The submodules
have their own ruff configs.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(ci): don't try to fetch the private configs/private submodule
The default GITHUB_TOKEN that actions/checkout uses is scoped to the
current repo only, so 'submodules: true' aborts with 404 when it
hits configs/private (the research-configs repo). Skip the checkout
action's submodule init and explicitly update just the three public
submodules.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: strip noisy comments
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor: prune [tool.uv.sources] to installed env packages only
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(ci): rewrite SSH to HTTPS for submodule init
Runners have no SSH key, so cloning git@github.com:... fails. The
actions/checkout step handles this automatically when submodules: true
is set, but the explicit submodule update we run after submodules: false
doesn't. Set the insteadOf rewrite before the update.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor: move third-party submodules from packages/ to deps/
packages/ is reserved for first-party prime-rl subpackages
(packages/prime-rl-configs). Vendored submodules live under deps/.
Ruff extend-exclude switches to deps/ so prime-rl-configs gets linted
again.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(install): apply SSH->HTTPS rewrite in SKIP_CLONE path too
The rewrite was inside the else branch of the clone check, so users
running with SKIP_CLONE=1 without SSH access would hit the same submodule
init failures the rewrite was meant to prevent. Move it after the
clone/skip block so it runs in either path.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(docker): copy deps/ and init submodules in release workflow
The submodule move from packages/ to deps/ left the Dockerfile and the
release workflow inconsistent: Dockerfile.cuda only COPYs packages/, and
release.yaml never initialized submodules. Add the deps/ COPY and the
explicit submodule init (matching the test workflows).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: warn against --recursive submodule init, use explicit paths
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* docs: remove note from submodule init step in README
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore: pin renderers to v0.1.6 and verifiers to aa428f3
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(verifiers): patch out renderers git source for workspace compat
uv requires workspace members to reference each other as workspace
sources. verifiers@aa428f3 still has renderers as a git source; this
local patch removes it so the workspace resolves.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(verifiers): advance to latest main
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(renderers): advance to latest main (v0.1.8.dev2)
Required by verifiers main which now pins renderers>=0.1.8.dev0.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore: revert ruff pre-commit hook to v0.13.0 to match CI
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(wandb): respect WANDB_MODE env var in WandbMonitor
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(ci): disable W&B on PR runs to prevent ID collision and missing key crashes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* refactor(ci): rename test_rl.py to test_reverse_text.py and split into own CI job
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(ci): reduce reverse-text RL run to 15+5 steps
Reward plateaus at step 8-9 and stays above the 0.65 threshold from
step 8 onward. 20 steps was ~40% wasted compute.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* test: add average mismatch KL check to reverse-text integration test
Asserts the average mismatch KL across the last 10 trainer steps stays
below 0.01, catching numerical instability early without being brittle
to per-step noise.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* test(alphabet-sort): add mismatch KL guard, tighten reward threshold, reduce steps
Cut max_steps 10→8 (reward plateaus by step 7 at ~0.22, saves ~16s).
Tighten reward min_threshold 0.05→0.10 to catch regressions earlier.
Add avg mismatch KL check (last 5 steps ≤ 0.15) based on observed ~0.05-0.09
range; 0.15 gives CI headroom while catching numerical instability.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* test(reverse-text): rename wandb run, reduce mismatch KL check window
Rename W&B run from test-rl to test-reverse-text:{branch} to match the
test file rename. Reduce last_n_steps from 10→3 for the mismatch KL
check to make it less brittle (3 steps is sufficient to catch instability).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore: remove unused alphabet_sort_branch CI config
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(tests): update config paths after renames, fix double newline in error output
- configs/ci/integration/rl/ → reverse_text/
- configs/ci/integration/alphabet_sort/start.toml → alphabet_sort.toml
- sep="\n" → sep="" in check_no_error (readlines() lines already end in \n)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(ci): respect WANDB_MODE in shared mode, align lora/alphabet-sort configs
- wandb.py: WANDB_MODE=disabled/offline now bypasses shared mode entirely
(shared mode requires a server connection and can't work offline)
- reverse_text_lora: reduce steps 20+5 → 15+5 to match reverse_text config
- gpu_tests.yaml: rename rl_lora job → reverse_text_lora, update ignore list
- test_reverse_text_lora.py: use colon separator in wandb run name
- test_alphabet_sort.py: drop rl_output_dir wrapper, use output_dir directly;
use colon separator in wandb run name
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* refactor: rename test_rl_moe → test_reverse_text_moe, split into own CI job
- Rename test file and config dir (rl_moe → reverse_text_moe)
- Add reverse_text_moe as a dedicated CI job; exclude from base
- Update config paths, wandb name (colon separator), output subdirs (hf/custom)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(test): add missing test function to test_reverse_text_moe
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix(ci): update config paths for renamed sft/multi-run dirs, tail orch logs
- test_sft.py: sft/ → reverse_text_sft/
- test_sft_lora.py: sft_lora/ → reverse_text_sft_lora/
- test_reverse_text_multi_run.py: rl_multi_run/ → reverse_text_multi_run/
- gpu_tests.yaml: rename rl_multi_run job → reverse_text_multi_run, update
ignore list to use test_reverse_text_multi_run.py
- rl.py: tail orchestrator.log instead of trainer.log on startup
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* refactor(tests): rename CI integration tests and configs to use descriptive names
Rename test files and config directories from generic rl/sft/rl_lora/rl_multi_run
prefixes to descriptive reverse_text/alphabet_sort/reverse_text_sft/etc names.
Flatten alphabet_sort config from a directory to a single file.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(ci): reduce SFT integration test steps from 10+10 to 5+5
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(ci): simplify CI - always offline W&B, drop OPENAI_API_KEY, fix wandb names
- WANDB_MODE hardcoded to offline (removes flaky conditional logic)
- Remove OPENAI_API_KEY (not referenced in code, client defaults to EMPTY)
- Remove WANDB_API_KEY (no longer needed with offline mode)
- Drop -m gpu from integration test args (all integration tests already carry the mark)
- Standardize wandb run names to use colon separator in sft/sft_lora/multi_run tests
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(ci): replace base integration job with explicit sft matrix jobs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore: ignore .claude/scheduled_tasks.lock
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore: untrack deps/renderers/_version.py, add to gitignore
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(ci): use dynamic matrix to avoid expanded skipped entries on draft PRs
Static matrix jobs get pre-registered by GitHub even when skipped, showing 8
individual "Skipped" entries on draft PRs. A dynamic matrix (output from a prior
job) can't be pre-expanded, so GitHub shows a single entry instead.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Revert "chore(ci): use dynamic matrix to avoid expanded skipped entries on draft PRs"
This reverts commit 0e835ed63ef467f8a33018f809b8ab182ebb2c56.
* chore(ci): disable uv cache on GPU jobs
The post-job cache save tars multi-GB pytorch/CUDA packages, adding 3+ min of
overhead. The save cost exceeds the restore benefit for large GPU dependencies.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore: remove deps/renderers/_version.py from gitignore
Handled in a separate PR.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* chore(ci): run integration tests with -vvs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* only 5 alphabet sort steps [skip ci]
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat(sft): accept tool_defs column alongside tools
The verifiers rollout format stores tool definitions under tool_defs
(list[dict] or list[str]); SFT was only reading the OAI tools column
(single JSON string), so rollout-derived datasets trained with an empty
system block — a major training/inference mismatch since vLLM injects
the tool definitions at inference time.
Falls back to tool_defs when tools is absent and parses both shapes.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* accept both JSON-encoded and pre-parsed shapes for tools/tool_defs
Either key may now arrive as: a JSON-encoded list string, a list[dict],
or a list[str] of JSON-encoded tool dicts. Result is always list[dict].
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* narrow accepted shapes to str | list[dict]
list[str] (each item a JSON-encoded tool) wasn't a real-world shape; drop it.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* simplify tools lookup
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* normalize tool defs to OAI shape before chat template
The orchestrator does this conversion in _convert_tools_to_oai_format
(trajectories.py); SFT was passing the raw verifiers shape directly. That
worked for chat templates that handle both shapes (e.g. NemotronH) but
would silently render an empty <tools> block on most others.
Detects verifiers-shape tools (top-level name/description/parameters) and
wraps them as {type: 'function', function: {...}}. Pre-wrapped OAI tools
pass through unchanged.
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: hallerite <git@hallerite.com>
Adds `use_renderer` flag to SFTConfig, mirroring the RL path. When enabled,
SFTDataset tokenizes via `renderers.base.build_training_sample` instead of
the incremental Jinja `apply_chat_template` path, fixing multiturn sample
drops and position-dependent template crashes.
Co-authored-by: Eric Botti <ericjbotti@gmail.com>
* Patch vLLM layerwise alias-buffer reload
* Remove layerwise buffer copy-back guard
* Skip alias buffers during layerwise copy-back
* ruff
* Skip absent buffers during layerwise copy-back
* Precompute layerwise alias storage pointers
* ruff
* simpler fix for layerwise alias buffer reload (#2486)
* meow
* dont think theres a need for this singletoning behavior?
* Simplify layerwise alias-buffer patch to copy-back-only
Drop the capture-time skip and the absent-buffer guard; detect aliasing
at copy-back via parameter storage pointers (recursing into submodules
so views like mixer.conv_weights → mixer.conv1d.weight are caught).
_place_kernel_tensors then restores the original aliased buffer, which
trivially reflects the parameter's freshly-loaded storage.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Apply suggestion from @Jackmin801
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(orchestrator): drop groups after max_error_reschedule_attempts
Adds a per-group retry cap to the rollout scheduler. Each `GroupState`
now tracks a `failed_attempts` counter, incremented whenever a batch of
rollouts comes back with at least one errored or empty trajectory. When
the counter reaches `orchestrator.max_error_reschedule_attempts`, the
group is dropped from the current step's batch (cancelling any
in-flight rollouts for that group) and the rest of the batch proceeds.
Default is `None` (retry indefinitely, current behavior). Set a value
to unblock single-example hangs in agent envs (e.g. a sandbox poll
that times out at 60s on every retry — that loop was previously
infinite because the AgentError surfaces as `rollout["error"]`, which
the scheduler treats as a normal "reschedule the group" signal with no
give-up condition).
Minimal local re-implementation of the abandoned PR #2076 — keeps the
retry-cap behavior without the larger GeneratedBatch / variable
group-size / deferred-scoring refactor in that PR.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(orchestrator): report and clear dropped_groups_by_env in metrics
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(orchestrator): off-by-one in max_error_reschedule_attempts check
failed_attempts is incremented on the initial failure, so >= caused the
group to be dropped without any reschedule. Use > so max_attempts
matches the configured number of retries.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(orchestrator): include last failure reason in drop log
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(orchestrator): count failed rounds, not failed rollouts, for drop cap
For non-group-scoring envs, each individual rollout returns as a
separate task, so a single failed dispatch round could increment
failed_attempts up to rollouts_per_example times and trip the cap before
any retry happened. Tag in-flight requests with a dispatch round and
dedupe failures by round.
Also switch the drop check to `>=` and reword the config description so
the field's semantics match — the group is dropped once this many of
its dispatch rounds have returned errored/empty 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>
* Fix: add layerwise as default
* Fix; cleanup
* fix(filesystem): apply layerwise reload to filesystem transport
Mirror the same fix as the NCCL path: replace
`model.load_weights + process_weights_after_loading` with
`load_weights_checkpoint_layerwise`. Without it, MoE
+ filesystem transport hits the same
`Current vLLM config is not set` AssertionError at
`worker/filesystem.py` on the first weight update.
Verified end-to-end on Qwen3-30B-A3B-Thinking-2507 + reverse-text:
filesystem broadcast returns 200 OK, orchestrator step 2 consumed
new weights cleanly (off-policy level 1, reward 0.3583), trainer
steady-state at ~29K tok/s, MFU 21%, no NaN, no errors.
---------
Co-authored-by: hallerite <git@hallerite.com>
`replace_linear_with_fp8_blockwise_linear` uses `re.search(pattern, name)`
to decide which linears to keep in BF16. The default ignore list had
"mlp.gate." which is a regex where `.` matches any character. As a
result, dense MLPs' `mlp.gate_proj` (the trailing `.` matched `_`)
were being skipped from FP8 conversion alongside the MoE router gate.
For FP8 inference checkpoints (e.g. `zai-org/GLM-5-FP8`) where the
dense MLP gate_proj IS quantized to FP8, this leaves the trainer's
copy in BF16 — causing hidden-state divergence in early dense layers
that propagates through the MoE router and inflates trainer↔inference
KL mismatch.
Escape the dots (`mlp\.gate\.`) so the pattern matches only the actual
MoE router gate (`mlp.gate.weight`, `mlp.gate.e_score_correction_bias`)
and not `mlp.gate_proj` / `mlp.gate_up_proj`.
Verified on a 12-node GLM-5.1-FP8 RL run: trainer log now reports
`Replaced 477` (was 474) with `mlp.gate_proj` no longer in the
`first skipped(name)` list.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Alternative implementation of fp32 lm_head proposed by @Jackmin801 on
PR #2438: use torch.mm(..., out_dtype=torch.float32) (PyTorch >= 2.10) so
the matmul accumulates and emits fp32 directly without zero-padding the
bf16 operands or maintaining a separate fp32 weight copy.
The win is purely in the epilogue: F.linear(bf16, bf16) accumulates in
fp32 internally on tensor cores but truncates the output to bf16 before
returning. Native out_dtype=fp32 keeps the full mantissa for the
downstream softmax/sample.
Removes the cached fp32 weight + tensor-version invalidation logic from
PR #2438 — not needed when there's no separate fp32 copy.
Wired identically to PR #2438: inference.enable_fp32_lm_head config flag
-> additional_config["fp32_lm_head"] -> captured on LogitsProcessor.__init__
-> per-instance flag read in _get_logits.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`temperature` is part of the forward signature but had no docstring entry,
which trips the auto_docstring check. Add a description matching the convention
used in the other model files.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(cp): add ulysses all-to-all path alongside ring
Adds a `model.cp_style` arg ("ring" default | "ulysses") that selects
between the existing ring CP and a new Ulysses all-to-all variant.
Ulysses redistributes Q/K/V via two seq <-> head all-to-alls and runs
vanilla flash attention on the full sequence with H/cp heads, so the
attention kernel does not need to be CP-aware. Works OOB with FA2/3/4,
linear attention, mamba, etc.
Constraint: cp_size must divide both num_attention_heads and num_kv_heads.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: ruff format ulysses_attn.py
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(cp): refuse cp_style='ring' on linear-attn / Mamba models
Ring CP is a softmax-attention algorithm (sequence ring all-gather of K/V).
It cannot correctly drive non-softmax kernels (Qwen3.5 DeltaNet linear-attn,
NemotronH Mamba). Previously the linear-attn CP setup hooks were called
unconditionally under ring, which silently mixed two different CP layouts
in the same model.
Now:
- Refuse cp_style='ring' at startup if the model has any linear/SSM
attention layer, with a clear error pointing at cp_style='ulysses'.
- Only call setup_hybrid_cp / setup_nemotron_h_cp under cp_style='ulysses'.
- setup_sparse_mla_cp (still softmax) keeps working under both.
Ulysses' all-to-all is purely on Q/K/V tensors, so the linear/SSM kernel
runs unchanged on a sequence shard — this is the correct CP path for
hybrid models.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat: weighted length shaping over completion + tool-response tokens
Generalize the length_shaping brevity bonus to a weighted combination of
model-completion tokens and tool-response tokens, so the brevity signal
can penalize tool-response token consumption (read from a harness metric
like rlm_total_tool_response_tokens) independently from model output.
- Add `tool_response_lengths` to AdvantageInputs (optional)
- Add `length_shaping_completion_weight` (default 1.0) and
`length_shaping_tool_response_weight` (default 0.0) to
DefaultAdvantageConfig — defaults preserve existing behavior.
- effective_lengths = a * completion + b * tool_response, fed to the
existing correctness-gated brevity bonus.
- Add get_tool_response_len() that pulls *_total_tool_response_tokens
from rollout metrics and returns 0 if absent (no-op for non-tool envs).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(advantage): guard zero-cost division in efficiency shaping
When `mean_correct_cost == 0` (e.g. tool-only shaping without a harness
metric, or all-zero turn counts), `costs / mean_correct_cost` was 0/0 →
NaN advantages. `clamp(0, 1)` doesn't recover from NaN.
Detect zero mean and zero out the bonus, falling back to plain GRPO for
that group. Also a latent bug for `length_penalty="turns"` if a group
ever had all empty trajectories — same fix covers it.
* fix(advantage): constrain weights to finite non-negative; cast rewards to float
- Config: add `ge=0, allow_inf_nan=False` on both weight fields. Negative
weights would invert the shaping (reward more tokens); inf/nan poison
advantages downstream.
- `default_advantage_fn`: cast rewards to float32. The previous
`dtype=rewards.dtype` for costs truncated fractional weighted sums when
rollouts emitted integer rewards. Casting also fixes a latent crash on
int rewards in `_efficiency_shaping`'s `rewards.mean()` (Long unsupported).
* refactor(advantage): discriminated length_penalty sub-config
Replace the scalar `length_penalty: Literal["tokens","turns"] | None` plus
two flat weight fields with a discriminated union on `type`:
TokensLengthPenaltyConfig(completion_weight, tool_response_weight)
TurnsLengthPenaltyConfig
Default for the tokens config is (1.0, 1.0), making total-context shaping
the default when token-shaping is enabled. The discriminator pattern
matches the existing AdvantageConfig (default | custom) shape and keeps
weight semantics scoped to the variant they apply to — no cross-field
validator needed.
CHANGELOG entry added.
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Feat: deep-gemm-fp8
* Feat: cleanup
* nit
* Style
* Feat: works now
* Feat: fp8 grouped gemm works
* Fix: skip unaligned + qwen3.5
* chore(deep_gemm): rebuild d30fc36 wheel against torch 2.11 / cu128
The wheel was built against torch 2.10 + cu128; the merge from main bumped
torch to 2.11.0+cu128 / vllm to 0.20.1, breaking ABI compat with the old
build. Rebuilt via scripts/install_deep_gemm.sh --wheel-dir tools/wheels.
Also updates install_deep_gemm.sh:
- default ref pinned to d30fc36 (was 477618c)
- script header documents the wheel-dir flow used to refresh tools/wheels/
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deep_gemm): pin to v0.5.0 release URL (uploaded d30fc36 wheel)
The d30fc36 wheel is now hosted on the v0.5.0 GitHub release alongside the
existing 477618c build, so we can drop the local path-based pin.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(fp8): make deep_gemm import optional for CPU-only envs
deep_gemm only ships CUDA wheels; importing prime_rl on a CPU box currently
fails with ImportError before any FP8 path is even touched. Wrap both call
sites in try/except so the import is graceful — actual deep_gemm calls live
inside autograd Function bodies that only run on GPU anyway.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(fp8): wire FP8 grouped GEMM into NemotronH; assert disabled for GPT-OSS
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* install: check platform and exit early on unsupported platforms
* handle stripped ansi escape prefix for color output
* Revert "handle stripped ansi escape prefix for color output"
This reverts commit b8850f73893c3189d86848fb3849986275a12963.
* bump vllm version
* fix cuda version pin
* correct flash attn
* chore: drop monkey patches now upstream in vLLM 0.20
vLLM 0.20.1 ships fixes for the LoRA+MoE+DP>1 corruption (#40338) and
the OffloadingConnector CPU block-count miscalculation (#39617), so
remove the local monkey patches and the corresponding call site in
transformers_v5_compat. Refresh stale "vLLM 0.16/0.19" comments.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
DeprecationWarning is silenced by default outside __main__, so users
never saw notices for max_tokens / [[orchestrator.env]] / [orchestrator.sampling].
FutureWarning is shown under default filters and is the right category
for "will be removed in a future release" notices.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat: split prime-rl-configs into separate workspace package
Goal: make `prime_rl.configs.*` pip-installable on its own (~13 deps)
without pulling the full GPU/ML stack (~329 deps).
Layout — uv workspace with two members:
- root `prime-rl` (heavy stack, unchanged location at src/prime_rl/)
- `packages/prime-rl-configs/` (slim wheel, owns prime_rl.configs.*
and the small slim utils: utils/config.py, utils/logger.py,
utils/validation.py)
Mechanism — both wheels contribute to a PEP 420 namespace package
`prime_rl/` (no __init__.py at the top level, nor under utils/). Each
wheel ships disjoint files; pip merges them at install time.
- `pip install prime-rl-configs` → schema only
- `pip install prime-rl` → full stack (depends on prime-rl-configs)
Code changes:
- Move src/prime_rl/configs/ → packages/prime-rl-configs/src/prime_rl/configs/
- Move utils/{config,logger,validation}.py → packages/prime-rl-configs/src/prime_rl/utils/
- Move rgetattr/rsetattr from utils/utils.py → utils/config.py (was the
only heavy import the configs needed; this breaks the dep)
- Replace `Path(prime_rl.__file__).parent / "templates"` (None on a
namespace package) with `find_package_resource("templates")` which
iterates `prime_rl.__path__` to locate the heavy wheel's data dir
- Delete src/prime_rl/__init__.py; move its `import _compat` side-effect
into the actual entrypoint scripts (orchestrator.py, entrypoints/rl.py,
entrypoints/sft.py — trainer/{rl,sft}/train.py already had it)
- Dockerfile.cuda: also COPY packages/ so the workspace member is
available during `uv sync`
Verified:
- `uv sync --all-extras` resolves and builds both wheels
- 333 unit tests pass (none touched)
- all 6 entrypoints (rl/sft/trainer/orchestrator/env-server/inference)
load and print --help
- fresh `pip install ./packages/prime-rl-configs` (no extras) installs
13 packages, imports all configs, parses examples/.../rl.toml with a
[slurm] section, and sys.modules contains zero of:
torch / transformers / vllm / wandb / ring_flash_attn / verifiers /
prime / datasets / liger_kernel
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* ci: add slim-configs-install job to cpu_tests
Fresh venv → `uv pip install ./packages/prime-rl-configs` → assert that:
- all 6 config modules import
- sys.modules contains zero of: torch, transformers, vllm, wandb,
ring_flash_attn, verifiers, prime, datasets, liger_kernel
- find_package_resource("templates") returns None (the heavy wheel's
data dir isn't shipped on slim)
- a real example config with [slurm] parses; template_path stays None
Guards the slim-import contract against future regressions where
something under prime_rl.configs.* might re-introduce a heavy import.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(ruff): mark prime_rl as first-party for isort
Without this, ruff's import sorter classifies prime_rl.configs.* as
third-party (because those files now live under packages/, not src/),
and groups them apart from prime_rl.utils.* / prime_rl.trainer.* etc.
Telling ruff that prime_rl is a single first-party namespace keeps
all prime_rl.* imports in one block, regardless of which workspace
wheel ships the submodule.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(configs): drop logger dep, use stdlib warnings
Configs were doing get_logger().warning(...) at validation time, which
forced loguru into the slim wheel and a logger.py copy alongside it.
None of these warnings need a configured logger — they're config-time
deprecation notices and misconfiguration hints. Stdlib `warnings.warn`
covers the use case without any runtime infrastructure.
- Replace 7 `get_logger().warning(...)` call sites in configs/rl.py and
configs/orchestrator.py with `warnings.warn(...)`. Deprecation messages
use `DeprecationWarning`; the rest use the default `UserWarning`.
- Move `prime_rl/utils/logger.py` back to the heavy `prime-rl` wheel
(`src/prime_rl/utils/`).
- Drop `loguru` from `prime-rl-configs` deps; add it to `prime-rl`.
- Slim CI: stop importing `prime_rl.utils.logger` (it's no longer in the
slim wheel) and add `loguru` to the forbidden-modules list.
Slim install drops from 13 to 12 packages.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: import _compat in remaining ring_flash_attn entry points
Integration tests like tests/integration/test_sft_lora.py import
prime_rl.trainer.weights, which transitively pulled ring_flash_attn
(via models layer / utils.cp) without prime_rl._compat ever running,
producing the ImportError that failed CI.
Add `import prime_rl._compat` to the two remaining top-level
ring_flash_attn import sites: utils/cp.py and trainer/models/layers/
ring_attn.py. The trainer entrypoints (rl/sft/train.py) already had
this import.
`# ruff: noqa: I001` on both files because ruff's isort, with
known-first-party=prime_rl, sorts the prime_rl._compat first-party
import after the third-party ring_flash_attn import — which defeats
the patch ordering. The shim must run before ring_flash_attn is
imported, so the file order is intentional.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: pin pydantic-config to git fork in slim package
The PyPI package named `pydantic-config` is a different project that
doesn't expose BaseConfig / cli (those are in samsja's fork). Without
this pin, plain `pip install prime-rl-configs` resolves the wrong
package and configs.* imports crash with:
ImportError: cannot import name 'BaseConfig' from 'pydantic_config'
uv pip install accidentally worked because it reads the root workspace
pyproject.toml's [tool.uv.sources] when installing from a git
subdirectory, which redirected pydantic-config to the fork. Plain pip
doesn't do that — it only sees the leaf pyproject.toml.
PEP 508 direct reference works for both uv and pip.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* ci: install slim wheel from /tmp to bypass workspace source discovery
The previous step did `uv pip install ./packages/prime-rl-configs` from
inside the cloned repo. uv silently reads the root pyproject.toml's
[tool.uv.sources] in that case and applies the pydantic-config git
override — masking the issue an external pip-only user would hit.
Build the wheel into /tmp/slim-wheel and install it from /tmp so uv
can't discover the workspace. This catches dep-resolution bugs that
only show up in a real external install.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: explain dist-name vs import-path in slim package README
Distribution name (`prime-rl-configs`) and import path
(`prime_rl.configs.*`) are different — easy to trip on.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: bump vllm 0.19 → 0.20
vLLM 0.20.0 lands MoE LoRA refactor (#40338) and CPU offloading fix
(#39617) upstream — drop now-redundant prime-rl monkey patches:
monkey_patch_fused_moe_lora_dp and monkey_patch_offloading_connector_
cpu_block_count.
PyPI vllm-0.20.0 is built against CUDA 13 and links libcudart.so.13;
our env is pytorch-cu128 (CUDA 12). Pin vllm to the cu129 wheel from
wheels.vllm.ai (libcudart.so.12) for binary compat. Promote
torchvision/torchaudio to direct deps so [tool.uv.sources] pins them
to pytorch-cu128 (cu13 transitive resolution would break torch ops).
Add vllm = false exemption to the 7-day exclude-newer cooldown since
0.20.0 was published 2026-04-27, inside the window.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat: migrate cu128 → cu130
Now that vllm 0.20.0 is the floor and PyPI ships it for CUDA 13
natively, drop our cu129-wheel detour and move the rest of the
GPU stack to cu130:
- pytorch-cu128{,-test} indices → pytorch-cu130{,-test}
torch/torchvision/torchaudio/flash_attn_3 follow.
- flash-attn extra: bump to v0.9.4 cu130torch2.11 prebuilt wheel.
- Drop the wheels.vllm.ai cu129 URL pin — PyPI vllm 0.20.0 (cu13)
is now the default.
- override-dependencies: nvidia-cudnn-cu12 → nvidia-cudnn-cu13.
Lockfile pulls torch 2.11.0+cu130, torchvision/torchaudio 0.26.0/2.11.0
+cu130, flash-attn 2.8.3+cu130torch2.11, vllm 0.20.0, and swaps every
nvidia-*-cu12 transitive for its cu13 counterpart.
Not addressed in this change (draft until ready):
- Host driver upgrade: 575.64.03 → ≥580.65.06 required for CUDA 13.
- samsja prebuilt wheels (deep-ep, deep-gemm, nixl-cu12) still
point at cu12 builds — runtime-incompatible with cu13. Need
rebuilds before merging.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): bump vllm 0.20.0 → 0.20.1
Picks up the DeepSeek V4 patch release and a handful of bug fixes
(CUDA-graph max_num_batched_token, num_gpu_blocks_override, cumem
expandable_segments, structured-output kwargs). Strict patch — none
of the kept/dropped monkey-patches are touched.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): ship cu13 disagg wheels, switch nixl to PyPI
deep-ep / deep-gemm: rebuilt against CUDA 13.1, stamped with `.cu13`
local version, uploaded alongside the existing cu12 wheels at v0.5.0.
nixl: dropped the URL pin entirely. PyPI `nixl-cu13` 1.0.1 ships UCX
auditwheel'd with mlx5_ib / rdmacm / cuda transports — verified
end-to-end with a 2-node basic_two_peers.py run that picked rc_mlx5
for inter-node RMA. The custom install_nixl_from_source.sh path is
kept (now generates `nixl-cuMAJOR` per torch's CUDA major) for
clusters that need a vendored UCX, but it's no longer the default.
install_ep_kernels.sh:
- Falls back to /usr/local/cuda-${MAJOR} when torch reports 13.0
but only cuda-13 (-> 13.1) is installed; rejects toolkit/torch
major mismatches.
- Exports CPATH=$CUDA_HOME/include/cccl for CUDA 13, where CCCL
headers (e.g. <cuda/std/tuple>) moved into the cccl/ subdir and
torch's CUDAExtension doesn't add it on its own.
- Post-build --set-runpath /tmp/deepep_build/nvshmem/lib rewrites
the DT_RUNPATH on deep_ep_cpp.so to match the cu12 convention the
existing inference/RL templates already hook (they symlink the
user's NVSHMEM at that path on each compute node).
install_deep_gemm.sh: post-build cu-suffix stamp.
scripts/wheel_add_cu_suffix.py (new): repacks a wheel with
+...cuXX appended to its local version, optionally stripping or
rewriting DT_RUNPATH on every .so. Keeps METADATA / dist-info /
RECORD / filename consistent.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(templates): fall back to ep_kernels_workspace nvshmem in disagg launchers
inference.sbatch.j2 and multi_node_rl.sbatch.j2 still set up the
/tmp/deepep_build/nvshmem/lib symlink the deep_ep wheel needs at
runtime, but now also try $PROJECT_DIR/ep_kernels_workspace/nvshmem/lib
(where install_ep_kernels.sh actually places NVSHMEM) if
$OUTPUT_DIR/nvshmem isn't staged.
Also adds the same hook to multi_node_rl.sbatch.j2's disagg block
(was previously only in inference.sbatch.j2, despite multi_node_rl
running deep_ep in-process when disagg is enabled).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* style: drop unused shutil import, apply ruff format
Caught by the Style workflow — `shutil` was speculatively imported
when wheel_add_cu_suffix.py was first sketched but never used, and
ruff's formatter wanted a couple of cosmetic tweaks.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(deps): exempt torchvision/torchaudio from exclude-newer cooldown
Both are sourced from the `pytorch-cu130` index alongside `torch` and
`flash_attn_3`. That index doesn't publish upload dates, so any package
pulled from it must be exempt from the 7-day `exclude-newer` cooldown
or `uv lock` may fail to resolve when a new release lands inside the
window.
Caught by bugbot.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(deps): refresh uv.lock metadata under uv 0.11.9
Previous lockfile was generated with uv 0.11.7. After the bugbot
fix added `torchvision`/`torchaudio` to `exclude-newer-package`,
CI (which runs uv 0.11.9) detected a metadata drift and failed
`uv sync --locked`, even though the resolved packages were
identical.
Re-locking with uv 0.11.9 reorders the `exclude-newer-package`
section and normalizes the `exclude-newer` value; no resolution
changes.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* add cu12 cudart to venv dep
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Jackmin801 <ongjackm@gmail.com>
The bench reported `num_tokens = batch * seq // cp`, which under-reports
tps and MFU by ~cp× when CP > 1. CP is sequence-sharded data parallelism
(cp ranks split the seq dim of the same `batch × seq` tokens), so the
unique training tokens per step is `batch × seq` regardless of cp —
identical to the convention RL already uses (which excludes cp from the
`dp` mesh used for token counting).
Effect: cp=2 runs no longer look 2× slower than they really are in
SFT bench output; numbers become directly comparable across cp values.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
66b277fb hardcoded is_causal + window_size_left/right assuming flash_attn_3
3.0.0 API, but forward uses causal while backward uses is_causal in the
installed package. Add _set_fa3_signature_params() that inspects the
get_default_args() dict to set whichever key is actually present, covering
both param name variants across FA3 versions.
Default TRITON_CACHE_DIR=~/.triton/cache lives on NFS in shared-home
clusters. Concurrent multi-node compiles race on that directory and
some ranks hit `ImportError: cannot stat shared object: Stale file
handle` when reading a .so that another node invalidated. One rank
dies, NCCL watchdog trips after 480s on all other ranks, job hangs.
Point TRITON_CACHE_DIR at /tmp/triton-cache-$USER-$SLURM_JOB_ID so
each node has its own local cache and no job shares state with any
other.
* feat(skills): add dotvenv skill warning against editing .venv/
* feat(agents): forbid editing .venv in AGENTS.md instead of skill
Replaces the dotvenv skill with a one-line rule under 'Running code'
in AGENTS.md, since AGENTS.md is always loaded and a 'never do X' rule
fits better there than as an on-demand skill.
* feat(advantage): add num_turns option to efficiency shaping
Replaces `length_shaping: bool` with `shaping_metric: Literal["length", "num_turns"] | None`
so the same correctness-gated efficiency shaping can score rollouts by trajectory
turn count instead of completion-token count. Generalizes the helper to operate
on a per-rollout cost tensor; both metrics are plumbed through `AdvantageInputs`.
* fix(advantage): remove extra blank line for ruff I001
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(advantage): rename shaping_metric -> length_penalty
Per review feedback, use clearer name and shorter literal values:
shaping_metric: Literal["length", "num_turns"] -> length_penalty: Literal["tokens", "turns"]
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(advantage): pass full rollouts through AdvantageInputs
AdvantageInputs now holds list[list[vf.RolloutOutput]] grouped by problem
instead of separate rewards/completion_lengths/num_turns tensors. Custom
advantage fns can read any rollout metadata; inputs.rewards is kept as a
convenience property for the common case.
Per @mikasenghaas review.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(advantage): drop AdvantageInputs.rewards convenience property
Per @samsja review: with rollouts as the single source of truth, the
rewards property was a partial holdover. Custom advantages now extract
rewards directly from rollouts, matching how all other metadata is read.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* test(advantage): regression test for per-problem advantage isolation
Two-problem case with very different reward scales — catches cross-group
leakage, slicing/transpose bugs, and out-of-order assignment in the
flat -> grouped -> flat round-trip through compute_advantages.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: update wandb to >=0.26.1
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(monitor): retry wandb.init on transient CommError
The W&B backend occasionally returns a 404 on upsertBucket during
wandb.init (server-side bug, see wandb/wandb#10497), which previously
killed the orchestrator since only non-primary shared-mode processes
retried. Now all callers retry CommError with a small backoff.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(orchestrator): bump verifiers to 3b77145, log per-turn timings
Adopt the new RolloutTiming schema from verifiers#1182 (TimeSpan-based,
seconds). Replace the flat generation_ms/scoring_ms metrics with a
timing/{all,env_name}/{key}/{mean,max,min} section covering total,
setup, generation, model, env, scoring, overhead.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(orchestrator): extract per-rollout timings into timing_df
Mirror the metrics_df / filter_df pattern so the timing keys aren't
flattened into results_df. Cleaner aggregation loops and no special
"timing_" column-name prefix.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(trainer): base MFU and TPS on forward+backward time only
PerfCounter previously used the wall-clock interval between successive
count_tokens() calls, which spanned optimizer step, grad clip, scheduler,
checkpointing, validation, etc. In rl/train.py the logged
time/forward_backward also covered optimizer.step() despite its name.
Drop the rolling window: compute throughput and MFU directly from each
step's token count and the measured forward+backward duration.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(trainer): include opt step in forward_backward_time
Place forward_backward_time capture after scheduler.step() in both SFT
and RL trainers so MFU/TPS reflects real GPU compute (fwd + bwd + grad
clip + optimizer step + scheduler step) without data-loading or other
host-side wait time.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(trainer): dual-mode PerfCounter — windowed for SFT, single-point for RL
PerfCounter now exposes both APIs on the same class:
- count_tokens / get_tokens_per_second / get_mfu — sliding-window smoothing
- get_step_tokens_per_second / get_step_mfu — single-step values
SFT uses the windowed API; RL uses the single-point API.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* revert(trainer): restore SFT sliding window over full step
SFT goes back to the original behavior: count_tokens(tokens) records its
own timestamp, smoothing happens over wall time between successive calls
(i.e. full step time, including opt step / validation / etc).
RL keeps the new single-point API on forward_backward_time.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Port the _compute_attention implementation from layers/attn.py so FA4
receives cu_seqlens via keyword args (its 4th positional is qv) and so
sliding_window is honored when set.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(orchestrator): bound monitor history and drop duplicate samples list
The orchestrator process was retaining two unbounded structures for the full
lifetime of a run, both accumulating per orchestrator step:
- `WandbMonitor.history` / `PrimeMonitor.history`: full metrics dict per step,
only ever read at end of run (orchestrator's --bench print, PrimeMonitor's
`history[-1]` summary).
- `WandbMonitor.samples`: full prompt/completion text + stringified token ids
per logged sample, only ever read once at end of run inside
`log_final_samples()` to package a redundant `final-samples` wandb table.
For long prod runs with sample logging enabled this is the dominant memory
growth in the orchestrator and a plausible source of orchestrator-side OOMs.
Changes:
- Add `Monitor.prune_history()` that truncates `history` to its last entry
(preserves `history[-1]` access for `save_final_summary`); `MultiMonitor`
delegates to wrapped monitors.
- Call `monitor.prune_history()` from the orchestrator loop, gated on
`not config.bench` so benchmark mode still gets the full history.
- Drop `WandbMonitor.samples` and the duplicate `final-samples` end-of-run
table — per-step samples are already streamed via the incremental
`samples` wandb table. Drops the now-unused `pandas` import.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(monitor): drop unneeded try/except around MultiMonitor.prune_history
prune_history is a list slice — it can't fail in any meaningful way, so
matching the defensive pattern of the other delegators here was just noise.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(monitor): gate history accumulation; drop log_final_samples
Address review feedback:
- Replace `prune_history()` + per-step orchestrator call with a constructor
`keep_full_history` flag on monitors. `Monitor.log()` either appends or
replaces in-place based on the flag. The orchestrator passes
`keep_full_history=config.bench` so non-bench runs never accumulate
history at all (rather than accumulating-then-pruning). Trainer keeps
the default `True`.
- Remove `log_final_samples` from the Monitor interface and all
implementations; it was a no-op everywhere after the prior commit.
Drops the corresponding orchestrator call site and the MultiMonitor
delegator.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Auto-generated example_ids start at 0 for every dataset, so multi-env
runs silently merge rollouts from different envs in global metrics
(solve rates, reward averages, problem counts). Scope all global
groupby/set operations by (env_name, example_id) instead of example_id
alone.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: rollout timeout config + verifiers 0.1.13.dev8
- Bump verifiers pin to v0.1.13.dev8 (rollout timeout, sandbox lifetime
auto-derive, per-turn timing display).
- New EnvConfig.timeout_seconds: float | None field on the orchestrator
config. When set, a model_validator auto-populates
extra_env_kwargs["timeout_seconds"], which the env server forwards to
the env constructor. MultiTurnEnv reads it as the per-rollout
asyncio.wait_for cap. Mirrors the existing
max_total_completion_tokens auto-populate pattern.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor: rename env timeout_seconds to timeout (with alias)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: pin verifiers to 980a9ea
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(orchestrator): make inference pool startup timeout configurable
Adds wait_for_ready_timeout to ClientConfig (default 1800s, matching
prior hardcoded value), threaded through StaticInferencePool and
ElasticInferencePool so it can be overridden via TOML per-client (e.g.
student vs teacher pools).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: ruff format
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Fake-data MoE training produces severely skewed expert assignments,
which under EP causes per-rank memory blowup and OOM. This adds an
opt-in DebugModelConfig flag that overrides token-choice routing with
a round-robin assignment so every expert receives an equal share of
tokens. Gating scores are gathered from the override indices to keep
the forward pass self-consistent. Gradient flow through the router is
broken, so this is for benchmarking memory/timing only.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat: per-batch loss type override for hosted SFT hard distill
Add loss_type field to TrainingSample and MicroBatch transport types so
the orchestrator can stamp samples with a loss override (e.g. "sft")
that the trainer dispatches per-batch. This allows a shared multi-tenant
trainer to handle both RL and SFT distill runs on the same cluster.
When teacher_rollout_model is configured, the orchestrator sets
loss_type="sft" on each sample. The trainer's compute_loss checks the
field and swaps to sft_loss_fn for that batch, falling back to the
configured default when None (fully backward compatible).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: explicit loss_type field, sft_loss bool, no auto-derive
Address review feedback:
- Replace loss_type: str | None with sft_loss: bool on TrainingSample
and MicroBatch (simpler, no string matching)
- Add explicit loss_type: Literal["rl", "sft"] on OrchestratorConfig
instead of auto-deriving from teacher_rollout_model presence
- Orchestrator stamps sample.sft_loss based on config.loss_type, not
teacher presence — user explicitly opts in
- Update validator: loss_type="sft" requires teacher_rollout_model
(direction reversed from "teacher implies sft")
- Update example TOML with explicit loss_type = "sft"
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* change to boolean
* conistency
* refactor: rename need_sft_loss to use_sft_loss and tighten hosted SFT invariants
- Rename `OrchestratorConfig.need_sft_loss` to `use_sft_loss` (clearer intent).
- Move the orchestrator-only SFT distill invariants (use_sft_loss paired
with teacher_rollout_model, use_token_client coupling) from RLConfig onto
OrchestratorConfig so the hosted `orchestrator` entrypoint enforces them
too, not just the combined `rl` entrypoint.
- Shrink RLConfig.validate_external_rollout_inference to the one truly
cross-config check (teacher_rollout_model vs self.inference).
- Drop redundant `[trainer.loss] type = "sft"` from the alphabet_sort
example so `use_sft_loss` is the single obvious knob.
- Access micro_batch["sft_loss"] directly in train.py (required TypedDict
field, no fallback needed).
- Document the override in skills/config/SKILL.md.
* test: cover hosted SFT loss override
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The transformers @auto_docstring decorator prints a warning at import
time for any forward-method param missing from the docstring. The five
custom *ForCausalLM models accept cache_position only for HuggingFace
API compatibility — training asserts use_cache is None and never decodes
autoregressively, so the param is unused. Documenting that fact makes
the behavior explicit and clears the warnings.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`broadcast_weights` used to guard both the orchestrator-notify and the
file-wait behind `if self.world.is_master`. The non-master ranks
skipped the wait and entered `nccl_broadcast_sender.broadcast_weights`
directly. Inside that path the preparation (DTensor resolution +
quantization / checkpoint preprocessing) enqueues NCCL collectives on
all ranks (FSDP all_gather in _resolve_dtensors). Those collectives
then sit in-flight with no counter-party until the inference engines
are paused and join — but the master has not yet waited for the
NCCL_READY marker because... only it was doing that.
Net effect: if the orchestrator took more than ~10 minutes to signal
NCCL_READY (e.g. eval + rollout-gen contention at the same time),
NCCL's watchdog would fire on a non-master rank and SIGABRT the
trainer. We've hit this repeatedly in large-cluster RL runs, always
with a non-master rank as the one to signal the timeout first.
Fix: split the existing `_notify_orchestrator` into a pure
`_compute_notified_runs` (safe on every rank) plus an impure
`_notify_orchestrator(notified_runs)` (master-only, does the
filesystem side-effects). Call the first unconditionally, call the
second only on master, then have every rank wait on the NCCL_READY
marker before proceeding. The file poll is filesystem-only with no
NCCL involvement, so a slow orchestrator now just blocks the whole
trainer safely instead of tripping NCCL's watchdog.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(slurm): cleanup stale node-local state before launch
Add a pre-workload srun step to the multi-node RL, multi-node SFT and
inference sbatch templates. It runs once per node and:
- kills orphan python/torchrun/vllm/prime_rl processes left over from a
prior job that wedged after scancel (SLURM doesn't always reap cleanly
when a job sits in CG for hours)
- removes stale vLLM and torch IPC state under /dev/shm/vllm-*,
/tmp/vllm-*, /tmp/torch-*, /tmp/torchelastic_*
Without this, decode engines on previously-used nodes can hang at
"Waiting for READY message from DP Coordinator" because the new vLLM
process finds a stale /dev/shm segment or port holder from the dead run.
Symptom we hit: a fresh job timing out after 1800s because 4 decode
engines never became READY; a manual pdsh cleanup of the same nodes
fixed it immediately.
Each node prints one line (hostname, residual proc count, total GPU
memory in use) so the sbatch log shows the nodes came up clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(slurm): explicitly cover vllm-router in cleanup
Address review feedback: add vllm-router to the pkill list and the
procs-count regex so the intent is explicit, even though the broader
"vllm" patterns already match it as a substring.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(slurm): also kill prctl-named vllm::router workers
pkill -f only matches the command line, so the vllm router's worker
processes — which set their kernel process name (comm) to "vllm::router"
via prctl but keep a different cmdline — slip through. Add process-name
pkill for "vllm" and "vllm::.*" to catch them.
Also broaden the post-cleanup procs count to look at both comm and args
(ps -eo comm,args) so we see these if any survive.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Rename '[orchestrator.sampling]' -> '[orchestrator.train.sampling]',
'[[orchestrator.env]]' -> '[[orchestrator.train.env]]', and
'max_tokens' -> 'max_completion_tokens' across all configs to remove
reliance on the deprecated auto-translation.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat: drop filtered rollouts from training batch instead of masking
Previously, enforced filters zeroed the completion_mask on detected
rollouts but still sent them through the entire training pipeline.
This wastes compute on samples that contribute nothing to the loss.
Now, `apply_filters` returns the subset of rollouts that should be
sent to the trainer. Enforced-detected rollouts are excluded before
pretokenization, VLM cache building, and sample construction.
The trainer handles the resulting empty batches ("phantom steps") by
skipping forward/backward and logging `data/is_empty_batch`.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: retry empty filtered batches instead of passing them to trainer
Keep the invariant that the trainer only receives non-empty batches. If
all rollouts are filtered out, regenerate the batch (up to 3 retries)
and crash the orchestrator on sustained failure. Warn at <=10% trainable.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: drop redundant num_rollouts guard
The retry loop only breaks when len(filtered_rollouts) > 0, which implies
num_rollouts > 0, so the guard is unreachable.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: expand low-trainable-ratio warning with env review hint
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: drop empty-df guard and inline filtered metrics
filtered_rollouts is guaranteed non-empty after the retry loop, so the
empty-df branch is unreachable and the intermediate locals add no value.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: hoist MAX_EMPTY_BATCH_RETRIES to module scope
Also rename the loop var and warning message to "retry N/MAX" so the
counter excludes the initial attempt and reads less ambiguously.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: adjust log style in filter retry warnings
Drop trailing periods and replace ";" with " - " as clause separator.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: clarify low-trainable-ratio warning hint
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor: compute metrics over all rollouts, drop only from trainer
Metric logging reverts to main's semantics: all rollouts contribute to
prefill_len, decode_len, samples_per_rollout, and results_df. Filtered
rollouts are still pretokenized and interleaved, but their samples are
simply not added to train_examples. Also inline the generate_batch
coroutine since it is awaited immediately.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor: move filter flags to rollout["filter"] + is_filtered
Per-filter detection booleans now live under rollout["filter"], and a
top-level rollout["is_filtered"] captures whether any enforcing filter
triggered. The orchestrator uses is_filtered directly as the keep gate
(no more id() mapping). apply_filters no longer returns filtered_rollouts
- the in-place flags are the single source of truth. Also unbound-var
fix for retry-loop locals, and per-env filter/<env>/<flag>_rate logging
that mirrors the metrics logging pattern.
Both new fields are serialized to train_rollouts.jsonl via save_rollouts,
which already writes all top-level rollout keys.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: cap to 3 total batch-generation attempts, not 3 retries
Rename MAX_EMPTY_BATCH_RETRIES to MAX_EMPTY_BATCH_ATTEMPTS and have the
loop run exactly that many times. Warning now reports the attempt that
just failed ("Attempt N/3 ... retrying").
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: log error line before raising on exhausted retries
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: align filter metric key names with per-env logging
Rename filter/total_detected_rate -> filter/detected_rate and
filter/total_enforced_rate -> filter/is_filtered_rate so the overall
keys mirror the per-env filter/<env>/is_filtered_rate naming.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor: unify filter logging under filter/{all,<env>}/{<filter>,is_filtered}
Move is_filtered into results_df so it can be aggregated per-env like
is_truncated. filter_df now holds just per-filter detection booleans.
apply_filters no longer returns an aggregate metrics dict - the
orchestrator derives the rates uniformly across the "all" and per-env
scopes, with symmetric key naming and no _rate/_count suffixes.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: rename rollout["filter"] to rollout["filters"] + log keys
Aligns with the plural configs list and the rollout-level "filters"
namespace. Log keys change from filter/{all,<env>}/... to
filters/{all,<env>}/....
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat: self-evict orchestrator when batches carry no learning signal
Write control/evicted.txt before raising, so the multi-run manager
skips the run on rediscovery instead of treating it as a hard crash.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove prefix-cache-salt and reset-prefix-cache config flags
Hardcode the defaults: always set cache_salt on inference requests
(keyed by ckpt_step) and never reset the prefix cache after weight or
LoRA updates. The salt alone is sufficient to invalidate stale KV
states across policy updates, so the reset path is redundant.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore: keep empty experimental sub-configs as extension points
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Use bearer auth for Prime monitor uploads
* Fix Prime monitor presign and finalize flow
* Sanitize non-finite Prime monitor payloads
* Simplify Prime monitor payload normalization
* Simplify Prime monitor public API contract
* Simplify public presign response parsing
* Simplify non-finite payload sanitization
* Inline public presign response parsing
* Inline non-finite payload sanitization logic
* Refine Prime monitor JSON sanitization
* Address review: inline auth headers and simplify sanitize
- Remove _api_headers() helper; store self._headers once in __init__
- Always sanitize payloads; drop silent try/except and log only when values are dropped
- Remove prime_cli sys.modules mocking from tests (real dep is installed)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
parallel training with FA4 kernels. Mirrors the FA3 ring attention
pattern (all-gather K/V, compute per GQA stride, reduce-scatter grads)
using FA4 low-level _flash_attn_fwd/_flash_attn_bwd.
Changes:
- ring_attn.py: FA4 forward/backward wrappers, _RingFA4Varlen autograd
Function, ring_fa4_varlen_func public API
- attn.py: route FA4 to ring_fa4_varlen_func in substitute_ring_attn
- trainer.py: allow CP with fa4 (requires model.impl='custom')
get_free_port() only holds the port until it returns, so parallel
env spawns under asyncio.gather could hand the same port to two
children — the loser died with EADDRINUSE. Serializing start()
and awaiting wait_for_server_startup() between envs ensures each
port is bound before the next one is picked.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When `verifiers` CliAgentEnv catches an agent crash pre-LLM-call, it
sets `state["error"]` but the trajectory stays `[]` because the agent
never produced any messages. The previous branch order fired the
"Empty trajectory" warning first and dropped the detailed AgentError
diagnostic. Swap the branches so error-bearing rollouts surface
"Rollout error ...: {error_chain_repr}" instead.
Related: PrimeIntellect-ai/verifiers#1127, #1130
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Previously `clean_future_steps` only ran when resuming from a checkpoint,
so a fresh run started in an output_dir containing stale rollouts or
broadcasts from a previous run would consume them: the trainer would
train on stale data and the orchestrator would compute a negative async
level because it sees a trainer that is seemingly ahead of it.
Run the same cleanup from step 0 when training from scratch so these
artifacts are removed before training begins.
Two fixes:
- Use setdefault so X-Session-ID: example_id is always present for
sticky DP-aware routing, even if user provides other
extra_headers_from_state entries
- Propagate extra_headers_from_state when rebuilding clients in the
elastic pool, so session headers survive pool refreshes
Keeps dp_rank_count as-is for direct DP rank routing.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Support runtime verifiers version override via VERIFIERS_VERSION env var
When set, the entrypoint reinstalls verifiers from the specified git ref
(tag, branch, or commit) before starting the main process.
* Drop --no-deps so transitive deps are updated with verifiers override
* Use --reinstall-package to only reinstall verifiers, not the entire dep tree
* feat: pre-download model weights in launcher instead of using HF_HUB_OFFLINE
Remove hardcoded `HF_HUB_OFFLINE=1` from multi-node SLURM templates and
instead pre-download model weights via `snapshot_download` in the rl/sft
launchers before dispatching to local or SLURM execution. This ensures
weights are cached on the shared filesystem before training starts,
removing the need to manually pre-download models.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: pre-download model weights in launcher instead of using HF_HUB_OFFLINE
Remove hardcoded `HF_HUB_OFFLINE=1` from multi-node SLURM templates and
instead pre-download model weights via `snapshot_download` in the rl/sft
launchers before dispatching to local or SLURM execution. This ensures
weights are cached on the shared filesystem before training starts,
removing the need to manually pre-download models.
Also replace `format_time` with the verifiers-style two-unit display
(e.g. "1h 30m" instead of "1.50h").
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: move pre_download_model to trainer.model
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: log cache path when model is already downloaded
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove redundant cache log from pre_download_model
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: move pre_download_model import to module top
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: skip download and log cache path when model already cached
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Revert "feat: skip download and log cache path when model already cached"
This reverts commit 5b2bac9f2bb9e22ae898fe54f66f48357931dc40.
* chore: keep HF_HUB_OFFLINE=1 in SLURM templates
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: set tool_call_parser default to 'auto'
Changed the default value of tool_call_parser from None to 'auto' to enable automatic tool call parser detection from model name by default. This provides better out-of-the-box experience for users working with tool-calling models.
* test: add unit tests for inference metrics collector
Tests parsing, aggregation (sum/max/mean), counter rates, histogram
latency, counter reset handling, server failures, and wandb logging.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Revert "test: add unit tests for inference metrics collector"
This reverts commit 48eb049144b51ec9a2562358b398c2be46bc8eca.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: add gpt-oss extra to Dockerfile uv sync
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix buffer init for meta loading
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add `reset_prefix_cache_after_update` config to disable prefix cache reset
When prefix caching correctness is not a concern, the cache reset after
weight updates and LoRA adapter loads can be skipped to avoid the extra
latency. The new `inference.reset_prefix_cache_after_update` flag
(default: True) controls this behavior.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add `use_prefix_cache_salt` to invalidate stale prefix caches via salt
Instead of resetting the entire prefix cache after weight updates,
this sets a `cache_salt` (= ckpt step) on every inference request.
vLLM uses the salt to partition cached prefixes, so KV states from
old weights are never reused while keeping the cache warm for the
current policy.
Covers train envs (updated in scheduler after weight update),
eval envs (updated before each evaluation), and initial setup.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: default salt on, default reset off
Salt (use_prefix_cache_salt) is now True by default — it partitions
the prefix cache by policy version with zero overhead.
Reset (reset_prefix_cache_after_update) is now False by default —
the full cache reset is still available for users who want to ensure
all KV states are recomputed at the cost of extra prefill.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: set use_prefix_cache_salt in test scheduler fixture
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: move prefix cache fields to experimental configs
Move reset_prefix_cache_after_update into InferenceExperimentalConfig
and use_prefix_cache_salt into OrchestratorExperimentalConfig.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: pass cache_salt as argument instead of mutating env state
Pass cache_salt through run_rollout/run_group/evaluate as an explicit
parameter instead of mutating env.sampling_args in place. The salt is
computed at schedule time from ckpt_step, so each rollout captures the
policy version it was scheduled under.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: collect per-engine inference server metrics via Prometheus
Poll vLLM /metrics endpoints every 5s from the orchestrator and log
aggregated inference metrics to W&B on a time-based axis. Metrics
include request queue sizes, KV cache usage, prefix cache hit rate,
prefill/decode throughput, completed requests/s, and NIXL transfer
latency. Gated on wandb config — no-op when W&B is disabled.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address review feedback on inference metrics collector
- Add collect_inference_metrics config (default True) to allow disabling
- Remove type hint on collector variable in orchestrator
- Log both max and mean for KV cache metrics to surface imbalance
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove unused _SUM_GAUGES variable
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Introduces empty experimental config classes for each user-facing config:
- RLExperimentalConfig for RLConfig
- InferenceExperimentalConfig for InferenceConfig
- OrchestratorExperimentalConfig for OrchestratorConfig
- SFTExperimentalConfig for SFTConfig
- TrainerExperimentalConfig for TrainerConfig
Each config now has an field with a default instance of its
corresponding experimental config. These are intentionally left empty for
now to provide a structured place for future experimental features.
* feat: KV cache offloading on both prefill and decode nodes in P/D disaggregated mode
Enable OffloadingConnector on decode nodes (previously prefill-only) and
fix several issues blocking disaggregated P/D with CPU KV cache offloading:
- **Fix CPUOffloadingSpec `num_blocks` miscalculation**: the spec multiplied
`page_size_bytes` by `len(kv_cache_tensors)`, but for
`UniformTypeKVCacheSpecs` the page size already aggregates all layers.
This made `num_blocks` ~156× too small for GLM-5, so pinned CPU tensors
were undersized and `swap_blocks` (`cuMemcpyDtoHAsync_v2`) segfaulted on
out-of-bounds pinned memory. Applied as a monkey-patch via the
`transformers_v5_compat` vLLM plugin.
(upstream: vllm-project/vllm#38395, vllm-project/vllm#39500)
- **OffloadingConnector on decode nodes**: when `kv_cache_offload` is
configured, both prefill and decode now get
`MultiConnector(NixlConnector + OffloadingConnector)`.
- **Router `--intra-node-data-parallel-size`**: was hardcoded to 1 (P/D
disaggregated) or missing (multi-replica), now set to `{{ gpus_per_node }}`
so the router correctly distributes across DP ranks.
- **`ulimit -l`**: raise locked-memory limit early in the sbatch script so
pinned allocations succeed.
- **Router bump**: vllm-router 0.1.14 → 0.1.18 for P/D disaggregation
fixes.
- Removed unused `block_size` pass-through from OffloadingConnector config
(was never read by CPUOffloadingSpec).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: align OffloadingConnector config and router DP across both templates
- Remove unused `block_size` field from KVCacheOffloadConfig and templates
- Add `dp_per_node` template variable (gpus_per_node // tp) for router
`--intra-node-data-parallel-size` (was hardcoded to 1 or missing)
- Align multi_node_rl template with inference template: decode nodes now
get OffloadingConnector when kv_offload is enabled
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* style: format patches.py and inference config
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: pass dp_per_node to all deployment types, not just disaggregated
The multi_node template branch also uses {{ dp_per_node }} for the
router --intra-node-data-parallel-size flag. Move the variable into the
common template_vars so it's always available.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Some changes
* Fix: ep backends
* Fix: router dp per node
---------
Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: propagate shared model name to trainer tokenizer config
TrainerConfig.auto_setup_tokenizer runs during TrainerConfig construction
(before RLConfig validators), so it copies the default model name to the
tokenizer. When RLConfig.auto_setup_model later overwrites trainer.model.name
with the shared [model] name, the tokenizer.name is left stale.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add chat_template as first-class config field and shared tokenizer config
- Add `chat_template` to `BaseModelConfig` (shared.py) so all model configs
(trainer, orchestrator, inference) support it
- Add `chat_template` to `SharedModelConfig` (rl.py) for propagation across
all RL components
- Add `TokenizerConfig` to `OrchestratorConfig` and use `setup_tokenizer` in
the orchestrator (same as trainer), replacing inline AutoTokenizer usage
- Wire `chat_template` through to vLLM via `to_vllm()` in inference config
- Fix tokenizer name not being propagated from shared `[model]` config to
trainer/orchestrator tokenizer configs (auto_setup_tokenizer ran before
RLConfig could set the correct model name)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: move chat_template to shared tokenizer config, not model config
- Remove chat_template from BaseModelConfig (it's a tokenizer concern)
- Add shared TokenizerConfig to RLConfig that propagates to trainer,
orchestrator, and inference
- Add chat_template as top-level field on InferenceConfig for vLLM
- RLConfig.auto_setup_tokenizer re-derives name/trust_remote_code from
model config in both shared and non-shared tokenizer cases
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* add validate_shared_tokenizer to enforce trainer/orchestrator match
Extracts tokenizer mismatch validation into a proper validator function
in validation.py, consistent with the existing validation patterns.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* validate inference chat_template matches shared tokenizer
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* move chat_template to inference model config
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* simplify docstring
* simplify: make shared tokenizer non-optional, single code path
Make `RLConfig.tokenizer` default to `TokenizerConfig()` instead of
`None`. This eliminates the `else` branch that unconditionally overwrote
per-component values. Now there's one code path: copy shared tokenizer
to components, fill None fields from model config.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Revert "simplify: make shared tokenizer non-optional, single code path"
This reverts commit 93460ed86dbd68d3897e21e9c6bc07764c2694be.
* fix: validate chat_template only, not full tokenizer config
The full tokenizer equality check failed for configs where inference
uses a different model variant (e.g. FP8 quantized), causing the
orchestrator tokenizer name to differ from the trainer's. Only
chat_template needs to be consistent across components.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add `router_policy` field to MultiNodeInferenceDeploymentConfig and
DisaggregatedInferenceDeploymentConfig, replacing the hardcoded
`consistent_hash` policy in the sbatch template.
Defaults to `consistent_hash` (no behavior change). Set to `round_robin`
for deployments where sticky routing is not needed (e.g. standalone user
model servers without prefix caching).
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix missing arg mm_token_type_ids for vlm
* fix: extend mm_token_type_ids when packing text-only samples
Follows the same pattern as teacher_logprobs and routed_experts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: move mm_token_type_ids after routed_experts in TrainingSample
array_like=True uses positional encoding — inserting before
routed_experts would shift its index and break deserialization.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* test: assert mm_token_type_ids in VLM cache trajectory test
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* style: run ruff format
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Signed-off-by: Mika Senghaas <mail@mikasenghaas.de>
Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
* feat: add option to filter zero advantage samples
Add config option to filter out training samples with zero advantage.
This is a simple postprocessing step in the orchestrator that filters
samples before sending them to the trainer.
* feat: use filter abstraction for zero advantage filtering
Keep simple filter_zero_advantages config option but use the filter
abstraction internally. ZeroAdvantageFilter is created and applied after
advantages are computed, masking zero-advantage rollouts.
* feat: enable zero advantage filtering by default
* refactor: integrate zero advantage filter into filter system
- Add ZeroAdvantageFilterConfig using BaseModel with ConfigDict
- Make compute_advantages in-place to store advantages on rollouts
- Remove separate zero advantage filtering branch
- Fix aggregate metrics overwrite by applying all filters in one place
- Change default to opt-in (not included in default filters list)
- Add CHANGELOG entry
* fix: remove references to undefined advantages variable
- Update loop to get advantage from rollout dict instead of undefined variable
- Extract advantages from rollouts for distribution logging
* refactor: simplify compute_advantages to extract rewards/lengths from rollouts
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: enable zero_advantage filter by default
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: move filter setup logging into setup_filters, show per-filter config
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: improve per-filter setup log format
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: inline get_logger() in setup_filters
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: save train and eval rollouts in verifiers format
Save rollouts to {output_dir}/rollouts/step_{x}/ as JSONL files using
verifiers serialization at every step. Also renames rollouts.bin to
train_rollouts.bin for consistency.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: run save_rollouts in background thread to avoid blocking event loop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: replace rollout_executor with asyncio.to_thread + scaled default executor
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: extract set_default_executor util, call in orchestrator init
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: document rollout JSONL files in monitor-run skill
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: fix rollouts path in monitor-run skill to include run_dir
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: save final eval rollouts to disk
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: await save_rollouts to prevent race with in-place rollout mutations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: await final eval rollouts save to prevent data loss on shutdown
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The RL and SFT trainers hardcode torch.set_float32_matmul_precision("high"),
which is fine on NVIDIA hardware but is not always the right setting on
ROCm/AMD GPUs, where the reduced-precision matmul path can affect softmax
accuracy for models with large vocabularies.
This adds a matmul_precision field to TrainerConfig and SFTConfig. The
default stays at "high" so nothing changes for existing runs, but users
who need full FP32 (e.g. on ROCm) can now set matmul_precision = "highest"
in their trainer config without patching the source.
Co-authored-by: Daniel Zautner <daniel.zautner@silo.ai>
* fix: handle chat template errors in eval sample logging
`apply_chat_template` can fail when completions contain tool calls
serialized as strings (e.g. from verifiers) that the model's Jinja
template expects as objects. Fall back to raw string representation
instead of crashing the orchestrator.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: deserialize tool call args before falling back to str() in eval logging
When apply_chat_template fails, try deserializing tool call arguments
from JSON strings to dicts first (matching the SFT entrypoint pattern)
before falling back to str(completion).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: deserialize tool call args upfront instead of nested fallback
Always deserialize tool call args before applying the chat template,
matching the SFT entrypoint pattern. deserialize_tool_calls is
idempotent so this is safe to call unconditionally.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: root <root@accomplished-lori-of-penetration.datacrunch.io>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: separate eval client type (openai_chat_completions) from training
Eval rollouts now use openai_chat_completions instead of the TITO
(token-in-token-out) client used for training. Adds eval_clients and
get_eval_client() to both StaticInferencePool and ElasticInferencePool.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: rename client_type to train_client_type for clarity
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: align pool constructors, rename clients -> train_clients, move TITO warning
Both StaticInferencePool and ElasticInferencePool now take the same
constructor signature: (client_config, model_name, train_client_type,
eval_client_type). Renamed clients property to train_clients for
symmetry with eval_clients.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* update warn log
* chore: fix TITO warning, remove get_next_client, add eval to alphabet sort config
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: rename _clients to _train_clients for consistency
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: default train_client_type to openai_chat_completions_token
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: teacher pool gets explicit non-TITO client type, clear eval_clients on stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: revert accidental rollouts.bin rename
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: guard get_eval_client on eval_clients instead of train_clients
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove unused has_clients property
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: make eval interval configurable per eval environment
Each eval env can now have its own `interval` field. If unset, it
inherits from the group-level `eval.interval`. The orchestrator
tracks last-eval-step per env so environments with different cadences
run independently.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove per-env interval unit test
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: make num_workers and max_retries shareable for train and eval groups
Both TrainConfig and EvalConfig now expose group-level `num_workers`
and `max_retries` fields that are inherited by individual envs unless
overridden per-env.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: consolidate per-env overrides into single resolve_env_defaults validator
Merge resolve_sampling and resolve_env_defaults into one model
validator for both TrainConfig and EvalConfig.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* update log
* update default interval
* fix: garbled eval log message from joining characters of a string
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove square brackets from eval log message
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* add eager attention implementation option since transformer kernels for gpt-oss don't support blackwell yet
* add check for gpt-oss attention kernel on non hopper
* add kernels dependency for gpt-oss
* ruff
* changelog
* disable hub kernels by default and only activate for gpt-oss
* uv lock merge conflict resolved
* fix: prepend base_model.model. prefix to broadcast LoRA keys
* fix: normalize LoRA key prefix on both broadcast and loading sides
* simplify: rewrite safetensors file in-place instead of wrapping safe_open
* ruff format
* add file lock to prevent race condition between workers
* only acquire lock/write when keys actually need fixing
* revert base model patch in ckpts
* use upstream patch
---------
Co-authored-by: Jackmin801 <ongjackm@gmail.com>
The /v1/chat/completions/tokens route had a blanket `except Exception`
that wrapped all errors as HTTPException(500), including
VLLMValidationError from prompt length validation. The regular
/v1/chat/completions route works correctly because it lets exceptions
propagate to FastAPI's app-level exception handler which recognizes
VLLMValidationError and returns 400.
Remove the try/except to match vLLM's own route pattern.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* ckpt
* chore: flatten env group config and move env_ratios to per-env ratio field
- Remove ValConfig and all val-related orchestrator code (not part of env group refactor)
- Move env_ratios from BufferConfig to per-env ratio field on EnvConfig
- Fix merge artifacts: train_env_names -> train_envs.names, env_cfg.server.address -> env_cfg.address
- Add validator ensuring env ratios are all-or-nothing across envs
- Update tests and example configs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: simplify orchestrator env setup and auto-detect group scoring
- Extract spawn/connect/shutdown into Envs class with atexit cleanup
- Auto-detect group rubric envs and use run_group instead of deferred scoring
- Remove deferred_group_scoring_tasks, max_concurrent from EnvConfig
- Fix stale eval references (eval_env_set, eval_env_names, config.eval.num_examples)
- Use Sequence[EnvConfig] for covariant type compatibility
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: introduce Env wrapper class and simplify orchestrator plumbing
- Env wraps vf.Environment + config with per-env state (group scoring,
max_retries, ratio, spawn/connect/shutdown, generate_rollout/generate_group)
- EvalEnv extends Env with num_examples, rollouts_per_example, and evaluate()
- Envs is now a thin container over Env instances
- Scheduler uses env.uses_group_scoring and env.generate_* directly instead
of maintaining parallel dicts/sets
- Buffer iterates Env instances directly for datasets and ratios
- evaluate_and_log replaces evaluate_env, taking an EvalEnv directly
- Tests use make_env/make_envs helpers for cleaner Env construction
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: store sampling_args on Env, remove temp scheduling from orch
- sampling_args set once at env init via Envs.set_sampling_args()
- Remove per-step compute_temperature + set_sampling_args from training loop
- get_sampling_args no longer takes temperature param
- Add TrainEnv/EvalEnv subclasses with distinct get_dataset behavior
- EvalEnv.get_dataset calls get_eval_dataset, base Env uses get_dataset
- Buffer no longer needs eval flag — uses env.get_dataset() polymorphically
- Raise on connect if address not configured
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: type-narrow TrainEnv constructor to TrainEnvConfig
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: set sampling args at env init, compute once per orchestrator
- TrainEnvs takes SamplingConfig and computes train sampling args once
- EvalEnvs takes EvalSamplingConfig and computes eval sampling args once
- Remove set_sampling_args, get_eval_sampling_args calls from orchestrator loop
- evaluate_and_log uses eval_env.sampling_args directly
- Access max_retries and ratio through config instead of duplicated attrs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: inline vf_utils into Env, rename get_sampling_args
- Inline run_rollout/run_group logic into Env.generate_rollout/generate_group
- Make uses_group_scoring a property on Env (reads rubric directly)
- Rename get_sampling_args -> get_train_sampling_args
- Move get_eval_sampling_args from eval_utils to utils (next to train variant)
- Rename vf_env -> _env
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: set sampling_args from orchestrator, rename to run_rollout/run_group
- Remove sampling config from TrainEnv/EvalEnv constructors
- Orchestrator computes sampling args and sets via Envs.set_sampling_args()
- Rename generate_rollout -> run_rollout, generate_group -> run_group
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove dead code, inline spawn/connect into Env
- Remove dead vf_utils functions: run_rollout, spawn_env_server,
setup_env_client, wait_for_env_servers, task_uses_group_scoring
- Inline spawn logic (ZMQEnvServer.run_server) directly into Env.spawn()
- Inline connect logic (ZMQEnvClient) directly into Env.connect()
- Convert name and uses_group_scoring from properties to attributes
- Clean up unused imports from vf_utils
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: revert math_group config changes
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove commented-out TrainEnvConfig stub
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: inline evaluate/generate/run_group into EvalEnv
- EvalEnv.evaluate() now contains the full eval pipeline (get inputs,
round-robin clients, gather groups, collect results)
- Remove run_group, generate, evaluate functions from vf_utils
- Remove dead constants (DEFAULT_RETRIES, DEFAULT_STATE_COLUMNS, REQUIRED_STATE_COLUMNS) from vf_utils
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: inline eval pipeline into EvalEnv, remove semaphore and dead code
- EvalEnv.evaluate() now handles rollout generation, metrics, and logging
- Support group scoring in evaluate() via requires_group_scoring branch
- Rename uses_group_scoring -> requires_group_scoring
- Remove semaphore (set_semaphore, get_semaphore) and max_concurrent config
- Remove log_eval_results, evaluate_and_log — eval_utils down to ckpt_step + pass@k
- Remove strip_env_version, add EnvConfig.stripped_id property
- Use model_name consistently
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: resolve num_workers in configs, cleanup naming and logging
- Resolve train env num_workers in OrchestratorConfig from max_inflight_rollouts
- Resolve eval env num_workers in EvalEnvConfig from num_examples * rollouts_per_example
- Remove resolve_num_workers from vf_utils, max_concurrent from Env.spawn()
- Rename by_task -> by_env in scheduler
- Add EnvConfig.stripped_id property, remove strip_env_version function
- Use debug-level logs for spawn/connect
- Use prime-rl logger in process utils instead of loguru
- Fix eval_envs unbound error when no eval config
- Add multi_reverse_text test config without external server
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: make Envs generic over env type for correct type narrowing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: fix tests — remove val config from all TOML files, fix task->env_name
- Remove [orchestrator.val] sections from all config files (ValConfig removed)
- Fix test_scheduler: task= -> env_name= in InflightRolloutInfo
- Warn when eval env defaults to 4 workers due to num_examples=-1
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: unify rollout dispatch with Env.run() helper
- Env.run() dispatches to run_rollout or run_group based on
requires_group_scoring and rollouts_per_example, always returns list
- Scheduler and EvalEnv.evaluate() both use env.run() — no more branching
- Unified result handling in scheduler (single path for both modes)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: rename EnvBuffer -> Buffer, BufferSet -> Buffers, narrow to TrainEnvs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: Buffer takes TrainEnv directly, gets its own dataset
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: merge Buffer naming — Buffer is the public API, _EnvBuffer is internal
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: stop hijacking vf task field for env identification
- Remove example["task"] = env.name override in buffer
- Change default hash_keys from ["task", "prompt"] to ["env_name", "prompt"]
- Add env_name column to wandb and prime monitor logging
- task field now purely vf-internal (set by verifiers, not overridden)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: restore eval interval gate, verification.enabled flag, and minor cleanups
- Restore `if eval_ckpt_step is not None` guard so evals run at interval steps only
- Use `self.verification.enabled and env.score_rollouts` so global flag is respected
- Fix stray `)` in spawn log message
- Fix `update_pools` return type annotation (str, not list[str])
- Use `get_logger().warning()` instead of `warnings.warn()` in EvalEnvConfig
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: add changelog entries for env group refactor breaking changes
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: improve EnvConfig and EvalEnvConfig field descriptions
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: silence noisy eval num_workers warning in config validator
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove dead parse helpers, fix ratio field description
- Remove unused parse_num_completion_tokens and parse_is_truncated_completions
- Fix ratio description: ratios are relative weights, not required to sum to 1
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove env-var modules, inline os.environ into World
- Delete utils/envs.py and trainer/envs.py (97 lines of env-var parsing ceremony)
- Inline os.environ.get() calls directly in World.__init__
- Remove dead parse helpers and fix ratio field description
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove temp scheduler, avoid list alloc in buffer sampling
- Delete TemperatureSchedulerConfig and temp_scheduling module
- Make SamplingConfig.temperature a plain float (default 1.0)
- Use tuple(dict) + random.choice for buffer sampling instead of
materializing a list of values on every call
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: merge spawn+connect into Env.start(), add requires_env_server_spawn
- Env.start() spawns (if needed) and connects in one call
- Envs.start() does the same for all envs in parallel
- Add requires_env_server_spawn property for readability
- Move spawn logic to private _spawn()
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: split run into run_rollout/run_group, fix eval group scoring
- Env.run_rollout() returns a single RolloutOutput
- Env.run_group() returns list[RolloutOutput] for group-scoring envs
- EvalEnv.evaluate() dispatches correctly: n*k individual run_rollout
calls for non-group envs, n run_group(k) calls for group-scoring envs
- Replace _get_eval_inputs with own logic (get_dataset + flat repeat)
- Scheduler normalizes single/list results via isinstance check
- Progress bar tracks n*k rollouts in both eval modes
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: simplify evaluate() dispatch into single run_with_progress
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: define run_with_progress per branch to avoid misleading param
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: move get_dataset to TrainEnv, inline get_eval_dataset in evaluate
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: load eval dataset once in EvalEnv constructor
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove redundant total_count variable in evaluate
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* mini
* update config
* chore: remove score_rollouts from EnvConfig, fix group scoring reschedule
- Remove score_rollouts field from EnvConfig (was internal, not user-facing)
- Fix group-scoring envs: discard entire group on partial failure and
reschedule from scratch (group rewards require all rollouts together)
- Fix "Eval environments ready" -> "Eval environment(s) ready"
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove VerificationConfig, rollout scoring is always enabled
- Delete VerificationConfig class and verification field from OrchestratorConfig
- Remove validate_verification_config validator
- Stop setting score_rollouts in extra_env_kwargs (defaults to True in verifiers)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: wrap single run_rollout result in list in scheduler
run_rollout returns a single RolloutOutput, not a list. Without
wrapping, iterating over the dict yields keys instead of the rollout.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: rename n/k to descriptive names in evaluate, fix k shadowing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove unused num_rollouts param from update_pools
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: rename InflightRolloutInfo to InflightRequest dataclass
Convert from NamedTuple to dataclass for direct mutation of
off_policy_steps, and rename to better reflect what it represents.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: count rollouts not tasks for group-scoring capacity and metrics
inflight_rollout_count, cancel_inflight_rollouts, and drop_group all
counted tasks (1 per group request) instead of actual rollouts. This
caused the capacity check to allow up to rollouts_per_example × more
concurrent rollouts than max_inflight_rollouts intended.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: document skip_first removal in changelog
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: rename envs to train_envs in Scheduler, move RolloutInput into Env
Narrows the Scheduler's dependency from generic Envs to TrainEnvs and
moves vf.RolloutInput construction into Env.run_rollout/run_group so
callers just pass plain dicts. Fixes a missed self.envs reference in
generate_batch that would have caused an AttributeError at runtime.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: update Scheduler kwarg from envs to train_envs in orchestrator
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: use composition for TrainConfig/EvalConfig, add per-env sampling
- OrchestratorConfig uses composition (train: TrainConfig) instead of
inheriting TrainEnvsConfig; before validator preserves [[env]] and
[sampling] TOML compat
- Rename SamplingConfig -> TrainSamplingConfig, TrainEnvsConfig -> TrainConfig
- Drop EvalEnvsConfig, inline into EvalConfig
- TrainEnvConfig supports per-env sampling overrides merged via
model_dump(exclude_unset=True) so only explicit keys override group defaults
- Resolve sampling args at TrainEnvs/EvalEnvs construction, remove
set_sampling_args
- Remove temperature from logged metrics
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: restore group-level num_examples/rollouts_per_example on EvalConfig
These fields were on EvalConfig on main and got dropped during the
refactor. Re-add them with resolution via model_fields_set so group
defaults propagate to per-env configs unless explicitly overridden.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: terminate env servers in parallel during shutdown
Send SIGTERM to all processes first, then join all — avoids sequential
25s timeouts when multiple env servers are slow to exit.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: move usage_reporter.close() outside _graceful_shutdown
Ensures the usage reporter is closed even if the shutdown task times
out, matching the pre-refactor behavior.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* better logs
* test config
* chore: move sampling args resolution to config classes
- Add `to_sampling_args()` methods on TrainSamplingConfig and
EvalSamplingConfig, replacing standalone get_*_sampling_args functions
- Resolve vLLM-specific extra_body defaults at config validation time
in OrchestratorConfig, removing the is_vllm flag from TrainEnv/TrainEnvs
- Add per-env sampling field to EvalEnvConfig with group-level merge,
matching the existing TrainEnvConfig pattern
- Use model_fields_set for sampling fallthrough instead of None sentinel
- Add deprecation warnings for [[orchestrator.env]] and [orchestrator.sampling]
shorthand with auto-translation
- Update multi_reverse_text config to exercise per-env eval sampling
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove unused EvalSaveHFConfig
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* minor
* docs: update CHANGELOG with recent config changes
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: restore top_k and min_p fields on EvalSamplingConfig
Keep these fields with concrete defaults (-1 and 0.0) to avoid a
breaking change. They flow into extra_body when non-default.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: copy group sampling config when resolving per-env defaults
Envs without explicit sampling overrides received a shared reference to
the group-level config object. resolve_env_config then mutated vLLM
defaults into that shared object, contaminating the group config.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: use orchestrator.train.env in SLURM entrypoint
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: only send non-default eval sampling args to inference server
EvalSamplingConfig.to_sampling_args() was sending temperature=1.0 and
top_p=1.0 even when the user didn't set them. This overrode the
inference server's own defaults, changing eval results vs main.
Now only includes fields that differ from defaults, matching the old
None-based behavior where unset fields were omitted entirely.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: revert EvalSamplingConfig to nullable fields
Concrete defaults caused temperature=1.0 and top_p=1.0 to always be
sent to the inference server, overriding its own defaults and changing
eval results. Nullable fields with None = "defer to server" is the
correct semantic.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: clean stale rollout and broadcast artifacts on resume
Replace the dangerous rm -rf shell cleanup in the sbatch template with a
targeted Python implementation that only removes step directories at or
after the resume point. Move broadcast cleanup (maybe_clean) from
FileSystemWeightBroadcast to the base class so it works for all
broadcast types, and simplify it by always cleaning old steps.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: check weights/ directory in get_weight_dir before falling back to broadcasts/
The orchestrator's get_weight_dir() checked checkpoints/step_X/weight/
and broadcasts/step_X/ but never weights/step_X/ where
WeightCheckpointManager saves HF-compatible weight checkpoints. This
caused filesystem broadcast runs to always load from the broadcast path
instead of the trainer's weight checkpoint.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* only delete future steps
* revert get_weight_dir from main
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Only disable and warn when NCCL_P2P_DISABLE / NCCL_SHM_DISABLE are not
already present in the environment.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Add nvidia-ml-py as an explicit dependency for the pynvml-based NVLink
detection. Upgrade the log message to warning level and tell users how
to override via NCCL_P2P_DISABLE=0 / NCCL_SHM_DISABLE=0.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
In environments without NVLink (e.g. VMs with GPU passthrough), NCCL's
P2P and SHM transports fail with 'unhandled cuda error' because CUDA IPC
is blocked. This adds a pynvml-based check in both the NCCL broadcast
sender and receiver that detects the absence of NVLink and sets
NCCL_P2P_DISABLE=1 and NCCL_SHM_DISABLE=1 to force socket transport.
Uses pynvml (driver-level) instead of torch.cuda so it works regardless
of CUDA_VISIBLE_DEVICES restrictions. No-op on NVLink machines (e.g. H200).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: make gradient clipping optional and error with DeepEP
Gradient clipping (optim.max_norm) can now be set to null to disable it.
When DeepEP is used (model.ep_comm_backend='deepep'), grad clipping must
be disabled as they are incompatible.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove unnecessary dict type annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: auto-disable grad clipping with DeepEP instead of erroring
When DeepEP is used, automatically set optim.max_norm to None with a
warning instead of raising a ValueError. Since there's only one valid
option, no need to make the user fix it manually.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: don't report misleading grad_norm=0.0 to Prometheus when clipping is off
Pass None instead of 0.0 and skip setting the gauge, consistent with
how W&B logging already handles this.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Bound admin client timeouts so a stuck inference server cannot wedge the orchestrator
setup_admin_clients used httpx.Timeout(None), so an unresponsive inference
server would hang the orchestrator forever inside update_weights /
load_lora_adapter (asyncio.gather across all admin clients makes one
stuck server stall the whole call). The existing tenacity retries only
fired on 404/500 status responses, never on a hung connection.
Replace the unbounded timeout with bounded per-phase timeouts (read=300s
covers legitimate LoRA load latency on large adapters), and widen the
retry predicate so transport-level failures (TimeoutException,
TransportError) actually retry instead of propagating as a hard error
on the first hiccup.
* Per-call NCCL timeouts on /init_broadcaster and /update_weights
The previous commit set the global admin-client read timeout to 300s,
which is shorter than the server-side NCCL store_timeout (default 1200s).
That would cause healthy NCCL init / weight broadcasts to abort with
ReadTimeout, and update_weights is not wrapped by tenacity so the abort
would propagate as a hard orchestrator failure.
Override the read timeout per call on the two endpoints whose server-side
work runs an NCCL collective:
- /init_broadcaster: derived from the actual NCCL timeout passed in
(rendezvous timeout + 300s buffer).
- /update_weights: documented constant NCCL_OP_READ_TIMEOUT_S = 1500s,
sized off the default NCCLWeightBroadcastConfig.timeout (1200s) plus
headroom.
The global default stays at 300s so health checks, model checks and LoRA
loads still detect a stuck server quickly.
* Fix ruff format
* Narrow fix: bound only the LoRA load HTTP call
Previous commits on this branch tightened the global admin-client timeout
and added per-call timeouts on the NCCL paths to compensate. That was
overreach: the only call we have evidence of hanging is the
`/load_lora_adapter` POST inside ElasticInferencePool._sync_server_adapter.
NCCL collectives, weight broadcasts and health checks were never broken
by the unbounded global timeout, and touching them just dragged in
NCCL-timeout coupling concerns that shouldn't have been part of this fix.
Revert all the global / NCCL-path changes and apply the bound at the
exact call site that actually wedges:
- /load_lora_adapter POST gets a per-call read=300s timeout via
httpx.Timeout, leaving the global admin-client timeout=None untouched.
- _is_retryable_lora_error keeps the TimeoutException / TransportError
widening so tenacity bounds the total wall time across the 10 retries
instead of letting the new timeout propagate as a hard failure.
* Tighten LoRA load timeouts and use tenacity stop_after_delay for the wall-clock cap
A LoRA load is single-digit seconds in practice; 300s read with 10
attempts and 30s backoff was effectively 'almost infinite'. Drop to a
30s per-attempt read timeout (still generous, just enough to convert a
hang into a TimeoutException that tenacity can see), and use tenacity's
own stop_after_delay(120s) as the wall-clock cap across all retries.
That keeps the bound in tenacity where it belongs — one number to tune,
no per-call wait_for or asyncio.wait reimplementation.
* Update tests for the new LoRA load timeout / retry behavior
- Existing assert_called_once_with broke because the call now passes a
timeout= kwarg. Replace with explicit field-by-field assertions and
also assert that timeout is set (the whole point of this PR).
- Add coverage for the widened _is_retryable_lora_error predicate
(ReadTimeout, ConnectTimeout, ConnectError).
- Add a load_lora_adapter retry test that simulates a stuck server via
ReadTimeout on the first attempt and succeeds on the second.
* Drop redundant predicate-level retry tests
The integration test test_load_lora_adapter_retries_on_timeout_then_succeeds
already exercises the retry-on-timeout path end-to-end, so the unit-level
predicate tests for TimeoutException / TransportError are redundant noise.
* Drop new lora-load retry test, keep minimal kwarg update
* Add training token usage reporting for platform billing
Orchestrator reports training tokens per step to the platform API
for billing. Env-var driven (PI_USAGE_BASE_URL), not user-facing.
- New UsageReporter with background thread + async HTTP POSTs
- run_id captured after setup_monitor to fix timing bug
- Idempotent on (run_id, step, usage_type) for crash-resume safety
- Self-hosted users unaffected (no-op when env var unset)
* Add missing os import in orchestrator
* Simplify usage reporter env vars: PI_USAGE_BASE_URL + PI_USAGE_API_KEY
* Guard UsageReporter instantiation on env var
* Extract BackgroundAsync helper to reduce duplication
The async-client-on-background-thread pattern was duplicated between
PrimeMonitor and UsageReporter. Extract a small reusable helper
(BackgroundAsync) and use it via composition in UsageReporter.
UsageReporter drops from ~160 lines to ~70 lines. PrimeMonitor still
has its own copy and can be migrated to BackgroundAsync in a follow-up
to avoid touching unrelated monitor logic in this PR.
* usage_reporter: drop init log to debug, use f-string
The platform's JSON formatter prints record.msg raw rather than
calling getMessage(), so the printf-style %s placeholder showed up
literally in logs. Switch to an f-string. Also drop the init line
to debug since it fires every run and isn't actionable -- warnings
on actual reporting failures are still surfaced at WARNING level.
* usage_reporter: require API key, gate orchestrator on both env vars
Cursor bot caught a real issue: when PI_USAGE_BASE_URL was set but
PI_USAGE_API_KEY was not, self._api_key was None and httpx rejected
the {"x-api-key": None} header with an obscure .encode() error on
every retry. Reports silently failed three times then logged a
confusing warning.
Fix in two layers:
- Orchestrator only constructs UsageReporter when BOTH env vars are
set, with a clear warning if one is set without the other.
- UsageReporter.__init__ validates both and raises ValueError so
any future caller (or unit test) fails fast at construction time
instead of inside httpx.
* Drop usage_reporter unit tests per review
* Bound orchestrator post-training cleanup with hard timeout
The orchestrator's post-training cleanup awaits scheduler/inference pool/
env teardown without any deadline. If any of those awaits wedges on a
remote peer (env-server ZMQ recv, inference admin httpx aclose, etc.) the
run pod sits in RUNNING forever even though training and the final
checkpoint upload have completed.
Wrap the cleanup sequence in an asyncio.wait with a 60s budget. If it
doesn't finish in time, log a warning and force-exit via os._exit so the
pod terminates and the run flips out of RUNNING. asyncio.wait_for is
deliberately not used because it would itself hang on an uncancellable
inner await — exactly the failure mode we're guarding against.
* Bump shutdown timeout to 5 minutes
* Re-raise cleanup exceptions on the non-timeout path
asyncio.wait does not propagate exceptions from the wrapped task. Without
this, a fast failure inside _graceful_shutdown would leave pending empty
and silently fall through to the success log. await the task once it is
done so cleanup errors surface the same way they did when each step was
awaited directly.
* bunch of stuff
* Feat: dbo/cpu offloading
* fix: ruff formatting for inference entrypoint and patches
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
When resuming from a checkpoint with optim_cpu_offload, set_state_dict()
materializes optimizer states on GPU. After _move_states("cpu") moves them
to CPU, the state_dict (owned by dcp_load) still holds references to the
stale GPU tensors, and the CUDA caching allocator retains the memory.
This causes OOM on the first training step.
Fix: clear the state_dict references, run gc.collect(), and call
torch.cuda.empty_cache() to fully reclaim GPU memory.
Measured on Qwen3-0.6B (single GPU):
- Before: 11.4GB wasted GPU memory after checkpoint load
- After: 58MB wasted (essentially zero)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
When resuming a run, users need to attach to the existing W&B run by
setting WANDB_SHARED_RUN_ID. Previously this was always overwritten
with a new UUID, making it impossible to resume logging to the same run.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: switch default loss from IPO to DPPO+KL
Condition the trust region mask on advantage sign instead of masking
both directions unconditionally. Rename ipo_mask -> dppo_mask in config
and internal variables.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* ruff
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
torchrun's --tee flag prepends every log line with [<role><rank>]: (e.g.
[default0]:). This adds noise without value since we already filter to
specific ranks. Strip the prefix with sed -u in the tail/tee pipelines
and set --role=trainer for clearer per-rank log files.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Add max_total_completion_tokens to EnvConfig
Companion change for verifiers PR #1101. Adds a configurable
max_total_completion_tokens field to EnvConfig that auto-populates
into extra_env_kwargs, flowing through to the verifiers
set_max_total_completion_tokens() setter on MultiTurnEnv.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* update pyproject.toml to apprpriate vf version
* update lockfile
* Rename max_tokens to max_completion_tokens in sampling configs
Renames the field in both SamplingConfig and EvalSamplingConfig for
consistency with OpenAI API naming and the new
max_total_completion_tokens field. The old name is still accepted
via a model validator that emits a DeprecationWarning.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Use logger instead of warnings for max_tokens deprecation
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* update uv.lock
* Use AliasChoices for max_tokens backward compatibility
Replace hand-rolled model_validator alias logic with Pydantic's
built-in AliasChoices on the field. The validator now only logs
the deprecation warning.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Non-breaking additions (new fields with defaults, new features) were
cluttering the changelog and creating unnecessary PR friction. Narrow
the scope to renames, removals, and moves that require users to update
existing configs.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* add `all` optional-dependency group that combines all extras
Makes it easier for downstream projects (e.g. research-prod) to depend
on prime-rl with all optional deps without repeating them individually.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* update lockfile
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* overhauled monitor run skill
* update monitor-run skill: metrics, errors, status format, tmux detection
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* add post-restart verification step to monitor-run skill
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* add cp for dsa
* remove local disk dataset loading from sft data
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* revert non-CP changes from dsa-cp branch
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Feat: cleanup cp
* fix: remove unused dist_nn import in rl/train.py
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: three CP bugs in DSA decoder layer
1. _context_parallel_state() read CP attrs from self_attn, but cleanup
moved them to the decoder layer — position_ids were never gathered.
2. shard_to_cp/gather_for_cp were swapped in decoder forward — hidden
states were double-sharded (8192→1024) instead of gathered (8192→65536),
causing the broadcast shape mismatch.
3. gather_for_cp in rl/train.py called with wrong arity (4 args vs 2 params).
4. count not initialized in setup_sparse_mla_cp.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
The deep-gemm wheel (added in the disagg extra) requires libcudart.so.13,
which is not available in the old CUDA 12.4 image. This caused the vLLM
inference server to crash on import, aborting all nightly CI runs.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* improvement: point vllm-router at PrimeIntellect-ai/router v0.1.13
- Update pre-built wheel URL from samsja/flash-attn-builds (v0.1.11)
to PrimeIntellect-ai/router releases (v0.1.13)
- Update install script from S1ro1 fork to PrimeIntellect-ai/router main
* fix: update router wheel URL to v0.1.14 with correct naming
* ci: retry after release assets available
* chore: update uv.lock for router v0.1.14
* chore: remove install_vllm_router.sh, wheels are now pre-built in CI
* chore: simplify tmux script — add Command window, remove Monitor
Replace the Monitor window (nvtop/htop) with a Command window for
running commands. Logs window stays the same.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: rename Command window to Launcher
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add Claude Code window with log context to tmux script
Starts an interactive Claude Code session with an appended system
prompt containing all log paths for the training run.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: use auto permission mode for Claude Code window
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: give Claude Code awareness of tmux session and Launcher pane
Adds the tmux session name and a capture-pane command to the system
prompt so Claude can read what was run in the Launcher window.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: kill full process trees on rl cleanup to prevent orphaned processes
Each subprocess is now started with `start_new_session=True` so it becomes
its own process group leader. `cleanup_processes` uses `os.killpg` to send
signals to the entire group, ensuring grandchildren (e.g. vLLM workers
spawned by `uv`) are also terminated. A SIGTERM handler is added so that
external termination (e.g. from test timeouts) triggers proper cleanup.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: handle NoSuchProcess race in children() during cleanup
Move parent.children() inside the try/except psutil.NoSuchProcess
block so a process exiting between Process() and children() doesn't
abort the cleanup loop.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove unbounded wait after SIGKILL in cleanup
process.wait() after SIGKILL can block indefinitely if a process is
in uninterruptible kernel state (D state). Just fire SIGKILL and move on.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: set process titles on all entrypoints for process tree visibility
Adds setproctitle dependency and labels every prime-rl process
(Launcher, Inference, Orchestrator, Trainer, SFT, EnvServer) so they
are identifiable in ps/htop/pstree. Bumps verifiers pin to include
the companion change (Verifiers::EnvServer, Verifiers::EnvWorkerN).
Updates the monitor-run skill with process tree documentation.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove intermediate uv wrappers from local launchers
The launcher already runs inside `uv run`, so child processes inherit
the venv. Invoke entrypoints (inference, orchestrator) and torchrun
directly, eliminating one unnecessary process per subprocess.
Also bumps verifiers pin to 73deb26 (set_proc_title in __init__).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add vLLM process discovery to monitor-run skill
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove noisy log from set_proc_title
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: bump verifiers pin to adf8138 (merged companion PR)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The test used random inputs without a fixed seed, causing gradient
differences to occasionally exceed the tolerance threshold.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* add watchdog to packer to detect silent hangs
packer on rank 0 can silently hang on NFS I/O, leaving all other
ranks waiting forever for rank_N.bin files. adds a heartbeat +
watchdog thread that kills the process after 30min of no progress,
letting the StatefulSet restart recover automatically.
* scope watchdog to only be active during pack()
watchdog is now armed/disarmed around pack() in wait_for_batch()
so long training steps, checkpoints, or weight broadcasts don't
trigger false-positive restarts.
* wrap pack() in try/finally to always disarm watchdog
* chore: unify log directories across local and SLURM deployments
Remove Python file logging (log.file config) — deployment-level capture
(stdout redirect for local, tee for SLURM) is sufficient. This eliminates
duplicate log files and simplifies the logging architecture.
Key changes:
- Remove log.file config option and JsonFileSink from logger
- Rename .stdout -> .log for deployment-captured logs
- Unify SLURM logs from slurm/ into logs/ (same as local)
- Trainer shows rank 0 only, all rank logs in logs/trainer/torchrun/
- Multi-node SLURM: logs/trainer/node_N.log, logs/inference/node_N.log
- Symlink logs/trainer.log -> trainer/node_0.log (multi-node)
- Historical per-job logs under logs/slurm/job_{id}/
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: update env log paths in docs to match actual structure
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: simplify env and torchrun logging sections
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: include per-node and per-rank log paths in log messages
Show where to find node-level logs (for multi-node) and per-rank
torchrun logs in the startup log messages for RL, SFT, and inference.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: extract format_log_message to shared utility
Move format_log_message from rl.py to utils/pathing.py and reuse it
in SFT and inference entrypoints, eliminating duplicated formatting logic.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove historical per-job SLURM log copies
The job_* log copies in logs/slurm/ added complexity without much value.
SLURM's own job output log (job_%j.log) already serves as the historical
record.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: move tmux helper section to bottom of logging.md
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: consolidate tmux.sh and slurm_tmux.sh into one script
Log paths are now unified across local and SLURM, so both scripts
were tailing the same files. Merge into a single tmux.sh with a Logs
window (4 panes tailing trainer/orchestrator/envs/inference) and a
Monitor window (nvtop + htop).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: fix logger docs to match actual behavior
setup_logger doesn't raise when called twice (it reconfigures).
get_logger always works (auto-initializes a default if needed).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: remove incorrect env_worker_logs reference
The env_worker_logs config field is defined but never read — env worker
logs are written unconditionally.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove dead env_worker_logs config field
Defined but never read anywhere in the codebase.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: add router logs to slurm monitoring section
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: mention per-node and per-rank trainer logs in performance section
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* docs: generalize config path references to {output_dir}/configs/
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: template rendering bugs and improve log message labels
- Fix Jinja2 tags on same line as tee commands (broken bash output)
- Rename "Trainer:" to "Trainer (rank 0):" in log messages
- Rename "Nodes:" to "All nodes:" and "Per-rank:" to "All ranks:"
- Make per-rank log line a tail -F command following torchrun structure
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: include stderr in all-ranks log tail command
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: update stale log paths in examples, SFT tests, and pathing test
- Fix torchrun glob: **/*.log → */*/*/*.log (tail -F doesn't support **)
- Update 5 example READMEs from slurm/latest_* to logs/ paths
- Update SFT tests from logs/trainer/rank_0.log to logs/trainer.log
- Update pathing test fixture to match new log structure
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: clean up log message code and fix test bug
- Remove hardcoded "Showing rank 0 logs only" message from trainers
(already communicated via format_log_message)
- Derive env_log_dir inside format_log_message instead of requiring
callers to pass it
- Fix test_pathing double mkdir crash (FileExistsError)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: split LogConfig into TrainerLogConfig and OrchestratorLogConfig
- TrainerLogConfig adds ranks_filter (configures torchrun
--local-ranks-filter, defaults to [0]) and log_data
- OrchestratorLogConfig adds vf_level
- Base LogConfig retains level and json_logging
- ranks_filter is passed through to SLURM templates
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: keep LogConfig as-is, only extend with TrainerLogConfig
Revert OrchestratorLogConfig — keep vf_level and log_data on the base
LogConfig for safety. Only TrainerLogConfig extends with ranks_filter.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: remove "(rank 0)" from trainer log message
ranks_filter is now configurable so it may show more than rank 0.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: use total_infer_nodes for log hint and add CHANGELOG entries
- Fix num_infer_nodes using per-replica count instead of total, which
suppressed "All nodes" hint for multi-replica inference
- Add CHANGELOG entries for removed config fields and new ranks_filter
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: use `uv run sft` entrypoint in SFT integration tests
The SFT tests were calling torchrun directly, bypassing the SFT
entrypoint which handles stdout redirection to trainer.log. This caused
tests to read stale/wrong log files from the shared output directory.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: add --clean-output-dir to initial SFT integration tests
The SFT entrypoint validates that output_dir doesn't contain stale
checkpoints. Since output_dir is session-scoped and shared across test
modules, the SFT tests need --clean-output-dir on the initial run.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: add --clean-output-dir to RL integration tests too
All integration tests sharing the session-scoped output_dir should
clean on initial run to avoid stale checkpoint validation errors.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: add GitHub PR guidelines to AGENTS.md
No test plan section in PRs unless tests were actually run or
explicitly requested.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: separate Git and GitHub sections, use bullet list
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: add draft PR guideline to AGENTS.md
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: format branch prefixes as bullet list
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add deterministic garbage collection to avoid stragglers
Disable Python's automatic GC and run manual collections at fixed
intervals so all distributed ranks collect simultaneously, preventing
one rank from stalling others at sync points.
Opt-in via config: `gc = { freq = 50 }` (both SFT and RL trainers).
Inspired by torchtitan's approach (https://arxiv.org/abs/2505.05713).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat: enable deterministic GC by default (freq=50)
Matches torchtitan's default. Can be disabled with `gc = null` in config.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: use f-string for loguru GC log message
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: address review feedback
- Rename `freq` to `interval` for consistency with codebase conventions
- Remove `@staticmethod` and `reason` param from `collect`, make it `_collect`
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* chore: replace toml-config skill with broader config skill
Replaces the narrow toml-config skill with a comprehensive config skill
covering TOML files, CLI overrides, config composition, inspection,
and all field type patterns (booleans, None, lists, dicts, unions, models).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: add entrypoints skill, remove inference-server skill
Add entrypoints skill covering rl, sft, and inference commands.
Remove inference-server skill as its content is now covered by entrypoints.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: streamline installation skill
Consolidate install commands into one code block with basic/advanced sections.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: clean up AGENTS.md, add release skill
Move release notes instructions into a dedicated skill. Streamline
AGENTS.md: concise code guidelines, updated running code section,
removed CLI usage (now covered by config skill).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: add monitor-rl-run skill
Covers finding output directories, log file locations (local vs SLURM),
node allocation, performance diagnostics (trainer wait, orchestrator wait,
env server event loop lag), and quick health checks.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: rename monitor-rl-run to monitor-run, add RL section
Restructure to support future SFT monitoring section alongside RL.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: restructure monitor-run into Check Logs and Check Performance sections
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore: detail GPU allocation for single-node and multi-node RL runs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* update readme
* fix revamp-readme
* update readme
* add real world example
* add real world example
* add swe and deepdive
* add qwen example
* add intellect 3.1 example
* add minimax swe
* add all
* fix wording and typos across example READMEs
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix README links and wording, add memory usage doc reference
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* updare training
* fix glm5 PD disagg config: num_infer_nodes must equal prefill + decode
num_infer_nodes was 16 but prefill (4) + decode (4) = 8.
Set num_infer_nodes = 8 with num_infer_replicas = 2 for 16 total.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix model table: move INTELLECT-3 to glm4_moe, add Trinity as afmoe
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* updare training
* address PR review comments
- Restore accidentally deleted examples/hendrycks_sanity/ from main
- Restore installation section (uv sync, FA3, python/flash-attn checks, eval step)
- Fix model table description: trainer works with HF/Prime ModelForCausalLM, not "built on HF Transformers"
- Improve activation checkpointing description and explain freq parameter
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The gradient comparison between HF and PrimeRL NemotronH diverges in the
attention path (139.5 vs atol=10), causing CI failures. The logits forward
check still passes, and test_nemotron_h_backward independently verifies
all parameters receive non-zero gradients.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Track how many eval rollouts failed due to sandbox/infra errors.
Derived from the difference between total eval inputs and successful
outputs. Also logged in the all-fail early return path.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
PyTorch 2.9 defaults torch.load to weights_only=True, which blocks
deserialization of DTensor types like _StridedShard used in EP checkpoints.
This caused checkpoint resume to fail silently on 397B models with EP=8.
* selective ac
* ruff
* fix
* some changes
* some changes
* some more
* fix
* some more
* some more
* small
* simplify
* address comments
* clean
* fix
* address comment
* address comments
* add attn_proj and mlp targets, remove attention_sdpa
Replace attention_sdpa (checkpointing the attention kernel saves zero
memory with flash attention) with two new selective AC targets:
- attn_proj: checkpoints QKV projections, QK norms, RoPE, and output
projection — everything in attention except the kernel
- mlp: checkpoints the entire dense MLP forward (skipped for MoE layers)
Refactor FlashAttention and SDPAAttention to extract _attn_projections
and _output_proj methods as checkpoint boundaries.
* fix: add rms_norm re-export for nemotron_h compatibility
The selective AC refactoring moved RMSNorm/RMSNormConfig to norms.py,
but nemotron_h (added in main) imports from rms_norm.py. Add a
re-export shim to keep both paths working.
* fix: handle position_embeddings=None in SDPAAttention
NemotronH passes position_embeddings=None since it uses its own rotary
scheme. The FlashAttention path already guarded for this but
SDPAAttention._attn_projections and both forward() signatures were
missing the None handling.
* fix: handle LatentMoE in buffer reset and allow impl=auto for selective AC
- _reset_runtime_moe_buffers now checks (MoE, LatentMoE) like all other
MoE instance checks in the file
- selective_ac_only_with_custom_impl accepts ("custom", "auto") matching
the pattern used by ep_only_with_custom_impl and
router_replay_only_with_custom_impl
* Fix selective AC LatentMoE target detection
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
* Delete tests/unit/train/models/test_selective_checkpointing.py
Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
* fixes for nemotron and GDN models
---------
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>
* feat: integrate verifiers multi-env-worker support
Pin verifiers to 8dffd10 (multi-env-worker branch) which introduces
env worker processes for parallel environment execution. Add per-env
`num_workers` config field (default "auto", scales as 1 worker per 256
concurrent rollouts). Update imports and API calls to match the new
verifiers serve module (workers → serve, log_file → log_dir).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* bump
* chore: unify env log dir and add env log tail commands
Move env server logs to output_dir/logs/envs/{env_name}/ for both
train and eval envs. Use resolved_name consistently instead of
env.name or env.id. Add env log tail commands to RL startup messages
(single_node and slurm) and add an Envs pane to the tmux script.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* bump vf
* docs: add changelog entry for orchestrator.env[].num_workers
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* formatting
* refactor: move env logs to main logs dir and improve log formatting
Move env logs from outputs/run_default/logs/envs/ to outputs/logs/envs/
so they live alongside trainer/orchestrator/inference logs. Also clean up
the log path display: truncate long env names, align columns, and reorder
tmux panes to put envs between orchestrator and inference.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: resolve eval env workers based on num_examples * rollouts_per_example
When num_examples=-1 (all samples), defaults max_concurrent to 1024
(4 workers) with a warning log explaining the fallback.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor: separate train/eval env logs and nested log display
Move env logs into envs/train/ and envs/eval/ subdirs to avoid name
clashes when the same env is used for both. Display logs in a nested
hierarchy: Envs > Train/Eval > individual envs.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix standalone env server logdir
* bump vf
* remove env server config
* address comments
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
`get_sampling_args` was gating `return_token_ids=True` on `use_token_client`,
which meant the non-TITO client path never received token IDs from vLLM.
The verifiers `parse_tokens()` then crashed with `len(None)` because the
response attributes existed but were None.
Replace the `use_token_client` flag with `is_vllm` (derived from
`config.teacher_rollout_model is None`) so vLLM-specific extra_body
params (`return_token_ids`, `top_k`, `min_p`) are always sent when
hitting a vLLM server, and skipped only for SFT distillation against
external non-vLLM APIs.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 10:51:39 -07:00
379 changed files with 32290 additions and 16674 deletions
Any PR that modifies configuration structures or usage patterns must update `CHANGELOG.md`. This includes changes to config fields (added, removed, renamed, moved, or default value changes) in:
Any PR that introduces **breaking** configuration changes must update `CHANGELOG.md`. Breaking changes are those that require users to update existing configs:
-`src/prime_rl/*/config.py`
-`src/prime_rl/rl.py`
-`src/prime_rl/utils/config.py`
-**Renamed** config fields (old name no longer accepted)
-**Removed** config fields (field deleted or moved to a different path)
-**Moved** config fields (field relocated in the config hierarchy)
If such changes are detected without a corresponding `CHANGELOG.md` update, request that the author add an entry.
Additive changes (new fields with defaults, new optional features) and default value changes do **not** require a changelog entry.
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.
- Avoid try/except blocks unless it's really necessary. It's fine that a program fails if something goes wrong as this helps us to catch non-obvious bugs and unforeseen side-effects earlier. You can add try catch on code that explicitly aims to be fault tolerant like adding retry mechanisms or explicit and intentional robustness.
- Do not add unnecessary comments. Especially do not try to explain code change that reflect your work process, do not refer to old code. "The code used to do that but now we are doing this" is not a pattern we want. Instead prefer to use targeted comments sparingly to explain ambiguous code.
## Zen of Python
remember the zen of python when writing code.
## Writing code
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
- **Don't touch `optimization_dtype` / `reduce_dtype`**: never change these model config fields (or their defaults in `trainer.py`) unless the user explicitly asks. They're load-bearing numerical knobs — flipping bfloat16/float32 silently changes training dynamics.
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
- **Zen of Python**: remember the Zen of Python when writing code.
```
Beautiful is better than ugly.
Explicit is better than implicit.
@@ -34,14 +30,14 @@ Namespaces are one honking great idea -- let's do more of those!
## Running code
-All code should be runnable with `uv run` or `uv run <command>`.
-All dependencies should already be installed and pin in the lock file. If not, add it to pyproject.toml and run `uv sync --all-extras` to install it.
-**Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
-**Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
- **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.
## CLI Usage
## Docs
-Config files use `@` syntax: `uv run sft @ path/to/config.toml`
- For multi-GPU with torchrun: `uv run torchrun --nproc-per-node 2 src/prime_rl/trainer/sft/train.py @ path/to/config.toml`
- See the `toml-config` skill in `skills/` for full details on TOML structure, CLI overrides, and available commands.
-**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
@@ -53,20 +49,15 @@ You are responsible for maintaining the skills folder. When a workflow fails and
Write tests as plain functions with pytest fixtures. Don't use class-based tests.
- **Conservative test additions**: don't add new tests unless the user explicitly asks for them or it's clearly necessary. Editing existing tests is fine, but adding new test files or test functions should be the exception, not the default.
- **Test what matters**: only test code with clear, isolated logic — pure functions, abstract base classes, data transformations, well-defined algorithms. Don't test runtime-level code, framework glue, or anything that requires extensive mocking/patching just to get a test to pass. If you need to patch everything out to make it testable, it's probably not worth testing.
## Git
Branch prefixes:`feature/`, `fix/`, `chore/`
- **Branch prefixes**: use`feat/`, `fix/`, `chore/`; use `exp/` for experiment branches (configs, run summaries, pins, notes).
## Releases
## GitHub
When preparing release notes:
1.**Style reference**: check the previous release (`gh release list --limit 1` then `gh release view <tag>`) to match the tone and formatting.
2.**Gather changes**: use `git log <last-tag>..origin/main --oneline --no-merges` to list all commits since the last release.
2.**Check for new commits**: always `git fetch origin main` and re-check right before publishing, since PRs may have been merged while drafting.
3.**Structure**: organize notes into numbered highlight sections (`# 1.`, `# 2.`, ...), then `# Breaking Changes`, `# Bug Fixes`, and `# Misc`.
4.**Highlights**: group related PRs under a single highlight. Use `##` subsections when a highlight contains multiple items (e.g. Performance & Parallelism). Keep the top highlights for the most impactful user-facing features.
5.**Config examples**: when referencing TOML config, verify the exact field names against the actual code or docs — don't guess.
6.**Links**: use clickable links for docs (`[docs/foo.md](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/docs/foo.md)`) and PR references (`[#1234](https://github.com/PrimeIntellect-ai/prime-rl/pull/1234)`).
7.**Contributors**: list all contributors ranked by number of commits, using their GitHub `@username`. Get usernames via the GitHub API, not git author names (which can be inconsistent).
8.**Draft first**: always create releases as `--draft` first, iterate on content, then publish.
- **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 -->`).
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`orchestrator.advantage` length-penalty overhaul + length-weighted baseline**: `length_penalty` is now a single shape — a linear penalty that subtracts `coef * pass_rate * (model completion tokens / orchestrator.seq_len)` from each reward before the baseline subtraction (`pass_rate` = group mean reward, so solved-often problems get the strongest concision pressure and never-solved groups get none), with an optional `gate_by_correctness` flag (default `false`) that restricts the penalty to correct rollouts (`reward == 1`). The previous discriminated `type = "tokens" | "turns"` efficiency-shaping variants and the per-penalty `max_length` field have been removed — configure `[orchestrator.advantage.length_penalty]` with `coef` (and optionally `gate_by_correctness`) instead; the denominator is always `orchestrator.seq_len`. Also adds `orchestrator.advantage.length_weighted_baseline` (default `false`): when enabled, the GRPO baseline is the token-length-weighted mean reward (`sum(len_i * reward_i) / sum(len_i)`) instead of the plain mean. (2026-06-03)
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
- **`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)
- **`orchestrator.teacher_rollout_model` now requires `orchestrator.use_sft_loss = true`**: External teacher rollout configs no longer rely on `trainer.loss.type = "sft"` to select SFT loss. Existing hard-distill configs must set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; the orchestrator validates the pair and stamps training samples with the per-batch SFT loss bool. (2026-04-26)
- **`model.attn = "eager"` (NEW option)**: Added `eager` as a valid value for the `model.attn` field. Required for GPT-OSS models on non-Hopper GPUs, since the only flash attention kernel GPT-OSS supports (`kernels-community/vllm-flash-attn3`) is Hopper-only. A clear error message is raised at model load time if GPT-OSS is used without `eager` on unsupported hardware. Also added `kernels` as a core dependency. (2026-04-05)
- **`[[orchestrator.env]]` → `[[orchestrator.train.env]]`**: Training environments and sampling are now configured under `[orchestrator.train]`. The old `[[orchestrator.env]]` and `[orchestrator.sampling]` paths are auto-translated with a deprecation warning and will be removed in a future release. (2026-04-09)
- **Per-env sampling overrides (NEW)**: Both `TrainEnvConfig` and `EvalEnvConfig` now accept a `[sampling]` section for per-env overrides. Unset fields inherit from the group-level sampling config (`[orchestrator.train.sampling]` or `[orchestrator.eval.sampling]`). (2026-04-09)
- **Per-env eval sampling overrides**: `EvalEnvConfig` now accepts a `[sampling]` section. Unset fields inherit from `[orchestrator.eval.sampling]`. All `EvalSamplingConfig` fields remain nullable (None = defer to inference server default). (2026-04-09)
- **`orchestrator.buffer.env_ratios` → per-env `orchestrator.train.env[].ratio`**: `buffer.env_ratios` has been removed. Set `ratio` on each `[[orchestrator.train.env]]` entry instead. Ratios must be all-or-nothing across envs (either all have a ratio or none do). (2026-04-05)
- **`orchestrator.val` removed**: The `[orchestrator.val]` config section (`ValConfig`) has been removed. Existing configs must delete this section. (2026-04-05)
- **`orchestrator.max_concurrent` removed**: Concurrency limiting via `max_concurrent` and the global semaphore have been removed. Existing configs must delete this field. (2026-04-05)
- **`orchestrator.buffer.hash_keys` default changed**: Default changed from `["task", "prompt"]` to `["env_name", "prompt"]`. The `task` field is no longer overridden by the orchestrator for env identification; `env_name` is used instead. Buffer checkpoints using the old default may not resume correctly. (2026-04-05)
- **`orchestrator.eval.env[].failed_rollouts` metric is now a ratio**: The `eval/{name}/failed_rollouts` metric now reports a ratio (0.0–1.0) instead of a raw count. Dashboards keying on this metric should be updated. (2026-04-05)
- **`orchestrator.sampling.temp_scheduler` removed**: Temperature scheduling (`TemperatureSchedulerConfig`) has been removed. `sampling.temperature` is now a required `float` (default `1.0`). Existing configs using `temp_scheduler` must replace it with a fixed `temperature` value. (2026-04-05)
- **`orchestrator.verification` removed**: The `[orchestrator.verification]` config section (`VerificationConfig`) has been removed. Rollout scoring is now always enabled. Existing configs must delete this section. (2026-04-05)
- **`orchestrator.eval.env[].skip_first` removed**: The `skip_first` field on `EvalEnvConfig` has been removed. Existing configs using this field must delete it. (2026-04-05)
- **`EvalSaveHFConfig` removed**: Unused config class removed. (2026-04-09)
- **`orchestrator.env[].max_total_completion_tokens` (NEW)**: Added `max_total_completion_tokens: int` to `EnvConfig` (default: `-1`, disabled). Limits the total completion tokens across all turns in a multi-turn rollout. Auto-populated into `extra_env_kwargs` and applied via the verifiers `set_max_total_completion_tokens()` setter. Works for both training and eval environments. (2026-04-06)
- **`sampling.max_tokens` → `sampling.max_completion_tokens`**: Renamed `max_tokens` to `max_completion_tokens` in both `SamplingConfig` and `EvalSamplingConfig` for consistency with OpenAI API naming. The old name is accepted with a deprecation warning. (2026-04-06)
- **`log.file` and `log.env_worker_logs` removed**: Removed `log.file` (from `LogConfig` and `SharedLogConfig`) and `log.env_worker_logs` (from `LogConfig`). Python file logging is replaced by deployment-level capture. Existing configs using these fields must delete them. Log paths unified: `.stdout` files renamed to `.log`, SLURM logs moved from `slurm/` to `logs/`. (2026-03-31)
- **`trainer.log.ranks_filter` (NEW)**: Added `ranks_filter: list[int]` to `TrainerLogConfig` (default: `[0]`). Controls which ranks appear in trainer console output via torchrun's `--local-ranks-filter`. (2026-03-31)
- **`wandb.log_extras.sample_ratio` / monitor sample logging defaults**: `wandb.log_extras.sample_ratio` is now actually applied to W&B sample-table logging via the shared monitor sampler (it was previously a no-op for WandB). Separately, the orchestrator no longer hard-caps sample logging to 8 rollouts before monitor-level sampling runs, so when monitor `sample_ratio` is `None`, monitors now receive and may log the full rollout batch for a step instead of at most 8 rollouts. This affects both W&B and Prime monitor sample logging behavior. (2026-03-27)
- **`[model.vlm].freeze_vision_encoder`**: Added to `VLMConfig`. Controls whether the vision encoder is frozen (default: `true`). When `false`, the vision encoder is trainable and FSDP-sharded per-block. Has no effect with LoRA. Moved from `[trainer.model].freeze_vision_encoder` into the VLM sub-config. (2026-03-25)
- **`loss_impl = "quack_fused"` (SFT)**: Added `quack_fused` option for the SFT `loss_impl` field. Uses quack-kernels for chunked linear + cross-entropy with CuTe DSL CUDA kernels, avoiding full logits materialization. Requires `quack-kernels` package. Does not support Gemma logit softcapping. Custom model impl (`model.impl = "custom"`) also gains quack RMSNorm acceleration on CUDA automatically. (2026-03-26)
- **`model.ac.targets`**: Removed the `mamba` selective activation checkpoint target and folded that behavior into the broader `linear_attn` target. Existing configs using `targets = ["mamba"]` will now fail validation at runtime with `ValueError`; switch them to `targets = ["linear_attn"]`. The `linear_attn` target description now covers supported token mixers outside the standard softmax-attention path, including NemotronH Mamba layers, Qwen3.5-MoE GatedDeltaNet layers, and AFMoE sliding-window attention layers. (2026-03-28)
- **`model.tp` (trainer `ModelConfig`)**: Removed from the trainer model config. Existing trainer configs must delete this field; it is no longer accepted. (2026-03-26)
- **`orchestrator.env[].num_workers`**: Added configurable env server worker count (`int | "auto"`, default: `"auto"`). When `"auto"`, scales based on concurrency (1 worker per 256 concurrent rollouts). Only used when the orchestrator spawns the env server (i.e. `address` is not set). (2026-03-25)
- **`[model.vlm]` (NEW — replaces auto-detection)**: VLM mode is now opt-in via a `[model.vlm]` sub-config with required `vision_encoder_attr` and `language_model_attr` fields. There is no auto-detection — if you train a VLM, you must add `[model.vlm]`. Existing multimodal configs need the new section. See `docs/multimodal.md` for the table of known model attrs. (2026-03-24)
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models, RL only)**: VLM dtype validation now only applies to RL training (`TrainerConfig`), not SFT. VLM models used with `sft` no longer require `optimization_dtype='bfloat16'` / `reduce_dtype='bfloat16'`. RL training still enforces both to match vLLM inference. (2026-03-24)
- **`model.ep_comm_backend`**: Added expert-parallel communication backend selection. Accepted values are `torch` (default, uses TorchTitan all-to-all collectives) and `deepep` (uses DeepEP custom kernels). This field only affects configurations with expert parallelism enabled via `model.ep > 1`. (2026-03-22)
- **`model.deepep_num_sms`**: Added DeepEP SM allocation control for intranode dispatch/combine kernels (default: `20`, minimum: `1`). This field is only used when `model.ep_comm_backend='deepep'`; it also determines the internode RDMA channel count (`num_channels = num_sms / 2`). (2026-03-22)
- **`model.deepep_token_chunk_size`**: Added optional token chunk size for DeepEP MoE pipelining (default: `None`, minimum: `1`). When set, DeepEP dispatch for chunk `i+1` overlaps expert compute for chunk `i`. This field is only used when `model.ep_comm_backend='deepep'`. (2026-03-22)
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models)**: Added validation that VLM models must use `optimization_dtype='bfloat16'` and `reduce_dtype='bfloat16'` to match vLLM inference. Previously valid configs with `float32` (the default) are now rejected for VLM model names. Set both fields to `"bfloat16"` when training VLMs. (2026-03-21)
- **`orchestrator.advantage.length_weighted_mean`**: Removed. The default advantage now always uses the plain per-problem mean baseline unless`orchestrator.advantage.length_shaping_alpha` is set. Existing configs must delete this field. (2026-03-19)
- **`orchestrator.advantage.length_shaping_alpha`**: Added Group Relative Reward Rescaling coefficient to the default advantage config. When set, applies length-based GR3 shaping during advantage computation and requires `orchestrator.buffer.online_difficulty_filtering = true` (default: `None`) (2026-03-18)
- **`model.ac.mode`** and **`model.ac.targets`**: Added selective activation checkpointing configuration. `model.ac.mode` accepts `full` (default) or `selective`. When `selective`, `model.ac.targets` selects subcomponents to checkpoint. Supported public targets are currently`norm`, `attention_sdpa`, `mla_up_proj`, and `routed_experts`; runtime validation remains the source of truth. `model.ac.targets` defaults to `["norm"]`, and selective mode requires at least one target. (2026-03-20)
- **`orchestrator.advantage.length_shaping_alpha` → `orchestrator.advantage.length_shaping`**: Replaced GR³ (`length_shaping_alpha: float | None`) with correctness-gated efficiency shaping (`length_shaping: bool`, default: `false`). No hyperparameter needed, no `online_difficulty_filtering` requirement. Existing configs using `length_shaping_alpha` must switch to `length_shaping = true`. (2026-04-13)
- **`orchestrator.advantage.length_weighted_mean`**: Removed. The default advantage now always uses the plain per-problem mean baseline unless `orchestrator.advantage.length_shaping` is enabled. Existing configs must delete this field. (2026-03-19)
- **`prime_monitor.log_extras.sample_ratio`**: Added ratio-based rollout sampling (0.0–1.0, default: None). When set, caps the number of rollouts logged per step to `len(rollouts) * sample_ratio`. `None` preserves current behavior (log all rollouts). Interacts with existing `interval` gate which still runs first. (2026-03-12)
- **`client.connect_timeout`**: Added configurable TCP connect timeout for inference API requests (default: 30.0s). Previously hardcoded to 5.0s. Helps with vLLM or cluster flakiness (2026-03-11)
- **`model.fused_lm_head_token_chunk_size`**: Added as the fused LM-head chunking field for the token-chunked implementation. Unlike the removed `model.fused_lm_head_chunk_size`, this chunks over flattened sequence tokens rather than vocabulary rows. `model.fused_lm_head_chunk_size` is no longer accepted; switch configs to `model.fused_lm_head_token_chunk_size` explicitly. (2026-03-09)
@@ -29,13 +29,38 @@ PRIME-RL: Async RL Training at Scale
## Overview
PRIME-RL is a framework for large-scale asynchronous reinforcement learning. It is designed to be easy-to-use and hackable, yet capable of scaling to 1000+ GPUs. Beyond that, here is why we think you might like it:
PRIME-RL is a framework for large-scale reinforcement learning. It is designed to be easytouse and hackable, yet capable of scaling to 1000+ GPUs. Here is what we think sets it apart:
1. Fully asynchronous RL for high-throughput agentic training at scale.
2. Performant: built to train 1T+ MoE models on 1000+ GPUs with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) for training and [vLLM](https://github.com/vllm-project/vllm) for inference, with FP8 inference, PD disaggregation, EP and CP parallelism, and more.
3. Native integration with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments through the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars), including built-in support for SWE and agentic environments.
4. End-to-end post-training: SFT, RL training, and evals.
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
7. Hackable, modular, and extensible by design.
## Models support
The trainer works with both Hugging Face and Prime custom `ModelForCausalLM` out of the box. For selected families (especially large MoE) we also ship highly optimized training code under `src/prime_rl/trainer/models/`, including expert parallelism (EP) for MoE layers and context parallelism (CP) for long sequences (see the table), and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels).
With `[model] impl = "auto"` (the default), the trainer selects that custom stack when the Hugging Face config type is registered.
1. Integrates natively with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments via the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars)
2. Supports end-to-end post-training, including SFT and RL training and evals
3. Multi-node deployment with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) training and [vLLM](https://github.com/vllm-project/vllm) inference backend
4. Designed for asynchronous agentic RL training at scale
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.
@@ -160,27 +200,39 @@ uv run hf auth login
## Training Examples
We provide end-to-end training examples in the [`examples`](examples) directory to highlight features of the framework and guide you through the process of training your own models.
### Basic Training: 1 to 8 GPUs
Follow this guide to learn the basics of Prime-RL. You can train your own models on 1 to 8 GPUs. Ideal for getting started and exploring the capabilities of the framework. These guides cover most use cases -- single-turn, multi-turn, tool calling, etc. -- on toy environments and small models.
1. [**Reverse Text**](examples/reverse_text/README.md): Train `Qwen3-0.6B` to reverse a small chunk of text. Demonstrates tiny-scale single-turn SFT and RL training. Can be trained on a single consumer GPU in a few minutes, and is ideal for getting started.
2. [**Wordle**](examples/wordle/README.md): Train `Qwen3-1.7B` to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
3. [**Alphabet Sort**](examples/alphabet_sort/README.md): Train `Qwen3-4B-Instruct-2507` to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
4. [**Wiki Search**](examples/wiki_search/README.md): Train `Qwen3-4B-Instruct-2507` to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
5. [**Hendrycks Sanity**](examples/hendrycks_sanity/README.md): Run a sanity check experiment on `DeepSeek-R1-Distill-Qwen-1.5B` using a filtered subset of MATH where the model already partially solves 20-80% of problems. Useful for algorithm ablations.
*More to come...*
### Advanced Training: 32 - 2048 GPUs:
Follow this guide to train large models on hard reasoning and agentic / swe environments.
These guides are designed to be run from a Slurm cluster but can also be adapted to k8s deployments.
1. [**Qwen 3 30B - A3B Math**](examples/qwen30b_math/README.md): Train `Qwen3-30B-A3B` to solve hard math problems.
2. [**Qwen 3 30B - A3B SWE**](examples/qwen30b_swe/README.md): Train `Qwen3-30B-A3B` to solve hard SWE problems.
3. [**Intellect-3.1**](examples/Intellect-3.1/README.md): Reproduce our `INTELLECT-3.1` training run.
4. [**MiniMax-M2.5 SWE**](examples/minimax_m2.5_swe/README.md): Train `MiniMax-M2.5` on agentic SWE tasks.
5. [**High-throughput GLM-5**](examples/glm5_pd_disag/README.md): Train `GLM-5` with PD disaggregation and FP8 inference on SWE.
## Docs
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
- [**Troubleshooting**](docs/troubleshooting.md) - Common issues and their solutions
- [**Overview**](docs/overview.md) - Architecture, install, and a copy-pasteable end-to-end RL run
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`:
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).
`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:
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.)
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:
| 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).
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:
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.
`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.

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:
$\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"`):
| `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.
teacher_logprobs:Float[Tensor,"seq"]|None# only set in OPD mode
advantages:Float[Tensor,"seq"]
loss_mask:Bool[Tensor,"seq"]
@dataclass
classLossOutputs:
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, …).
A **length penalty** can be layered on top of the default advantage to discourage rambling. Configured under `[orchestrator.advantage.length_penalty]`, it subtracts a `coef * pass_rate * (completion tokens / orchestrator.seq_len)` term from every reward before the baseline subtraction, where `pass_rate` is the problem's mean reward across the group. The pass-rate factor means problems the model already solves reliably get the strongest push toward concise outputs, while rarely-solved problems are barely penalized (a never-solved group, mean reward 0, gets none). Set `gate_by_correctness = true` to apply the penalty only to correct rollouts (`reward == 1`), leaving incorrect ones untouched:
gate_by_correctness=false# when true, only penalize rollouts with reward == 1
```
By default the baseline is the plain group mean reward. Set `length_weighted_baseline = true` to instead use the token-length-weighted mean — `sum(len_i * reward_i) / sum(len_i)` — which centers advantages by per-token expected reward when rollouts vary a lot in length:
```toml
[orchestrator.advantage]
length_weighted_baseline=true
```
### Custom Advantage
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.
`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
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:
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.
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.
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$.
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.
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
*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.
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.
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
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.
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 `enable_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)
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 @ 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.
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 \
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:
`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.
- [**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:
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.
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
exportGLOO_SOCKET_IFNAME=...
exportNCCL_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
exportMASTER_ADDR=...
exportMASTER_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
exportGLOO_SOCKET_IFNAME=...
exportNCCL_SOCKET_IFNAME=...
```
Then, configure the data parallel address as the private IP address of the head node.
```bash
# On both nodes
exportDATA_PARALLEL_ADDRESS=...
exportDATA_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*)
> 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
exportOUTPUT_DIR=... # Path to directory in shared file system
exportINFERENCE_SERVER_IP=... # Reachable IP address of the inference node
exportINFERENCE_SERVER_API_KEY=... # API key for the inference server
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:
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:
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.
The main usecase of PRIME-RL is RL training. Three main abstractions facilitate RL training: the **orchestrator**, the **trainer**, and the **inference** service.

### 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`.
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.
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.
`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.
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.
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.
prime-rl uses [loguru](https://loguru.readthedocs.io/en/stable/) for logging with a global logger pattern. Logs are written to both console and files under `{output_dir}/logs/`. For RL training, we recommend streaming file logs into tmux panes (as set up by `tmux.sh`).
## tmux helper (`scripts/tmux.sh`)
`scripts/tmux.sh` sets up a tmux session for RL runs with **three panes (one per subprocess)**:
Environment are run via `vf.EnvServer` in separate processes. By default, each environment logs to a file in its run directory under `{output_dir}/run_default/train/{env_name}.log` and `{output_dir}/run_default/eval/{env_name}.log`. The log verbosity can be controlled with `orchestrator.log.vf_level`.
```toml
[orchestrator.log]
level="debug"# Log level for prime-rl logger
vf_level="info"# Log level for verifiers library
```
```
output_dir/
└── run_default/
└── train/
├── {env_name_1}.log
├── {env_name_2}.log
└── ...
└── eval/
├── {env_name_1}.log
├── {env_name_2}.log
└── ...
```
## Torchrun
For multi-node training with `torchrun`, all ranks log simultaneously. To filter to master rank only:
```bash
uv run torchrun \
--local-ranks-filter 0\
--nproc-per-node 8\
...
```
You can also use torchrun's native log redirection:
```bash
uv run torchrun \
--local-ranks-filter 0\
--nproc-per-node 8\
--log-dir outputs/torchrun \
--redirects 3\
--tee 3\
...
```
This writes to `outputs/torchrun/{rdzv_id}/attempt_0/{rank}/{stdout,stderr}.log`.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.