Compare commits

...
67 Commits
Author SHA1 Message Date
e26b505039 feat: run dir + resume from path (#3268)
* Add named run directories under output_dir

output_dir now groups related runs: each run writes all its artifacts
(logs, configs, checkpoints, weights, rollouts) to output_dir/run.name.
The new run.name field defaults to a random UUID, so every launch gets
a fresh run directory and concurrent runs no longer need a manually
unique output_dir. Set an explicit name to make the run directory
predictable, which is also what resume points back at.

Launching into a run directory that already contains run artifacts now
fails unless resuming or clean_output_dir is set; clean_output_dir
wipes only the run directory, not its output_dir siblings.

The rl entrypoint derives trainer/orchestrator output_dir from the run
directory, so sub-processes and standalone sub-configs are unchanged.

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

* Add run id and propagate run identity everywhere

RunConfig gains an id (locally generated for now; the Prime SDK will
issue it once runs are registered there). The run identity now flows
to every surface that names or groups a run's artifacts:

- traces: the orchestrator stamps RunInfo with name + id (id prefers
  the monitor identity, falling back to run.id); requires the
  verifiers RunInfo.name companion (submodule bump)
- W&B: unset wandb.name inherits run.name; the shared W&B run id
  defaults to run.id
- Prime platform: unset prime_monitor.run_name inherits run.name
- sandboxes: env-server TOMLs carry sandbox_labels=[run.name], applied
  process-wide via verifiers' set_base_sandbox_labels, so every Prime
  sandbox of a run is labeled with the run name; runtime-config labels
  extend the base labels

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

* Bump verifiers for RunInfo ruff fix and rename

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

* Keep the run id out of config; inject identity

The run id is not user config: the rl entrypoint mints it (TODO: fetch
it from the Prime SDK once runs are registered there) and injects it —
with the resolved run name — as a launcher-managed [run] block into the
orchestrator and every env-server TOML. The orchestrator stamps it on
traces (monitor identity still preferred); env servers label every
Prime sandbox with the run name via set_base_sandbox_labels, now
imported from verifiers.v1.runtimes (the root export is gone).

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

* Auto-generate readable run names; add run.dir

run.name now auto-generates as <train-envs>--<model>--<short-id> (SFT:
<dataset>--<model>--<short-id>, env names joined with +) instead of a
bare UUID, so default run directories and inherited W&B/platform names
read like the experiment they are while the short-id suffix keeps
launches collision-free. run.dir names the run directory and defaults
to run.name, for when the directory must differ from the display name.

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

* Rename clean_output_dir to clean; lowercase names

The flag cleans the run directory, not the output directory, and now
matches the eval CLI's --clean. No alias for the old spelling; the
NEVER_CLEAN_OUTPUT_DIR escape hatch becomes NEVER_CLEAN. Auto-generated
run names are lowercased.

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

* Use /tmp as the grouping dir in the dry-run example

* Split output_dir and run name in the GLM-5.2 example

* Carry the run id as PRL_RUN_ID, never in config

The run id is a runtime concept: the launcher sets $PRL_RUN_ID (once,
respecting an externally provided value — the future Prime SDK hookup
point) and every spawned process inherits it; the SLURM templates
export it job-wide the same way as the shared W&B id, which now
defaults to it. Configs carry only the run name. $PRL_RUN_ID is the
general vehicle for transporting runtime info between processes, so it
joins the protected env vars.

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

* Retire WANDB_SHARED_RUN_ID in favor of PRL_RUN_ID

The shared W&B run id was always just the run identity under another
name; the monitor now reads $PRL_RUN_ID directly. WANDB_SHARED_MODE
(the toggle) and WANDB_SHARED_LABEL (the per-process label) carry
distinct information and stay.

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

* Make resume a top-level config block

resume: ResumeConfig | None replaces ckpt.resume_step on the rl and
sft entrypoints: None (default) does not resume, a bare --resume (or
empty [resume] block) resumes from the latest checkpoint, and
--resume.step N resumes from step N — mirroring the eval CLI's
--resume. The block maps onto the sub-configs' internal resume_step
(-1 = latest), so trainer and orchestrator are unchanged. Also guard
--clean against a run.dir resolving outside output_dir (matches the
eval fix) and validate it in validate_run_dir.

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

* Unify resume consumers on ResumeConfig

The sub-config checkpoint configs (trainer, orchestrator, SFT) carry
the same resume block as the entrypoints instead of an internal
resume_step with a -1 sentinel: step None means latest everywhere, and
the checkpoint managers and resume resolution read resume.step.

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

* Bump verifiers for name-only eval resume

* Add resume.dir to fork an external checkpoint

--resume.dir points at another run's checkpoint step directory (e.g.
other/checkpoints/step_50) and forks it into this run: the step comes
from the directory name, the trainer and orchestrator load their state
from that path, and everything else (saving, weights, rollouts) stays
in this run's own directory. Mutually exclusive with resume.step.
Also bump verifiers: eval --resume is now a plain flag on the resolved
config, prl-style.

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

* Bump verifiers for eval resume cleanup

* Bump verifiers for unified validate resume

* Bump verifiers for eval resume config hash check

* Carry the run name as PRL_RUN_NAME, drop RunInfoConfig

The whole run identity is now runtime-only: the launcher exports
$PRL_RUN_NAME next to $PRL_RUN_ID and every spawned process reads it
for trace stamping and sandbox labels; the multi-node template exports
it job-wide. Sub-configs carry no run info at all — components run
standalone simply have no run identity.

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

* Bump verifiers for schema-level resume hash

* Bump verifiers for configs/ layout and digest check

* Move resume to the top level on trainer and orchestrator

resume sits next to ckpt on every config, not inside it — the same
shape at every level. The checkpoint managers take it as a parameter
instead of reading it off CheckpointConfig.

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

* Write resolved configs as JSON

Machine-written configs (rl/sft/trainer/orchestrator/inference/env
server) become JSON: it keeps nulls, so explicit None overrides
round-trip exactly and to_toml_dict's "None"-string convention is
deleted. Hand-written configs stay TOML; the format split marks
intent vs resolved artifact. Aligns with verifiers' configs/<cli>.json
(submodule bumped).

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

* Bump verifiers for gepa guard ordering

* Bump verifiers for logs/ run-dir layout

* Pin verifiers to main with #2358 merged

* Always construct checkpoint managers; fix skip-scheduler horizon

The checkpoint manager now always exists: resume decides whether it
loads, ckpt whether it saves. A standalone trainer or orchestrator
launched with --resume and no [ckpt] previously skipped the load path
silently; now it resumes (and saves no new checkpoints). The
resume-requires-ckpt validators are gone accordingly.

SFT's skip_scheduler sized the rebuilt schedule from resume.step,
which is unset for a bare --resume and for --resume.dir; it now uses
the resolved checkpoint step, so warmup/decay run on the remaining
steps.

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

* Skip the HF weight load on any resume

loading_from_ckpt_later still required config.ckpt, so a resume
without [ckpt] loaded HuggingFace weights before the checkpoint
overwrote them — failing offline or OOMing on large models. The
resolved checkpoint step alone decides: resuming initializes an empty
model and loads from the checkpoint.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 20:54:25 -07:00
70caa7c61f chore: bump verifiers for prime vm runtime default (#3270)
* Bump verifiers for prime VM runtime default

vf#2356 makes the prime VM runtime the default agent runtime:
PrimeConfig now defaults vm=true, AgentConfig.runtime defaults to
PrimeConfig(), and prime auth is checked when a prime runtime or
tunnel is instantiated. Also picks up vf#2357 (stable task keys).

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

* Drop vm = true from example configs

Prime sandboxes default to vm=true after the verifiers bump, so the
explicit flag in the example runtime sections is redundant.

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

* Drop redundant prime runtime keys from example configs

The default agent runtime is now the prime VM sandbox, so
type = "prime" (pydantic_config falls back to the default union
variant when the tag is omitted) is redundant. The
idle_timeout = "None" lines go too: PrimeRuntime always drops
idle_minutes for VM sandboxes, so the key is a no-op there.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 17:13:31 -07:00
5a005de2d6 feat: warn when inference queue exceeds inflight-episode budget (#3269)
Poll-time check in InferenceMetricsCollector: when aggregate waiting
requests exceed 20% of max_inflight_episodes, inference is saturated
and rollout latency (and thus training throughput) suffers. Emit a
throttled warning (at most once per 60s) advising to wait if the
spike is intermittent and to lower max_inflight_episodes if it
persists.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 16:45:55 -07:00
AtirnaandGitHub 756afd40eb docs: remove retired zero-gradient metric (#3267) 2026-08-13 16:37:40 -07:00
c1674ac93c feat: dynamic pass-through vLLM inference metrics to W&B (#3240)
* feat: dynamic pass-through vLLM inference metrics to wandb

Replace the hand-curated inference metric allowlist with a dynamic
pass-through collector: every vllm:* Prometheus family is logged,
per-engine under inference/engine/{id}/ and cross-engine aggregations
(min/max/mean/median/sum) under inference/{agg|prefill|decode}/.

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

* refactor: drop InferenceMetricsConfig, keep collect_inference_metrics flag

Hardcode poll interval, aggregations, and per-engine logging in the
collector; config surface is unchanged from main (collect_inference_metrics
+ inference_metrics_roles).

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

* Add inference health section to the overview view

Seven panels, each pairing the fleet aggregate (mean/sum) with the
cross-engine tail that flags a single sick engine - max for pressure
(KV usage, preemptions, waiting, prompt-token recompute), min for
health (prefix hit rate, generation throughput). A saturated engine
thrashing its KV cache hides inside fleet means; the tails surface it.

Also compute the prefix-cache hit-rate ratio per engine (not only
pooled over the fleet) so the min/max aggregations exist for it.

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

* Flatten metric keys to inference/{scope}/{metric}/{stat}

Drop the vllm: family prefix (the collector only admits vllm:* families,
so it carries no information), flatten per-engine series from
inference/engine/{id}/... to inference/{id}/..., and move scope-level
quantiles (:p50 -> /p50) and the pooled ratio (-> /pooled) into the
stat segment so every key reads inference/{scope}/{metric}/{stat}.

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

* Add min series to KV usage and waiting panels

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 16:03:10 -07:00
halleriteandGitHub b1d4f2fa6c chore(ruff): pin path-dep import classification (#3263) 2026-08-13 19:14:25 +02:00
d43e0f329b perf!: remove the zero-gradient-ratio metric (#3249)
get_zero_gradient_ratio launched a device-scalar transfer and a
count_nonzero kernel per parameter plus two all-reduces and a sync every
step, serializing the post-backward path on models with many tensors: on
Qwen3-30B-A3B (8xH200, seq 8K) it cost 1.4 s of a 4.6 s step. The metric
also read 1.0 on every validation run, so it was likely not measuring
what it intended on FSDP2 DTensor gradients. Removes the metric, its
trainer call sites, and the Prometheus gauge.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 09:10:44 -07:00
8c1f196dd3 chore: bump verifiers for prime-sandboxes 0.2.36 (#3259)
* Bump verifiers for prime-sandboxes 0.2.36

prime-sandboxes 0.2.36 gives each live ACP process its own HTTP
transport (prime#831), fixing the h2 stream-cap deadlock that made
rlm rollouts fail with 'process stdin RPC failed (deadline_exceeded)'
above ~100 concurrency.

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

* Repoint verifiers submodule to merged main

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 16:43:09 -07:00
chethanukandGitHub 753a3fec0a docs(k8s): drop dead docs links and fix PVC name in Helm README (#3242)
k8s/README.md links to /prime-rl/kubernetes, /prime-rl/deployment and
/prime-rl/troubleshooting. All three return 404: those pages are not in
docs/ and have no entry in docs/mint.json. Drop the two Kubernetes links
and the troubleshooting bullet — the README's own sections are the chart
documentation — and retarget the deployment bullet at /prime-rl/scaling,
which is where the multi-node and SLURM content lives now.

The uninstall snippets also name the wrong PVC. templates/pvc.yaml names
it {{ .Release.Name }}-shared-data, so after the documented
`helm install my-exp`, `kubectl delete pvc prime-rl-shared-data` fails
NotFound and reads as if the data is already gone.

Closes #3054
2026-08-12 09:42:34 -07:00
3ad13dd0bc fix: skip weight pre-download for random-init debug runs (#3247)
pre_download_model fetched the full weight snapshot even when
debug.random_init never reads the weights — for large models that pulls
hundreds of GB (GLM-5: ~1.4 TB) into the shared HF cache before a fake-data
debug run. Random-init runs now fetch only config and tokenizer files.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 08:51:06 -07:00
ee06d333e4 chore: bump verifiers to latest main (#3246)
verifiers 42a6c95de..a506236ec:
- fix: compact harness runs without a container (#2329)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 20:02:42 -07:00
91d4b92597 chore: bump verifiers and prime-envs to latest main (#3245)
verifiers d53ab56f0..42a6c95de:
- feat: metadata-only overrides for config-plugged functions (#2323)
- feat(compact): one tool call per turn, notes-only carryover (#2313)

prime-envs 1f1f915a..b30aad36:
- feat!: add train/eval graph split to wikispeedia (#759)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 19:40:27 -07:00
82acb12ed7 fix: revert default DPPO masking thresholds to 0.2 (#3244)
Revert bb23623d6 (#3236). The tighter 0.1 trust region masks the few
high-leverage decision tokens once their probability moves >0.1 across
off-policy staleness, slowing LoRA convergence (reverse-text LoRA CI
smoke: 0.5-0.6 reward @ step 15 vs 0.8 with 0.2).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 19:35:13 -07:00
124f9694a6 chore: stop dumping resolved orchestrator config to control/ (#3243)
The orchestrator wrote its resolved config to <output_dir>/control/orch.toml,
a relict of the deprecated multi-tenant setup. The launcher already persists
resolved configs under the output directory.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 19:27:44 -07:00
4308fe3aba chore!: point at the renamed prime-envs repo (#3241)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 14:54:54 -07:00
minh hoangandGitHub da53d4c064 chore: bump renderers for Nemotron 3.5 (Lightning) renderer (#3239) 2026-08-11 12:23:08 -07:00
minh hoangandGitHub efe8e7fda8 feat: auto-resolve parsers for Nemotron 3.5 (Lightning) (#3237)
* feat: auto-resolve parsers for Nemotron 3.5 (Lightning)

* test: drop NVFP4 expectation, BF16 only

* clean up docstrings
2026-08-11 11:57:36 -07:00
bb23623d6e feat: change default masking thresholds to 0.1 (#3236)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 11:23:41 -07:00
03f12efbaf feat!: drop v0 env compat (#3226)
* feat!: drop v0 env compat from the orchestrator and configs

The verifiers legacy bridge is removed upstream, so every v0 code path
goes:

- configs: drop the [legacy] block, is_legacy, the legacy/env conflict
  validators, and resolve_legacy_env_kwargs from EnvConfig and
  EnvServerConfig; env-server TOMLs no longer carry a legacy section
- env-server entrypoint: always serve a taskset (no bridge fork)
- orchestrator: Env always loads its taskset client-side (info()/
  run_group()/task_idx addressing removed); requires_group_scoring and
  its consumers (variable permit costs, group-scored partial drops,
  run_group fan-out) are gone — one permit is one episode everywhere
- TrainSource rows always carry the task; the pending-draw head-of-line
  hold and per-env permit costs are gone (next_example takes no args)
- GroupState.task is required; task_idx derives from task.data.idx
- env taskset ids drop the -v1 suffix across configs, examples, docs,
  skills, and the workspace members (companion renames in verifiers and
  research-environments)
- port the qwen3-vl features-payload test from the v0 RendererClient to
  renderers.client.generate (the path the v1 train client drives)

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

* chore: bump verifiers + research-environments to the rename branches and relock

deps/verifiers -> feat/legacy-package (6a8de86), deps/research-environments
-> feat/drop-v1-suffix (27ed790). Re-pin to the merged commits before landing.

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

* chore: bump verifiers pin to the reworked branch head

v0 code stays in place upstream; the branch now only removes the v1
legacy bridge and the -v1 suffixes (lock unchanged).

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

* chore: bump verifiers pin (v1 CLI simplifications)

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

* chore: bump verifiers pin (main merged, python floors)

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

* chore: bump verifiers pin (v1 drops on-demand Hub installs)

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

* chore: bump verifiers pin (v0 tree under verifiers.legacy, aliased)

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

* chore: bump verifiers pin (ID plain str, public alias names)

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

* chore: bump verifiers pin (ruff fixes)

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

* chore: bump verifiers pin (static-tooling fixes)

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

* chore: bump verifiers pin (gepa schema id fix)

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

* chore: bump verifiers pin (docs/legacy move)

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

* chore: bump verifiers pin (hub installs restored in v1)

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

* chore: pin verifiers to the merged main commit

deps/verifiers -> main 91d4f69e6 (#2303 merged); research-environments
-> the rename branch head with the automationbench_env collision fix.

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

* chore: floor verifiers at 0.3.1.dev12

The first dev release carrying the v0 deprecation (verifiers#2303);
submodule follows main.

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

* fix: verifiers submodule points at main head (the #2303 merge), not its parent

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

* chore: pin submodules to the merged mains and floor verifiers at 0.3.1.dev13

deps/verifiers -> f24b8ec0 (#2311), deps/research-environments ->
c0a0d1d7a (#754); 0.3.1.dev13 is the release cut from that verifiers
commit.

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

* chore: bump verifiers to main d53ab56f (0.3.1.dev14)

Picks up the model-catalog revert (verifiers#2314).

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-10 21:54:01 -07:00
f2ead102d1 feat(laguna): support per-element attention gating (#3229)
Laguna's config carries a `gating` field that prime-rl's port dropped, so
g_proj was always sized for per-head gating:

    self.g_proj = nn.Linear(config.hidden_size, num_heads, bias=False)

That matches Laguna S (`gating = "per-head"`, g_proj [48, 3072]) and is wrong
for Laguna M (`gating = "per-element"`, g_proj [8192, 4096] = num_heads x
head_dim). Loading M.1 fails with

    ValueError: Size mismatch between saved torch.Size([8192, 4096]) and
    current: torch.Size([64, 4096]) for model.layers.0.self_attn.g_proj.weight

Carry `gating` on LagunaConfig and size g_proj from it, following upstream's
semantics exactly (poolside/Laguna-M.1 modeling_laguna.py):

    True / "per-element"  one gate per (head, head_dim) channel
    "per-head"            one gate per head, broadcast across head_dim
    False                 no gating

Note the default is `True`, not "per-head": a checkpoint that omits the field
gets per-element upstream, so defaulting the other way would silently mis-size
it. bool and str are both accepted for the same reason.

Verified against both checkpoints: g_proj matches [48, 3072] for S-2.1 and
[8192, 4096] for M.1, and the gate math is bit-identical to upstream in both
modes (max abs diff 0.0). End to end, a 4-node trainer probe loads the real
452GB M.1 checkpoint through load_dcp_from_hf with no size mismatch, where it
previously failed at model construction.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 21:41:50 -07:00
halleriteandGitHub c698bdeb2a chore: bump research-environments for the toolset register() fix (#3230) 2026-08-10 20:11:43 +02:00
6e33f3f82f chore: bump verifiers for the unbounded model-call timeout (#3227)
Bumps deps/verifiers 29e3a0f7 -> a298bcfe, picking up two commits:

  a298bcfe fix(v1): restore the unbounded model-call timeout (#2304)
  9ca7f5d6 Fix plain HTTP CONNECT for Docker framework routes (#2298)

verifiers#2218 had consolidated client construction into
build_async_openai/DEFAULT_TIMEOUT and, in doing so, replaced the relay
client's explicit `timeout=None` with a 600s read timeout mirroring the OAI
SDK default. That cap reached every model-call path, since DEFAULT_TIMEOUT
feeds clients/eval.py as well as build_async_openai, which judge.py and
clients/train.py use.

600s is fine for chat-shaped evals and wrong for RL: a single agentic turn on
a long SWE trajectory routinely runs past ten minutes, and when it does the
rollout dies as `ProviderError: Request timed out` even though the model was
still producing. Because it truncates the longest trajectories specifically,
the loss is biased rather than uniform. Seen on the laguna-s SWE RL run here.
#2304 restores unbounded read/write/pool and keeps connect at 5.0 so an
unreachable endpoint still fails fast.

No lockfile change: verifiers is an editable path dependency
(`source = { editable = "deps/verifiers" }`), and neither commit touches its
pyproject, so only the submodule pointer moves.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 21:41:10 -07:00
c282262e6e fix(slurm): export ORCH_PROCID so the orchestrator actually launches (#3225)
#3189 hoisted ORCH_PROCID out of the srun body into the outer batch script so
ORCH_ADDR could be derived from it. ORCH_ADDR was exported; ORCH_PROCID was
not.

The srun body is a quoted heredoc, so `$ORCH_PROCID` in

    if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then

is expanded per task, and a plain (unexported) shell variable never reaches
the task environment. The test becomes `[ "4" -eq "" ]`, which errors with
"integer expression expected" and evaluates false on every rank, so the block
that starts the orchestrator and both env servers is skipped entirely.

The failure is silent and expensive. Inference comes up, the trainer reaches
weight-broadcast init, and then the job sits there until the 3600s NCCL
watchdog fires on a 1-element ALLREDUCE, holding the whole allocation. There
is no error in the job log pointing at the orchestrator, and no
orchestrator.log to look at, because the `tee` that would create it is inside
the skipped block. Observed on a 6-node run: 20 minutes in, only
PRIME-RL::Trainer processes on the orchestrator node and no logs/envs/
directory, which the block's own `mkdir -p` would have created.

Export it. Verified by rendering multi_node_rl.sbatch.j2 and running the guard
with SLURM_PROCID=4: the branch is taken now and skipped before.

Audited the other templates for the same pattern — variables assigned in the
outer script but read inside a quoted heredoc. multi_node_sft, single_node_rl
and single_node_sft are clean. Two apparent hits are false positives:
HOSTNAMES is rebuilt inside the body from the exported HOSTNAMES_STR, and
inference.sbatch.j2's DP_PER_NODE is rendered directly into the body by Jinja.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 20:51:20 -07:00
289562d2ec feat: remove multi-tenant (#3189)
* feat(client): single-string base_url, remove elastic inference pool

The data plane is now a single endpoint (put a router in front for
multi-replica deployments); admin_base_url stays a list for per-server
admin operations (weight updates, health checks, NCCL rank offsets).
Removes ElasticInferencePool (DNS discovery + per-tenant adapter sync),
the InferencePool protocol/factory, and client-side load balancing.

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

* feat: orchestrator-side packing, single-tenant trainer, flat output dir

Removes the multi-tenant infrastructure:

- Bin-packing moves into the orchestrator (BatchPacker), which now ships
  per-DP-rank micro batches directly to the trainer — one transport hop
  instead of two (the rank-0 packer and its second filesystem write are
  gone). ZMQ data moves to port, READY barrier to port+1; the transport
  binds in the orchestrator process.
- MultiRunManager, run discovery, eviction, the control/orch.toml
  handshake, MultiPacker, MultiCheckpointManager, MultiLoRAOptimizer,
  MultiLoRAScheduler, per-run metrics, and trainer.max_concurrent_runs
  are deleted. A slim LoRAState in trainer/lora.py keeps single-tenant
  LoRA (RL + SFT) working: module registry, adapter state dicts, resets,
  and the shared lora_num_tokens/scaling tensors (n_adapters=1).
- The run_default nesting is gone: orchestrator.output_dir equals
  trainer.output_dir, with rollouts, broadcasts, checkpoints, and token
  exports in one flat experiment dir.
- RL LoRA optimizers now include modules_to_save params (matching SFT).

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

* feat: always broadcast step-0 weights at startup

The trainer's startup broadcast of the incoming policy (v0 from scratch,
v{resume_step} on resume) now runs for every transport, not just the
in-memory ones, and the orchestrator's startup weight sync is
unconditional to match. This validates the broadcast path at startup
instead of after the first optimizer step and aligns fresh starts with
the restart flow. The orchestrator always waits for the startup weight
directory (default 1200s; ckpt.wait_for_weights_timeout overrides).

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

* fix: assign base_url as str in auto_setup_inference_client

Leftover list assignment from before the base_url list[str] -> str
migration; pydantic doesn't validate assignment, so the list survived
until rl_local's urlparse crashed on it (sft-distill path only).

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-08 19:49:42 -07:00
3ab5e04c4c feat: per-source env-server address via serve.address (#3218)
* feat(configs): per-source env-server address via serve.address

Setting serve.address on a train/eval source marks its env server
externally managed: the launcher neither writes its TOML nor spawns a
server for it, and the orchestrator connects to the given address.
Unset sources keep the derived loopback address, with indices still
positional across all sources.

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

* refactor: subclass vf.ServeConfig instead of mirroring its fields

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

* refactor: consume vf.ServeConfig as-is

Companion verifiers bump makes ServeConfig.address optional with no
default, so the per-source serve block needs no prime-rl subclass.

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

* chore: bump verifiers to merged optional-serve-address rev

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-08 16:38:07 -07:00
d1046b876c feat!: vllm pass-through inference config (#3202)
* feat!: flatten inference config into vLLM pass-through [vllm] section

Replace ModelConfig/ParallelConfig and the flat vLLM fields on
InferenceConfig with a single flat VllmConfig under [inference.vllm]
(standalone: [vllm]) that uses vLLM's own argument names and passes
unknown keys through to the server verbatim (extra="allow"), replacing
the vllm_extra escape hatch. to_vllm()'s rename table becomes a direct
to_namespace() dump.

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

* test: pin VALID_VLLM_LORA_RANKS against vllm.config.lora.MaxLoRARanks

The constant stays hardcoded (prime-rl-configs has no vLLM dependency,
and importing vLLM costs ~5s per config-parsing process); a unit test
now fails on any vLLM bump that changes the accepted ranks.

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

* fix: no apostrophe in the srun-quoted launch helper, guard with bash -n

The per-rank launch helper is rendered inside the single-quoted
`srun bash -c '...'` body, so the apostrophe in the new "can't be inlined
as CLI flags" comment ended the quoted body and the rest of the script was
parsed by the outer shell — every SLURM inference launch (single-node,
multi-node and disaggregated alike) died at parse time with
`syntax error near unexpected token ')'`.

Reword the comment, drop the quotes around printf's format string for the
same reason, and add a unit test that renders both sbatch templates across
the deployment shapes and runs `bash -n` on the output, so this class of
quoting bug fails CI instead of the cluster.

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

* fix: feed srun launch bodies to bash on stdin via a quoted heredoc

The multi-node launch bodies were passed as a single-quoted `bash -c '...'`
argument, so a lone single quote anywhere inside them — including in the
shared _launch_*.sh.j2 includes, and including in a comment — ended the
quoted body and left the rest of the script to be parsed by the outer shell.
The apostrophe in this branch's "can't be inlined as CLI flags" comment did
exactly that and killed every SLURM inference launch at submit time with
`syntax error near unexpected token ')'`.

Deliver the bodies the way the cleanup block already does: `bash -s` with a
quoted heredoc, which srun broadcasts to every task and which passes the
script through verbatim, so no character in the body needs escaping. This
removes the hazard from inference, multi-node RL and multi-node SFT rather
than policing it, drops the `'"'"'` escape dance around
DECODE_COMPILE_CFG, and fixes the trainer log filter, whose sed script was
silently losing its backslashes to the outer shell.

Nothing in the bodies reads stdin, which would otherwise consume the rest
of the script.

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

* test: drop the VALID_VLLM_LORA_RANKS pin against vllm.config.lora.MaxLoRARanks

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-08 10:50:41 -07:00
samsjaandGitHub 381df0a658 chore: bump version to 0.8.0 (#3209)
* chore: bump version to 0.8.0

* fix: revert accidental annotated-types version change in uv.lock
2026-08-07 10:20:28 -07:00
532d622b4c chore: bump verifiers to 0.3.0 (#3205)
* chore: bump verifiers + research-environments to latest main

verifiers d30a3f48e -> f940bf7a7 (0.2.2.dev76 -> dev91), floors follow.
research-environments f9c43a74f -> b10db7640 (adds mmk12-v1).

Adapts to vf#2244 (run info moved from Trace onto Episode): the
orchestrator stamps the run into each rollout's info instead of the
removed Trace.record_run, keeping per-trace records placeable.

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

* feat!: write traces.jsonl in verifiers' native episode format

One vf.Episode record per line, matching what verifiers' own eval CLI
writes and read_episodes loads. The run is stamped on the episode via
Episode.record_run, and prime-rl's orchestration metadata (env_name,
group_id, policy_version) lives in Episode.info; a multi-agent episode
is one line holding all its traces.

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

* Revert "feat!: write traces.jsonl in verifiers' native episode format"

This reverts commit b5972ef9b16970420df558071e33bea63f9fddba.
traces.jsonl stays one trace record per line - the episode-native format
only pays off with the episode-first pipeline, which is not being taken.

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

* chore: re-pin verifiers to run-info revert, drop the dev91 adaptation

deps/verifiers moves to vf#2264 (revert of vf#2244), which restores
Trace.record_run - the orchestrator code is untouched by the bump again.
Re-pin to verifiers main once vf#2264 merges.

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

* chore: re-pin verifiers to main (vf#2264 merged)

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

* chore: bump verifiers to dev102, enumerate used vf env members

verifiers eb2c3fe11 -> b23b5c2ca (0.2.2.dev102). The vf environments/*
workspace glob becomes an explicit list of the envs prime-rl trains or
tests on, so upstream examples with conflicting pins (nemo-gym-weather-v1
pins openai<=2.7.2 via nemo-gym against verifiers' openai>=2.9.0) never
enter the shared lock. Floors stay dev92 - nothing in the range is
API-required, and PyPI publishing lags main.

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

* chore: pin verifiers to fix/interception-owned-clients for validation

One commit on top of main (dev102). Re-pin to main once it merges.

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

* chore: re-pin verifiers to main (interception fix merged)

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

* chore: bump verifiers to dev112 + renderers to 0.1.10.dev1 for 0.3.0 prep

verifiers 2efe0a138 -> 0a4d872f0 (0.2.2.dev112). renderers follows to main
(0.1.10.dev1, adds Laguna M.1) since vf now floors renderers>=0.1.9.
Re-pin to the 0.3.0 release tag and flip floors once it is published.

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

* chore: floor verifiers at dev112 (published to PyPI)

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

* chore: verifiers floors to 0.3.0 (released)

The submodule pin 0a4d872f0 is the v0.3.0 tag commit.

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

* chore: relock for the 0.3.0 floors

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

* chore: renderers floor to 0.1.9 (released)

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 10:17:16 -07:00
minh hoangandGitHub ec92686fbc perf(docker): cut ghcr image build from 74m to 16m (#3160)
* fix(docker): pin prebuilt aarch64 flash-attn wheel instead of building from source

The arm64 image built flash-attn 2.8.3 from source on every build: 53m46s of the
1h13m arm64 job, 74% of it, and the critical path for the whole multi-arch build.

mjun0812/flash-attention-prebuild-wheels publishes the exact aarch64 counterpart of
the x86_64 wheel already pinned here — same flash-attn 2.8.3, cu128, torch 2.11,
cp312. Pin it behind a platform_machine marker and drop the source build.

GPU coverage is unchanged. The old source build and both wheels carry identical
fatbinaries: 288 entries, sm_80 / sm_90 / sm_100 / sm_120 with 72 kernels each. The
53-minute compile was reproducing what the wheel already shipped. Verified by
walking the fatbin entry headers of flash_attn_2_cuda.so in the old arm64 image
alongside both wheels; the .so sizes agree to within 0.013%.

Also drops the post-install script's side effects. It re-resolved without
--no-deps, re-downloading 897 MB and downgrading the image's cudnn from 9.22.0.52
to 9.19.0.56 relative to the lockfile, so arm64 now matches amd64 and the lock
again. Its flash-attn-cute reinstall existed only because the source build shipped
a flash_attn/cute stub that clobbered FA4; the wheel has no cute directory, so
arm64 takes the same install path as amd64.

Removes the local aarch64 build step from scripts/install.sh and the README too —
uv sync resolves flash-attn from the wheel there as well, so the 20-30 minute
compile and its "don't run uv sync afterwards or it gets uninstalled" caveat are
both gone.

The lock diff is large but mechanical: the second platform-forked URL makes uv
restate fork markers across the file. The resolved (name, version, source) set is
unchanged except for the one added aarch64 wheel.

* perf(docker): split the venv into parallel-compressible layers and push zstd

The image was 18 layers / 8.5 GB compressed, but a single layer held 7.76 GB of it —
the monolithic `COPY --from=builder /app /app` of the whole venv. BuildKit
compresses and pushes layers concurrently, so that one layer serialized the export
behind a single gzip stream: 562.7s of the amd64 job and 411.8s of the arm64 job,
plus 210.8s / 114.4s pushing.

Split the venv's largest trees (nvidia, torch, vllm, flash_attn, and the ~1 GB
flash_attn_2_cuda .so) into their own layers via `COPY --exclude`, and switch the
image export to zstd.

Measured on the first green build of this branch:

  exporting layers   amd64  562.7s -> 42.2s     arm64  411.8s -> 42.1s
  export + push      amd64    778s -> 100.1s    arm64    528s -> 85.2s
  image size         amd64   8.52  -> 7.04 GB   arm64   7.91  -> 6.64 GB

The size drop is zstd beating gzip on ratio here, and it also confirms the excludes
line up with the per-tree copies — a mismatch would have shipped the data twice and
grown the image. The registry shows 18 zstd + 5 gzip layers, the gzip ones being
base-image layers passed through untouched.

`COPY --exclude` needs Dockerfile syntax >= 1.19, hence the syntax directive. Keep
the excludes in sync with the per-tree copies that follow them. Excluding
`flash_attn` deliberately does not swallow `flash_attn_3`.

zstd is set without `force-compression` so base-image layers are reused as-is
instead of recompressed for nothing. Pulling zstd layers needs containerd >= 1.5 or
Docker >= 23. `push: true` is replaced by `push=true` inside `outputs` because the
two would otherwise register two image exporters and export the image twice. The
`digest` output the Summary step reads comes from the metadata file, so it is
unaffected.

Splitting also lets cluster nodes pull these layers in parallel.
2026-08-06 16:01:26 -07:00
samsjaandGitHub fb31b51e84 fix: disable dynamo on Ulysses all-to-all to prevent FSDP×compile NCCL deadlock (#3195)
When torch.compile is used with Ulysses context parallelism and FSDP,
the all-to-all collectives are traced into the compiled backward graph
while FSDP's reduce-scatter hooks fire eagerly via the autograd engine.
The compiler may reorder the all-to-all backward differently across
ranks, causing rank 0 to wait on reduce_scatter while rank 1 waits on
all_to_all — a classic collective ordering mismatch that deadlocks NCCL
after the 1-hour watchdog timeout (PR #3186, job 1578).

Wrapping _all_to_all_seq_to_head and _all_to_all_head_to_seq with
torch._dynamo.disable forces a graph break around the collectives so
they execute eagerly in the autograd engine, restoring a single
consistent backward ordering between the two collective systems.
2026-08-05 21:43:25 -07:00
samsjaandGitHub 33b7d19cb1 Revert "chore: release v0.8.0 (#3207)" (#3208)
This reverts commit 56a9402953.
2026-08-05 20:53:32 -07:00
samsjaandGitHub 56a9402953 chore: release v0.8.0 (#3207) 2026-08-05 20:42:26 -07:00
0c0b92f99c chore: remove padded vLLM input scrub (#3203)
The scrub from #2506 was a temporary mitigation for NaN logits caused by
stale padded decode inputs poisoning CUDA-graph replay. The root cause is
fixed in the pinned vLLM 0.26.0: the non-contiguous logits bug in the
native Triton top-k/top-p kernel (vllm-project/vllm#42739) is included,
and _preprocess now zeros the padded positions tail natively.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 15:53:27 -07:00
samsjaandGitHub 84ce4d6677 fix: add eval.retrigger_on_resume to re-fire evals at checkpoint step on resume (#3123)
On resume, the orchestrator defaults to assuming a clean exit where all
evals already completed. When a run crashes mid-eval, the user can set
eval.retrigger_on_resume=True to re-trigger interval-aligned evals
at the checkpoint step instead of the next interval boundary.

No changes to EvalSource — the existing first_trigger = not is_resumed
already skips the base eval on resume and just checks step % interval,
so passing resume_step to trigger() is sufficient.
2026-08-05 15:49:32 -07:00
01e959596a feat: auto-resolve parsers for Laguna, gpt-oss, and Trinity (#3201)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 15:06:50 -07:00
HubertandGitHub 738eb5016a fix(nemotron-h): use fla causal_conv1d for packed Mamba conv (#3192)
Both NemotronH Mamba paths built their packed-document metadata with a
`cu_seqlens.tolist()` and a Python loop over documents, once per Mamba
layer. On Super that is 40 host-device syncs per forward (80 with
activation recompute): each one blocks the Python thread until the CUDA
stream drains, so the CPU never runs ahead and, under context
parallelism, every rank re-synchronizes to its slowest CP partner at
every layer instead of absorbing jitter in queue depth.

Replace the per-document conv loop and the hand-built seq_idx with
fla's Triton `causal_conv1d` and `prepare_sequence_ids`, matching the
call shape already used for Qwen3.5 GDN in `trainer/model.py` and
`qwen3_5_moe`. Both fla helpers derive boundaries from `cu_seqlens`
directly and are `@tensor_cache`d by argument identity, so the 40
layers of a forward share one build.

fla is already a required dependency and its Triton backend needs no
arch-specific CUDA compilation, which was the stated reason for
avoiding a fused conv here.
2026-08-04 20:41:49 -07:00
06eb91d7c8 fix: accept seq_lens contract kwargs in GlmMoeDsaModel.forward (#3197)
* fix: accept seq_lens contract kwargs in GlmMoeDsaModel.forward

The fused LM head wrapper forwards seq_lens/seq_lens_are_pre_shard to the
inner model, but only GlmMoeDsaForCausalLM accepted them.

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

* review: drop inline comment above seq_lens kwargs

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 20:21:03 -07:00
327f378e07 feat!: standalone env servers (#3162)
* feat!: remove env-server sidecaring, launcher spawns at deterministic addresses

The orchestrator never spawns env servers anymore — it always connects to
each source's serve.address and polls until the server is up. Addresses
are assigned deterministically at config validation (tcp://127.0.0.1:5000+
across train then eval sources), so the launcher (local rl + multinode
sbatch template) spawns the servers in parallel with the orchestrator and
both sides agree on where each server lives from the config alone.

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

* chore: docstring + test tidy

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

* refactor!: derive env-server addresses, require address on env-server config

Addresses are wiring, not intent — like the transport blocks, they are no
longer configurable on sources. The orchestrator derives each server's
address from the source's position in the config; the env-server entrypoint
takes a required address the launcher writes per source.

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

* refactor: env-server config mirrors verifiers' serve CLI, per-run base port

EnvServerConfig composes vf's env/serve/legacy blocks verbatim, so an
env-server TOML reads like a vf serve config. orchestrator.env_server_base_port
offsets the derived port range, giving concurrent runs on one host (e.g.
multi-run orchestrators) each their own 1:1 env server.

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

* feat(configs): multi-env debug config (2 reverse-text train sources + eval)

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

* feat: rename env server entrypoint to `env` (keep `env-server` alias), env_server_addresses -> env_addresses

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

* chore: env/ prefix for env server stop-event keys

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

* refactor: rename env server naming to env throughout

EnvServerConfig -> configs/env.py:EnvConfig, source-level EnvConfig -> SourceConfig,
entrypoint moves to entrypoints/env.py, env_server_base_port -> env_base_port,
proctitle PRIME-RL::Env

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

* docs: trim env entrypoint row

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

* feat: drop the verifiers serve CLI, adopt vf.ServeConfig

Bumps deps/verifiers to PrimeIntellect-ai/verifiers#2237 (serve CLI removed,
ServingConfig renamed ServeConfig); prl's source-level ServingConfig follows suit

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

* docs: drop the removed serve CLI reference from EnvConfig

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

* chore: pin verifiers to main (serve CLI removal merged)

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

* ci: slim install imports configs.env

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

* revert: keep env-server naming, validate env identity on EnvServerConfig

The env console script shadows coreutils env in activated shells — back to
env-server as the sole entrypoint (still at entrypoints/, orchestrator source
class stays EnvConfig as on main). EnvServerConfig regains the identity
validation the nested source config used to provide (missing env, mixed v0/v1)

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

* fix(slurm): remove apostrophe from env-server launch comment

The multi-node srun body is one single-quoted bash -c string, so the
apostrophe in "source's" closed it early: every rendered sbatch failed to
parse with a syntax error near unexpected token '(' and the job died before
any component started. Reword the comment and note the constraint.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 16:48:48 -07:00
4aeca13870 chore: scope the jaxtyping lint ignores so F821 runs everywhere else (#3194)
* chore: scope the jaxtyping lint ignores so F821 runs everywhere else

F821 (undefined name) was disabled repo-wide for jaxtyping's shape
strings, so ruff could not report a missing import anywhere in prime-rl —
and style CI runs only ruff. Four modules actually use those annotations;
the ignore now names them.

The fifth file the rule fired on was not jaxtyping: rotary_emb annotated
a config it never imported, so the name resolved to nothing. Imported.

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

* chore: trim the ignore comment

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 15:50:49 -07:00
minh hoangandGitHub 8ab86036b2 fix(ci): allow branch/commit refs in ghcr image build (#3126)
* fix(ci): allow branch/commit refs in ghcr image build

The `ref` input already advertises "Branch, tag, or commit to build",
but Resolve image vars rejected anything that wasn't main, v*, or *.dev*,
so dispatching a build off a feature branch failed.

Drop the allowlist (the ref is checked out — hence existence-validated —
before this step) and name non-tag builds with `git describe` so a
branch build tags as e.g. v0.7.1.dev55-3-gfea5aadcf-<branch>, carrying
the nearest release + commit distance + short sha and never colliding
with a clean release tag. Exact-tag refs still build under the tag
verbatim, and the commit-<sha> tag is kept since the platform pins it.

* ci: restrict manual image builds to maintain/admin

workflow_dispatch already requires write access, but that includes any
write-level collaborator. Add an authorize job that gates the build on
the dispatcher having maintain or admin (via the collaborator permission
API). Automated in-repo dispatches run as github-actions[bot] and are
allowed so devx_tag dev-image builds and the release build keep working.
prepare now needs authorize, gating the whole build + manifest chain.

* ci: gate only manual dispatches in authorize job

The authorize job ran for every trigger, including on:release. Scope the
permission check to workflow_dispatch (manual builds) so release/other
events pass through. Guard the step (not the job) so a skip still leaves
prepare's `needs: authorize` satisfied.
2026-08-04 12:46:29 -07:00
f0bc8f1fab fix: standalone inference at dp=1 EP (template) + poolside_v1 tool-call regex (#3184)
* fix: port dp=1 EP dense-style launch to standalone inference template

Same bug as #3094, same fix: the multi-node branch of inference.sbatch.j2
still passed external-LB DP args (data_parallel_rank/address) at dp=1
(e.g. tp=8 on 8-GPU nodes), which vLLM >=0.24 rejects with
'data_parallel_external_lb can only be set when data_parallel_size > 1'.

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

* fix: accept poolside_v1 tool calls without newline after function name

Laguna S 2.1 emits <tool_call>name<arg_key>... with no newline; the
non-streaming func_detail_regex required one, so every tool call failed
detail parsing and leaked verbatim into content (finish_reason=stop).
Upstream vLLM >=0.25 accepts both forms; patch only the regex via the
shared vLLM plugin.

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

* Revert "fix: accept poolside_v1 tool calls without newline after function name"

This reverts commit b054923274aecb39f82671b2f9eae22ef0590fb9.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-04 09:16:46 -07:00
756f217f22 fix: bump vf + fix lock (#3187)
* fix: relock uv.lock after research-environments bump

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

* fix: bump verifiers to 0.2.2.dev76 and rename ServingConfig to ServeConfig

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 18:34:18 -07:00
78cef2844f chore: bump research-environments to latest main (#3185)
Bump the deps/research-environments submodule pin 21a284618 -> f9c43a74 (latest
main), which includes research-environments #744 fixing senior_swe_bench_v1's stale
verifiers.v1.clients.config import (moved to verifiers.v1.configs.client) so
senior-swe-bench-v1 resolves against latest verifiers.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 17:26:39 -07:00
ef42886edc feat(orchestrator): multi-agent native metrics (#3165)
* feat(orchestrator): episode- and agent-level rollout metrics

Adapt to verifiers#2187 (Episode derived aggregates): episode.last_error
rename, submodule bump. Mirror the episode/trace hierarchy in the wandb
layout: count metrics read at the episode level (per-episode sums), and
a new {scope}/{subset}/<agent>/<metric>/<stat> level reports trace-level
metrics per agent, averaging in-episode fan-outs first.

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

* chore: bump verifiers to vf#2187 head, episode wording cleanups

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

* refactor(orchestrator): RolloutMetrics -> EpisodeMetrics, AgentMetrics -> TraceMetrics

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

* feat(orchestrator)!: trace-level metrics are agent-only, timing generation span renamed agent

Env level now carries only episode-level facts (count sums, pipeline
rates, eval scores); reward, truncation, errors, stop conditions, timing,
custom metrics and solve rates move under {scope}/{subset}/<agent>/.
Adapts to the vf span rename (Timing.agent, AgentSpan, split_agent_time)
and re-pins deps/verifiers. Overview reward/error/truncation panels match
the per-agent keys by regex.

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

* feat(configs): agentic-judge reverse-text debug config

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

* chore(configs): deterministic two-call judge policy for the agentic-judge debug config

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

* chore: bump verifiers to vf#2187 head

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

* chore: bump verifiers to vf#2187 head (main merged)

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

* chore: bump verifiers pin

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

* chore: bump verifiers pin

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

* chore: re-pin verifiers to the vf#2187 merge commit

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

* chore: bump verifiers and research-environments to latest main

verifiers f646beb37 -> f6e420b99 (0.2.2.dev66, 17 commits) and
research-environments 6a2dee6fc -> ccb375ce5 (main + the scicode-v1
pin relax from research-environments#740).

Adaptations to the verifiers changes:
- Episode.error is now Episode.errors + a last_error property (vf#2187)
- verifiers.v1.loaders / verifiers.v1.push moved into
  verifiers.v1.utils.{loaders,platform} (vf#2204)
- verifiers floors bumped to 0.2.2.dev66 (root and prime-rl-configs)

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

* chore: bump research-environments to latest main

ccb375ce5 -> 9a57c713c: research-environments#740 refreshed on current
main, picking up the ViRL39K v1 taskset (RE#689) and the taskset prompt
config fixes (RE#742). verifiers main is unchanged since f6e420b99.

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

* chore: bump verifiers to 0.2.2.dev73 (per-rollout clients)

f6e420b99 -> 576506d66 (7 commits). vf#2218 builds one client per
rollout with a process-wide elastic renderer pool: TrainClientConfig
drops pool_size for a multiplex knob, and the config module moved from
clients.config to configs.client. The orchestrator config follows suit
(pool_size -> multiplex, None = client default). Floors to dev73.

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

* chore!: pin research-environments to the scicode merge commit, drop orchestrator.multiplex

deps/research-environments -> 21a284618 (research-environments#740 on
main). The orchestrator-level renderer knob (pool_size, briefly
multiplex) is removed instead of renamed: clients resolve inside env-
server workers, whose concurrency is already bounded per env by
serve.pool.multiplex (default 128, below the client-side renderer
default of 256), so each worker warms one renderer and the elastic pool
grows on demand.

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

* feat(orchestrator)!: pipeline verdicts and eval scores are per-agent too

is_trainable / is_filtered / filters and avg@k / pass@k all score a
single trace, so they read per agent like every other trace-level
metric instead of pooling an episode's seats.

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

* chore: drop the agentic-judge debug config from this PR

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

* docs: spell out the per-agent metric level in the monitor-run skill

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

* docs: eval's overview score is the per-agent avg@k

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

* fix(orchestrator): agent-level rates are flat over traces

is_truncated / is_completed rode the per-episode mean path with the
distributions, so an uneven fan-out — what the effective subset leaves
whenever a sibling errors — reweighted them away from the plain
fraction their siblings and the docs promise.

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

* refactor(orchestrator)!: agent-level metrics are flat over traces

One aggregation per level: the episode level sums an episode's traces,
the agent level takes each trace as a sample. Reward, avg@k and the
per-agent counts had been collapsing each episode's fan-out to a mean
first, which left them the odd ones out among the seat's own metrics and
made avg@k's k — a trace count — disagree with what it averaged.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 16:04:14 -07:00
ed05a1418d fix: count unscored reward components as zero in rollout metrics (#3182)
* fix(metrics): count unscored reward components as zero

Verifiers now seeds expected reward/metric names with None when scoring
starts, so a scoring failure leaves seeded-unscored entries instead of an
empty dict. CustomMetrics counts unscored rewards as 0.0 (matching the
scalar reward, which sums them as 0) and keeps averaging metrics over the
rollouts that scored them, so all-subset per-key reward means no longer
collapse onto effective when scoring errors occur.

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

* chore: bump verifiers submodule

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

* chore: bump verifiers submodule

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

* fix(metrics): count unscored metrics as zero too

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

* chore: bump verifiers to main

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 15:25:25 -07:00
1ef8f1a843 chore: bump verifiers and research-environments to latest main (#3172)
* chore: bump verifiers and research-environments to latest main

verifiers f646beb37 -> f6e420b99 (0.2.2.dev66, 17 commits) and
research-environments 6a2dee6fc -> ccb375ce5 (main + the scicode-v1
pin relax from research-environments#740).

Adaptations to the verifiers changes:
- Episode.error is now Episode.errors + a last_error property (vf#2187)
- verifiers.v1.loaders / verifiers.v1.push moved into
  verifiers.v1.utils.{loaders,platform} (vf#2204)
- verifiers floors bumped to 0.2.2.dev66 (root and prime-rl-configs)

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

* chore: bump research-environments to latest main

ccb375ce5 -> 9a57c713c: research-environments#740 refreshed on current
main, picking up the ViRL39K v1 taskset (RE#689) and the taskset prompt
config fixes (RE#742). verifiers main is unchanged since f6e420b99.

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

* chore: bump verifiers to 0.2.2.dev73 (per-rollout clients)

f6e420b99 -> 576506d66 (7 commits). vf#2218 builds one client per
rollout with a process-wide elastic renderer pool: TrainClientConfig
drops pool_size for a multiplex knob, and the config module moved from
clients.config to configs.client. The orchestrator config follows suit
(pool_size -> multiplex, None = client default). Floors to dev73.

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

* chore!: pin research-environments to the scicode merge commit, drop orchestrator.multiplex

deps/research-environments -> 21a284618 (research-environments#740 on
main). The orchestrator-level renderer knob (pool_size, briefly
multiplex) is removed instead of renamed: clients resolve inside env-
server workers, whose concurrency is already bounded per env by
serve.pool.multiplex (default 128, below the client-side renderer
default of 256), so each worker warms one renderer and the elastic pool
grows on demand.

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

* fix(orchestrator): read the agent timing span

vf#2187 renamed Timing.generation to Timing.agent (GenerationSpan ->
AgentSpan); the timing metrics group crashed every RL run's first
to_wandb. Metric keys follow (timing/agent, timing/agent/{model,
harness}). The unit fixture missed it because mk() duck-types Trace;
its namespace now mirrors the real field names.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 13:43:28 -07:00
e229a286f2 fix: checkpoint and resume the orchestrator train data position (#3164)
* fix(orchestrator): checkpoint and resume the train data position

Shuffle each finite env's task table with seed=epoch (1-indexed) so the
permutation is reproducible, snapshot per-env {epoch, cursor} into
Progress.data_positions at checkpoint time, and restore + log the
position on resume.

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

* fix(orchestrator): track and fast-forward infinite taskset cursors on resume

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

* chore(orchestrator): drop old-checkpoint load compat

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

* refactor(orchestrator): make the data position first-class checkpoint state

TrainSource is a torch Stateful (state_dict/load_state_dict) saved under
its own train_source key next to progress, mirroring the SFT dataloader.

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

* docs: simplify orchestrator checkpoint table row

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

* refactor(orchestrator): simplify TrainSource surface

Hardcode the env-choice seed, drop the torch Stateful base (nothing
consumes the protocol), log the restored position from ckpt.load, and
rename _shuffled to _shuffle.

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

* feat(orchestrator): make the cross-env dispatch sequence reproducible

Advance the env-choice RNG exactly once per dispatched example - a draw
whose permit cost doesn't fit is held (head-of-line) instead of redrawn -
and checkpoint the RNG state and pending draw with the per-env positions.

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

* fix(orchestrator): save the interval checkpoint on the event loop

state_dict() on a to_thread worker raced the dispatcher mutating
TrainSource; the payload is tiny, so snapshot and write synchronously.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-03 11:31:56 -07:00
2ffe374e02 fix(trainer): add B300/GB200/GB300 peak FLOPS for MFU (#3168)
B300 device names fell through to the A100 fallback (312 TFLOPS),
inflating reported MFU ~7x. Add dense BF16 peaks per NVIDIA datasheets:
GB200/GB300 superchips at 2.5 PFLOPS, HGX B200/B300 at 2.25 PFLOPS.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-01 21:51:18 +02:00
bbb90a1b41 chore(configs): expand inline TOML tables to sections (#3167)
Every checked-in config, example, and doc snippet now uses [section]
headers instead of key = { ... } inline tables. Purely stylistic: all
48 rewritten TOML files parse identically to their previous versions.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-30 15:24:35 -07:00
Matej SirovatkaandGitHub 9f0d41e23d chore(inference): bump vLLM to 0.26.0 (#3166) 2026-07-30 21:57:55 +02:00
e0638c7eb6 chore: adapt to the verifiers trace record cleanups (#3157)
* rename training environments to sources

* fix CPU test config fixtures

* rename evaluation environments to sources

* chore(orchestrator)!: rename max_inflight_rollouts to max_inflight_episodes

A dispatcher permit has always bought one episode, not one rollout: for a v1
env one `run` request is one episode (however many agents play it), and a
legacy group-scoring call reserves one permit per bridged v0 rollout, each of
which is its own single-agent episode. Name the knob what it counts.

`max_inflight_rollouts` still parses as an alias, as `rollouts_per_example`
does for `group_size`.

* feat(orchestrator)!: compose the verifiers env, serve and legacy blocks

verifiers split `EnvServerConfig` into three blocks, so an env entry composes
them instead of inheriting one class:

    [[orchestrator.train.source]]
    env    = { taskset = { id = "..." } }   # what runs
    serve  = { pool = { ... }, address, max_concurrent }   # how it's hosted
    legacy = { id, args }                   # a classic v0 env instead

`serve.pool` sizes the spawned server (was `pool`), `serve.address` points at an
external one (was `address`), and `serve.max_concurrent` bounds one worker's
episodes in flight — usually left unset, since `max_inflight_episodes` is the
run's bound. Each moved key raises with a pointer home, including the
`num_workers` shorthand the old validator migrated silently.

BREAKING: `pool` / `address` / `num_workers` on an env entry move under `serve`,
and a v0 env's `id` / `args` / `extra_env_kwargs` move under `legacy`.

TEMPORARY: `deps/verifiers` points at the `feat/one-agent-per-episode` branch
(PrimeIntellect-ai/verifiers#2157) so the two sides can be run together; re-pin
to a merged `main` commit before this lands.

* fix the source-config readers the compose commit missed

The Prime monitor still built its run-registration payload from `env.id`, which
the composed entry doesn't have — `AttributeError` at registration whenever
Prime monitoring is on. It reads `env_id` now, the property that spans both the
v1 and the v0 shape.

The packer's fixture still used the bare `id` shorthand, so its three runs were
rejected at config parse and skipped by `discover_runs`. Full CPU unit suite:
416 passed.

Re-pins `deps/verifiers` to the branch tip of verifiers#2157, which fixes the
same class of stale access on that side (`config.legacy.id`). Still a branch
commit — re-pin to a merged `main` before this lands.

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

* spell the env annotation out instead of vf.EnvField

verifiers dropped the `EnvField` alias, which was only ever
`SerializeAsAny[EnvConfig]` under a name that collided with `env_field()`.

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

* declare the env default with the factory verifiers exports

`vf.env_field()` is gone: it only wrapped `Field(default_factory=...)`.

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

* inline the legacy helpers, use the config class as the default

Follows verifiers dropping the three `configs/legacy.py` helpers and the
`single_agent_env_config` factory: `is_legacy` and `env_id` are one-liners here,
the mixed-run refusal is spelled out in `validate_env`, and the `env` default is
`vf.SingleAgentEnvConfig()`. `env.max_concurrent` now works as an alias for
`env.max_concurrent_agents`.

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

* drop the serving-key pointers here too

The same call as verifiers a0ebc408: `num_workers` / `pool` / `address` on a source
entry now fail as an ordinary `extra_forbidden` instead of naming their new home.

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

* bump verifiers: no max_concurrent alias on the env block

`env.max_concurrent` used to bound a served worker's agent runs across episodes, so
accepting it as `max_concurrent_agents` multiplied it by the episodes in flight. It
errors now, like every other moved key. 416 unit tests pass.

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

* bump verifiers to 0.2.2.dev43 (merged main)

deps/verifiers d0bb0ffe5 -> fcb48822e, which is the squash-merge of the composed
env/serve/legacy config blocks (#2157) plus everything else since the last bump:
Harbor 0.20.0 (#2161), runtime-blamed box failures (#2156), standalone MCP clients
pinned to v1 (#2155), and the v1 test/E2E split (#2127).

Lock: harbor 0.14.0 -> 0.20.0, which drops claude-agent-sdk and datasets from its
own deps and adds filelock/platformdirs, so those move with it.

Replaces the temporary branch pin this PR carried.

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

* fix: spawn the env server again, and let a pip-only install resolve verifiers

Two CI failures from the compose commit.

The orchestrator stopped spawning env servers. It decides spawn-vs-connect by
`address is None`, and prime-rl's own field defaulted to None; `vf.ServingConfig`
defaults to `tcp://127.0.0.1:5000`, so every env looked external and the run waited
120s for a server nobody started. It now asks whether the address was *pinned*
(`model_fields_set`), so an unset `[serve]` spawns on a free port as before, and
pinning any address — including verifiers' own default — connects.

The slim `prime-rl-configs` wheel is installed from /tmp with no workspace context,
so `verifiers` resolves from PyPI, where `>=0.2.1` picks stable 0.2.1 — no
`SingleAgentEnvConfig`. Floor is `>=0.2.2.dev43` now, a pre-release specifier so the
dev release is eligible.

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

* chore: adapt to the verifiers trace record cleanups

Companion to PrimeIntellect-ai/verifiers#2172: record_* mutators, required
agent seat and RunInfo.id, last_error, and agent.name/.trainable reads.

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

* chore: re-pin verifiers to merged main (f646beb37)

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

---------

Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 10:34:53 -07:00
halleriteandGitHub 0b583306eb feat(orchestrator): hierarchical GRPO for proposer-solver envs (#3138) 2026-07-30 15:31:13 +02:00
halleriteandGitHub d612e23c1d chore(configs)!: remove every config shim (#3156) 2026-07-30 01:50:01 +02:00
halleriteandGitHub d135ed4c90 feat(orchestrator)!: rename env collections to sources, compose the verifiers config blocks (#3150) 2026-07-30 01:41:54 +02:00
1fd2d732c2 fix: read overview quality metrics from effective subset (#3159)
* fix: read overview quality metrics from effective subset

The all subset counts errored rollouts as zeros for num_branches,
num_turns, num_total_tokens, and is_truncated, which skews the
distributions and makes the panels uninterpretable. Point the wandb
overview panels and the eval success line at the effective subset;
has_error stays on all since effective drops errors by construction.

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

* fix: reword zero-skew rationale, drop subset guidance from skill

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-29 16:36:13 -07:00
6a9969e61a chore: bump renderers to 0.1.9.dev9 (#3158)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-29 16:06:49 -07:00
1385e0722c fix: compute trainable rate over effective rollouts (#3152)
* fix(orchestrator): compute trainable rate over effective rollouts

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

* chore: drop comment

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-07-28 23:52:21 -07:00
e2ad3beaaa feat(monitor): effective reward/score in wandb overview (#3153)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 23:40:39 -07:00
9551e20fa8 chore: single global router in front of engines for all deployments (#3105)
* chore: single global router in front of engines for all deployments

Every deployment shape now runs one client-facing router on server.port
with engines behind it on backend_port: local single-node runs spawn a
vllm-router in the inference entrypoint, and the SLURM templates collapse
per-replica routers into a single global router on inference node 0.
router/backend_port move to InferenceConfig top level; router = "None"
runs a bare engine (used for per-rank SLURM engine processes).

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

* fix: finish single-node router integration

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-07-29 05:17:43 +02:00
6df90dc0aa feat: default rollout transport to zmq and inject host for multi-node (#3149)
* feat(config): shared [rollout_transport] propagated to trainer + orchestrator

Add rollout_transport as a shared RLConfig field (mirroring weight_broadcast /
ckpt / wandb), propagated to trainer.rollout_transport and
orchestrator.rollout_transport via propagate_shared_fields. A single
[rollout_transport] block configures both sub-configs.

auto_setup_rollout_transport (like auto_setup_weight_broadcast) resolves the
shared field from the sub-configs so the launcher's ZMQ host-injection gate is
correct whether transport is set via the shared block or directly on
trainer/orchestrator.rollout_transport (the documented fallback), and rejects
mismatched sub-config transports.

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

* feat(launcher): inject rollout_transport.host for multi-node zmq transport

ZMQ rollout transport binds/connects a single rollout_transport.host (default
localhost). On multi-node trainer deployments the training-batch PUSH/PULL and
micro-batch PUB/SUB span nodes, so data ranks on non-head nodes connect to their
own localhost and hang at step 0. The launcher already injects
weight_broadcast.host=$MASTER_ADDR for nccl but had no equivalent for
rollout_transport.

When config.rollout_transport resolves to zmq, inject --rollout_transport.host
$MASTER_ADDR into the trainer torchrun and the orchestrator (mirrors the existing
weight_broadcast.host injection). Filesystem transport is unaffected.

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

* feat(config): default rollout transport to zmq

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-29 04:43:50 +02:00
8372c37a15 fix: plot overview time panels on relative wall time (#3148)
* fix(monitor): plot overview time panels on relative wall time

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

* chore: drop view_signature docstring

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-07-28 15:21:05 -07:00
15f5355f5f chore: bump verifiers + research-environments to latest main (#3147)
- deps/verifiers -> d0bb0ffe5 (network-policy alignment #2124, Codex MCP tools
  #2140, Ruff 0.16 / ty tooling, and everything since the last bump)
- deps/research-environments -> 6a2dee6fc (judges/swe agentic-judge setups #720,
  MMMU-Pro / CharXiv tasksets, wideseek verifiers-pin fix #731)
- uv.lock relocked (adds charxiv-v1, mmmu-pro-v1; bfcl-v3-v1 0.2.0 -> 0.3.0)

No code changes needed: the runtime-on-agent config addressing and Reward-record
metrics landed with the earlier bump (#3137).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 12:50:01 -07:00
JannikStandGitHub d1bfcbc636 chore(ci): enable nightly FFT cron (#3142) 2026-07-28 13:06:46 +02:00
f50ec5c4c8 feat(orchestrator): RAE — role-conditioned advantage estimation for self-play envs (SPIRAL) (#3136)
* feat(orchestrator): RAE — SPIRAL's role-conditioned advantage estimation for self-play envs

Add the `rae` algorithm (SPIRAL, arXiv:2506.24119): each trainable agent
keeps an EMA baseline of its own rewards, and every trace's advantage is
its reward minus its agent's pre-update baseline. Group-relative baselines
mis-credit multi-agent self-play — in a zero-sum game the group mean is ~0
whatever the policy does, and centering both agents against it turns any
structural asymmetry (first-mover edge) into permanent credit. Baselines
are keyed per (env, agent) — the paper's per (game, role) — and any
group_size works, including 1.

configs/debug/algo/rae.toml runs shared-policy Kuhn poker self-play
(kuhn-poker-v1, both agents late-bound to the run's model).

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

* chore(tests): drop RAE unit tests

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-27 19:34:50 +02:00
9b944591c4 chore: bump verifiers to latest main; adopt runtime-on-agent, Reward records, textarena player (#3137)
* chore: bump verifiers to latest main; adopt runtime-on-agent, Reward records, textarena player

deps/verifiers b13ba60da → 295a06505 (+12: interleaving agents + kuhn-poker-v1,
runtime moves from the harness onto the agent (#2106), trace rewards become
Reward{score, weight} records (#2119), wordle-v1 rides the rewritten
TextArenaEnv, pluggable harness skills, agentic-judge grading knobs).

Adoption:
- every `env.<agent>.harness = { ..., runtime = ... }` config line splits into
  `harness = { ... }` + `env.<agent>.runtime = ...` (configs/, examples/, docs/,
  skills/)
- wordle configs address the textarena seat as `env.player`
- reward metrics read the weighted `Reward.value` (CustomMetrics gains a value
  extractor); unit-test trace builders record `vf.Reward(score=...)`
- uv.lock re-locked for verifiers 0.2.2.dev29

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

* fix(tests): adopt Reward records in prime-monitor rollout builder

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-27 18:26:18 +02:00
JannikStandGitHub 3b22dd951c fix(nightly-fft): restore auto-resolve latest v*.dev* when no image_tag input (#3134)
* fix(nightly-fft): restore auto-resolve latest v*.dev* when no image_tag input

The nightly's whole point is to catch regressions on tip-of-main, so a
plain 'gh workflow run "Nightly FFT"' must dispatch against the newest
built v*.dev* by default. #3133 removed that fallback and made no-input
dispatches emit an empty tag, which falls through to the platform's
default 'main' alias — currently baked ~50 commits stale — so the run
crashes on validation.

Restores the original behavior: no input → auto-resolve latest dev.
Explicit image_tag input still overrides (from #3132). Dispatch step
always passes --image-tag since the tag is always populated now.

* fix(ci): guard dev-tag resolver against pipefail

GitHub Actions runs the shell under `bash -eo pipefail` by default.
Two failure modes:
- `grep -E ...` returns 1 when no v*.dev* tags exist yet
- `head -n 10` closes the pipe after 10 lines, SIGPIPE-ing `sort`

Either aborts the step before the explicit no-candidates guard runs.
Wrap the pipeline in set +o pipefail / set -o pipefail.
2026-07-24 10:10:26 +02:00
JannikStandGitHub 13770289ef fix(nightly-fft): don't force --image-tag when no dispatch input (#3133)
* fix(nightly-fft): pin image_tag to commit-c505e07a1 in each config

The default 'main' image the platform validator ships is baked ~50
commits behind tip and predates cb74ae2be (which added the env.
wrapper on train.env entries). It rejects env.taskset with
'train.env[0].env — Extra inputs are not permitted' and doesn't know
the 'prime-qwen3' renderer name, so every nightly orchestrator
crash-loops on validation.

- Pin top-level image_tag = 'commit-c505e07a1' in each nightly-fft
  toml. c505e07a1 is post-cb74ae2be and accepts the current v1 shape.
- Workflow: when no dispatch input is set, emit an empty tag and skip
  --image-tag on prime train so the toml pin wins. Explicit
  workflow_dispatch image_tag still overrides.
- Drop this pin once v0.7.1+ (with the v1 schema) is released and the
  backend default resolves to it.

* revert: drop image_tag pin from nightly-fft configs

Keep the workflow change (only pass --image-tag when explicit input);
rely on prime-cli's built-in fallback: --image-tag > toml image_tag >
backend default. No commit-hash pin baked into the checked-in configs.
2026-07-24 06:59:43 +02:00
214 changed files with 6126 additions and 9232 deletions
+56 -15
View File
@@ -34,8 +34,42 @@ concurrency:
cancel-in-progress: false
jobs:
authorize:
name: Authorize dispatcher
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Require maintain or admin
# Gate MANUAL dispatches only; other events (e.g. release) are
# already privileged and pass through. Guard the step, not the job —
# a skipped job would skip `prepare` via `needs: authorize`.
if: github.event_name == 'workflow_dispatch'
env:
GH_TOKEN: ${{ github.token }}
ACTOR: ${{ github.triggering_actor }}
REPO: ${{ github.repository }}
run: |
# Restricted to repo members with maintain or admin. Automated
# in-repo dispatches (devx_tag dev-image builds, the release build)
# run as github-actions[bot] via GITHUB_TOKEN — allow those through.
if [ "$ACTOR" = "github-actions[bot]" ]; then
echo "Dispatcher is repo automation ($ACTOR); allowed."
exit 0
fi
role=$(gh api "repos/${REPO}/collaborators/${ACTOR}/permission" --jq '.role_name' 2>/dev/null || true)
echo "Dispatcher $ACTOR has repo role: ${role:-<none>}"
case "$role" in
admin|maintain)
echo "Authorized." ;;
*)
echo "::error::$ACTOR (role: ${role:-none}) is not allowed to trigger image builds; requires maintain or admin." >&2
exit 1 ;;
esac
prepare:
name: Prepare build
needs: authorize
runs-on: ubuntu-latest
permissions:
contents: read
@@ -81,27 +115,30 @@ jobs:
INPUT_TAG: ${{ env.BUILD_TAG }}
PLATFORMS: ${{ env.BUILD_PLATFORMS }}
run: |
case "$INPUT_REF" in
main|v[0-9]*|*.dev[0-9]*) ;;
*)
echo "ref '${INPUT_REF}' not allowed for ghcr publish (must be main, v*, or *.dev*)" >&2
exit 1
;;
esac
if [ -n "$INPUT_TAG" ] && [ "$INPUT_TAG" != "$INPUT_REF" ] && [ "$INPUT_REF" != "main" ]; then
echo "custom 'tag' that differs from 'ref' is only allowed when ref=main; got ref='${INPUT_REF}' tag='${INPUT_TAG}'" >&2
exit 1
fi
raw_tag="$INPUT_TAG"
if [ -z "$raw_tag" ]; then
raw_tag="$INPUT_REF"
sanitize() {
echo "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//' | cut -c1-50
}
# A ref that is exactly a git tag builds under that tag verbatim;
# any other ref (branch / arbitrary commit) is prefixed with
# `git describe` so the tag carries the nearest release, commit
# distance and short sha (e.g. v0.7.0-42-g1a2b3c4d5-fix-my-branch)
# and can't collide with a clean release tag.
if [ -n "$INPUT_TAG" ]; then
tag=$(sanitize "$INPUT_TAG")
elif tag=$(git describe --tags --exact-match 2>/dev/null); then
:
else
tag="$(git describe --tags --always)-$(sanitize "$INPUT_REF")"
fi
tag=$(echo "$raw_tag" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | cut -c1-50 | sed 's/^-//;s/-$//')
if [ -z "$tag" ]; then
echo "Could not derive a valid image tag from '${raw_tag}'." >&2
echo "Could not derive a valid image tag from ref='${INPUT_REF}' tag='${INPUT_TAG}'." >&2
exit 1
fi
@@ -137,7 +174,7 @@ jobs:
run: |
if [ -f .gitmodules ]; then
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/pydantic-config deps/verifiers deps/renderers deps/research-environments
git submodule update --init --recursive -- deps/pydantic-config deps/verifiers deps/renderers deps/prime-envs
fi
- name: Log in to GitHub Container Registry
@@ -156,7 +193,11 @@ jobs:
with:
context: .
file: ./Dockerfile.cuda
push: true
# zstd compresses the multi-GB venv layers several times faster than gzip at a
# comparable ratio. No `force-compression`, so base-image layers are reused as-is
# rather than needlessly recompressed. Pulling zstd layers needs containerd >= 1.5
# or Docker >= 23.
outputs: type=image,push=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
with:
+2 -5
View File
@@ -32,7 +32,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Install dependencies
@@ -84,9 +84,6 @@ jobs:
- test: reverse_text_moe
runner: vm
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: reverse_text_multi_run
runner: 4xa6000
pytest_args: "tests/integration/test_reverse_text_multi_run.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py"
@@ -103,7 +100,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Install dependencies
+16 -8
View File
@@ -13,9 +13,9 @@ on:
required: false
default: ""
# Scheduled run at 3AM PST (11AM UTC) — disabled for now, enable once dry-run passes
# schedule:
# - cron: "0 11 * * *"
# Scheduled run at 3AM PST (11AM UTC)
schedule:
- cron: "0 11 * * *"
permissions:
contents: read
@@ -113,16 +113,24 @@ jobs:
exit 0
fi
# The GHCR versions API can list a tag before its manifest is
# actually pullable (build in-flight, or manifest step didn't
# finish). So: pull the top N candidate tags, then verify each
# with a manifest HEAD via the anonymous registry token flow;
# take the newest one that resolves.
# No dispatch input: auto-resolve the newest v*.dev* tag on
# GHCR (the point of a nightly is to catch regressions on
# tip-of-main). The GHCR versions API can list a tag before
# its manifest is actually pullable (build in-flight, or
# manifest step didn't finish), so pull the top N candidates
# and verify each with a manifest HEAD via the anonymous
# registry token flow; take the newest one that resolves.
# Disable pipefail locally: `grep` may exit 1 on no matches
# (empty tag list) and `head` may SIGPIPE `sort` after
# reading its 10 lines. Both would abort the step before the
# explicit no-candidates guard below runs.
set +o pipefail
candidates=$(gh api --paginate \
"/orgs/primeintellect-ai/packages/container/prime-rl/versions" \
--jq '.[].metadata.container.tags[]' \
| grep -E '^v[0-9]+\.[0-9]+\.[0-9]+\.dev[0-9]+$' \
| sort -Vru | head -n 10)
set -o pipefail
if [ -z "$candidates" ]; then
echo "No v*.dev* tag listed on GHCR." >&2
exit 1
+1 -1
View File
@@ -79,7 +79,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
with:
+3 -3
View File
@@ -4,9 +4,9 @@
[submodule "renderers"]
path = deps/renderers
url = git@github.com:PrimeIntellect-ai/renderers.git
[submodule "research-environments"]
path = deps/research-environments
url = git@github.com:PrimeIntellect-ai/research-environments.git
[submodule "prime-envs"]
path = deps/prime-envs
url = git@github.com:PrimeIntellect-ai/prime-envs.git
[submodule "pydantic-config"]
path = deps/pydantic-config
url = https://github.com/PrimeIntellect-ai/pydantic-config
+21 -7
View File
@@ -1,3 +1,7 @@
# syntax=docker/dockerfile:1
# ^ `COPY --exclude` (used to split the venv into parallel-compressible layers) needs
# Dockerfile syntax >= 1.19; `docker/dockerfile:1` resolves to the latest stable 1.x.
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
# Build stage - multi-arch base (supports amd64 + arm64)
@@ -128,11 +132,6 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
&& rm -rf /tmp/nixl /app/deps/nixl_cu12-*.whl; \
fi
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
ARG TARGETARCH
COPY scripts/docker-arm64-post-install.sh /app/scripts/docker-arm64-post-install.sh
RUN if [ "$TARGETARCH" = "arm64" ]; then /app/scripts/docker-arm64-post-install.sh; fi
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
# COPY ships only the trimmed result (~1.5 GB) instead of the full ~6.6 GB. Drops the math
# runtime libs (cublas/cusparse/cufft/cusolver/curand/npp/nvjpeg) and big static .a
@@ -217,8 +216,23 @@ RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.
USER appuser
ENV PATH="/usr/local/bin:$PATH"
WORKDIR /app
# Copy the application from the builder
COPY --from=builder --chown=appuser:appuser /app /app
# Copy the application from the builder, splitting the venv's largest trees into their
# own layers. BuildKit compresses and pushes layers in parallel, so shipping the whole
# ~20 GB venv as one layer serialized the export behind a single compressor. Splitting
# also lets nodes pull the image in parallel. Keep the excludes below in sync with the
# per-tree copies that follow, or the data lands in the image twice.
COPY --from=builder --chown=appuser:appuser \
--exclude=.venv/lib/python3.12/site-packages/nvidia \
--exclude=.venv/lib/python3.12/site-packages/torch \
--exclude=.venv/lib/python3.12/site-packages/vllm \
--exclude=.venv/lib/python3.12/site-packages/flash_attn \
--exclude=.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so \
/app /app
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/nvidia /app/.venv/lib/python3.12/site-packages/nvidia
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/torch /app/.venv/lib/python3.12/site-packages/torch
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/vllm /app/.venv/lib/python3.12/site-packages/vllm
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn /app/.venv/lib/python3.12/site-packages/flash_attn
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so /app/.venv/lib/python3.12/site-packages/
COPY --from=builder /opt/ucx /opt/ucx
# Copy and set up entrypoint script
+3 -12
View File
@@ -95,7 +95,7 @@ cd prime-rl
2. Initialize submodules
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
```
3. Install [uv](https://docs.astral.sh/uv/)
@@ -113,15 +113,6 @@ uv sync --all-extras
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
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.
@@ -166,7 +157,7 @@ uv run trainer @ configs/debug/fake/rl.toml
5. Check that you can run the inference server (*this requires 1 GPU*)
```bash
uv run inference --model.name Qwen/Qwen3-0.6B
uv run inference --vllm.model Qwen/Qwen3-0.6B
```
6. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
@@ -227,7 +218,7 @@ Check out the [docs](docs) directory for in-depth guides on how to use prime-rl.
- [**Training**](docs/training.md) - RL, SFT, evals, checkpointing, observability, rules of thumb
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA, multi-tenant training
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA
- [**Development**](docs/development.md) - Test suite, pre-commit hooks, adding a new model
## Contributing
+3 -2
View File
@@ -8,8 +8,9 @@ Configurations for running prime-rl.
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
- **`ci/`** — integration and nightly configs used by CI.
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
(per-algorithm smokes) and `fake/` (fake-data trainer/SFT smokes). Not guaranteed
functional or up to date.
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
(two reverse-text train sources + one eval source, one env server per source). Not
guaranteed functional or up to date.
```bash
uv run rl @ configs/basic/<env>/rl.toml
+15 -3
View File
@@ -32,10 +32,22 @@ group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 768
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[ckpt] # Checkpoint at the end of training
+13 -6
View File
@@ -19,18 +19,25 @@ batch_size = 128
group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[trainer.model]
seq_len = 16384
[inference.model]
[inference.vllm]
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+10 -3
View File
@@ -22,10 +22,17 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
+11 -4
View File
@@ -40,12 +40,19 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[ckpt] # Checkpoint at the end of training
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
+10 -3
View File
@@ -21,10 +21,17 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 128
group_size = 8
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
+18 -3
View File
@@ -22,10 +22,25 @@ group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 384
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, task = { similarity_power = 4, power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 2
max_turns = 2
min_names_per_turn = 1
max_names_per_turn = 3
[orchestrator.train.source.env.taskset.task]
similarity_power = 4
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
@@ -2,7 +2,9 @@ max_steps = 20
seq_len = 2048
[ckpt]
resume_step = 15
[resume]
step = 15
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -26,16 +28,25 @@ name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[inference.vllm]
enable_lora = true
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "prime-qwen3"
@@ -25,16 +25,25 @@ name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[inference.vllm]
enable_lora = true
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "prime-qwen3"
@@ -25,17 +25,22 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
gpu_memory_utilization = 0.7
[inference.model]
[inference.vllm]
max_model_len = 2048
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "default"
@@ -1,13 +0,0 @@
# Inference config for multi-run RL integration test
enable_lora = true
max_lora_rank = 8
max_loras = 4
gpu_memory_utilization = 0.7
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
max_model_len = 2048
[weight_broadcast]
type = "filesystem"
@@ -1,32 +0,0 @@
# Orchestrator config for multi-run RL integration test
# model.lora.name and output_dir are set via CLI
batch_size = 128
group_size = 16
seq_len = 2048
max_steps = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[optim]
lr = 3e-5
[train.sampling]
max_completion_tokens = 128
[[train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[ckpt]
interval = 10
resume_step = -1
[weight_broadcast]
type = "filesystem"
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[renderer]
name = "prime-qwen3"
@@ -1,21 +0,0 @@
# Trainer config for multi-run RL integration test
max_concurrent_runs = 2
enable_token_export = true
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
seq_len = 65536
fused_lm_head_token_chunk_size = 8192
optim_cpu_offload = false
[model.lora]
rank = 8
[model.ac]
freq = 1
[model.compile]
fullgraph = false
[weight_broadcast]
type = "filesystem"
@@ -29,7 +29,7 @@ type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
[orchestrator.renderer]
name = "prime-qwen3"
@@ -37,10 +37,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -49,13 +56,22 @@ num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.4
@@ -30,7 +30,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -43,10 +43,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -55,13 +62,22 @@ num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.4
@@ -1,7 +1,9 @@
max_steps = 10
[ckpt]
resume_step = 5
[resume]
step = 5
[ckpt.weights]
save_adapter_separately = true
@@ -1,7 +1,9 @@
max_steps = 10
[ckpt]
resume_step = 5
[resume]
step = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -8,7 +8,9 @@ seq_len = 2048
type = "filesystem"
[ckpt]
resume_step = 15
[resume]
step = 15
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -23,10 +25,17 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
+10 -3
View File
@@ -22,10 +22,17 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
+17 -5
View File
@@ -18,15 +18,27 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 768
[trainer]
[inference.parallel]
dp = 4
[inference.vllm]
data_parallel_size = 4
+24 -11
View File
@@ -18,32 +18,45 @@ batch_size = 512
group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "aime2024"
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer]
[trainer.model]
seq_len = 16384
attn = "flash_attention_2"
[inference.parallel]
dp = 4
[inference.model]
[inference.vllm]
max_model_len = 8192
data_parallel_size = 4
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+10 -3
View File
@@ -18,10 +18,17 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
batch_size = 128
group_size = 16
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 128
+12 -7
View File
@@ -23,18 +23,23 @@ oversampling_factor = 2.0
type = "zero_advantage"
enforce = true
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
[trainer]
[inference.parallel]
dp = 4
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
data_parallel_size = 4
+12 -6
View File
@@ -18,18 +18,24 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer]
[inference.parallel]
dp = 6
[inference.vllm]
data_parallel_size = 6
[orchestrator.renderer]
name = "prime-qwen3"
@@ -20,10 +20,18 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "color-codeword"
env.taskset = { id = "color-codeword-v1", images_per_turn = 1 }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "color-codeword"
images_per_turn = 1
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[trainer]
+4 -4
View File
@@ -24,15 +24,15 @@ Needed for `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--server.port 8001 \
--gpu-memory-utilization 0.5 \
--model.enforce-eager
--vllm.gpu-memory-utilization 0.5 \
--vllm.enforce-eager
```
## Run the debug configs
Every config writes to the default `outputs/` directory, so running two back-to-back — or re-running one — fails with `FileExistsError`. Pass a distinct `--output-dir outputs/<algo>` per config (recommended for a sweep) or `--clean-output-dir` to wipe and restart.
Every config writes to the default `outputs/` directory, so running two back-to-back — or re-running one — fails with `FileExistsError`. Pass a distinct `--output-dir outputs/<algo>` per config (recommended for a sweep) or `--clean` to wipe and restart.
```bash
# GRPO (no frozen model)
+17 -3
View File
@@ -24,10 +24,22 @@ type = "echo"
[orchestrator.algo.roles.user]
alpha = 0.1
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
@@ -46,4 +58,6 @@ name = "prime-qwen3"
lr = 1e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+22 -6
View File
@@ -21,10 +21,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -33,10 +40,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -44,4 +58,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+22 -6
View File
@@ -21,10 +21,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -33,10 +40,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -44,4 +58,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+37 -14
View File
@@ -3,8 +3,8 @@
# ref_logprobs, GRPO samples don't, and both pack into the same micro batches.
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/mixed_grpo_opd.toml
@@ -31,22 +31,36 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text-grpo"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text-opd"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.env.algo]
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.source.algo]
type = "opd"
[orchestrator.train.env.algo.teacher]
[orchestrator.train.source.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
[orchestrator.eval]
interval = 5
@@ -55,13 +69,22 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+25 -9
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/opd.toml
@@ -24,7 +24,7 @@ type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
@@ -33,10 +33,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -45,10 +52,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -56,4 +70,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+25 -9
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/opd_lora.toml
@@ -24,7 +24,7 @@ type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
@@ -33,10 +33,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -45,10 +52,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 1e-4
@@ -62,4 +76,6 @@ save_adapter_separately = true
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+75
View File
@@ -0,0 +1,75 @@
max_steps = 20
seq_len = 4096
[model]
name = "Qwen/Qwen3-0.6B"
[wandb]
project = "algorithms-debug"
name = "debug-rae"
[orchestrator]
batch_size = 32
group_size = 1
[orchestrator.algo]
type = "rae"
[orchestrator.renderer]
name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.source]]
name = "kuhn-poker"
[orchestrator.train.source.env.taskset]
id = "kuhn-poker"
[orchestrator.train.source.env.player0.harness]
id = "null"
[orchestrator.train.source.env.player0.runtime]
type = "subprocess"
[orchestrator.train.source.env.player1.harness]
id = "null"
[orchestrator.train.source.env.player1.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 512
[[orchestrator.eval.source]]
name = "kuhn-poker"
[orchestrator.eval.source.env.taskset]
id = "kuhn-poker"
[orchestrator.eval.source.env.player0.harness]
id = "null"
[orchestrator.eval.source.env.player0.runtime]
type = "subprocess"
[orchestrator.eval.source.env.player1.harness]
id = "null"
[orchestrator.eval.source.env.player1.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+22 -6
View File
@@ -29,10 +29,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -41,13 +48,22 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+25 -9
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/sft_distill.toml
@@ -25,7 +25,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -38,10 +38,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -50,10 +57,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -61,4 +75,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+25 -9
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/sft_distill_lora.toml
@@ -25,7 +25,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -38,10 +38,17 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -50,10 +57,17 @@ num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 1e-4
@@ -67,4 +81,6 @@ save_adapter_separately = true
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+69
View File
@@ -0,0 +1,69 @@
# Minimal multi-env debug run: two reverse-text train sources + one eval source.
# The launcher spawns one env server per source at its derived address
# (tcp://127.0.0.1:5000-5002); the orchestrator connects to each.
max_steps = 10
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.renderer]
name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text-a"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text-b"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 5
num_examples = 64
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
Vendored Submodule
+1
Submodule deps/prime-envs added at b30aad3637
+1 -1
+1 -1
+1 -8
View File
@@ -1,6 +1,6 @@
# Advanced
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, multi-tenant training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
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, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
## Table of Contents
@@ -11,7 +11,6 @@ This page covers the specialized features layered on top of the core training st
- [Enabling VLM Mode](#enabling-vlm-mode)
- [Limitations](#limitations)
- [LoRA Training](#lora-training)
- [Multi-Tenant Training](#multi-tenant-training)
- [Disaggregated Prefill/Decode Inference](#disaggregated-prefilldecode-inference)
## Custom Modeling
@@ -123,12 +122,6 @@ LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** su
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:
+135 -15
View File
@@ -17,6 +17,8 @@ This page covers the math and the configurable algorithmic components: the algor
- [Custom Loss](#custom-loss)
- [Advantage](#advantage)
- [Default Advantage](#default-advantage)
- [Hierarchical GRPO](#hierarchical-grpo)
- [Self-Play Advantage (RAE)](#self-play-advantage-rae)
- [Authoring an Algorithm](#authoring-an-algorithm)
- [Reference Scoring](#reference-scoring)
- [Filters](#filters)
@@ -33,7 +35,7 @@ A training algorithm in `prime-rl` is configured under `[orchestrator.algo]`, wh
1. **Sampling** (`algo.sampling`) — how train rollouts are produced: which model generates them. `source` is a [model reference](#model-references): `"policy"` (the live policy, the default) or an inline frozen hosted model. Group sizing stays on the env config (`group_size`).
2. **The per-token training signal** — credit assignment and loss routing, fused; the algorithm's own parameters sit directly on `algo`. One mapping from a finalized rollout to per-token *(loss component, weight)* pairs — the credit a token gets and the loss that consumes it are two coordinates of the same output. Group-relative algorithms compute credit on the orchestrator and ship per-token advantage streams; reference-KL algorithms query a reference model at batch-ship time (bounded concurrency) and ship its prefill logprobs for the trainer to evaluate against the live policy. The `type` determines which loss component consumes the action tokens (`rl` / `ce` / `ref_kl`) and what happens to env-provided observation tokens in multi-turn rollouts (masked out by default; `echo` trains on them with weighted CE).
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, packer, or trainer hot path.
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, batch packing, or trainer hot path.
### Model References
@@ -45,7 +47,7 @@ type = "opd"
[orchestrator.algo.teacher] # opd's teacher: the frozen model it scores against
name = "Qwen/Qwen3-32B"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
```
Model *roles* are algorithm-local vocabulary — each algorithm names its reference on the field where the model is actually used, and there is no shared `teacher` slot. `opd` declares a `teacher` field (the frozen model whose reverse KL the policy distills toward); `sft`'s teacher *is* its `sampling.source` (the frozen model it imitates); `opsd` self-distills against the live policy and names no model at all. No role exists outside the algorithm that declares it: the dispatcher, sink, and trainer branch on liveness alone, never on what an algorithm calls a model.
@@ -67,6 +69,8 @@ type = "grpo" # the default
|---|---|---|---|
| `grpo` | policy | `rl` on actions | Standard group-relative RL. |
| `max_rl` | policy | `rl` on actions | MaxRL ([arXiv:2602.02710](https://arxiv.org/abs/2602.02710)): GRPO's centered reward normalized by the group **mean** instead of the standard deviation — the gradient is unbiased for the order-`group_size` truncation of the maximum-likelihood objective, upweighting hard examples like `1/p`. |
| `rae` | policy | `rl` on actions | RAE (SPIRAL, [arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): reward minus a per-agent EMA baseline of that agent's own rewards — the estimator for multi-agent self-play envs, where the group mean would mix the agents' opposite reward scales. See [Self-Play Advantage](#self-play-advantage-rae). |
| `hierarchical_grpo` | policy | `rl` on actions | GRPO for proposer-solver envs. Solvers are compared only with attempts on the same proposed problem; proposers are compared with the other proposals in the group. See [Hierarchical GRPO](#hierarchical-grpo). |
| `opd` | policy | `ref_kl` on actions | On-policy distillation ([Thinking Machines](https://thinkingmachines.ai/blog/on-policy-distillation/)): the policy samples, per-token reverse KL against a reference model as the gradient signal. Needs a `teacher`. |
| `sft` | *(the teacher)* | `ce` on actions | Hard distillation: a frozen model generates rollouts, the policy trains with CE on its tokens. Needs a frozen `sampling.source` (the teacher it samples from). |
| `opsd` | policy | `ref_kl` on actions | SDFT ([arXiv:2601.19897](https://arxiv.org/abs/2601.19897)): the model is its own reference, conditioned on an expert demonstration. The teacher *is* the live policy (the paper's setting, no extra deployment) — no model to configure. |
@@ -96,7 +100,9 @@ Echo also takes an optional user-supplied token filter that narrows the role sel
```toml
[orchestrator.algo.filter]
import_path = "my_module.drop_warnings"
kwargs = { patterns = ["WARNING"] }
[orchestrator.algo.filter.kwargs]
patterns = ["WARNING"]
```
```python
@@ -116,17 +122,33 @@ Both components resolve per environment. Each env inherits `[orchestrator.algo]`
[orchestrator.algo]
type = "grpo"
[[orchestrator.train.env]]
name = "math"
taskset = { id = "math-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
# inherits the top-level grpo
[[orchestrator.train.source]]
name = "math" # inherits the top-level grpo
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "math"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "terminal"
taskset = { id = "terminal-v1" }
harness = { id = "bash", runtime = { type = "subprocess" } }
algo = { type = "echo" } # this env runs its own algorithm
[orchestrator.train.source.env.taskset]
id = "terminal"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
# this env runs its own algorithm
[orchestrator.train.source.algo]
type = "echo"
```
### The Algorithm Classes
@@ -138,6 +160,8 @@ At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_r
| `grpo` | `GRPOAlgorithm` | `score_group`: group-norm credit (optional length penalty) |
| `echo` | `EchoAlgorithm` | `score_rollout`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
| `max_rl` | `MaxRLAlgorithm` | `score_group`: mean-normalized group credit |
| `rae` | `RAEAlgorithm` | `score_group`: per-agent EMA-baseline credit |
| `hierarchical_grpo` | `HierarchicalGRPOAlgorithm` | `score_group`: GRPO baseline per episode for solvers, per group for the proposer |
| `opd` | `OPDAlgorithm` | `score_rollout`: own-context prefill under the teacher |
| `opsd` | `OPSDAlgorithm` | `score_rollout`: demo-conditioned prefill under the live policy |
| `sft` | `SFTDistillAlgorithm` | `score_group`: group-norm credit (feeds filters) |
@@ -174,7 +198,7 @@ $$
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
$$
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the group-relative algorithms (`grpo`, `max_rl`, and `echo`'s action tokens).
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
@@ -245,7 +269,9 @@ Wire it up:
[trainer.loss]
type = "custom"
import_path = "my_module.ppo_clip_loss"
kwargs = { clip_eps = 0.2 }
[trainer.loss.kwargs]
clip_eps = 0.2
```
The dataclasses:
@@ -276,6 +302,8 @@ The per-token training signal is set by `algo.type` and the [algorithm](#the-alg
|---|---|---|
| `grpo` | `rl` | Group-norm: reward minus per-group baseline, optional length penalty. |
| `max_rl` | `rl` | Mean-normalized group credit (maximum-likelihood RL). |
| `rae` | `rl` | Reward minus a per-agent EMA baseline (SPIRAL's role-conditioned advantage estimation) — for multi-agent self-play envs. |
| `hierarchical_grpo` | `rl` | GRPO for proposer-solver envs: solvers are compared within one proposed problem, while proposers are compared across proposals. |
| `echo` | `rl` + `ce` | Group-norm on action tokens, plus weighted CE on env-provided tokens selected by message role (each role's `alpha` is its ECHO λ), optionally narrowed by a user filter. |
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream; `group_size` only fans out sampling. |
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream. |
@@ -297,6 +325,98 @@ type = "grpo"
type = "linear"
```
### Hierarchical GRPO
GRPO gives each rollout its reward minus the average reward of comparable rollouts. In an ordinary single-agent group, every rollout answers the same task, so one group average is enough.
A proposer-solver env is different. Starting from one source task, it produces several proposed problems, then runs several solver attempts on each problem:
```text
one source task
├── proposed problem A
│ ├── proposer trace
│ ├── solver attempt 1
│ └── solver attempt 2
└── proposed problem B
├── proposer trace
├── solver attempt 1
└── solver attempt 2
```
The solver attempts for A should not be compared with the solver attempts for B: the two problems may have very different difficulty. Proposer and solver rewards should not be compared either: they measure different jobs.
`hierarchical_grpo` therefore chooses the average separately for each role:
| Trace | Compared with | Why |
|---|---|---|
| Solver | Other solver attempts on the same proposed problem | They attempted the same problem. |
| Proposer | Other proposer traces in the group | They started from the same source task and proposed alternatives. |
For example, if three solvers receive rewards `[1, 1, 0]` on one proposed problem, their average is `2/3` and their advantages are `[1/3, 1/3, -2/3]`. Solver rewards from other proposed problems do not affect those values. The proposers are scored separately according to how useful their problems were for the solvers, then compared with the other proposers in the group.
Configure which roles are compared within a single proposed problem with `episode_agents`. For `proposer-solver`, that role is `solver`:
```toml
[orchestrator.algo]
type = "hierarchical_grpo"
episode_agents = ["solver"]
[[orchestrator.train.source]]
name = "proposer-solver"
group_size = 4 # proposed problems per source task
env.n = 4 # solver attempts per proposed problem
[orchestrator.train.source.env.taskset]
id = "proposer-solver"
[orchestrator.train.source.env.proposer.harness]
id = "null"
[orchestrator.train.source.env.proposer.runtime]
type = "subprocess"
[orchestrator.train.source.env.solver.harness]
id = "null"
[orchestrator.train.source.env.solver.runtime]
type = "subprocess"
```
`group_size` controls how many problems are proposed from each source task. `env.n` controls how many solvers attempt each proposed problem. If a comparison contains only one trace—for example, a solver when `env.n = 1`—its advantage is zero and the zero-advantage filter removes it.
This algorithm is accepted only for proposer-solver envs. Use the env's `train_proposer` and `train_solver` settings if you want to train only one role.
### Self-Play Advantage (RAE)
Group-relative baselines assume the group is exchangeable attempts by one agent. A multi-agent self-play env breaks that: one episode yields one trace per agent, all trainable, and in a zero-sum game the rewards sum to ~0 whatever the policy does — the group mean carries no information, and centering against it converts any structural asymmetry (a first-mover edge) into permanent credit for one agent.
`rae` implements SPIRAL's role-conditioned advantage estimation ([arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): each agent keeps an exponential-moving-average baseline of its own rewards, and every trace's advantage is its reward minus its agent's baseline — measured against the *pre-update* baseline (the unbiased order), then folded in at `decay` (SPIRAL's α, default 0.95). The algorithm instance is per-env, so baselines are keyed per (env, agent) — the paper's per (game, role). Advantages are not normalized, and `group_size` is free (RAE needs no sibling rollouts; `group_size = 1` is fine). Baselines live in orchestrator memory and re-warm from 0 over ~`1/(1 − decay)` traces per agent after a restart.
```toml
[orchestrator.algo]
type = "rae"
decay = 0.95
[[orchestrator.train.source]]
name = "kuhn-poker"
[orchestrator.train.source.env.taskset]
id = "kuhn-poker"
[orchestrator.train.source.env.player0.harness]
id = "null"
[orchestrator.train.source.env.player0.runtime]
type = "subprocess"
[orchestrator.train.source.env.player1.harness]
id = "null"
[orchestrator.train.source.env.player1.runtime]
type = "subprocess"
```
Both of `kuhn-poker`'s agents late-bind to the run's own model — shared-policy self-play against a continuously improving opponent. Pin one agent to a frozen endpoint (`env.player1.model = ...`) for asymmetric play; its traces are marked untrainable by the env and never reach the advantage computation. A single-agent env under `rae` degrades to REINFORCE with an EMA baseline.
### Authoring an Algorithm
@@ -361,7 +481,7 @@ Filtered rollouts still appear in W&B distributions, just not in the trainer bat
## 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.
For multi-turn rollouts (tool use, browser environments, long conversations), `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
+55 -28
View File
@@ -17,7 +17,7 @@ Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeInt
- [Optional Sub-Configs](#optional-sub-configs)
- [None](#none)
- [Discriminated Unions](#discriminated-unions)
- [Environments](#environments-orchestratortrainenv)
- [Environments](#environments)
- [Environment Variables](#environment-variables)
- [Examples](#examples)
@@ -50,18 +50,18 @@ CLI flags mirror the TOML tree using dots:
--max-steps 50 # top-level
--model.name Qwen/Qwen3-4B # nested
--trainer.optim.lr 1e-5 # double-nested
--inference.parallel.tp 4
--inference.vllm.tensor-parallel-size 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.
> A renamed field keeps no alias for its old name: the old spelling fails as an unknown key rather than being silently translated.
## Inspecting and Validating
```bash
uv run rl --help # full schema
uv run rl @ rl.toml --dry-run --output-dir /tmp/check # write resolved configs
uv run rl @ rl.toml --dry-run --output-dir /tmp --run.name check # write resolved configs (JSON) to /tmp/check/configs
```
## Syntax
@@ -71,12 +71,12 @@ uv run rl @ rl.toml --dry-run --output-dir /tmp/check # write resolved configs
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
uv run rl @ rl.toml --clean # True
uv run rl @ rl.toml --no-clean # False
```
```toml
clean_output_dir = true
clean = true
```
### Lists
@@ -93,20 +93,23 @@ uv run rl @ rl.toml --trainer.model.lora.target-modules '["q_proj", "k_proj", "v
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).
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables, see [Environments](#environments).
### 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:
CLI takes a JSON literal. TOML uses a 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 \
uv run rl @ rl.toml --orchestrator.train.source.0.args \
'{"dataset_name": "openai/gsm8k", "dataset_subset": "main"}'
```
```toml
[[orchestrator.train.env]]
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
[[orchestrator.train.source]]
[orchestrator.train.source.args]
dataset_name = "openai/gsm8k"
dataset_subset = "main"
```
### Optional Sub-Configs
@@ -123,11 +126,11 @@ To **disable** a sub-config that's on by default, use `--no-<name>` on the CLI o
TOML has no `null`. Use the string `"None"`, which the loader coerces:
```toml
[inference.model]
[inference.vllm]
max_model_len = "None"
```
On the CLI: `--inference.model.max-model-len None`.
On the CLI: `--inference.vllm.max-model-len None`.
### Discriminated Unions
@@ -142,27 +145,50 @@ mu = 0.95
Omit `type` to keep the default variant.
### Environments (`[[orchestrator.train.env]]`)
### Environments
Training environments are an array of tables — set one per env, optionally with sampling weights:
Training and evaluation sources are arrays of tables. Set one source per environment; training sources can optionally carry sampling weights:
```toml
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "gsm8k"
env.taskset = { id = "gsm8k-v1", split = "train" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
ratio = 3 # 75% of batches
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "gsm8k"
split = "train"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
ratio = 1 # default — 25% of batches
[[orchestrator.eval.env]]
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.eval.source]]
name = "gsm8k-eval"
env.taskset = { id = "gsm8k-v1", split = "test" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval.source.env.taskset]
id = "gsm8k"
split = "test"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
```
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
@@ -234,14 +260,15 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
--wandb.name my-experiment \
--trainer.optim.lr 5e-6 \
--output-dir /tmp/reverse-dry \
--run.name check \
--dry-run
```
Then inspect the resolved config:
```bash
ls /tmp/reverse-dry/configs/
# rl.toml trainer.toml orchestrator.toml inference.toml
ls /tmp/reverse-dry/check/configs/
# rl.json trainer.json orchestrator.json inference.json
```
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.
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/check/configs/trainer.json`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
+3 -3
View File
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
| 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`) |
| [`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_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.
@@ -118,8 +118,8 @@ Then run the full RL stack on reverse-text:
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
--inference.vllm.gpu-memory-utilization 0.7 \
--inference.vllm.max-model-len 2048
```
What to look for:
+51 -40
View File
@@ -30,7 +30,9 @@ We support 3 distinct deployment shapes:
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `backend_port`, and a `[...deployment.router]` block, etc.
Every deployment shape has the same client-facing layout: a single global router listens on `inference.server.port` and fronts all vLLM engines, which listen on `inference.backend_port` (+ rank offset). Clients always talk to one URL, regardless of how many engines run behind it.
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 and topology knobs such as `num_nodes` and `num_replicas`.
```toml
[inference.deployment]
@@ -40,7 +42,7 @@ 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]
[inference.vllm]
model = "PrimeIntellect/INTELLECT-3"
...
```
@@ -56,15 +58,15 @@ The single-node deployment is the default deployment shape. It runs the inferenc
type = "single_node"
```
The launcher starts a `vllm-router` on `inference.server.port` (default `8000`) fronting the vLLM engine on `inference.backend_port` (default `8100`). Clients connect to the router URL; admin operations (weight updates, health checks) bypass the router and hit the engine port directly — the RL entrypoint wires `orchestrator.model.client.admin_base_url` accordingly.
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]
[inference.vllm]
enable_expert_parallel = true # defaults to False
[inference.parallel]
tp = 2
dp = 4
tensor_parallel_size = 2
data_parallel_size = 4
[inference.deployment]
type = "single_node"
@@ -72,7 +74,7 @@ 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.
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.vllm.enable_expert_parallel` or `inference.vllm.tensor_parallel_size` 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.
@@ -82,7 +84,7 @@ You can also increase the available KV cache memory by enabling `inference.kv_ca
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.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.vllm.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
@@ -94,35 +96,31 @@ Parallelism configuration is the same as the single-node deployment. The shape i
type = "multi_node"
num_nodes = 2
[inference]
[inference.vllm]
model = "PrimeIntellect/INTELLECT-3"
[inference.parallel]
tp = 2
dp = 4
tensor_parallel_size = 2
data_parallel_size = 4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a router instance running on the same node as the 1st replica — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[...deployment.router]` block. You can read more about the supported routing options in the [router](#router) section.
This configuration will run 2 independent vLLM replicas, each with `tensor_parallel_size=2` and `data_parallel_size=4`. Routing is handled by a single global router running on the first inference node, fronting the per-rank endpoints of all replicas — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[inference.router]` block. 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`.
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.vllm.enable_expert_parallel = true`.
```toml
[inference.deployment]
type = "multi_node"
num_nodes = 2
[inference]
[inference.vllm]
model = "PrimeIntellect/INTELLECT-3"
enable_expert_parallel = true
[inference.parallel]
tp = 2
dp = 8
tensor_parallel_size = 2
data_parallel_size = 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`.
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tensor_parallel_size = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
## P/D Disaggregation
@@ -160,25 +158,31 @@ num_train_nodes = 4
num_infer_replicas = 3
```
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes and start 3 separate router instances.
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes, fronted by the single global router.
## Router
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
Every deployment fronts its vLLM engines with a single global router — it listens on `inference.server.port` and is the one URL clients connect to. The backend is configured via a discriminated `[inference.router]` block (`type = "vllm-router" | "llm-d"`):
```toml
[inference.deployment.router] # or [deployment.router] for the standalone inference entrypoint
[inference.router] # or [router] for the standalone inference entrypoint
type = "llm-d" # "vllm-router" (default) or "llm-d"
# llm-d-only knobs (all optional):
scorers = { "prefix-cache-scorer" = 3.0, "active-request-scorer" = 2.0 } # base, applied to every profile
prefill_scorer_overrides = { "queue-scorer" = 2.0, "kv-cache-utilization-scorer" = 2.0 } # merged onto the P/D prefill profile
decode_scorer_overrides = {} # merged onto the P/D decode profile
non_cached_tokens = 16 # below this many non-cached prompt tokens, skip remote prefill (P/D)
non_cached_tokens = 16 # llm-d only: below this many non-cached prompt tokens, skip remote prefill (P/D)
# llm-d only: base scorer weights, applied to every profile
[inference.router.scorers]
"prefix-cache-scorer" = 3.0
"active-request-scorer" = 2.0
# llm-d only: merged onto the P/D prefill profile (decode_scorer_overrides for decode)
[inference.router.prefill_scorer_overrides]
"queue-scorer" = 2.0
"kv-cache-utilization-scorer" = 2.0
```
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy. Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`. The only backend supported for single-node (local) deployments.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy (multi-node / disaggregated SLURM deployments only). Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
Both backends support the 2 most important things:
- Request routing - KV cache re-use and balanced routing
@@ -251,34 +255,41 @@ For configuring various knobs with environment variables, we enable you to confi
[inference.deployment]
type = "disaggregated"
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip"}
[inference.deployment.prefill_env_vars]
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
[inference.deployment.decode_env_vars]
"VLLM_DEEP_GEMM_WARMUP" = "skip"
```
These are role-specific and layer on top of [`env_vars`](configuration.md#environment-variables) shared by all inference processes regardless of role.
### Other vLLM features
We support various other vLLM features. Some of those, such as `enable_dbo`, `enable_eplb` are exposed as a top-level config fields. For those that are not, you can configure them by setting `inference.vllm_extra` to the desired value.
The `[inference.vllm]` section is a pass-through: every key is forwarded to the vLLM server under vLLM's own argument name, whether prime-rl types it or not. Anything `vllm serve` accepts can be set here.
```toml
[inference.vllm_extra]
[inference.vllm]
headless = true
max_num_seqs = 256
```
On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (or `--vllm.max-num-seqs 256` for the standalone inference entrypoint); dict-valued arguments take a JSON string, e.g. `--vllm.compilation-config '{"cudagraph_mode": "NONE"}'`.
### 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`.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`.
```toml
[trainer]
enable_router_replay = true # this will also auto-set the inference.enable_return_routed_experts = true
enable_router_replay = true # this will also auto-set inference.vllm.enable_return_routed_experts = true
[inference]
[inference.vllm]
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.
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) 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.
+5 -5
View File
@@ -10,9 +10,9 @@ A `prime-rl` RL run is three cooperating processes:
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/inference/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). We are trying to stay up-to-date with the latest vLLM features, you can read more about the supported features and deployment options in the dedicated [inference documentation](inference.md).
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, and LoRA. You can read more in the dedicated [training documentation](training.md).
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses ZMQ, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap the rollout link to the local filesystem (`rollout_transport.type = "filesystem"`) if you want rollouts persisted to disk. See [Scaling](scaling.md) for the deployment options.
## Installation
@@ -20,7 +20,7 @@ The three processes communicate through configurable transports — by default t
curl -sSL https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/main/scripts/install.sh | bash
```
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`research-environments`](https://github.com/PrimeIntellect-ai/research-environments) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`prime-envs`](https://github.com/PrimeIntellect-ai/prime-envs) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
You need at least one NVIDIA GPU (RTX 3090/4090/5090, A100, H100, H200, or B200). Single-GPU runs are supported for debugging; production RL is typically 1× inference node + 1+ trainer nodes.
@@ -32,7 +32,7 @@ Train an SFT-warmed `Qwen3-0.6B` on the `reverse-text` task — the env is bundl
uv run rl @ examples/basic/reverse-text/rl.toml
```
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into `outputs/logs/{trainer,orchestrator,inference}.log`. Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes and final HF-compatible weights land at `outputs/weights/step_20`.
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into the run directory at `outputs/<run_name>/logs/{trainer,orchestrator,inference}.log` (`run.name` auto-generates as `<envs>--<model>--<short-id>`; pass `--run.name <name>` for a predictable path). Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes and final HF-compatible weights land at `outputs/<run_name>/weights/step_20`.
## Documentation
@@ -41,5 +41,5 @@ The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into
- **[Inference](inference.md)** — vLLM-backed server (or fleet) holding the current policy.
- **[Scaling](scaling.md)** — Single-GPU through multi-node clusters via FSDP / EP / CP and SLURM.
- **[Algorithms](algorithms.md)** — Async semantics, loss / advantage / filter plugins, trajectory merging.
- **[Advanced](advanced.md)** — Custom modeling, multimodal, LoRA, multi-tenant, P/D inference.
- **[Advanced](advanced.md)** — Custom modeling, multimodal, LoRA, P/D inference.
- **[Development](development.md)** — Test suite, pre-commit hooks, adding a new model.
+6 -6
View File
@@ -38,7 +38,7 @@ The `rl`, `sft`, and `inference` entrypoints all accept a `[deployment]` block (
uv run rl @ rl.toml \
--deployment.num-infer-gpus 6 \
--deployment.num-train-gpus 2 \
--inference.parallel.dp 6
--inference.vllm.data-parallel-size 6
```
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
@@ -48,14 +48,14 @@ For quick A/B ablations on the same node, run two RL instances side-by-side in s
```bash
# session 1, GPUs 0–1, default port 8000
bash scripts/tmux.sh -s exp1 -o outputs/exp1
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --output-dir outputs/exp1
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --run.name exp1
# session 2, GPUs 2–3, port 8001
bash scripts/tmux.sh -s exp2 -o outputs/exp2
CUDA_VISIBLE_DEVICES=2,3 uv run rl @ rl.toml \
--inference.server.port 8001 \
--orchestrator.model.client.base-url http://localhost:8001/v1 \
--output-dir outputs/exp2
--run.name exp2
```
#### SFT and Torchrun
@@ -69,7 +69,7 @@ uv run torchrun \
src/prime_rl/trainer/sft/train.py @ sft.toml
```
`--local-ranks-filter 0` keeps console output to rank 0 only; per-rank stdout/stderr is still captured in `<output_dir>/logs/trainer/torchrun/`.
`--local-ranks-filter 0` keeps console output to rank 0 only; per-rank stdout/stderr is still captured in `<run_dir>/logs/trainer/torchrun/`.
### Multi-Node
@@ -144,7 +144,7 @@ Offloading optimizer states to CPU is enabled by default (`optim_cpu_offload = t
optim_cpu_offload = true # already the default
```
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training) — set `optim_cpu_offload = false` for multi-run. Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
Mutually exclusive with `fsdp_cpu_offload`. Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
### LM Head Chunking
@@ -231,7 +231,7 @@ Full multi-node configs ship under [`examples/advanced/`](https://github.com/Pri
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), and the launcher prints one URL per node. Front the URLs with a router or point clients at any of them.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
### Custom Templates
+41 -32
View File
@@ -36,7 +36,8 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer + inference. |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at a derived loopback address); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
## RL Trainer
@@ -59,9 +60,9 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | How many distinct policies may have contributed to one rollout before it's discarded (default 8). The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `errored_rollouts` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.env]]` | Training environments. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Environments](configuration.md#environments-orchestratortrainenv). |
| `[[orchestrator.eval.env]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
**Monitoring:**
@@ -76,10 +77,11 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| Knob | What it does |
|---|---|
| `--clean-output-dir` | Wipe `<output_dir>` before starting. Useful when re-running an experiment with the same name during iteration. |
| `--output-dir outputs/<name>` | Per-run output directory. Always set this when running more than one experiment in parallel. |
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). |
| `--run.name <name>` | Run name, also the run directory name under `<output_dir>` (override the directory separately via `--run.dir`). Auto-generated as `<envs>--<model>--<short-id>` when unset, so every launch gets a fresh, readable run directory. Set an explicit name for a predictable path — required to resume the run later. |
| `--clean` | Wipe the run directory before starting. Useful when re-running a named run during iteration. |
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
| `--dry-run` | Resolve + validate the full config, write per-process TOMLs to `<output_dir>/configs/`, and exit without launching. The fastest way to debug a misbehaving config. |
| `--dry-run` | Resolve + validate the full config, write per-process TOMLs to `<run_dir>/configs/`, and exit without launching. The fastest way to debug a misbehaving config. |
### Algorithms
@@ -89,6 +91,8 @@ The RL entrypoint supports several training algorithms, switched via `[orchestra
|---|---|---|
| `grpo` (default) | None | Standard group-relative RL |
| `max_rl` | None | [MaxRL](https://arxiv.org/abs/2602.02710): GRPO with mean-normalized advantages (maximum-likelihood RL) |
| `rae` | None | [SPIRAL](https://arxiv.org/abs/2506.24119)'s role-conditioned advantage estimation: reward minus a per-agent EMA baseline, for multi-agent self-play envs (e.g. `kuhn-poker`) |
| `hierarchical_grpo` | None | GRPO for proposer-solver envs: compare solvers only with attempts on the same proposed problem, and compare proposers with the other proposals in the group |
| `opd` | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): the policy generates rollouts, the trainer minimizes per-token reverse KL to a reference model |
| `sft` | Required, any OpenAI-compatible endpoint | Hard-distill: a frozen model generates rollouts, the policy trains on its tokens |
| `opsd` | None — the live policy is its own reference (no deployment) | [SDFT](https://arxiv.org/abs/2601.19897): the model is its own reference conditioned on expert demonstrations |
@@ -100,7 +104,7 @@ Frozen models are declared inline on the algorithm, named where the model is use
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name <frozen-model> --server.port 8001
--vllm.model <frozen-model> --server.port 8001
```
The standalone `uv run sft` entrypoint is the more traditional SFT path — pure dataset-based, no orchestrator. Use the `sft` algorithm only when you want a frozen model to generate the supervision on the fly.
@@ -196,7 +200,7 @@ Pulled from the console log and mirrored to W&B.
**Stability and optimization:**
- `optim/grad_norm` — spikes precede divergence.
- `optim/lr`, `optim/zero_grad_ratio` — LR schedule and the fraction of params that received zero gradients (high → dead path or wrong loss masking).
- `optim/lr` — LR schedule.
- For MoE: `max_vio/mean` (load-balancing violation), `routing_confidence/mean` — both are logged when non-zero.
**Performance:**
@@ -214,10 +218,10 @@ Checkpointing is split across processes because the orchestrator and trainer can
| Process | What's saved | Where |
|---|---|---|
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<output_dir>/checkpoints/step_N/trainer/` |
| Orchestrator | Step counter, total tokens / samples / problems | `<output_dir>/checkpoints/step_N/orchestrator/` |
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_N/trainer/` |
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_N/orchestrator/` |
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
| Trainer (HF weights) | HF-compatible weight snapshot for serving | `<output_dir>/weights/step_N/` |
| Trainer (HF weights) | HF-compatible weight snapshot for serving | `<run_dir>/weights/step_N/` |
### Enabling Checkpoints
@@ -232,22 +236,29 @@ uv run rl @ rl.toml --ckpt.interval 25 --ckpt.keep-interval 100 # …plus perma
### Resuming a Run
Re-run the same launch command and pass `--ckpt.resume-step <N>` (or `-1` for "latest"). Make sure `--max-steps` is at least the target final step, not the remaining delta:
Re-run the same launch command and pass `--resume` (latest checkpoint) or `--resume.step <N>`. Resuming reuses the run directory, so the run needs a name you can point back at — launch with `--run.name` (or pass the first run's auto-generated name). Make sure `--max-steps` is at least the target final step, not the remaining delta:
```bash
# First run: steps 1–10
uv run rl @ rl.toml --max-steps 10 --ckpt
uv run rl @ rl.toml --max-steps 10 --ckpt --run.name my-run
# Resume: continue to step 20
uv run rl @ rl.toml --max-steps 20 --ckpt.resume-step 10
# Resume from the latest checkpoint: continue to step 20
uv run rl @ rl.toml --max-steps 20 --ckpt --resume --run.name my-run
# ...or from a specific step
uv run rl @ rl.toml --max-steps 20 --ckpt --resume.step 10 --run.name my-run
# ...or fork another run's checkpoint into a fresh run
uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
--resume.dir outputs/my-run/checkpoints/step_10
```
### Serving Checkpoints
HF-compatible weight snapshots are written under `<output_dir>/weights/step_N/` whenever a full checkpoint runs (or you can write weights-only via `--ckpt.weights-only` for cheaper snapshots). Upload directly:
HF-compatible weight snapshots are written under `<run_dir>/weights/step_N/` whenever a full checkpoint runs (or you can write weights-only via `--ckpt.weights-only` for cheaper snapshots). Upload directly:
```bash
uv run hf upload <user>/<model>-RL outputs/weights/step_100
uv run hf upload <user>/<model>-RL outputs/<run_name>/weights/step_100
```
For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write the raw adapter alongside the merged weights — useful when serving the adapter through a separate `/load_lora_adapter` call.
@@ -256,10 +267,10 @@ For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write t
### Log Files
The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The full layout (single-node runs skip the `node_*.log` and `router_*.log` files):
The launcher tees every process's stdout/stderr into `<run_dir>/logs/`. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
```
<output_dir>/logs/
<run_dir>/logs/
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
├── orchestrator.log # single instance, single file
├── inference.log # symlink → inference/node_0.log on multi-node
@@ -268,20 +279,18 @@ The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The f
│ └── torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log # per-rank
├── inference/
│ ├── node_*.log # per-node inference stdout (multi-node only)
│ └── router_*.log # vllm-router per replica (multi-node only)
└── envs/{train,eval}/<env_name>/
├── env_server.log
└── env_worker_<id>.log
│ └── router.log # the single global router (multi-node only)
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
```
Env worker logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
```bash
tail -F <output_dir>/logs/{trainer,orchestrator,inference}.log
tail -F <output_dir>/logs/trainer/node_*.log # multi-node only
tail -F <output_dir>/logs/inference/router_*.log # multi-node only
tail -F <run_dir>/logs/{trainer,orchestrator,inference}.log
tail -F <run_dir>/logs/trainer/node_*.log # multi-node only
tail -F <run_dir>/logs/inference/router.log # multi-node only
```
### Console Output
@@ -289,12 +298,12 @@ tail -F <output_dir>/logs/inference/router_*.log # multi-node only
`scripts/tmux.sh` opens a 4-pane tmux session that follows `trainer.log`, `orchestrator.log`, `inference.log`, and the union of env worker logs. Start it before launching:
```bash
bash scripts/tmux.sh
bash scripts/tmux.sh -o outputs/my-run
# then in the Launcher window:
uv run rl @ ... --output-dir outputs/my-run
uv run rl @ ... --run.name my-run
```
Pass `-s <session>` and `-o <output_dir>` to run multiple parallel experiments side-by-side in different sessions. The helper also works on a SLURM head node — `bash scripts/tmux.sh my-rl-job /shared/outputs/my-rl-job`.
Pass `-s <session>` and `-o <run_dir>` (the run directory, `<output_dir>/<run_name>`) to run multiple parallel experiments side-by-side in different sessions. The helper also works on a SLURM head node — `bash scripts/tmux.sh my-rl-job /shared/outputs/my-rl-job`.
### Weights & Biases
@@ -340,5 +349,5 @@ Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted t
- **Start small.** Run `examples/basic/reverse-text/rl.toml` end-to-end on 2 GPUs before scaling. If the smoke run finishes cleanly, your install is good.
- **Batch size ≥ 64.** Smaller batches give noisy gradient estimates and the trainer's overhead-per-step dominates throughput. 64 is the practical floor; 128–512 is the range for quick ablations; production RL often runs at 1024+.
- **Group size ≥ 8.** Bigger groups (`orchestrator.group_size`) make it more likely that a task produces a mix of high- and low-reward rollouts, which is what gives the trainer a usable signal — if all rollouts in a group succeed or all fail, the within-group advantage collapses to zero and the trainer learns nothing from that task. Bigger groups also tighten advantage normalization. 8 is the floor; 16–32 is common.
- **Pin `output_dir` per run.** Sharing a directory across runs will mix rollouts and break resumes. `--output-dir outputs/<unique-name>` is the simplest discipline.
- **Runs never share a directory.** Every launch writes to its own run directory `<output_dir>/<run_name>`, auto-named `<envs>--<model>--<short-id>` by default. Name runs you want to find again or resume with `--run.name <name>`; re-using a name blocks unless you resume or pass `--clean`.
- **Use `--dry-run` before SLURM.** Validators (e.g. CP needs flash-attention) fail fast in dry-run and slow in queue.
+56 -29
View File
@@ -32,7 +32,8 @@ timeout = 3600
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[resume]
[model]
name = "zai-org/GLM-4.5-Air"
@@ -71,7 +72,7 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
max_inflight_episodes = 512
[orchestrator.renderer]
name = "glm-4.5"
@@ -93,14 +94,22 @@ num_turns_weight = 0.0
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
# entry wholesale (keep `name`/`question_field`/`choices` in sync with the taskset defaults —
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "openseeker"
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
[orchestrator.train.env.env.taskset]
id = "openseeker-v1"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = [65536, 131072]
[[orchestrator.train.env.env.taskset.task.judges]]
[orchestrator.train.source.env.agent.runtime]
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "openseeker"
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
@@ -108,21 +117,29 @@ question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.env.env.taskset.task.judges]]
# [[orchestrator.train.source.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "redsearcher"
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
[orchestrator.train.env.env.taskset]
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = [65536, 131072]
[[orchestrator.train.env.env.taskset.task.judges]]
[orchestrator.train.source.env.agent.runtime]
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
@@ -130,10 +147,10 @@ question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.env.env.taskset.task.judges]]
# [[orchestrator.train.source.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
@@ -142,36 +159,46 @@ choices = ["A", "B"]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "browsecomp"
num_examples = 500 # full set is 1266; cap eval at 500
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.env.env.taskset]
id = "browsecomp-v1"
task = { judge = { model = "Qwen/Qwen3-235B-A22B-Instruct-2507" } }
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm45air-search"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "browsecomp"
[orchestrator.eval.source.env.taskset.task.judge]
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.eval.env.env.taskset.task.judges]]
# [[orchestrator.eval.source.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
[inference.vllm]
max_model_len = 131072
[inference.parallel]
tp = 8
tensor_parallel_size = 8
enable_return_routed_experts = true
+32 -15
View File
@@ -1,4 +1,4 @@
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, rlm harness on a prime sandbox
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, rlm harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
# a glm4_moe model, which supports routed_experts.
@@ -43,7 +43,8 @@ timeout = 3600
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[resume]
[model]
name = "zai-org/GLM-4.5-Air"
@@ -82,7 +83,7 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
max_inflight_episodes = 512
[orchestrator.algo]
type = "grpo"
@@ -97,10 +98,18 @@ num_turns_weight = 0.1
name = "glm-4.5"
thinking_retention = "all"
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
[orchestrator.train.source.env.taskset]
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["glm45air-swe"]
[orchestrator.prime_monitor]
@@ -109,24 +118,32 @@ env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm45air-swe"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
[inference.vllm]
max_model_len = 131072
[inference.parallel]
tp = 8
tensor_parallel_size = 8
enable_return_routed_experts = true
+54 -33
View File
@@ -33,7 +33,8 @@ timeout = 3600
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[resume]
[model]
name = "zai-org/GLM-4.5-Air"
@@ -72,7 +73,7 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
max_inflight_episodes = 512
[orchestrator.renderer]
name = "glm-4.5"
@@ -91,25 +92,31 @@ num_turns_weight = 0.1
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "tmax"
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
[orchestrator.train.env.env.taskset]
id = "tmax-v1"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["glm45air-terminal"]
[orchestrator.train.source.env.taskset]
id = "tmax"
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
# [[orchestrator.train.env.env.taskset.judges]]
# [[orchestrator.train.source.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.train.env.env.taskset.judges]]
# [[orchestrator.train.source.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# path = "deps/prime-envs/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
@@ -118,63 +125,77 @@ id = "tmax-v1"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swebench-verified"
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.env.env.taskset]
id = "swebench-verified-v1"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
# [[orchestrator.eval.env.env.taskset.judges]]
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm45air-terminal"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.eval.env.env.taskset.judges]]
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# path = "deps/prime-envs/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "terminal-bench-2"
group_size = 4 # avg@4
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.env.env.taskset]
id = "terminal-bench-2-v1"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
# [[orchestrator.eval.env.env.taskset.judges]]
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm45air-terminal"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "terminal-bench-2"
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.eval.env.env.taskset.judges]]
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# path = "deps/prime-envs/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
[inference.vllm]
max_model_len = 131072
[inference.parallel]
tp = 8
tensor_parallel_size = 8
enable_return_routed_experts = true
+33 -19
View File
@@ -6,22 +6,9 @@
output_dir = "/shared/outputs/glm5.2-16node-llmd"
enable_expert_parallel = true
gpu_memory_utilization = 0.75
enable_eplb = false
use_deep_gemm = true
enable_fp32_lm_head = true
[model]
name = "zai-org/GLM-5.2-FP8"
max_model_len = 91000
tool_call_parser = "glm47"
reasoning_parser = "glm45"
[vllm_extra]
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[kv_cache_offload]
type = "mooncake"
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
@@ -35,16 +22,43 @@ prefill_nodes_per_replica = 2
num_prefill_replicas = 4
decode_nodes_per_replica = 8
num_decode_replicas = 1
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
[deployment.router]
[deployment.prefill_env_vars]
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
[deployment.decode_env_vars]
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
[router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 }
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 }
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 }
non_cached_tokens = 128
[router.scorers]
"prefix-cache-scorer" = 3.0
[router.prefill_scorer_overrides]
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[router.decode_scorer_overrides]
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[slurm]
job_name = "glm5.2-16node-llmd"
partition = "all"
[vllm]
model = "zai-org/GLM-5.2-FP8"
max_model_len = 91000
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
+8 -8
View File
@@ -1,12 +1,4 @@
enable_expert_parallel = true
enable_eplb = false
use_deep_gemm = true
gpu_memory_utilization = 0.85
[model]
name = "zai-org/GLM-5-FP8"
tool_call_parser = "auto"
reasoning_parser = "glm45"
[deployment]
type = "disaggregated"
@@ -17,3 +9,11 @@ gpus_per_node = 8
[slurm]
job_name = "glm5"
partition = "cluster"
[vllm]
model = "zai-org/GLM-5-FP8"
tool_call_parser = "auto"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.85
enable_expert_parallel = true
enable_eplb = false
+56 -30
View File
@@ -1,7 +1,10 @@
max_steps = 10000000
seq_len = 131072
output_dir = "/shared/outputs/glm5-llmd" # FILL IN: point at your shared filesystem
clean_output_dir = true
output_dir = "/shared/outputs" # FILL IN: point at your shared filesystem
clean = true
[run]
name = "glm5-llmd"
[log]
level = "debug"
@@ -28,23 +31,53 @@ prefill_nodes_per_replica = 2
num_prefill_replicas = 4
decode_nodes_per_replica = 8
num_decode_replicas = 1
# skip warmup for faster start in cost of some jit overhead early
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
[inference.deployment.prefill_env_vars]
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
[inference.deployment.decode_env_vars]
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
# gives the most KV cache while keeping decent throughput, KV cache increase comes in from lower deep-ep LL static buffers
prefill_vllm_overrides = {"enable_dbo"=true}
decode_vllm_overrides = {"max_num_batched_tokens"=96, "max_num_seqs"=96}
[inference.deployment.prefill_vllm_overrides]
"enable_dbo" = true
[inference.deployment.router]
[inference.deployment.decode_vllm_overrides]
"max_num_batched_tokens" = 96
"max_num_seqs" = 96
[inference.router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 } # need some prefix-cache routing, however due to shared mooncake pool do low prio
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 } # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 } # decode doesn't really create queue, it fills in KV cache fast, give 4.0
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[inference.vllm]
model = "zai-org/GLM-5.1-FP8"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[slurm]
job_name = "glm5-llmd"
partition = "all" # FILL IN: set to your cluster's partition
@@ -81,7 +114,7 @@ weight_decay = 0.0
[orchestrator]
batch_size = 256
group_size = 16
max_inflight_rollouts = 2048
max_inflight_episodes = 2048
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
[orchestrator.model]
@@ -93,34 +126,27 @@ clear_thinking = false
[orchestrator.train.sampling]
temperature = 1.0
extra_body = {chat_template_kwargs = {clear_thinking = false}}
[orchestrator.train.sampling.extra_body.chat_template_kwargs]
clear_thinking = false
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "r2e"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "rlm", runtime = { type = "prime", labels = ["glm5-llmd"] } }
[orchestrator.train.source.env.taskset]
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
[orchestrator.train.source.env.agent.runtime]
labels = ["glm5-llmd"]
[inference]
enable_expert_parallel = true
# <0.80 because glm5 layers are too large for 0.85
gpu_memory_utilization = 0.75
enable_eplb = false
use_deep_gemm = true
enable_fp32_lm_head = true
[inference.model]
name = "zai-org/GLM-5.1-FP8"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
# Speed up GLM-5.1 weight load: EP weight filtering + safetensors prefetch.
[inference.vllm_extra]
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
# Mooncake distributed CPU KV store: 1TB/node shared pool across all inference nodes.
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
+16 -11
View File
@@ -23,10 +23,15 @@ type = "disaggregated"
prefill_nodes_per_replica = 4
decode_nodes_per_replica = 4
[inference.vllm]
model = "zai-org/GLM-5-FP8"
tool_call_parser = "glm47"
gpu_memory_utilization = 0.80
enable_expert_parallel = true
enable_eplb = false
[slurm]
job_name = "glm5-pd-disag"
[ckpt]
interval = 100
@@ -58,7 +63,6 @@ type = "adamw"
lr = 1e-6
weight_decay = 0.1
[orchestrator]
batch_size = 4096
group_size = 16
@@ -71,22 +75,23 @@ name = "zai-org/GLM-5-FP8"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] } }
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm5-pd-disag", "swe-bench-verified"]
[[orchestrator.post_batch_filters]]
type = "gibberish"
enforce = true
[inference]
enable_expert_parallel = true
# we need <0.85 bc glm5 layers are too large for 0.85
gpu_memory_utilization = 0.80
enable_eplb = false
use_deep_gemm = true
[inference.model]
name = "zai-org/GLM-5-FP8"
tool_call_parser = "glm47"
+76 -24
View File
@@ -47,35 +47,75 @@ weight_decay = 0.01
batch_size = 2048
oversampling_factor = 2
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "swe"
ratio = 0.3
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe"] } }
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
labels = ["intellect-3.1", "swe"]
[[orchestrator.train.source]]
name = "deepdive"
ratio = 0.2
env.taskset = { id = "deepdive-v1" }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] } }
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "deepdive"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
[orchestrator.train.source.env.agent.runtime]
labels = ["intellect-3.1", "deepdive"]
[[orchestrator.train.source]]
name = "math"
ratio = 0.3
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "i3_math"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "logic"
ratio = 0.2
env.taskset = { id = "i3_logic_v1", filter = { max = 0.874 } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.env]]
[orchestrator.train.source.env.taskset]
id = "i3_logic"
[orchestrator.train.source.env.taskset.filter]
max = 0.874
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "code"
ratio = 0.2
env.taskset = { id = "i3_code_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "i3_code"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
@@ -84,19 +124,31 @@ enforce = true
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] } }
[[orchestrator.eval.env]]
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["intellect-3.1", "swe-bench-verified"]
[[orchestrator.eval.source]]
name = "aime2025"
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference.parallel]
tp = 8
[orchestrator.eval.source.env.taskset]
id = "aime25"
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[inference.vllm]
tensor_parallel_size = 8
[orchestrator.renderer]
name = "default"
+21 -10
View File
@@ -48,23 +48,34 @@ batch_size = 2048
oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "swe"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe"] } }
[orchestrator.train.source.env.taskset]
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
labels = ["minimax-swe", "swe"]
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] } }
[inference.parallel]
tp = 8
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
# PrimeIntellect/MiniMax-M2.5-bf16 — template-identical to MiniMaxAI/MiniMax-M2.5 (mapped).
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["minimax-swe", "swe-bench-verified"]
[inference.vllm]
tensor_parallel_size = 8
[orchestrator.renderer]
name = "minimax-m2"
+34 -17
View File
@@ -29,7 +29,8 @@ timeout = 3600
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[resume]
[model]
name = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
@@ -66,7 +67,7 @@ type = "adamw"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 1536
max_inflight_episodes = 1536
[orchestrator.algo]
type = "grpo"
@@ -81,30 +82,46 @@ num_turns_weight = 0.1
name = "nemotron-3"
truncate_history_thinking = false
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
[orchestrator.train.source.env.taskset]
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["nemotron-3-super-swe"]
[orchestrator.prime_monitor]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
labels = ["nemotron-3-super-swe"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[inference]
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
enable_prefix_caching = true
enable_expert_parallel = true
enable_return_routed_experts = true
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
enable_prefix_caching = true
[inference.model]
max_model_len = 131072
[inference.parallel]
tp = 8
+22 -8
View File
@@ -48,18 +48,32 @@ max_off_policy_steps = 8
[orchestrator.train.sampling]
max_completion_tokens = 32768
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "math"
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "i3_math"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "aime2025"
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference.parallel]
tp = 8
[orchestrator.eval.source.env.taskset]
id = "aime25"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[inference.vllm]
tensor_parallel_size = 8
+22 -8
View File
@@ -46,18 +46,32 @@ batch_size = 512
oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "swe"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] } }
[orchestrator.train.source.env.taskset]
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
labels = ["qwen30b-swe", "swe"]
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] } }
[inference.parallel]
tp = 8
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["qwen30b-swe", "swe-bench-verified"]
[inference.vllm]
tensor_parallel_size = 8
+18 -9
View File
@@ -35,16 +35,25 @@ batch_size = 512
group_size = 16
max_off_policy_steps = 32
[[orchestrator.train.env]]
env.taskset = { id = "general-agent-v1", task = { tools = { colocated = true } }, min_tier = 1 }
env.agent.harness = { id = "null", runtime = { type = "modal" } }
[[orchestrator.train.source]]
[orchestrator.train.source.env.taskset]
id = "general-agent"
min_tier = 1
[orchestrator.train.source.env.taskset.task.tools]
colocated = true
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "modal"
[inference]
gpu_memory_utilization = 0.85
[inference.model]
[inference.vllm]
max_model_len = 32768
[inference.parallel]
dp = 2
tp = 4
data_parallel_size = 2
tensor_parallel_size = 4
gpu_memory_utilization = 0.85
+9 -8
View File
@@ -1,6 +1,6 @@
# Alphabet Sort
In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to sort names alphabetically using LoRA. Unlike other examples, this task doesn't require SFT warmup as the base model already understands the conversation format. We proceed directly to multi-turn RL against the `alphabet-sort-v1` taskset.
In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to sort names alphabetically using LoRA. Unlike other examples, this task doesn't require SFT warmup as the base model already understands the conversation format. We proceed directly to multi-turn RL against the `alphabet-sort` taskset.
> This example runs on a single H100 GPU.
@@ -9,7 +9,7 @@ In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to sort na
The taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import alphabet_sort_v1"
uv run python -c "import alphabet_sort"
```
Start the tmux session:
@@ -32,13 +32,13 @@ We use non-default settings to balance the difficulty: 3 fixed turns (instead of
Start the inference server:
```bash
# In the `Inference` pane
uv run inference --enable-lora --model.name Qwen/Qwen3-4B-Instruct-2507
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507
```
Evaluate the base model:
```bash
# In the `Trainer` pane
uv run eval alphabet-sort-v1 --harness.id null \
uv run eval alphabet-sort --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
-n 20 \
@@ -93,14 +93,15 @@ We train with LoRA (rank 32, alpha 64) for 100 steps.
```bash
# In the `Trainer` pane
uv run rl @ examples/basic/alphabet-sort/rl.toml \
--run.name rl \
--wandb.project ... \
--wandb.name ...
```
This will write a weight checkpoint in `outputs/weights/step_100`. Upload it to HF to be able to use it as the final model for evaluation.
This will write a weight checkpoint in `outputs/rl/weights/step_100`. Upload it to HF to be able to use it as the final model for evaluation.
```bash
uv run hf upload <user>/Qwen3-4B-Instruct-AlphabetSort-RL outputs/weights/step_100
uv run hf upload <user>/Qwen3-4B-Instruct-AlphabetSort-RL outputs/rl/weights/step_100
```
We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL`](https://huggingface.co/PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL).
@@ -110,12 +111,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetS
Let's see how our final RL checkpoint performs on the eval set.
```bash
# In the `Inference` pane
uv run inference --enable-lora --model.name PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
```
```bash
# In the `Trainer` pane
uv run eval alphabet-sort-v1 --harness.id null \
uv run eval alphabet-sort --harness.id null \
-m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL \
--client.base-url http://localhost:8000/v1 \
-n 20 \
+15 -3
View File
@@ -31,9 +31,21 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 768
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference] # Default inference config
+23 -9
View File
@@ -16,27 +16,41 @@ batch_size = 512
group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
[[orchestrator.eval.source]]
name = "aime2024"
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.model]
seq_len = 16384
[inference.model]
[inference.vllm]
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+21 -19
View File
@@ -1,15 +1,15 @@
# Reverse Text
We demonstrate how to train `Qwen3-0.6B` to reverse a small chunk of text. We will use a SFT warmup to learn the skill of text reversal on longer documents and then a quick RL run on the `reverse-text-v1` taskset. We use a similar setup in our CI and for development.
We demonstrate how to train `Qwen3-0.6B` to reverse a small chunk of text. We will use a SFT warmup to learn the skill of text reversal on longer documents and then a quick RL run on the `reverse-text` taskset. We use a similar setup in our CI and for development.
> The commands in this example were designed to be run on 2 GPUs (one trainer and one inference GPU). It is possible to run on less or more GPUs using different deployment strategies. If you run on a different setup, you may need to adjust the start commands.
## Setup
The `reverse-text-v1` taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
The `reverse-text` taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import reverse_text_v1"
uv run python -c "import reverse_text"
```
First, let's start a `tmux` session which we will use throughout the experiment.
@@ -22,12 +22,12 @@ Let's check how well `Qwen3-0.6B` does out-of-the-box on the `reverse-text` envi
```bash
# Run this in the `Inference` pane
uv run inference --model.name Qwen/Qwen3-0.6B
uv run inference --vllm.model Qwen/Qwen3-0.6B
```
```bash
# Run this in the `Trainer` pane
uv run eval reverse-text-v1 --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval reverse-text --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
This is of course just a quick vibe check and no full-fledged evaluation, but we can see that the model struggles with this task. In this specific instance, we got an **average reward of ~0.05** across the 20x3 rollouts. Let's do some training!
@@ -43,6 +43,7 @@ To train on a single GPU, run
```bash
# In the `Trainer` pane
uv run sft @ examples/basic/reverse-text/sft.toml \
--run.name sft \
--wandb.project ... \
--wandb.name ...
```
@@ -59,10 +60,10 @@ uv run torchrun \
--wandb.name ...
```
This should write a weight checkpoint in `outputs/weights/step_100`. Upload it to HF to be able to use it as the base model for RL.
This should write a weight checkpoint in `outputs/sft/weights/step_100`. Upload it to HF to be able to use it as the base model for RL.
```bash
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT outputs/weights/step_100
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT outputs/sft/weights/step_100
```
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT).
@@ -77,14 +78,15 @@ For the RL we will only do 20 steps at 8x16 rollouts, for a total batch size of
# Run this in the `Trainer` pane
uv run rl @ examples/basic/reverse-text/rl.toml \
--model.name ... \
--run.name rl \
--wandb.project ... \
--wandb.name ...
```
This will write a weight checkpoint in `outputs/weights/step_20`. As before, let's upload it to HF.
This will write a weight checkpoint in `outputs/rl/weights/step_20`. As before, let's upload it to HF.
```bash
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-RL outputs/weights/step_20
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-RL outputs/rl/weights/step_20
```
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL).
@@ -95,12 +97,12 @@ Let's see how our final RL checkpoints perform on the `reverse-text` environment
```bash
# Run this in the `Inference` pane
uv run inference --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
uv run inference --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
```
```bash
# Run this in the `Trainer` pane
uv run eval reverse-text-v1 --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval reverse-text --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
Way better! Now we get an **average reward of ~0.8**.
@@ -131,18 +133,18 @@ Exec into the trainer pod and run SFT:
```bash
kubectl exec -it my-exp-trainer-0 -- bash
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs
# This will save checkpoints to /data/outputs/weights/step_100
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs --run.name sft
# This will save checkpoints to /data/outputs/sft/weights/step_100
```
Upload the checkpoint to HuggingFace or use it directly from shared storage:
```bash
# Option 1: Upload to HuggingFace (from within the pod)
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT /data/outputs/weights/step_100
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT /data/outputs/sft/weights/step_100
# Option 2: Use local checkpoint path in RL config
# Update the model.name in the RL configs to point to /data/outputs/weights/step_100
# Update the model.name in the RL configs to point to /data/outputs/sft/weights/step_100
```
### Step 3: Deploy RL Training
@@ -210,10 +212,10 @@ kubectl exec -it my-exp-trainer-0 -- bash
# If inference server isn't running with the RL model, start it in another terminal:
kubectl exec -it my-exp-inference-0 -- bash
uv run inference --model.name /data/outputs/weights/step_20
uv run inference --vllm.model /data/outputs/weights/step_20
# Back in trainer pod, run evaluation
uv run eval reverse-text-v1 --harness.id null \
uv run eval reverse-text --harness.id null \
-m /data/outputs/weights/step_20 \
--client.base-url $INFERENCE_URL \
-n 20 -r 3 --sampling.max-tokens 1024 --no-push
@@ -223,8 +225,8 @@ uv run eval reverse-text-v1 --harness.id null \
```bash
helm uninstall my-exp
# Optionally delete shared data:
kubectl delete pvc prime-rl-shared-data
# Optionally delete shared data. The PVC is named <release-name>-shared-data:
kubectl delete pvc my-exp-shared-data
```
**What the Helm chart provides:**
+10 -3
View File
@@ -15,10 +15,17 @@ group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
+12 -10
View File
@@ -16,7 +16,7 @@ In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to answer
The taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import wiki_search_v1"
uv run python -c "import wiki_search"
```
Set up the credentials for the configured reference judge:
@@ -70,14 +70,14 @@ Start the inference server:
```bash
# In the `Inference` pane
uv run inference --enable-lora --model.name Qwen/Qwen3-4B-Instruct-2507 --model.tool_call_parser hermes
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507 --vllm.tool-call-parser hermes
```
Evaluate the base model:
```bash
# In the `Trainer` pane
uv run eval wiki-search-v1 --harness.id null \
uv run eval wiki-search --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
-n 20 \
@@ -93,6 +93,7 @@ Train with the unified config file:
```bash
# In the `Trainer` pane
uv run rl @ examples/basic/wiki-search/rl.toml \
--run.name rl \
--wandb.project your-project-name \
--wandb.name your-run-name
```
@@ -102,10 +103,10 @@ The unified config file automatically configures:
- **Orchestrator**: Rollout generation with tool calling enabled
- **Inference**: vLLM server for Qwen3-4B-Instruct-2507 with tool parsing enabled
This will write weight checkpoints in `outputs/weights/step_*`. Upload the final checkpoint to HuggingFace:
This will write weight checkpoints in `outputs/rl/weights/step_*`. Upload the final checkpoint to HuggingFace:
```bash
uv run hf upload <user>/Qwen3-4B-Instruct-WikiSearch-RL outputs/weights/step_500
uv run hf upload <user>/Qwen3-4B-Instruct-WikiSearch-RL outputs/rl/weights/step_500
```
## Evaluation
@@ -114,12 +115,12 @@ Evaluate your trained model:
```bash
# In the `Inference` pane
uv run inference --enable-lora --model.name <user>/Qwen3-4B-Instruct-WikiSearch-RL --model.tool_call_parser hermes
uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSearch-RL --vllm.tool-call-parser hermes
```
```bash
# In the `Trainer` pane
uv run eval wiki-search-v1 --harness.id null \
uv run eval wiki-search --harness.id null \
-m <user>/Qwen3-4B-Instruct-WikiSearch-RL \
--client.base-url http://localhost:8000/v1 \
-n 20 \
@@ -133,10 +134,11 @@ uv run eval wiki-search-v1 --harness.id null \
The V1 taskset fixes the question bank and searchable corpus. You can replace its reference judge in `rl.toml`:
```toml
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wiki-search"
taskset = { id = "wiki-search-v1", task = { judges = [{ id = "reference", model = "openai/gpt-5.4-nano" }] } }
harness = { id = "null", runtime = { type = "subprocess" } }
taskset = { id = "wiki-search", task = { judges = [{ id = "reference", model = "openai/gpt-5.4-nano" }] } }
harness = { id = "null" }
runtime = { type = "subprocess" }
```
## Notes
+13 -6
View File
@@ -40,16 +40,23 @@ name = "qwen3-4b-wiki-search"
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.source]]
name = "wiki-search"
[orchestrator.train.source.env.taskset]
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[[orchestrator.train.env]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[ckpt] # Checkpoint at the end of training
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
+12 -10
View File
@@ -1,6 +1,6 @@
# Wordle
In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This will require a SFT warmup to learn the format and, finally, multi-turn RL against the `wordle-v1` taskset to improve performance.
In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This will require a SFT warmup to learn the format and, finally, multi-turn RL against the `wordle` taskset to improve performance.
> The commands in this example were designed to be run on 2 GPUs (one trainer and one inference GPU). It is possible to run on less or more GPUs using different deployment strategies. If you run on a different setup, you may need to adjust the start commands.
@@ -9,7 +9,7 @@ In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This w
The taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import wordle_v1"
uv run python -c "import wordle"
```
Start the pre-layouted `tmux` session which we will use to run all experiments and view logs conveniently
@@ -22,14 +22,14 @@ Before training, we want to get a baseline score and test how well `Qwen3-1.7B`
```bash
# Run this in the `Inference` pane
uv run inference --model.name Qwen/Qwen3-1.7B
uv run inference --vllm.model Qwen/Qwen3-1.7B
```
Then, use the `eval` entrypoint to evaluate the model in the `wordle` environment. We evaluate on the 20 evaluation examples which are distinct words not appearing in the training set of the environment. We constrain the response length to 1024 tokens as this should be more than enough to play a full game.
```bash
# Run this in the `Trainer` pane
uv run eval wordle-v1 --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval wordle --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
We got an **average reward of ~0.2** across the 20x3 rollouts. From the summary, we can see that the most of the reward is coming from format and partial rewards. In fact, the model does not guess the correct word within any game, leading to a win rate of **0%**. Looking at some samples, it is evident repeatedly submitting guesses in the wrong format and is not able to revise its strategy from the environment feedback. Let's do some SFT warmup to get the model to learn the format of the environment.
@@ -45,6 +45,7 @@ To train on a single GPU, run
```bash
# In the `Trainer` pane
uv run sft @ examples/basic/wordle/sft.toml \
--run.name sft \
--wandb.project ... \
--wandb.name ...
```
@@ -61,10 +62,10 @@ uv run torchrun \
--wandb.name ...
```
After training completes, you will find the final weight checkpoint in `outputs/weights/step_20`. Upload it to HF to be able to use it as the base model for RL we will do in the next section.
After training completes, you will find the final weight checkpoint in `outputs/sft/weights/step_20`. Upload it to HF to be able to use it as the base model for RL we will do in the next section.
```bash
uv run hf upload <user>/Qwen3-1.7B-Wordle-SFT outputs/weights/step_20
uv run hf upload <user>/Qwen3-1.7B-Wordle-SFT outputs/sft/weights/step_20
```
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-SFT).
@@ -80,14 +81,15 @@ Finally, we will do multi-turn RL against the `wordle` environment using the mod
# Run this in the `Trainer` pane
uv run rl @ examples/basic/wordle/rl.toml \
--model.name ... \
--run.name rl \
--wandb.project ... \
--wandb.name ...
```
This will write a weight checkpoint in `outputs/weights/step_100`. As before, let's upload it to HF.
This will write a weight checkpoint in `outputs/rl/weights/step_100`. As before, let's upload it to HF.
```bash
uv run hf upload <user>/Qwen3-1.7B-Wordle-RL outputs/weights/step_100
uv run hf upload <user>/Qwen3-1.7B-Wordle-RL outputs/rl/weights/step_100
```
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-RL).
@@ -98,12 +100,12 @@ Let's see how our final RL checkpoint performs on the eval set.
```bash
# Run this in the `Inference` pane
uv run inference --model.name PrimeIntellect/Qwen3-1.7B-Wordle-RL
uv run inference --vllm.model PrimeIntellect/Qwen3-1.7B-Wordle-RL
```
```bash
# Run this in the `Trainer` pane
uv run eval wordle-v1 --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval wordle --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
Way better! Our model now wins **~60%** and gets an average reward of **~1.5**.
+12 -7
View File
@@ -18,19 +18,24 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer] # Default trainer config
[inference.parallel]
dp = 6
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
[inference.vllm]
data_parallel_size = 6
[orchestrator.renderer]
name = "prime-qwen3"
+4 -6
View File
@@ -2,8 +2,6 @@
This directory contains a Helm chart for deploying prime-rl training infrastructure on Kubernetes clusters.
For complete documentation, see the [Kubernetes guide](https://docs.primeintellect.ai/prime-rl/kubernetes).
## Quick Start
```bash
@@ -64,11 +62,11 @@ helm install my-exp ./prime-rl \
```bash
helm uninstall my-exp
kubectl delete pvc prime-rl-shared-data # Warning: deletes data!
# The PVC is named <release-name>-shared-data (see templates/pvc.yaml)
kubectl delete pvc my-exp-shared-data # Warning: deletes data!
```
## Learn More
- [Full Kubernetes documentation](https://docs.primeintellect.ai/prime-rl/kubernetes) - Architecture, configuration, distributed training
- [Deployment guide](https://docs.primeintellect.ai/prime-rl/deployment) - Non-Kubernetes deployments
- [Troubleshooting](https://docs.primeintellect.ai/prime-rl/troubleshooting) - Common issues
- [Scaling guide](https://docs.primeintellect.ai/prime-rl/scaling) - Non-Kubernetes multi-node deployment (SLURM), parallelism, benchmarking
+1 -1
View File
@@ -11,7 +11,7 @@ image:
orchestrator:
enabled: true
autoStart: true
command: "uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs/run_default --client.base-url $INFERENCE_URL ; sleep infinity"
command: "uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL ; sleep infinity"
resources:
requests:
memory: "1Gi"
+10 -3
View File
@@ -13,10 +13,17 @@ name = "reverse-text"
[train.sampling]
max_completion_tokens = 128
[[train.env]]
[[train.source]]
name = "reverse-text"
taskset = { id = "reverse-text-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[train.source.env.taskset]
id = "reverse-text"
[train.source.env.agent.harness]
id = "null"
[train.source.env.agent.runtime]
type = "subprocess"
[renderer]
name = "prime-qwen3"
+6 -8
View File
@@ -59,9 +59,6 @@ spec:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.orchestrator.replicas }}"
- name: HEADLESS_SERVICE
value: "{{ .Release.Name }}-orchestrator-headless.{{ .Values.namespace }}.svc.cluster.local"
- name: INFERENCE_URL
{{- $releaseName := .Release.Name }}
{{- $namespace := .Values.namespace }}
{{- $port := int .Values.inference.service.port }}
@@ -71,6 +68,9 @@ spec:
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
{{- $urls = append $urls $url }}
{{- end }}
- name: INFERENCE_URL
value: {{ first $urls | quote }}
- name: ADMIN_INFERENCE_URLS
value: {{ $urls | join "," | quote }}
{{- with .Values.orchestrator.env }}
{{- toYaml . | nindent 8 }}
@@ -163,8 +163,6 @@ spec:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.inference.replicas }}"
- name: HEADLESS_SERVICE
value: "{{ .Release.Name }}-inference-headless.{{ .Values.namespace }}.svc.cluster.local"
{{- with .Values.inference.env }}
{{- toYaml . | nindent 8 }}
{{- end }}
@@ -294,13 +292,10 @@ spec:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.trainer.replicas }}"
- name: HEADLESS_SERVICE
value: "{{ .Release.Name }}-trainer-headless.{{ .Values.namespace }}.svc.cluster.local"
{{- if .Values.trainer.pytorchCudaAllocConf }}
- name: PYTORCH_CUDA_ALLOC_CONF
value: {{ .Values.trainer.pytorchCudaAllocConf | quote }}
{{- end }}
- name: INFERENCE_URL
{{- $releaseName := .Release.Name }}
{{- $namespace := .Values.namespace }}
{{- $port := int .Values.inference.service.port }}
@@ -310,6 +305,9 @@ spec:
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
{{- $urls = append $urls $url }}
{{- end }}
- name: INFERENCE_URL
value: {{ first $urls | quote }}
- name: ADMIN_INFERENCE_URLS
value: {{ $urls | join "," | quote }}
{{- with .Values.trainer.env }}
{{- toYaml . | nindent 8 }}
+6 -3
View File
@@ -28,9 +28,12 @@ orchestrator:
# Auto-start configuration (set to false to use sleep infinity for debugging)
autoStart: false
# Example command - use $INFERENCE_URL directly (comma-separated list of all inference server URLs)
command: "" # e.g., 'uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs/run_default --client.base-url $INFERENCE_URL'
# $INFERENCE_URL is auto-set to: 'http://<release>-inference-0...:8000/v1,http://<release>-inference-1...:8000/v1,...'
# Example command - use $INFERENCE_URL directly (the first inference server URL)
command: "" # e.g., 'uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL'
# $INFERENCE_URL is auto-set to 'http://<release>-inference-0...:8000/v1'. With more than one
# inference replica, put a router in front and point --client.base-url at it; admin operations
# (weight updates, health checks) fan out to every replica via
# --client.admin-base-url $ADMIN_INFERENCE_URLS (comma-separated list of all replica URLs).
resources:
requests:
+2 -2
View File
@@ -7,10 +7,10 @@ requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.4.2",
"renderers>=0.1.8",
"renderers>=0.1.9",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.2.1",
"verifiers>=0.3.0",
]
[build-system]
@@ -35,6 +35,7 @@ executes them.
from typing import Annotated, Any, ClassVar, Literal, TypeAlias
import verifiers.v1 as vf
from pydantic import Field, model_validator
from renderers import AutoRendererConfig, RendererConfig
@@ -57,7 +58,7 @@ class FrozenModelConfig(ClientConfig):
@model_validator(mode="after")
def require_explicit_endpoint(self):
if "base_url" not in self.model_fields_set and not self.is_elastic:
if "base_url" not in self.model_fields_set:
raise ValueError(
"a frozen model reference needs base_url — frozen models are externally "
"hosted; prime-rl only ever hosts the trainable policy."
@@ -188,6 +189,13 @@ class BaseAlgoConfig(BaseConfig):
)
return self
def validate_env(self, env_config: vf.EnvConfig) -> None:
"""Raise if this algorithm cannot run on the env it is configured for,
given that env's resolved config. Most algorithms read only the rollouts
and their rewards, so they run on any env and the base does nothing;
override where the credit assignment encodes an env's episode structure.
Called once per train env after algorithm inheritance resolves."""
class GRPOAlgoConfig(BaseAlgoConfig):
type: Literal["grpo"] = "grpo"
@@ -232,6 +240,60 @@ class MaxRLAlgoConfig(BaseAlgoConfig):
action_loss_type: ClassVar[ActionLossType] = "rl"
class RAEAlgoConfig(BaseAlgoConfig):
type: Literal["rae"] = "rae"
"""RAE — role-conditioned advantage estimation (SPIRAL,
https://arxiv.org/abs/2506.24119): scalar advantage = reward minus a
per-agent EMA baseline of that agent's own rewards, consumed by the ``rl``
loss component. The advantage estimator for multi-agent self-play envs
(``kuhn-poker`` and friends): in a zero-sum game the group mean is ~0
whatever the policy does, so a group-relative baseline mixes the agents'
opposite reward scales — a structural first-mover edge would read as
permanent credit. Per-agent baselines measure each agent against its own
expected reward instead. Works with any ``group_size`` (including 1)."""
action_loss_type: ClassVar[ActionLossType] = "rl"
decay: float = Field(0.95, ge=0.0, lt=1.0)
"""EMA decay of the per-agent baselines (SPIRAL's α): after a trace is
scored, its agent's baseline moves as ``baseline ← decay · baseline +
(1 − decay) · reward``. Baselines start at 0 and live in orchestrator
memory — a restart re-warms them over ~1/(1 − decay) traces per agent."""
class HierarchicalGRPOAlgoConfig(BaseAlgoConfig):
type: Literal["hierarchical_grpo"] = "hierarchical_grpo"
"""GRPO for proposer-solver envs.
Agents in ``episode_agents`` are compared with same-role attempts on the
same proposed problem. Other agents are compared with the same role across
proposals generated from one source task. This keeps rewards from different
problems and different roles out of the same average."""
action_loss_type: ClassVar[ActionLossType] = "rl"
episode_agents: list[str] = Field(min_length=1)
"""Roles compared within one proposed problem. Use ``["solver"]`` for
``proposer-solver``."""
def validate_env(self, env_config: vf.EnvConfig) -> None:
"""Require the proposer-solver structure used by the comparisons."""
try:
from proposer_solver import ProposerSolverEnvConfig
except ImportError as e:
raise ValueError(
"algorithm 'hierarchical_grpo' requires a proposer-solver env, but the "
"proposer-solver package is not installed (`uv sync --all-packages`)."
) from e
if not isinstance(env_config, ProposerSolverEnvConfig):
raise ValueError(
f"algorithm 'hierarchical_grpo' needs a proposer-solver env, but this env resolved to "
f"{type(env_config).__name__}. It compares solver attempts on the same proposed "
"problem and proposers across proposals. Use 'grpo' for a flat env or 'rae' for "
"multi-agent self-play."
)
class OPDAlgoConfig(BaseAlgoConfig):
type: Literal["opd"] = "opd"
"""On-policy distillation: the per-token signal is the reverse KL to
@@ -305,7 +367,14 @@ class SFTAlgoConfig(BaseAlgoConfig):
AlgoConfig: TypeAlias = Annotated[
GRPOAlgoConfig | EchoAlgoConfig | MaxRLAlgoConfig | OPDAlgoConfig | OPSDAlgoConfig | SFTAlgoConfig,
GRPOAlgoConfig
| EchoAlgoConfig
| MaxRLAlgoConfig
| RAEAlgoConfig
| HierarchicalGRPOAlgoConfig
| OPDAlgoConfig
| OPSDAlgoConfig
| SFTAlgoConfig,
Field(discriminator="type"),
]
"""The training algorithm: sampling plus the per-token training signal (credit
@@ -314,6 +383,8 @@ its class defaults are the vetted setting.
- ``grpo`` — policy group sampling, group-relative advantage, RL loss (the default).
- ``max_rl`` — GRPO with mean-normalized advantages (maximum-likelihood RL).
- ``rae`` — reward minus a per-agent EMA baseline (SPIRAL), for multi-agent self-play envs.
- ``hierarchical_grpo`` — GRPO for proposer-solver envs: solvers are compared within one proposed problem and proposers across proposals. Needs ``episode_agents``.
- ``opd`` — on-policy distillation: policy samples, per-token reverse KL against a reference model. Needs ``teacher``.
- ``opsd`` — SDFT: policy samples, demo-conditioned reverse KL against the live policy (the teacher is the policy itself).
- ``sft`` — a frozen model samples, the policy trains with CE on its tokens. Needs a frozen ``sampling.source``.
@@ -1,14 +1,40 @@
from pathlib import Path
from prime_rl.configs.orchestrator import EnvConfig
import verifiers.v1 as vf
from pydantic import SerializeAsAny, model_validator
from prime_rl.configs.shared import LogConfig
from prime_rl.utils.config import BaseConfig
class EnvServerConfig(BaseConfig):
env: EnvConfig
"""``uv run env-server``: what to serve (``[env]``) and how it's hosted (``[serve]``).
The ``rl`` launcher writes one of these per train/eval source, with ``serve.address``
set to the source's derived address."""
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
"""The environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
serve: vf.ServeConfig = vf.ServeConfig()
"""How it's served: the worker pool, the bind address, each worker's episode bound."""
log: LogConfig = LogConfig()
output_dir: Path = Path("outputs")
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
@model_validator(mode="before")
@classmethod
def _resolve_env(cls, data):
"""Narrow ``env`` to the selected env's config class."""
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
@property
def env_id(self) -> str:
return self.env.env_id or ""
@model_validator(mode="after")
def validate_env(self):
if not self.env_id:
raise ValueError('no env configured — set env = { taskset = { id = "<id>" } }')
return self
@@ -1,12 +1,13 @@
import json
from argparse import Namespace
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import Field, model_validator
from pydantic import ConfigDict, Field, model_validator
from pydantic_config import BaseConfig
from prime_rl.configs.shared import BaseModelConfig, EnvVars, LogConfig, SlurmConfig
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
from prime_rl.configs.shared import EnvVars, LogConfig, SlurmConfig
from prime_rl.utils.config import find_package_resource
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
# TODO: Set thinking/ solution budget
@@ -23,61 +24,192 @@ class ServerConfig(BaseConfig):
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. With Kubernetes liveness probes, keep the probe ``timeoutSeconds`` at least this high."""
class ParallelConfig(BaseConfig):
tp: int = 1
"""Tensor parallel size. Forwarded to vLLM as ``--tensor-parallel-size``."""
# Valid vLLM max_lora_rank values (`vllm.config.lora.MaxLoRARanks`), excluding 1 so
# tiny adapters round up to 8. Hardcoded rather than imported: prime-rl-configs does
# not depend on vLLM, and importing it costs seconds in every config-parsing process.
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
dp: int = Field(1, ge=1)
"""Data parallel size. Forwarded to vLLM as ``--data-parallel-size``."""
def __str__(self) -> str:
return f"tp={self.tp} dp={self.dp}"
# vLLM all2all backend options for expert-parallel deployments.
All2AllBackend = Literal[
"allgather_reducescatter",
"deepep_high_throughput",
"deepep_low_latency",
"flashinfer_nvlink_one_sided",
"flashinfer_nvlink_two_sided",
]
class ModelConfig(BaseModelConfig):
"""Configures the inference model. Most arguments are passed directly to the vLLM LLM class (https://docs.vllm.ai/en/latest/api/vllm.LLM.html).
class VllmConfig(BaseConfig):
"""Arguments forwarded to the vLLM server, under vLLM's own argument names
(https://docs.vllm.ai/en/latest/configuration/engine_args.html).
The fields below are the arguments prime-rl types, defaults, or reads back;
any other vLLM argument can be set as well (``[inference.vllm] max_num_seqs = 256``
or ``--vllm.max-num-seqs 256``) and passes through to the server verbatim.
Parser fields (``tool_call_parser``, ``reasoning_parser``) default to ``"auto"``,
which resolves to a concrete parser name at validation time from the model name.
Set to ``None`` to disable.
"""
model_config = ConfigDict(extra="allow")
model: str = "Qwen/Qwen3-0.6B"
"""HF model name or local path."""
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models. Forwarded as ``--dtype``."""
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models."""
max_model_len: int | None = None
"""Maximum model context length. If None, uses the model config's value. Forwarded as ``--max-model-len``."""
"""Maximum model context length. If None, uses the model config's value."""
enforce_eager: bool = False
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance. Forwarded as ``--enforce-eager``."""
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance."""
trust_remote_code: bool = False
"""Trust remote code. Forwarded to vLLM engine init."""
"""Trust remote code when loading the model."""
chat_template: str | None = None
"""Chat template — a Jinja2 template string or path to a template file. Forwarded as ``--chat-template``. If None, uses the model's default."""
"""Chat template — a Jinja2 template string or path to a template file. If None, uses the model's default."""
tool_call_parser: str | None = "auto"
"""Tool-call parser. Forwarded as ``--tool-call-parser``. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
"""Tool-call parser. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
reasoning_parser: str | None = "auto"
"""Parser for extracting reasoning content from model outputs. Forwarded as ``--reasoning-parser``. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
"""Parser for extracting reasoning content from model outputs. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
rope_scaling: dict[str, Any] | str | None = None
"""RoPE scaling configuration as a dict (e.g. ``{rope_type="yarn", factor=4.0, original_max_position_embeddings=32768}``). Forwarded as ``--rope-scaling``."""
"""RoPE scaling configuration as a dict (e.g. ``{rope_type="yarn", factor=4.0, original_max_position_embeddings=32768}``)."""
tensor_parallel_size: int = 1
"""Tensor parallel size."""
data_parallel_size: int = Field(1, ge=1)
"""Data parallel size."""
data_parallel_size_local: int | None = Field(None, ge=1)
"""Data parallel replicas to run on this node."""
data_parallel_rpc_port: int = Field(13345, ge=1, le=65535)
"""RPC port for data parallel communication."""
api_server_count: int = Field(1, ge=0)
"""API servers to run. Set to 0 for headless mode."""
seed: int = 0
"""Seed the inference components."""
gpu_memory_utilization: float = 0.9
"""GPU memory utilization."""
enable_prefix_caching: bool | None = None
"""Enable prefix caching."""
quantization: str | None = None
"""Online inference quantization method. If None, vLLM infers it from the checkpoint."""
enable_lora: bool = False
"""Enable LoRA."""
max_loras: int = 8
"""Maximum number of LoRAs."""
# TODO: The default value is very high because our areal impl for lora isn't ideal
# We add a lora with the same name instead of changing weights inplace
# Because we dont cancel requests that are past max_async, these requests could be using a LoRA that gets unloaded which will crash the inference server
max_cpu_loras: int = 100
"""Maximum number of LoRAs on CPU."""
max_lora_rank: int | None = None
"""Maximum LoRA rank. Rounded up to the nearest value vLLM accepts."""
lora_target_modules: list[str] | None = None
"""LoRA target modules."""
enable_expert_parallel: bool = False
"""Enable expert parallelism for MoE models."""
all2all_backend: All2AllBackend = "allgather_reducescatter"
"""All-to-all backend for expert-parallel communication."""
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB)."""
enable_dbo: bool = False
"""Enable dual batch overlap (DBO)."""
enable_return_routed_experts: bool = False
"""Return routed experts in responses."""
@model_validator(mode="before")
@classmethod
def parse_extra_values(cls, data: dict) -> dict:
"""Normalize pass-through (untyped) entries: kebab-case keys become snake_case,
and string values — which is how CLI overrides arrive — are JSON-parsed so
``--vllm.max-num-seqs 256`` lands as an int and ``--vllm.compilation-config
'{"cudagraph_mode": "NONE"}'`` as a dict. Non-JSON strings stay strings."""
if not isinstance(data, dict):
return data
for key in [k for k in data if k not in cls.model_fields]:
value = data.pop(key)
if isinstance(value, str):
try:
value = json.loads(value)
except json.JSONDecodeError:
pass
data[key.replace("-", "_")] = value
return data
@model_validator(mode="after")
def auto_resolve_parsers(self):
"""Resolve ``"auto"`` parser values to concrete parser names from the model name.
Runs after ``RLConfig.auto_setup_shared_configs`` (mode=before) has
propagated the shared ``[model] name`` into ``inference.model``, so the
propagated the shared ``[model] name`` into ``inference.vllm``, so the
name is set even when only the shared block specifies it.
"""
if self.tool_call_parser == "auto":
self.tool_call_parser = resolve_tool_call_parser(self.name)
self.tool_call_parser = resolve_tool_call_parser(self.model)
if self.reasoning_parser == "auto":
self.reasoning_parser = resolve_reasoning_parser(self.name)
self.reasoning_parser = resolve_reasoning_parser(self.model)
return self
@model_validator(mode="after")
def auto_setup_max_lora_rank(self):
"""Auto-setup max_lora_rank by rounding up to the nearest valid vLLM value.
vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512).
This validator ensures that any configured rank is rounded up to the minimum valid value
that can serve adapters of the requested rank.
"""
if self.max_lora_rank is not None:
original_rank = self.max_lora_rank
for valid_rank in VALID_VLLM_LORA_RANKS:
if valid_rank >= self.max_lora_rank:
self.max_lora_rank = valid_rank
break
else:
raise ValueError(f"max_lora_rank={original_rank} exceeds vLLM maximum of {VALID_VLLM_LORA_RANKS[-1]}")
return self
@model_validator(mode="after")
def auto_setup_api_server_count(self):
"""
Ensures that we have at least as many API servers as data parallel
size. Unless LoRA is enabled, in which case only one API server is
supported (vLLM limitation).
"""
if self.model_extra and self.model_extra.get("headless", False):
self.api_server_count = 0
return self
if "api_server_count" not in self.model_fields_set:
min_api_server_count = self.data_parallel_size_local or self.data_parallel_size
if self.api_server_count < min_api_server_count:
self.api_server_count = min_api_server_count
if self.enable_lora:
self.api_server_count = 1 # LoRA requires only one API server
return self
@@ -153,20 +285,6 @@ KVCacheOffloadConfig: TypeAlias = Annotated[
]
# Valid vLLM max_lora_rank values (from vllm/config/lora.py)
# TODO: on newer vLLM, can import via `get_args(vllm.config.lora.MaxLoRARanks)`
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
# vLLM all2all backend options for expert-parallel deployments.
All2AllBackend = Literal[
"allgather_reducescatter",
"deepep_high_throughput",
"deepep_low_latency",
"flashinfer_nvlink_one_sided",
"flashinfer_nvlink_two_sided",
]
# Known llm-d EPP scorer plugins (used to guard the ``scorers`` map against typos).
KNOWN_SCORERS = frozenset(
{
@@ -190,9 +308,6 @@ class VllmRouterConfig(BaseConfig):
type: Literal["vllm-router"] = "vllm-router"
port: int = 8000
"""Port the router listens on — becomes the client-facing router URL."""
policy: str = "consistent_hash"
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
@@ -202,9 +317,6 @@ class LlmdRouterConfig(BaseConfig):
type: Literal["llm-d"] = "llm-d"
port: int = 8000
"""Port the Envoy gateway listens on — becomes the client-facing router URL."""
scorers: dict[str, float] = {
"prefix-cache-scorer": 3.0,
"active-request-scorer": 2.0,
@@ -254,12 +366,6 @@ class BaseInferenceDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
"""GPUs per node."""
backend_port: int = 8100
"""Port for the per-rank vLLM backend instances."""
router: RouterConfig = VllmRouterConfig()
"""Router fronting the per-rank endpoints."""
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
type: Literal["single_node"] = "single_node"
@@ -331,10 +437,14 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
class InferenceConfig(BaseConfig):
server: ServerConfig = ServerConfig()
model: ModelConfig = Field(default_factory=ModelConfig)
router: RouterConfig | None = Field(default_factory=VllmRouterConfig)
"""Router fronting the engine(s). Every deployment runs a single global router as the client-facing endpoint on ``server.port``, with the engines listening on ``backend_port``. Set to ``None`` to run a bare engine on ``server.port`` without a router (the SLURM launchers do this for per-rank engine processes; the sbatch script starts the router)."""
parallel: ParallelConfig = ParallelConfig()
"""Multi-node and multi-GPU parallelism (TP, DP, PP)."""
backend_port: int = 8100
"""Port for the vLLM engine(s) behind the router. Defaults to ``server.port + 100``. Multi-node deployments start one engine per local DP rank at ``backend_port + rank``."""
vllm: VllmConfig = Field(default_factory=VllmConfig)
"""vLLM server arguments, under vLLM's own argument names. Unknown fields pass through verbatim."""
log: LogConfig = LogConfig()
"""Logging configuration."""
@@ -342,57 +452,6 @@ class InferenceConfig(BaseConfig):
env_vars: EnvVars = {}
"""Extra environment variables for the inference server process(es). Merged on top of the launcher defaults."""
enable_lora: bool = False
"""Enable LoRA. Forwarded as ``--enable-lora``."""
max_loras: int = 8
"""Maximum number of LoRAs. Forwarded as ``--max-loras``."""
# TODO: The default value is very high because our areal impl for lora isn't ideal
# We add a lora with the same name instead of changing weights inplace
# Because we dont cancel requests that are past max_async, these requests could be using a LoRA that gets unloaded which will crash the inference server
max_cpu_loras: int = 100
"""Maximum number of LoRAs on CPU. Forwarded as ``--max-cpu-loras``."""
max_lora_rank: int | None = None
"""Maximum LoRA rank. Forwarded as ``--max-lora-rank``."""
lora_target_modules: list[str] | None = None
"""LoRA target modules. Forwarded as ``--lora-target-modules``."""
enable_prefix_caching: bool | None = None
"""Enable prefix caching. Forwarded as ``--enable-prefix-caching``."""
gpu_memory_utilization: float = 0.9
"""GPU memory utilization. Forwarded as ``--gpu-memory-utilization``."""
quantization: str | None = None
"""Online inference quantization method. Forwarded as ``--quantization``."""
api_server_count: int = Field(1, ge=0)
"""API servers to run. Forwarded as ``--api-server-count``. Set to 0 for headless mode."""
data_parallel_size_local: int | None = Field(None, ge=1)
"""Data parallel replicas to run on this node. Forwarded as ``--data-parallel-size-local``."""
data_parallel_rpc_port: int = Field(13345, ge=1, le=65535)
"""RPC port for data parallel communication. Forwarded as ``--data-parallel-rpc-port``."""
seed: int = 0
"""Seed the inference components. Forwarded as ``--seed``."""
enable_expert_parallel: bool = False
"""Enable expert parallelism for MoE models. Forwarded as ``--enable-expert-parallel``."""
all2all_backend: All2AllBackend = "allgather_reducescatter"
"""All-to-all backend for expert-parallel communication. Forwarded as ``--all2all-backend``."""
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB). Forwarded as ``--enable-eplb``."""
enable_dbo: bool = False
"""Enable dual batch overlap (DBO). Forwarded as ``--enable-dbo``."""
use_deep_gemm: bool = False
"""Enable vLLM DeepGEMM FP8 kernels ``VLLM_USE_DEEP_GEMM=1``. Only works with block-wise FP8 quantization (e.g. GLM-5-FP8)."""
@@ -404,18 +463,12 @@ class InferenceConfig(BaseConfig):
use_pd_kv_transfer: bool = False
"""Auto-set for disaggregated P/D: emit the NIXL transfer connector. Persisted into the per-node config (which drops ``deployment``) so the connector is still built per worker. Not meant to be set by hand."""
enable_return_routed_experts: bool = False
"""Return routed experts in responses. Forwarded as ``--enable-return-routed-experts``."""
enable_fp32_lm_head: bool = True
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
enable_fp32_router_logits: bool = True
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
vllm_extra: dict[str, Any] = {}
"""Extra arguments forwarded to vLLM. Applied as attributes on the vLLM namespace after config translation."""
# Launcher-only fields
deployment: InferenceDeploymentConfig = SingleNodeInferenceDeploymentConfig()
@@ -438,8 +491,7 @@ class InferenceConfig(BaseConfig):
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
router = getattr(self.deployment, "router", None)
if router is not None and router.type == "llm-d" and self.enable_return_routed_experts:
if self.router is not None and self.router.type == "llm-d" and self.vllm.enable_return_routed_experts:
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(enable_return_routed_experts): it breaks P/D and is unverified for multi-node. "
@@ -447,13 +499,28 @@ class InferenceConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_router_deployment(self):
"""The llm-d router (EPP + Envoy) is launched by the SLURM templates only; multi-node deployments need a router to front the per-rank engines."""
if self.router is not None and self.router.type == "llm-d" and self.deployment.type == "single_node":
raise ValueError("The llm-d router backend requires a multi-node or disaggregated SLURM deployment.")
if self.router is None and self.deployment.type in ("multi_node", "disaggregated"):
raise ValueError("Multi-node / disaggregated deployments require a router fronting the per-rank engines.")
return self
@model_validator(mode="after")
def auto_setup_backend_port(self):
if self.router is not None and "backend_port" not in self.model_fields_set:
self.backend_port = self.server.port + 100
return self
@model_validator(mode="after")
def auto_setup_kv_cache_offload(self):
if self.kv_cache_offload is not None:
if self.enable_prefix_caching is False:
raise ValueError("KV cache offloading requires inference.enable_prefix_caching to be true.")
if "enable_prefix_caching" not in self.model_fields_set:
self.enable_prefix_caching = True
if self.vllm.enable_prefix_caching is False:
raise ValueError("KV cache offloading requires inference.vllm.enable_prefix_caching to be true.")
if "enable_prefix_caching" not in self.vllm.model_fields_set:
self.vllm.enable_prefix_caching = True
return self
@@ -462,19 +529,19 @@ class InferenceConfig(BaseConfig):
"""Auto-configure inference for disaggregated P/D: enable EP and compute DP."""
if self.deployment.type == "disaggregated":
self.use_pd_kv_transfer = True
if "enable_expert_parallel" not in self.model_fields_set:
self.enable_expert_parallel = True
if "enable_eplb" not in self.model_fields_set:
self.enable_eplb = False
if "enable_expert_parallel" not in self.vllm.model_fields_set:
self.vllm.enable_expert_parallel = True
if "enable_eplb" not in self.vllm.model_fields_set:
self.vllm.enable_eplb = False
gpus_per_node = self.deployment.gpus_per_node
tp = self.parallel.tp
tp = self.vllm.tensor_parallel_size
dp_per_node = gpus_per_node // tp
if self.data_parallel_size_local is None:
self.data_parallel_size_local = dp_per_node
if self.parallel.dp == 1:
self.parallel.dp = dp_per_node
if self.api_server_count == 1:
self.api_server_count = dp_per_node
if self.vllm.data_parallel_size_local is None:
self.vllm.data_parallel_size_local = dp_per_node
if self.vllm.data_parallel_size == 1:
self.vllm.data_parallel_size = dp_per_node
if self.vllm.api_server_count == 1:
self.vllm.api_server_count = dp_per_node
return self
@model_validator(mode="after")
@@ -485,44 +552,6 @@ class InferenceConfig(BaseConfig):
self.slurm.template_path = templates_dir / "inference.sbatch.j2"
return self
@model_validator(mode="after")
def auto_setup_max_lora_rank(self):
"""Auto-setup max_lora_rank by rounding up to the nearest valid vLLM value.
vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512).
This validator ensures that any configured rank is rounded up to the minimum valid value
that can serve adapters of the requested rank.
"""
if self.max_lora_rank is not None:
original_rank = self.max_lora_rank
for valid_rank in VALID_VLLM_LORA_RANKS:
if valid_rank >= self.max_lora_rank:
self.max_lora_rank = valid_rank
break
else:
raise ValueError(f"max_lora_rank={original_rank} exceeds vLLM maximum of {VALID_VLLM_LORA_RANKS[-1]}")
return self
@model_validator(mode="after")
def auto_setup_api_server_count(self):
"""
Ensures that we have at least as many API servers as data parallel
size. Unless LoRA is enabled, in which case only one API server is
supported (vLLM limitation).
"""
if self.vllm_extra.get("headless", False):
self.api_server_count = 0
return self
if "api_server_count" not in self.model_fields_set:
min_api_server_count = self.data_parallel_size_local or self.parallel.dp
if self.api_server_count < min_api_server_count:
self.api_server_count = min_api_server_count
if self.enable_lora:
self.api_server_count = 1 # LoRA requires only one API server
return self
def build_kv_transfer_config(self) -> dict[str, Any] | None:
"""Build the single vLLM ``kv_transfer_config`` from the transfer + offload connectors.
@@ -552,90 +581,49 @@ class InferenceConfig(BaseConfig):
"kv_connector_extra_config": {"connectors": connectors},
}
def to_vllm(self) -> Namespace:
"""Convert InferenceConfig to vLLM-compatible Namespace."""
namespace = Namespace()
to_vllm = {
"server.host": "host",
"server.port": "port",
"server.liveness_timeout_seconds": "liveness_timeout_seconds",
"model.name": "model",
"model.dtype": "dtype",
"model.max_model_len": "max_model_len",
"model.enforce_eager": "enforce_eager",
"model.trust_remote_code": "trust_remote_code",
"model.chat_template": "chat_template",
"model.tool_call_parser": "tool_call_parser",
"model.reasoning_parser": "reasoning_parser",
"model.rope_scaling": "rope_scaling",
"parallel.tp": "tensor_parallel_size",
"parallel.dp": "data_parallel_size",
"data_parallel_size_local": "data_parallel_size_local",
"data_parallel_rpc_port": "data_parallel_rpc_port",
"enable_lora": "enable_lora",
"enable_prefix_caching": "enable_prefix_caching",
"max_loras": "max_loras",
"max_cpu_loras": "max_cpu_loras",
"max_lora_rank": "max_lora_rank",
"lora_target_modules": "lora_target_modules",
"gpu_memory_utilization": "gpu_memory_utilization",
"quantization": "quantization",
"api_server_count": "api_server_count",
"enable_return_routed_experts": "enable_return_routed_experts",
"enable_expert_parallel": "enable_expert_parallel",
"all2all_backend": "all2all_backend",
"enable_eplb": "enable_eplb",
"enable_dbo": "enable_dbo",
"seed": "seed",
}
# Fields vLLM rejects as None — omitted from the namespace so vLLM applies its
# own default (e.g. quantization is inferred from the checkpoint).
_OMIT_IF_NONE = frozenset(
{"chat_template", "tool_call_parser", "reasoning_parser", "lora_target_modules", "quantization", "rope_scaling"}
)
for config_key, vllm_key in to_vllm.items():
value = rgetattr(self, config_key.replace("-", "_"))
rsetattr(namespace, vllm_key, value)
def to_namespace(self) -> Namespace:
"""Dump the server + vllm sections into a vLLM-compatible Namespace."""
namespace = Namespace(
host=self.server.host,
port=self.server.port,
liveness_timeout_seconds=self.server.liveness_timeout_seconds,
)
# Set `logprobs_mode` to `processed_logprobs` by default
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
extra_fields = self.vllm.model_extra or {}
for key in (*type(self.vllm).model_fields, *extra_fields):
value = getattr(self.vllm, key)
# None extras are dropped too: `--vllm.foo None` means "use vLLM's default".
if value is None and (key in self._OMIT_IF_NONE or key in extra_fields):
continue
setattr(namespace, key, value)
# Auto tool choice is gated on a tool-call parser being resolved, unless
# explicitly overridden.
if "enable_auto_tool_choice" not in extra_fields:
namespace.enable_auto_tool_choice = hasattr(namespace, "tool_call_parser")
# Default `logprobs_mode` to `processed_logprobs`
if not hasattr(namespace, "logprobs_mode"):
namespace.logprobs_mode = "processed_logprobs"
kv_transfer_config = self.build_kv_transfer_config()
if kv_transfer_config is not None:
rsetattr(namespace, "kv_transfer_config", kv_transfer_config)
namespace.kv_transfer_config = kv_transfer_config
# Pass prime-rl-specific flags through vLLM's additional_config dict;
# workers read these via get_current_vllm_config().additional_config.
additional_config = getattr(namespace, "additional_config", None) or {}
if self.enable_fp32_lm_head:
existing = getattr(namespace, "additional_config", None) or {}
existing["fp32_lm_head"] = True
rsetattr(namespace, "additional_config", existing)
additional_config["fp32_lm_head"] = True
if self.enable_fp32_router_logits:
existing = getattr(namespace, "additional_config", None) or {}
existing["fp32_router_logits"] = True
rsetattr(namespace, "additional_config", existing)
# Remove chat_template if not set (vLLM doesn't accept None)
if namespace.chat_template is None:
delattr(namespace, "chat_template")
# Remove tool_call_parser if not set (vLLM doesn't accept None) and gate
# `enable_auto_tool_choice` on its presence.
if namespace.tool_call_parser is None:
delattr(namespace, "tool_call_parser")
namespace.enable_auto_tool_choice = hasattr(namespace, "tool_call_parser")
# Remove reasoning_parser if not set (vLLM doesn't accept None)
if namespace.reasoning_parser is None:
delattr(namespace, "reasoning_parser")
# Remove lora_target_modules if not set (vLLM doesn't accept None)
if hasattr(namespace, "lora_target_modules") and namespace.lora_target_modules is None:
delattr(namespace, "lora_target_modules")
# Remove quantization if not set so vLLM can infer it from the checkpoint.
if namespace.quantization is None:
delattr(namespace, "quantization")
# Remove rope_scaling if not set (vLLM doesn't accept None)
if hasattr(namespace, "rope_scaling"):
if namespace.rope_scaling is None:
delattr(namespace, "rope_scaling")
additional_config["fp32_router_logits"] = True
if additional_config:
namespace.additional_config = additional_config
return namespace
@@ -1,9 +1,8 @@
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
import verifiers.v1 as vf
from pydantic import AliasChoices, Field, model_validator
from pydantic import Field, SerializeAsAny, model_validator
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.algorithm import (
@@ -15,22 +14,18 @@ from prime_rl.configs.shared import (
ClientConfig,
EnvVars,
FileMonitorConfig,
FileSystemTransportConfig,
HeartbeatConfig,
LogConfig,
PrimeMonitorConfig,
ResumeConfig,
TransportConfig,
WandbWithExtrasConfig,
ZMQTransportConfig,
)
from prime_rl.configs.trainer import TokenizerConfig
from prime_rl.utils.config import BaseConfig
class OptimizerConfig(BaseConfig):
lr: float = Field(1e-4, ge=0)
"""Learning rate for this run (per-run override for multi-run training)."""
class LoRAConfig(BaseConfig):
name: str | None = None
"""LoRA adapter name. If None, auto-generated from rank and alpha."""
@@ -54,9 +49,7 @@ class TrainSamplingConfig(BaseConfig):
temperature: float = Field(1.0, ge=0, le=2.0)
"""Sampling temperature."""
max_completion_tokens: int | None = Field(
None, validation_alias=AliasChoices("max_completion_tokens", "max_tokens")
)
max_completion_tokens: int | None = None
"""Maximum output tokens per turn. If None, generates until max context length or EOS."""
# Strictly speaking, extra_body is not a sampling parameter, but it is the
@@ -79,18 +72,6 @@ class TrainSamplingConfig(BaseConfig):
return args
@model_validator(mode="before")
@classmethod
def _deprecate_max_tokens(cls, data: Any) -> Any:
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
warnings.warn(
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
return data
class EvalSamplingConfig(BaseConfig):
temperature: float | None = Field(None, ge=0, le=2.0)
@@ -105,9 +86,7 @@ class EvalSamplingConfig(BaseConfig):
min_p: float | None = Field(None, ge=0)
"""Min-p sampling threshold. None defers to the inference server default."""
max_completion_tokens: int | None = Field(
None, validation_alias=AliasChoices("max_completion_tokens", "max_tokens")
)
max_completion_tokens: int | None = None
"""Maximum output tokens per turn. None defers to the inference server default."""
reasoning_effort: Literal["minimal", "low", "medium", "high"] | None = None
@@ -138,40 +117,32 @@ class EvalSamplingConfig(BaseConfig):
return args
@model_validator(mode="before")
@classmethod
def _deprecate_max_tokens(cls, data: Any) -> Any:
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
warnings.warn(
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
return data
class EnvConfig(BaseConfig):
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
runs, ``serve`` — how it's hosted) plus this orchestrator's own per-env knobs."""
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
"""The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
serve: vf.ServeConfig = vf.ServeConfig()
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config with an unset ``address`` filled in as the derived ``tcp://127.0.0.1:<env_server_base_port + index>``. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
class EnvConfig(vf.EnvServerConfig):
name: str | None = None
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
address: str | None = None
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically. The ``pool`` sizes the spawned server."""
ratio: float = Field(1.0, gt=0)
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
@model_validator(mode="before")
@classmethod
def _migrate_num_workers(cls, data):
"""Back-compat: the removed ``num_workers`` maps onto ``pool`` — an int becomes a
fixed ``static`` pool, ``"auto"`` falls through to the default ``elastic`` pool. An
explicit ``pool`` always wins."""
if isinstance(data, dict) and "num_workers" in data:
num_workers = data.pop("num_workers")
if "pool" not in data and num_workers != "auto":
data["pool"] = {"type": "static", "num_workers": num_workers}
return data
def _resolve_env(cls, data):
"""Narrow ``env`` to the selected env's config class."""
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
@property
def env_id(self) -> str:
return self.env.env_id or ""
@property
def resolved_name(self) -> str:
@@ -180,37 +151,19 @@ class EnvConfig(vf.EnvServerConfig):
@model_validator(mode="after")
def validate_env(self):
if not self.env_id:
raise ValueError(
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or id = "<id>" (v0/legacy)'
)
raise ValueError('no env configured — set env = { taskset = { id = "<id>" } }')
if self.resolved_name == "agg":
raise ValueError(
'Environment name "agg" is reserved for cross-env metric aggregation. Use a different name or id.'
)
return self
@model_validator(mode="after")
def resolve_legacy_env_kwargs(self):
"""For a v0/legacy env, surface the v1 knobs the legacy bridge applies via
``extra_env_kwargs`` (``env.set_kwargs(...)``): the per-rollout wall-clock timeout and
the multi-turn completion-token budget, read off ``env.agent``. (``max_seq_len`` is
added per train run in ``OrchestratorConfig.resolve_env_config``, which knows
``seq_len``.)"""
if self.is_legacy:
agent = getattr(self.env, "agent", None)
if agent is not None:
if agent.timeout.rollout is not None:
self.extra_env_kwargs["timeout_seconds"] = agent.timeout.rollout
if agent.max_output_tokens is not None:
self.extra_env_kwargs["max_total_completion_tokens"] = agent.max_output_tokens
return self
class TrainEnvConfig(EnvConfig):
class TrainSourceConfig(EnvConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
group_size: int = Field(1, ge=1)
"""Rollouts generated per example for GRPO group-relative advantages.
Inherits from ``orchestrator.group_size`` when unset."""
@@ -220,14 +173,14 @@ class TrainEnvConfig(EnvConfig):
this env its own algorithm."""
class EvalEnvConfig(EnvConfig):
class EvalSourceConfig(EnvConfig):
sampling: EvalSamplingConfig = EvalSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
num_examples: int = -1
"""Eval examples to sample from the dataset. ``-1`` uses all available examples."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
group_size: int = Field(1, ge=1)
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8)."""
interval: int = Field(100, ge=1)
@@ -235,8 +188,8 @@ class EvalEnvConfig(EnvConfig):
class TrainConfig(BaseConfig):
env: list[TrainEnvConfig] = Field(default_factory=list)
"""Training environments."""
source: list[TrainSourceConfig] = Field(default_factory=list)
"""Training sources."""
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
@@ -246,7 +199,7 @@ class TrainConfig(BaseConfig):
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
is configured per env, defaulting to elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.env:
for env in self.source:
if "sampling" not in env.model_fields_set:
env.sampling = TrainSamplingConfig(**group_sampling)
else:
@@ -256,7 +209,7 @@ class TrainConfig(BaseConfig):
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [env.resolved_name for env in self.env]
env_names = [env.resolved_name for env in self.source]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(
@@ -266,8 +219,8 @@ class TrainConfig(BaseConfig):
class EvalConfig(BaseConfig):
env: list[EvalEnvConfig] = Field(default_factory=list)
"""Evaluation environments."""
source: list[EvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources."""
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
"""Shared eval sampling configuration; can differ from training sampling."""
@@ -275,7 +228,7 @@ class EvalConfig(BaseConfig):
num_examples: int = -1
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
group_size: int = Field(1, ge=1)
"""Default rollouts per example. Can be overridden per env."""
interval: int = Field(100, ge=1)
@@ -285,38 +238,43 @@ class EvalConfig(BaseConfig):
"""If True, skip the startup eval that otherwise runs before any
train rollouts."""
retrigger_on_resume: bool = False
"""If True, re-trigger evals at the checkpoint step on resume (e.g. after a
crash that left in-flight evals unfinished). By default, assumes a clean
exit where all evals already completed."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.env:
if "sampling" not in env.model_fields_set:
env.sampling = EvalSamplingConfig(**group_sampling)
for source in self.source:
if "sampling" not in source.model_fields_set:
source.sampling = EvalSamplingConfig(**group_sampling)
else:
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
env.sampling = EvalSamplingConfig(**merged)
if "num_examples" not in env.model_fields_set:
env.num_examples = self.num_examples
if "group_size" not in env.model_fields_set:
env.group_size = self.group_size
if "interval" not in env.model_fields_set:
env.interval = self.interval
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
source.sampling = EvalSamplingConfig(**merged)
if "num_examples" not in source.model_fields_set:
source.num_examples = self.num_examples
if "group_size" not in source.model_fields_set:
source.group_size = self.group_size
if "interval" not in source.model_fields_set:
source.interval = self.interval
return self
@model_validator(mode="after")
def validate_non_empty_envs(self):
if not self.env:
def validate_non_empty_sources(self):
if not self.source:
raise ValueError(
"EvalConfig must define at least one env. Either drop the "
"EvalConfig must define at least one source. Either drop the "
"[orchestrator.eval] block entirely (to disable eval) or "
"add a [[orchestrator.eval.env]] block."
"add a [[orchestrator.eval.source]] block."
)
return self
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [env.resolved_name for env in self.env]
env_names = [source.resolved_name for source in self.source]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(
@@ -329,11 +287,8 @@ class CheckpointConfig(BaseConfig):
interval: int | None = Field(None, ge=1)
"""Step interval at which to save the orchestrator checkpoint."""
resume_step: int | None = Field(None, ge=-1)
"""Step to resume the orchestrator from. None starts from scratch; ``-1`` resumes from the latest checkpoint available."""
wait_for_weights_timeout: int | None = Field(None, ge=1)
"""When resuming, wait up to this many seconds for the weight directory to appear. Useful when the orchestrator restarts while the trainer is still saving weights. If None, fail immediately when weights are not found."""
"""Wait up to this many seconds for the startup weight directory to appear (the trainer broadcasts the incoming policy — v0 from scratch, the resumed step's version on resume — before the first step). If None, fall back to a default timeout. Raise this for large models on slow shared filesystems."""
keep_last: int | None = Field(None, ge=1)
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
@@ -437,7 +392,7 @@ class OrchestratorConfig(BaseConfig):
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
assignment and loss routing, fused — its ``type`` names the algorithm).
Defaults to ``grpo``. Override per env via ``[[orchestrator.train.env]]``'s
Defaults to ``grpo``. Override per source via ``[[orchestrator.train.source]]``'s
``algo``."""
model: ModelConfig = ModelConfig()
@@ -456,14 +411,6 @@ class OrchestratorConfig(BaseConfig):
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. RL/OPD roll out through the renderer
client; SFT uses it to backfill tokens for its chat-completions teacher."""
pool_size: int | None = Field(None, ge=1)
"""Number of renderer slots shared across concurrent rollouts. Bump
for long multi-turn prompts where client-side jinja tokenization
serializes."""
optim: OptimizerConfig = OptimizerConfig()
"""Per-run optimizer configuration for multi-run training."""
eval: EvalConfig | None = None
"""Evaluation configuration."""
@@ -504,19 +451,25 @@ class OrchestratorConfig(BaseConfig):
"""Role for each policy admin client when collecting P/D inference metrics."""
ckpt: CheckpointConfig | None = None
resume: ResumeConfig | None = None
"""Resume the orchestrator from a checkpoint. None starts from scratch; an empty block resumes from the latest checkpoint, ``resume.step`` from that step, ``resume.dir`` from an external checkpoint step directory. Without ``ckpt`` the run loads but saves no new checkpoints."""
"""Checkpoint configuration."""
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
"""Transport used to receive updated weights from the trainer."""
rollout_transport: TransportConfig = FileSystemTransportConfig()
rollout_transport: TransportConfig = ZMQTransportConfig()
"""Transport used to ship rollouts from orchestrator to trainer."""
output_dir: Path = Path("outputs/run_default")
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Rate limit per environment worker, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. With multiple workers, the effective total rate is ``workers × this value``. None disables rate limiting."""
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the source at position ``i`` (train, then eval) is served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address`` keep it instead, without shifting the other sources' ports (indices stay positional). Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
batch_size: int | None = Field(None, ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
@@ -525,20 +478,22 @@ class OrchestratorConfig(BaseConfig):
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
oversampling_factor: float | None = Field(None, gt=0)
"""Rollout-mode batching only. Multiplier used to derive ``max_inflight_rollouts`` from ``batch_size`` when ``max_inflight_rollouts`` is unset. Values below 1.0 intentionally cap in-flight rollout capacity below ``batch_size``."""
"""Rollout-mode batching only. Multiplier used to derive ``max_inflight_episodes`` from ``batch_size`` when ``max_inflight_episodes`` is unset. Values below 1.0 intentionally cap in-flight episode capacity below ``batch_size``."""
max_inflight_rollouts: int | None = Field(None, ge=1)
"""Maximum number of rollouts kept in-flight. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
max_inflight_episodes: int | None = Field(None, ge=1)
"""Maximum number of episodes kept in-flight — one episode is one agent run at a time, whatever the env's agents are. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
group_size: int = Field(1, ge=1)
"""Output sequences returned per example during training."""
seq_len: int = 2048
"""Training sequence length. Shorter samples are padded; longer samples are truncated."""
# TODO(Mika): This should be automatic from the number of ZMQ connections
num_train_workers: int = Field(1, ge=1)
"""Training workers to use."""
"""Trainer data-parallel world size (trainer world size // cp). The orchestrator packs one micro-batch list per DP rank, so this must match the trainer topology. Auto-filled by the ``rl`` entrypoint; set explicitly for standalone orchestrator runs."""
pad_to_multiple_of: int = Field(1, ge=1)
"""Pad each packed micro batch to a multiple of this value (the trainer's cp degree). Auto-filled by the ``rl`` entrypoint; set explicitly for standalone orchestrator runs with cp > 1."""
max_steps: int | None = None
"""Maximum training steps. If None, runs indefinitely."""
@@ -552,33 +507,6 @@ class OrchestratorConfig(BaseConfig):
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
@model_validator(mode="before")
@classmethod
def _env_to_train(cls, data: Any) -> Any:
"""Allow [[env]] and [sampling] as shorthand for [train] with [[train.env]] and [train.sampling]."""
if not isinstance(data, dict):
return data
if "env" in data or "sampling" in data:
train = data.setdefault("train", {})
if isinstance(train, dict):
if "env" in data:
warnings.warn(
"'[[orchestrator.env]]' is deprecated, use '[[orchestrator.train.env]]' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
train.setdefault("env", data.pop("env"))
if "sampling" in data:
warnings.warn(
"'[orchestrator.sampling]' is deprecated, use '[orchestrator.train.sampling]' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
train.setdefault("sampling", data.pop("sampling"))
return data
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
@@ -617,31 +545,23 @@ class OrchestratorConfig(BaseConfig):
def inherit_env_algorithms(self):
"""Envs without their own algorithm inherit the top-level one.
Declared before any validator that reads ``algo``."""
for env_cfg in self.train.env:
for env_cfg in self.train.source:
if env_cfg.algo is None:
env_cfg.algo = self.algo.model_copy(deep=True)
return self
@model_validator(mode="after")
def validate_env_algorithms(self):
"""Let each algorithm reject environments it cannot score correctly."""
for env_cfg in self.train.source:
assert env_cfg.algo is not None # resolved by inherit_env_algorithms
env_cfg.algo.validate_env(env_cfg.env)
return self
@property
def any_policy_sourced(self) -> bool:
"""True when at least one train env samples rollouts from the live policy."""
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.env)
@model_validator(mode="after")
def validate_pool_size(self):
"""``pool_size`` sizes the renderer-client pool for policy-sourced
sampling. Reject it when that path never runs — no train env samples
from the policy — so callers don't silently pass it and wonder why
it's ignored."""
if self.pool_size is None:
return self
if not self.any_policy_sourced:
raise ValueError(
f"orchestrator.pool_size={self.pool_size!r} is set but no train env samples "
"from the policy — the renderer-client sampling pool never runs (the renderer "
"is still used for client-side tokenization). Remove pool_size."
)
return self
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.source)
@model_validator(mode="after")
def validate_renderer_auto_resolves(self):
@@ -691,29 +611,29 @@ class OrchestratorConfig(BaseConfig):
if has_token_batch:
if self.oversampling_factor is not None:
raise ValueError("oversampling_factor can only be set when batch_size is set")
if self.max_inflight_rollouts is None:
raise ValueError("max_inflight_rollouts must be set when token_batch_size is set")
if self.max_inflight_episodes is None:
raise ValueError("max_inflight_episodes must be set when token_batch_size is set")
else:
assert self.batch_size is not None
if self.batch_size % self.group_size != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
resolved_max_inflight_rollouts = max(
resolved_max_inflight_episodes = max(
self.group_size,
int(self.batch_size * oversampling_factor),
)
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
expected_max_inflight_rollouts = resolved_max_inflight_rollouts
if self.max_inflight_rollouts != expected_max_inflight_rollouts:
raise ValueError("max_inflight_rollouts conflicts with oversampling_factor * batch_size")
if self.max_inflight_rollouts is None:
self.max_inflight_rollouts = resolved_max_inflight_rollouts
if self.max_inflight_episodes is not None and self.oversampling_factor is not None:
expected_max_inflight_episodes = resolved_max_inflight_episodes
if self.max_inflight_episodes != expected_max_inflight_episodes:
raise ValueError("max_inflight_episodes conflicts with oversampling_factor * batch_size")
if self.max_inflight_episodes is None:
self.max_inflight_episodes = resolved_max_inflight_episodes
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.group_size:
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
if self.max_inflight_episodes is not None and self.max_inflight_episodes < self.group_size:
raise ValueError("max_inflight_episodes must be at least the number of rollouts per example")
# Propagate the top-level ``group_size`` into each train env that didn't set its own.
for env_cfg in self.train.env:
for env_cfg in self.train.source:
if "group_size" not in env_cfg.model_fields_set:
env_cfg.group_size = self.group_size
@@ -735,8 +655,8 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_config(self):
"""Set vLLM sampling defaults + legacy env kwargs on each train env from top-level fields."""
for env in self.train.env:
"""Set vLLM sampling defaults on each train env from top-level fields."""
for env in self.train.source:
# Policy-sourced rollouts hit our vLLM server; frozen-sourced
# rollouts may hit external OAI endpoints that reject these knobs.
assert env.algo is not None
@@ -744,8 +664,27 @@ class OrchestratorConfig(BaseConfig):
env.sampling.extra_body.setdefault("top_k", -1)
env.sampling.extra_body.setdefault("min_p", 0.0)
env.sampling.extra_body.setdefault("return_token_ids", True)
if env.is_legacy:
# v0 env: cap per-turn response tokens to the training budget (the legacy
# bridge applies extra_env_kwargs via env.set_kwargs).
env.extra_env_kwargs["max_seq_len"] = self.seq_len
return self
@property
def env_sources(self) -> list[tuple[str, EnvConfig]]:
"""Every ``(split, source)`` this run pulls from, train first then eval — the
order that fixes each source's deterministic env-server port."""
sources: list[tuple[str, EnvConfig]] = [("train", source) for source in self.train.source]
if self.eval is not None:
sources += [("eval", source) for source in self.eval.source]
return sources
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each source's env server lives, keyed by ``(split, resolved_name)``:
the source's own ``serve.address`` when set (an externally managed server), else
``tcp://127.0.0.1:<port>`` with ports from ``env_server_base_port`` in
``env_sources`` order. The launcher binds env servers at exactly these addresses
and the orchestrator connects to them, so both sides agree from the config
alone."""
return {
(split, source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, (split, source) in enumerate(self.env_sources)
}
@@ -1,3 +1,4 @@
import uuid
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
@@ -21,7 +22,10 @@ from prime_rl.configs.orchestrator import (
from prime_rl.configs.shared import (
EnvVars,
FileMonitorConfig,
ResumeConfig,
RunConfig,
SlurmConfig,
TransportConfig,
VLMConfig,
)
from prime_rl.configs.trainer import (
@@ -45,7 +49,6 @@ from prime_rl.utils.validation import (
validate_shared_ckpt_config,
validate_shared_max_steps,
validate_shared_model_name,
validate_shared_output_dir,
validate_shared_seq_len,
validate_shared_tokenizer,
validate_shared_wandb_config,
@@ -99,9 +102,6 @@ class SharedCheckpointConfig(BaseConfig):
interval: int | None = None
"""Interval at which to save checkpoints."""
resume_step: int | None = None
"""Step to resume from. If None, does not resume from a checkpoint."""
keep_last: int | None = Field(None, ge=1)
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
@@ -221,16 +221,34 @@ class RLConfig(BaseConfig):
orchestrator: OrchestratorConfig
inference: InferenceConfig | None = None
"""Inference server configuration. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."""
"""Inference server configuration. If None, the rl entrypoint will not start an inference server (useful for manually started servers)."""
env_vars: EnvVars = {}
"""Extra environment variables for every launched RL component. Component-specific env_vars override these."""
output_dir: Path = Path("outputs")
"""Output directory. Should be unique per experiment."""
run: RunConfig = Field(default_factory=RunConfig)
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
clean_output_dir: bool = False
"""Delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming."""
output_dir: Path = Path("outputs")
"""Directory that groups related runs. Each run writes its artifacts to ``output_dir / run.name``."""
clean: bool = False
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
@property
def run_dir(self) -> Path:
assert self.run.dir is not None # resolved at construction
return self.output_dir / self.run.dir
def _resolve_run_name(self) -> None:
"""Fill the auto-generated run name and directory (idempotent — called by every
validator that reads them, so it does not depend on validator ordering)."""
if self.run.name is None:
envs = "+".join(dict.fromkeys(source.resolved_name for source in self.orchestrator.train.source))
model = self.trainer.model.name.split("/")[-1]
self.run.name = f"{envs or 'no-env'}--{model}--{uuid.uuid4().hex[:8]}".lower()
if self.run.dir is None:
self.run.dir = self.run.name
### Shared configurations
@@ -240,6 +258,9 @@ class RLConfig(BaseConfig):
ckpt: SharedCheckpointConfig | None = None
"""Shared checkpoint config. If None, falls back to the sub-config checkpoint settings."""
resume: ResumeConfig | None = None
"""Resume the run from a checkpoint (point at it with the previous run's ``run.name``). Without ``[ckpt]`` the run loads the checkpoint but saves no new ones. If None, does not resume."""
wandb: SharedWandbConfig | None = None
"""Shared W&B config. If None, falls back to the sub-config W&B settings."""
@@ -260,6 +281,8 @@ class RLConfig(BaseConfig):
weight_broadcast: SharedWeightBroadcastConfig | None = None
rollout_transport: TransportConfig | None = None
bench: bool = False
"""Benchmark mode. Sets trainer and orchestrator to benchmark mode and, when set, suffixes the W&B project with ``-bench``."""
@@ -357,12 +380,58 @@ class RLConfig(BaseConfig):
"""
return propagate_shared_fields(data)
@model_validator(mode="after")
def auto_setup_run_dir(self):
"""Point trainer and orchestrator at the run directory (``output_dir / run.name``).
The sub-configs' ``output_dir`` is fully derived here: sub-processes spawned by
the launcher receive the resolved run directory and never re-derive it.
"""
self._resolve_run_name()
run_dir = self.run_dir
for sub in (self.trainer, self.orchestrator):
if "output_dir" in sub.model_fields_set and sub.output_dir != run_dir:
raise ValueError(
f"{type(sub).__name__}.output_dir ({sub.output_dir}) conflicts with the run directory "
f"({run_dir}). Under the rl entrypoint, sub-config output directories are derived from "
"output_dir / run.name — set those instead."
)
sub.output_dir = run_dir
return self
@model_validator(mode="after")
def auto_setup_resume(self):
"""Propagate the top-level resume onto the sub-configs."""
if self.resume is None:
return self
self.trainer.resume = self.resume.model_copy()
self.orchestrator.resume = self.resume.model_copy()
return self
@model_validator(mode="after")
def auto_setup_run_identity(self):
"""Default the W&B and Prime platform run names to ``run.name``.
Explicit names always win: only unset names inherit. Runs after the
orchestrator's own ``auto_setup_prime_monitor_run_name``, so an explicitly
set W&B name still takes precedence for the platform run name. The run
identity itself is runtime-only ($PRL_RUN_ID / $PRL_RUN_NAME, set by the
``rl`` entrypoint), never sub-config.
"""
self._resolve_run_name()
for wandb in (self.wandb, self.trainer.wandb, self.orchestrator.wandb):
if wandb is not None and wandb.name is None:
wandb.name = self.run.name
prime_monitor = self.orchestrator.prime_monitor
if prime_monitor is not None and prime_monitor.run_name is None:
prime_monitor.run_name = self.run.name
return self
### Validate shared configs (after sub-config construction)
@model_validator(mode="after")
def validate_shared_configs(self):
"""Validate consistency of shared configs across trainer, orchestrator, and inference."""
validate_shared_output_dir(self.trainer, self.orchestrator)
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
validate_shared_tokenizer(self.trainer, self.orchestrator, self.inference)
validate_shared_max_steps(self.trainer, self.orchestrator)
@@ -390,7 +459,11 @@ class RLConfig(BaseConfig):
"Set weight_broadcast.type = 'filesystem'."
)
if self.weight_broadcast.type in ("nccl", "nixl"):
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
inference_world_size = (
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
if self.inference
else 1
)
common_config = dict(
host=self.weight_broadcast.host,
port=self.weight_broadcast.port,
@@ -419,16 +492,38 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def auto_setup_rollout_transport(self):
"""Resolve the shared ``rollout_transport`` from the sub-configs so the launcher can
gate multi-node ZMQ host injection on it (mirrors ``auto_setup_weight_broadcast``).
``rollout_transport`` may be set either as the shared block (propagated down to both
sub-configs by ``propagate_shared_fields``) or directly on
``trainer.rollout_transport`` / ``orchestrator.rollout_transport`` (the documented
fallback). Either way the shared field must reflect the resolved per-component
transport, otherwise the launcher would leave ZMQ trainers connecting to localhost.
"""
if self.trainer.rollout_transport.type != self.orchestrator.rollout_transport.type:
raise ValueError(
"trainer.rollout_transport.type "
f"({self.trainer.rollout_transport.type!r}) != orchestrator.rollout_transport.type "
f"({self.orchestrator.rollout_transport.type!r}); set the shared [rollout_transport] "
"block or make both sub-configs the same type."
)
if self.rollout_transport is None:
self.rollout_transport = self.trainer.rollout_transport
return self
@model_validator(mode="after")
def validate_eplb_requires_quantized_weight_transfer(self):
if self.inference is None or not self.inference.enable_eplb:
if self.inference is None or not self.inference.vllm.enable_eplb:
return self
# TODO(matej): check if weight reloading works itself before supporting EPLB without quantized transfer.
trainer_weight_broadcast = self.trainer.weight_broadcast
if trainer_weight_broadcast.type != "nccl" or not trainer_weight_broadcast.quantize_in_weight_transfer:
raise ValueError(
"inference.enable_eplb requires weight_broadcast.type = 'nccl' and "
"inference.vllm.enable_eplb requires weight_broadcast.type = 'nccl' and "
"weight_broadcast.quantize_in_weight_transfer = true."
)
@@ -492,8 +587,8 @@ class RLConfig(BaseConfig):
)
if self.inference is not None:
self.inference.enable_lora = True
self.inference.max_lora_rank = self.trainer.model.lora.rank
self.inference.vllm.enable_lora = True
self.inference.vllm.max_lora_rank = self.trainer.model.lora.rank
else:
warnings.warn(
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
@@ -507,12 +602,12 @@ class RLConfig(BaseConfig):
def auto_setup_router_replay(self):
if self.trainer.enable_router_replay:
if self.inference is not None:
if self.inference.enable_return_routed_experts is False:
if self.inference.vllm.enable_return_routed_experts is False:
warnings.warn(
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True.",
"Router replay is enabled, but inference.vllm.enable_return_routed_experts is False. Setting to True.",
stacklevel=2,
)
self.inference.enable_return_routed_experts = True
self.inference.vllm.enable_return_routed_experts = True
else:
warnings.warn(
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server.",
@@ -528,17 +623,23 @@ class RLConfig(BaseConfig):
``trainer.enable_router_replay`` path, which sets the inference flag here
(after InferenceConfig's own validators, which therefore miss it).
"""
if self.inference is not None and self.inference.enable_return_routed_experts:
router = getattr(self.inference.deployment, "router", None)
if self.inference is not None and self.inference.vllm.enable_return_routed_experts:
router = self.inference.router
if router is not None and router.type == "llm-d":
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(inference.enable_return_routed_experts / trainer.enable_router_replay): it "
"(inference.vllm.enable_return_routed_experts / trainer.enable_router_replay): it "
"breaks P/D and is unverified for multi-node. Use router type 'vllm-router' "
"for router-replay runs."
)
return self
@model_validator(mode="after")
def validate_multi_node_requires_router(self):
if self.deployment.type == "multi_node" and self.inference is not None and self.inference.router is None:
raise ValueError("Multi-node deployments require inference.router to front the per-rank engines.")
return self
@model_validator(mode="after")
def validate_router_replay_without_kv_offload(self):
if (
@@ -568,6 +669,7 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_deployment(self):
self.orchestrator.pad_to_multiple_of = self.trainer.model.cp
if self.deployment.type == "single_node": # single-node
# set num_train_workers to the number of data replicas
non_data_parallel_size = self.trainer.model.cp
@@ -577,20 +679,22 @@ class RLConfig(BaseConfig):
# fill up inference capacity with dp ranks
if self.inference is not None:
num_infer_gpus = self.deployment.num_infer_gpus
if num_infer_gpus != self.inference.parallel.dp * self.inference.parallel.tp:
assert num_infer_gpus % self.inference.parallel.tp == 0, (
if num_infer_gpus != self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size:
assert num_infer_gpus % self.inference.vllm.tensor_parallel_size == 0, (
"Number of inference GPUs must be divisible by the tensor parallel size"
)
self.inference.parallel.dp = num_infer_gpus // self.inference.parallel.tp
self.inference.vllm.data_parallel_size = num_infer_gpus // self.inference.vllm.tensor_parallel_size
# Ensure api_server_count matches DP so all workers are created.
# Without this, in-memory weight transfer expects dp*tp workers
# but only api_server_count*tp exist, causing a deadlock.
dp = self.inference.parallel.dp
if self.inference.api_server_count < dp and not self.inference.enable_lora:
self.inference.api_server_count = dp
dp = self.inference.vllm.data_parallel_size
if self.inference.vllm.api_server_count < dp and not self.inference.vllm.enable_lora:
self.inference.vllm.api_server_count = dp
elif self.deployment.type == "multi_node": # multi-node
self.orchestrator.num_train_workers = self.deployment.num_train_nodes * self.deployment.gpus_per_node
self.orchestrator.num_train_workers = (
self.deployment.num_train_nodes * self.deployment.gpus_per_node // self.trainer.model.cp
)
if self.deployment.nodes_per_fsdp_group is not None:
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
@@ -604,35 +708,38 @@ class RLConfig(BaseConfig):
if (
self.inference is not None
and self.inference.enable_expert_parallel
and self.inference.vllm.enable_expert_parallel
and self.inference.deployment.type != "disaggregated"
):
inference_tp = self.inference.parallel.tp
inference_tp = self.inference.vllm.tensor_parallel_size
if self.deployment.gpus_per_node % inference_tp != 0:
raise ValueError(
"deployment.gpus_per_node must be divisible by inference.parallel.tp "
"when inference.enable_expert_parallel is enabled in multi-node deployment."
"deployment.gpus_per_node must be divisible by inference.vllm.tensor_parallel_size "
"when inference.vllm.enable_expert_parallel is enabled in multi-node deployment."
)
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
total_infer_gpus = self.deployment.infer_nodes_per_replica * self.deployment.gpus_per_node
expected_global_world_size = self.inference.parallel.dp * inference_tp
expected_global_world_size = self.inference.vllm.data_parallel_size * inference_tp
if expected_global_world_size != total_infer_gpus:
raise ValueError(
"For multi-node expert parallel inference, inference.parallel.dp * inference.parallel.tp "
"For multi-node expert parallel inference, inference.vllm.data_parallel_size * inference.vllm.tensor_parallel_size "
f"must match total inference GPUs ({total_infer_gpus}), got {expected_global_world_size}."
)
if self.inference.data_parallel_size_local is None:
self.inference.data_parallel_size_local = inferred_dp_local
elif self.inference.data_parallel_size_local != inferred_dp_local:
if self.inference.vllm.data_parallel_size_local is None:
self.inference.vllm.data_parallel_size_local = inferred_dp_local
elif self.inference.vllm.data_parallel_size_local != inferred_dp_local:
raise ValueError(
"inference.data_parallel_size_local must equal deployment.gpus_per_node / inference.parallel.tp "
f"({inferred_dp_local}) when inference.enable_expert_parallel is enabled in multi-node deployment."
"inference.vllm.data_parallel_size_local must equal deployment.gpus_per_node / inference.vllm.tensor_parallel_size "
f"({inferred_dp_local}) when inference.vllm.enable_expert_parallel is enabled in multi-node deployment."
)
if not self.inference.enable_lora and self.inference.api_server_count == self.inference.parallel.dp:
self.inference.api_server_count = inferred_dp_local
if (
not self.inference.vllm.enable_lora
and self.inference.vllm.api_server_count == self.inference.vllm.data_parallel_size
):
self.inference.vllm.api_server_count = inferred_dp_local
# Auto-infer DP and api_server_count for standard multi-node inference.
# Without EP, vLLM only creates api_server_count * tp workers per node,
@@ -640,16 +747,16 @@ class RLConfig(BaseConfig):
# more workers than exist, deadlocking in-memory transfer initialization.
if (
self.inference is not None
and not self.inference.enable_expert_parallel
and not self.inference.vllm.enable_expert_parallel
and self.inference.deployment.type != "disaggregated"
):
dp_per_node = self.deployment.gpus_per_node // self.inference.parallel.tp
if self.inference.parallel.dp == 1 and dp_per_node > 1:
self.inference.parallel.dp = dp_per_node
if self.inference.data_parallel_size_local is None and dp_per_node > 1:
self.inference.data_parallel_size_local = dp_per_node
if self.inference.api_server_count == 1 and dp_per_node > 1:
self.inference.api_server_count = dp_per_node
dp_per_node = self.deployment.gpus_per_node // self.inference.vllm.tensor_parallel_size
if self.inference.vllm.data_parallel_size == 1 and dp_per_node > 1:
self.inference.vllm.data_parallel_size = dp_per_node
if self.inference.vllm.data_parallel_size_local is None and dp_per_node > 1:
self.inference.vllm.data_parallel_size_local = dp_per_node
if self.inference.vllm.api_server_count == 1 and dp_per_node > 1:
self.inference.vllm.api_server_count = dp_per_node
if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "nixl"):
# Every allocated inference GPU is an in-memory transfer worker.
@@ -690,7 +797,7 @@ class RLConfig(BaseConfig):
# External-LB: one admin client per DP rank, so roles expand per rank
# (stride = dp_local = gpus_per_node / tp). ADMIN_URLS lists all prefill
# ranks, then all decode ranks, per replica — match that order.
stride = self.deployment.gpus_per_node // self.inference.parallel.tp
stride = self.deployment.gpus_per_node // self.inference.vllm.tensor_parallel_size
role_order = ["prefill"] * (infer_deploy.num_prefill_nodes * stride) + ["decode"] * (
infer_deploy.num_decode_nodes * stride
)
@@ -707,27 +814,27 @@ class RLConfig(BaseConfig):
def auto_setup_inference_client(self):
"""Auto-configure the orchestrator policy client from the inference server config.
Direct single-node runs expose all local DP ranks behind one base URL,
so pin logical clients with ``X-data-parallel-rank``. Multi-node SLURM
runs expose a vllm-router URL instead; the router balances across
per-rank backend URLs and forwards request headers, so the orchestrator
must not inject a DP-rank header there. When no train env samples from
the policy (e.g. sft_distill), also set base_url — policy-sourced
algorithms rely on the ClientConfig default (``["http://localhost:8000/v1"]``)
which already matches the auto-launched policy vLLM at inference.server.port = 8000.
When no train env samples from the policy (e.g. sft_distill), set
base_url. Policy-sourced algorithms rely on the ClientConfig default
(``["http://localhost:8000/v1"]``), which already matches the
auto-launched policy router at inference.server.port = 8000.
"""
if self.inference is None:
return self
client = self.orchestrator.model.client
if "dp_rank_count" not in client.model_fields_set:
if self.deployment.type == "multi_node":
client.dp_rank_count = 1
else:
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
if not self.orchestrator.any_policy_sourced and "base_url" not in client.model_fields_set:
host = self.inference.server.host or "localhost"
port = self.inference.server.port
client.base_url = [f"http://{host}:{port}/v1"]
client.base_url = f"http://{host}:{port}/v1"
if (
self.deployment.type == "single_node"
and self.inference.router is not None
and "admin_base_url" not in client.model_fields_set
):
# Admin ops (pause/update_weights/resume) must bypass the router and hit
# the engine directly; multi-node runs get ADMIN_URLS from the sbatch.
host = self.inference.server.host or "localhost"
client.admin_base_url = [f"http://{host}:{self.inference.backend_port}/v1"]
return self
@model_validator(mode="after")
@@ -1,3 +1,4 @@
import uuid
import warnings
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
@@ -10,6 +11,8 @@ from prime_rl.configs.shared import (
EnvVars,
FileMonitorConfig,
HeartbeatConfig,
ResumeConfig,
RunConfig,
SlurmConfig,
TrainerLogConfig,
WandbConfig,
@@ -188,6 +191,9 @@ class SFTConfig(BaseConfig):
ckpt: CheckpointConfig | None = None
resume: ResumeConfig | None = None
"""Resume the run from a checkpoint (point at it with the previous run's ``run.name``). Without ``[ckpt]`` the run loads the checkpoint but saves no new ones. If None, does not resume."""
log: TrainerLogConfig = TrainerLogConfig()
wandb: WandbConfig | None = None
@@ -195,11 +201,34 @@ class SFTConfig(BaseConfig):
file_monitor: FileMonitorConfig | None = None
"""Local JSONL metric sink. If set, metrics are appended to ``<output_dir>/metrics.jsonl``."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
run: RunConfig = Field(default_factory=RunConfig)
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
clean_output_dir: bool = False
"""Delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming."""
output_dir: Path = Path("outputs")
"""Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space."""
clean: bool = False
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
@property
def run_dir(self) -> Path:
assert self.run.dir is not None # resolved at construction
return self.output_dir / self.run.dir
@model_validator(mode="after")
def auto_setup_run_identity(self):
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
default the run directory and W&B run name to it when not set explicitly."""
if self.run.name is None:
dataset = str(getattr(self.data, "name", "")).split("/")[-1]
model = self.model.name.split("/")[-1]
parts = [part for part in (dataset, model) if part]
self.run.name = "--".join([*parts, uuid.uuid4().hex[:8]]).lower()
if self.run.dir is None:
self.run.dir = self.run.name
if self.wandb is not None and self.wandb.name is None:
self.wandb.name = self.run.name
return self
matmul_precision: Literal["highest", "high", "medium"] = "high"
"""Precision for float32 matrix multiplications. ``highest`` is full FP32 (required on ROCm/AMD GPUs to avoid catastrophic precision loss in softmax over large vocabularies). ``high`` enables TF32 on NVIDIA GPUs for a speedup with minor precision tradeoff. See ``torch.set_float32_matmul_precision``."""
@@ -1,4 +1,5 @@
import os
import re
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
@@ -10,7 +11,7 @@ from prime_rl.utils.config import BaseConfig
# and the single shared W&B run. The launcher always sets these last, so allowing them in
# `env_vars` would be a silent no-op (or, on multi-node, a footgun) — reject them instead.
PROTECTED_ENV_VARS = frozenset(
{"CUDA_VISIBLE_DEVICES", "WANDB_SHARED_MODE", "WANDB_SHARED_RUN_ID", "WANDB_SHARED_LABEL"}
{"CUDA_VISIBLE_DEVICES", "PRL_RUN_ID", "PRL_RUN_NAME", "WANDB_RUN_ID", "WANDB_SHARED_MODE", "WANDB_SHARED_LABEL"}
)
@@ -27,6 +28,41 @@ EnvVars: TypeAlias = Annotated[dict[str, str], AfterValidator(reject_protected_e
"""A per-component `env_vars` mapping, validated to not clobber `PROTECTED_ENV_VARS`."""
class RunConfig(BaseConfig):
name: str | None = None
"""Run name. Auto-generated as ``<envs>--<model>--<short-id>`` when unset, so every launch gets a fresh, readable run directory; set an explicit name (e.g. an experiment name) to get a predictable run directory, which is also required to resume a previous run. Unless set explicitly, the W&B run name and the Prime platform run name inherit it."""
dir: str | None = None
"""Run directory name — the run writes all its artifacts to ``output_dir / dir``. Defaults to ``run.name``; set it only when the directory should differ from the display name."""
class ResumeConfig(BaseConfig):
"""Resume the run from a checkpoint. A bare ``--resume`` (or empty ``[resume]`` block)
resumes from the latest checkpoint."""
step: int | None = Field(None, ge=1)
"""Checkpoint step to resume from. None resumes from the latest checkpoint."""
dir: Path | None = None
"""External checkpoint step directory to resume from (e.g. ``other/run/checkpoints/step_50``) — forks another run's checkpoint into this run. Mutually exclusive with ``step``."""
@model_validator(mode="after")
def validate_step_xor_dir(self):
if self.step is not None and self.dir is not None:
raise ValueError(
"resume.step and resume.dir are mutually exclusive — the step is taken from the directory name"
)
if self.dir is not None and not re.fullmatch(r"step_\d+", self.dir.name):
raise ValueError(f"resume.dir must point at a checkpoint step directory (`.../step_<N>`), got '{self.dir}'")
return self
@property
def dir_step(self) -> int:
"""The step encoded in ``dir``'s name (validated to exist)."""
assert self.dir is not None
return int(self.dir.name.removeprefix("step_"))
class SlurmConfig(BaseConfig):
job_name: str = "prime-rl"
"""SLURM job name."""
@@ -108,23 +144,12 @@ class BaseModelConfig(BaseConfig):
"""VLM configuration. Setting this enables vision-language model support."""
class ElasticConfig(BaseConfig):
hostname: str
"""DNS hostname that resolves to inference server IPs."""
port: int = 8000
"""Port that inference servers listen on."""
sync_interval: float = 5.0
"""Seconds between server discovery checks."""
class ClientConfig(BaseConfig):
wait_for_ready_timeout: int = 1800
"""Seconds to wait at startup for the inference pool to become ready. Applies to both the static health check and elastic DNS-based discovery."""
"""Seconds to wait at startup for the inference pool to become ready."""
base_url: list[str] = ["http://localhost:8000/v1"]
"""Base URLs for the OpenAI API. With more than one URL, the client round-robins (chat) completion requests across all servers. Ignored when ``elastic`` is set."""
base_url: str = "http://localhost:8000/v1"
"""Base URL for the OpenAI API. For multi-replica deployments, point this at a router in front of the replicas."""
api_key_var: str = "VLLM_API_KEY"
"""Environment variable name containing the API key, resolved via ``os.getenv``. Can be any string when the server is not protected by an API key; the same key is used for every URL."""
@@ -141,22 +166,8 @@ class ClientConfig(BaseConfig):
skip_model_check: bool = False
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
dp_rank_count: int = Field(1, ge=1)
"""Number of data-parallel ranks behind each base URL. When > 1, each URL is expanded into ``dp_rank_count`` logical clients pinned via the ``X-data-parallel-rank`` header, so every request within a rollout hits the same DP engine and reuses KV cache. Auto-set from the inference config when using the RL entrypoint."""
admin_base_url: list[str] | None = None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in disaggregated P/D deployments where the router must not handle admin traffic."""
elastic: ElasticConfig | None = None
"""Elastic inference pool config for DNS-based service discovery. When set, ``base_url`` is ignored and inference servers are discovered dynamically via DNS."""
router_url: str | None = None
"""vllm-router URL for load-aware inference routing. With elastic mode, inference requests go through the router while admin ops still hit discovered pods directly."""
@property
def is_elastic(self) -> bool:
"""Check if elastic mode is enabled."""
return self.elastic is not None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in multi-replica or disaggregated P/D deployments where the router must not handle admin traffic."""
class LogConfig(BaseConfig):
@@ -8,12 +8,13 @@ from prime_rl.configs.shared import (
BaseModelConfig,
EnvVars,
FileMonitorConfig,
FileSystemTransportConfig,
HeartbeatConfig,
MetricsServerConfig,
ResumeConfig,
TrainerLogConfig,
TransportConfig,
WandbConfig,
ZMQTransportConfig,
)
from prime_rl.utils.config import BaseConfig
@@ -431,9 +432,6 @@ class CheckpointConfig(BaseConfig):
weights_only: bool = False
"""Save only weight checkpoints (no optimizer/scheduler state). Much faster and smaller than full checkpoints, but cannot resume training."""
resume_step: int | None = Field(None, ge=-1)
"""Step to resume training from. None starts from scratch; ``-1`` restarts from the latest checkpoint available."""
keep_last: int | None = Field(None, ge=1)
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
@@ -577,12 +575,15 @@ class TrainerConfig(BaseConfig):
scheduler: SchedulerConfig = ConstantSchedulerConfig()
ckpt: CheckpointConfig | None = None
resume: ResumeConfig | None = None
"""Resume training from a checkpoint. None starts from scratch; an empty block resumes from the latest checkpoint, ``resume.step`` from that step, ``resume.dir`` from an external checkpoint step directory. Without ``ckpt`` the run loads but saves no new checkpoints."""
"""Full training-state checkpoint configuration (model + optimizer + scheduler). If None, no resume-capable checkpoints are written."""
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
"""Transport used to broadcast updated weights from trainer to inference."""
rollout_transport: TransportConfig = FileSystemTransportConfig()
rollout_transport: TransportConfig = ZMQTransportConfig()
"""Transport used to ship rollouts from orchestrator to trainer."""
log: TrainerLogConfig = TrainerLogConfig()
@@ -625,9 +626,6 @@ class TrainerConfig(BaseConfig):
metrics_server: MetricsServerConfig | None = None
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
max_concurrent_runs: int = Field(1, ge=1)
"""Maximum number of concurrent runs to allow. If 1, only one run may run at a time."""
enable_token_export: bool = False
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
@@ -702,12 +700,6 @@ class TrainerConfig(BaseConfig):
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
@model_validator(mode="after")
def validate_optim_cpu_offload_single_run(self):
if self.model.optim_cpu_offload and self.max_concurrent_runs > 1:
raise ValueError("Optimizer CPU offload is not supported with max_concurrent_runs > 1")
return self
@model_validator(mode="after")
def validate_lora_broadcast(self):
if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "nixl"):
@@ -6,38 +6,14 @@ from pydantic_config import BaseConfig as BaseConfig # noqa: F401
from pydantic_config import cli # noqa: F401
def to_toml_dict(config: BaseModel, exclude: set[str] | None = None) -> dict:
"""Dump a config to a TOML-serializable dict.
def dump_resolved_config(config: BaseModel, exclude: set[str] | None = None) -> dict:
"""Dump a resolved config for a machine-written JSON artifact.
TOML cannot represent null, so None fields left at their default are dropped
(they re-resolve identically on re-parse) while explicitly-set None fields
are encoded as the string ``"None"``, which ``BaseConfig`` converts back to
``None``. Dropping those too would silently revert explicit None overrides
(e.g. ``--trainer.model.compile None``) to their non-None defaults when the
written config is re-parsed.
Resolved configs are written as JSON, not TOML: JSON keeps nulls, so explicit None
overrides (e.g. ``--trainer.optim.max-norm None``) round-trip exactly on re-parse.
Hand-written configs stay TOML (sparse, commented); the format split is the marker.
"""
return _encode_model(config, config.model_dump(exclude=exclude, mode="json"))
def _encode_model(model: BaseModel, dumped: dict) -> dict:
encoded = {}
for name, value in dumped.items():
if value is None:
if name in model.model_fields_set:
encoded[name] = "None"
continue
encoded[name] = _encode_value(getattr(model, name), value)
return encoded
def _encode_value(attr: Any, value: Any) -> Any:
if isinstance(attr, BaseModel) and isinstance(value, dict):
return _encode_model(attr, value)
if isinstance(value, list) and isinstance(attr, (list, tuple)):
return [_encode_value(a, v) for a, v in zip(attr, value)]
if isinstance(value, dict) and isinstance(attr, dict):
return {k: _encode_value(a, v) for (k, v), a in zip(value.items(), attr.values())}
return "None" if value is None else value
return config.model_dump(exclude=exclude, mode="json")
def find_package_resource(subdir: str) -> Path | None:
@@ -2,12 +2,17 @@ import re
# (regex, parser_name) — first match wins.
TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
# Trinity-Large-Thinking uses the Qwen3-Coder tool format; the rest of the family is Hermes.
(re.compile(r"^arcee-ai/Trinity-Large-Thinking"), "qwen3_coder"),
(re.compile(r"^arcee-ai/Trinity-"), "hermes"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.2"), "deepseek_v32"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.1"), "deepseek_v31"),
(re.compile(r"^zai-org/GLM-4\.5"), "glm45"),
(re.compile(r"^zai-org/GLM-4\.7"), "glm47"),
(re.compile(r"^zai-org/GLM-5"), "glm47"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2"),
(re.compile(r"^openai/gpt-oss"), "openai"),
(re.compile(r"^poolside/Laguna"), "poolside_v1"),
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "qwen3_coder"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3"), "qwen3_coder"),
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
@@ -18,12 +23,17 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
]
REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
# Trinity-Large-Preview doesn't reason; the Thinking/Mini/Nano variants do.
(re.compile(r"^arcee-ai/Trinity-(Large-Thinking|Mini|Nano)"), "deepseek_r1"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.[12]"), "deepseek_r1"),
(re.compile(r"^zai-org/GLM-"), "glm45"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
# openai/gpt-oss has no entry here — vLLM's harmony serving path splits reasoning natively.
(re.compile(r"^poolside/Laguna"), "poolside_v1"),
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3\.5"), "nano_v3"),
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
# Only Qwen3 Thinking models reason — Instruct/base models do not.
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
@@ -68,13 +68,12 @@ def propagate_shared_fields(data: Any) -> Any:
propagate(
"model.name",
"trainer.model.name",
"inference.model.name",
"inference.vllm.model",
"orchestrator.model.name",
)
propagate(
"model.vlm",
"trainer.model.vlm",
"inference.model.vlm",
"orchestrator.model.vlm",
)
@@ -91,7 +90,6 @@ def propagate_shared_fields(data: Any) -> Any:
# ``orchestrator.ckpt`` has no ``output_dir`` field — trainer-only.
propagate("ckpt.output_dir", "trainer.ckpt.output_dir")
propagate("ckpt.interval", "trainer.ckpt.interval", "orchestrator.ckpt.interval")
propagate("ckpt.resume_step", "trainer.ckpt.resume_step", "orchestrator.ckpt.resume_step")
propagate("ckpt.keep_last", "trainer.ckpt.keep_last", "orchestrator.ckpt.keep_last")
propagate("ckpt.keep_interval", "trainer.ckpt.keep_interval", "orchestrator.ckpt.keep_interval")
@@ -109,7 +107,7 @@ def propagate_shared_fields(data: Any) -> Any:
# [file_monitor] leaf. (Bare empty ``[file_monitor]`` block enablement is at the end.)
propagate("file_monitor.filename", "trainer.file_monitor.filename", "orchestrator.file_monitor.filename")
# [tokenizer]. ``chat_template`` also flows to ``inference.model`` (vLLM's
# [tokenizer]. ``chat_template`` also flows to ``inference.vllm`` (vLLM's
# ``--chat-template``); ``name`` and ``trust_remote_code`` can legitimately
# differ between sub-configs (auto-derived from model names, which may
# differ for FP8-quantized inference variants).
@@ -123,9 +121,12 @@ def propagate_shared_fields(data: Any) -> Any:
"tokenizer.chat_template",
"trainer.tokenizer.chat_template",
"orchestrator.tokenizer.chat_template",
"inference.model.chat_template",
"inference.vllm.chat_template",
)
# [rollout_transport] → both sub-configs (host is launcher-injected for zmq multi-node).
propagate("rollout_transport", "trainer.rollout_transport", "orchestrator.rollout_transport")
# Top-level scalars.
propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps")
propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len")
@@ -136,23 +137,7 @@ def propagate_shared_fields(data: Any) -> Any:
# pass (the per-rank inference.toml drops slurm, so each rank still runs locally).
propagate("slurm", "inference.slurm")
# output_dir: orchestrator gets a ``/run_default`` subdir so trainer +
# orchestrator nest under the same experiment root without colliding.
# Conflicts are reported against the *transformed* sub-config value, not
# the raw shared path, so the materialized config round-trips cleanly.
output_dir = get("output_dir")
if output_dir is not None:
expected = {
"trainer.output_dir": output_dir,
"orchestrator.output_dir": f"{output_dir}/run_default",
}
for sub, expected_value in expected.items():
sub_value = get(sub)
if sub_value is not None and sub_value != expected_value:
conflicts.append(("output_dir", sub))
fill(sub, expected_value)
# Cascade trainer.tokenizer.chat_template → inference.model.chat_template
# Cascade trainer.tokenizer.chat_template → inference.vllm.chat_template
# (vLLM ``--chat-template``). Read trainer's value *after* the shared
# propagation above so we cover both:
# - shared ``[tokenizer] chat_template`` (already filled all three above,
@@ -162,7 +147,7 @@ def propagate_shared_fields(data: Any) -> Any:
# would otherwise complain about the missing inference value).
trainer_chat_template = get("trainer.tokenizer.chat_template")
if trainer_chat_template is not None:
fill("inference.model.chat_template", trainer_chat_template)
fill("inference.vllm.chat_template", trainer_chat_template)
# Bare ``[ckpt]`` / ``[wandb]`` block: presence-only signal that enables
# the section with defaults on both sub-configs. Necessary because
@@ -209,9 +194,9 @@ def validate_shared_ckpt_config(
raise ValueError(
f"Trainer checkpoint interval ({trainer.ckpt.interval}) and orchestrator checkpoint interval ({orchestrator.ckpt.interval}) are not the same. Please specify the same checkpoint interval for both."
)
if trainer.ckpt and orchestrator.ckpt and trainer.ckpt.resume_step != orchestrator.ckpt.resume_step:
if trainer.resume != orchestrator.resume:
raise ValueError(
f"Trainer checkpoint resume step ({trainer.ckpt.resume_step}) and orchestrator checkpoint resume step ({orchestrator.ckpt.resume_step}) are not the same. Please specify the same checkpoint resume step for both."
f"Trainer resume ({trainer.resume}) and orchestrator resume ({orchestrator.resume}) are not the same. Please specify the same resume config for both."
)
@@ -222,9 +207,9 @@ def validate_shared_model_name(
) -> None:
# Orchestrator must match inference (it queries the inference server)
if inference is not None:
if inference.model.name != orchestrator.model.name:
if inference.vllm.model != orchestrator.model.name:
raise ValueError(
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
f"Inference model name ({inference.vllm.model}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
"The orchestrator queries the inference server and must use the same model name."
)
return
@@ -237,16 +222,6 @@ def validate_shared_model_name(
)
def validate_shared_output_dir(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.output_dir != orchestrator.output_dir.parent:
raise ValueError(
f"Trainer outputs directory ({trainer.output_dir}) and orchestrator outputs directory parent ({orchestrator.output_dir.parent}) are not the same. Please specify the same outputs directory for both."
)
def validate_shared_wandb_config(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
@@ -307,9 +282,9 @@ def validate_shared_tokenizer(
f"Use the shared [tokenizer] config to set chat_template for both."
)
if inference is not None:
if trainer.tokenizer.chat_template != inference.model.chat_template:
if trainer.tokenizer.chat_template != inference.vllm.chat_template:
raise ValueError(
f"Inference chat_template ({inference.model.chat_template!r}) does not match "
f"Inference chat_template ({inference.vllm.chat_template!r}) does not match "
f"the shared tokenizer chat_template ({trainer.tokenizer.chat_template!r}). "
f"Use the shared [tokenizer] config to set chat_template for all components."
)
+40 -20
View File
@@ -1,6 +1,6 @@
[project]
name = "prime-rl"
version = "0.7.0"
version = "0.8.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
@@ -18,7 +18,7 @@ dependencies = [
"torchaudio",
"torchdata>=0.11.0",
"transformers==5.6.2",
"vllm>=0.24.0",
"vllm>=0.26.0",
"mooncake-transfer-engine>=0.3.10.post2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.2.1",
"verifiers[harbor]>=0.3.1.dev14",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -53,14 +53,19 @@ sft = "prime_rl.entrypoints.sft:main"
inference = "prime_rl.entrypoints.inference:main"
trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
env-server = "prime_rl.orchestrator.env_server.env_server:main"
env-server = "prime_rl.entrypoints.env_server:main"
[project.entry-points."vllm.general_plugins"]
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
[project.optional-dependencies]
# Both wheels are the same flash-attn 2.8.3 / cu128 / torch 2.11 / cp312 build and carry
# sm_80 / sm_90 / sm_100 / sm_120 cubins. `attn="auto"` picks FA4 on sm_100 and FA3 on
# sm_90, so FA2 is the resolved backend on sm_120 (see `_resolve_attn_impl` in
# trainer/model.py).
flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.22/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
]
flash-attn-3 = ["flash_attn_3"]
@@ -123,19 +128,28 @@ override-dependencies = [
"openenv-core",
]
# Environment packages (research-environments + verifiers) are auto-discovered as
# workspace members, so new envs need no per-package registration. Install them
# with `uv sync --all-packages`.
# prime-envs packages are auto-discovered as workspace members, so new
# envs there need no per-package registration. verifiers' example envs are opt-in:
# only the ones prime-rl trains or tests on are listed, so an upstream example with
# conflicting pins can't break the shared lock. Install them with
# `uv sync --all-packages`.
[tool.uv.workspace]
members = [
"deps/research-environments/environments/*/*",
"deps/verifiers/environments/*",
"deps/prime-envs/environments/*/*",
"deps/verifiers/environments/alphabet_sort",
"deps/verifiers/environments/color_codeword",
"deps/verifiers/environments/gsm8k",
"deps/verifiers/environments/kuhn_poker",
"deps/verifiers/environments/proposer_solver",
"deps/verifiers/environments/reverse_text",
"deps/verifiers/environments/wiki_search",
"deps/verifiers/environments/wordle",
]
# tau2-synth-v1 and tau3-bench-v1 pin `tau2` forks/revs that conflict with the
# canonical tau2-bench-v1; a workspace shares one lock, so these can't coexist.
# tau2-synth and tau3-bench pin `tau2` forks/revs that conflict with the
# canonical tau2-bench; a workspace shares one lock, so these can't coexist.
exclude = [
"deps/research-environments/environments/tool_use/tau2_synth_v1",
"deps/research-environments/environments/tool_use/tau3_bench_v1",
"deps/prime-envs/environments/tool_use/tau2_synth",
"deps/prime-envs/environments/tool_use/tau3_bench",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -181,10 +195,8 @@ torchao = false
[tool.uv.sources]
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
# prime-rl depends on the one `verifiers` package (v0 + v1 + the legacy bridge + the built-in v1
# harnesses/tasksets, now bundled in verifiers.v1). v0 envs resolve from
# deps/{verifiers,research-environments}/environments; v1 tasksets (`-v1`) and the `compact`
# example live under deps/{verifiers,research-environments}/environments.
# prime-rl consumes `verifiers.v1` (incl. the built-in harnesses/tasksets); env tasksets
# live under deps/{verifiers,prime-envs}/environments.
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
@@ -200,8 +212,8 @@ vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
@@ -235,13 +247,21 @@ explicit = true
[tool.ruff.lint]
select = ["F", "I"]
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
# jaxtyping writes shapes as string annotations (`Int[Tensor, "batch seq"]`), which ruff reads as
# forward references and reports as syntax errors / undefined names.
[tool.ruff.lint.per-file-ignores]
"src/prime_rl/trainer/model.py" = ["F722", "F821"]
"src/prime_rl/trainer/rl/data.py" = ["F722", "F821"]
"src/prime_rl/trainer/rl/loss.py" = ["F722", "F821"]
"src/prime_rl/trainer/sft/data.py" = ["F722", "F821"]
[tool.ruff.lint.isort]
# `prime_rl` is split across two editable wheels (prime-rl + prime-rl-configs).
# Without this, ruff classifies prime_rl.configs.* as third-party because it
# doesn't live under src/.
known-first-party = ["prime_rl"]
known-third-party = ["verifiers", "renderers", "pydantic_config"]
[tool.ruff]
line-length = 120
-44
View File
@@ -1,44 +0,0 @@
#!/bin/bash
# arm64 post-install fixups: rebuild flash-attn from source for the target GPU.
#
# Why this exists: pyproject.toml sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE to keep
# `uv sync` fast; on x86_64 it pins a prebuilt wheel to fill in the binary, but no
# such wheel exists for aarch64. Without this script, `import flash_attn` fails on
# aarch64 with `ModuleNotFoundError: No module named 'flash_attn_2_cuda'`.
#
# Defaults preserve the existing Docker behavior (sm_100 / GB200). On a host with
# `nvidia-smi` available, the compute capability is auto-detected from the local
# GPU. Override via env vars if needed:
# TORCH_CUDA_ARCH_LIST e.g. 9.0 (Hopper), 10.0 (Blackwell)
# VENV_PATH path to the venv (default: $(pwd)/.venv)
# MAX_JOBS parallel nvcc jobs (default: 4)
set -euo pipefail
if [ -z "${TORCH_CUDA_ARCH_LIST:-}" ]; then
# Try to detect from the local GPU. Tolerate any failure mode (binary missing,
# driver not loaded, Docker buildx without --gpus) and fall back to GB200.
TORCH_CUDA_ARCH_LIST="$(nvidia-smi --query-gpu=compute_cap --format=csv,noheader 2>/dev/null | head -1 | tr -d ' ' || true)"
: "${TORCH_CUDA_ARCH_LIST:=10.0}"
fi
export TORCH_CUDA_ARCH_LIST
VENV_PATH="${VENV_PATH:-$(pwd)/.venv}"
if [ ! -x "$VENV_PATH/bin/python" ]; then
echo "ERROR: no python at $VENV_PATH/bin/python. Run from the project root or set VENV_PATH." >&2
exit 1
fi
export MAX_JOBS="${MAX_JOBS:-4}"
export FLASH_ATTENTION_FORCE_BUILD=TRUE
export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
echo "=== building flash-attn from source (TORCH_CUDA_ARCH_LIST=$TORCH_CUDA_ARCH_LIST, MAX_JOBS=$MAX_JOBS) ==="
echo " target venv: $VENV_PATH"
# Run from /tmp so uv ignores the project's [tool.uv.extra-build-variables],
# which sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and would prevent kernel compilation.
(cd /tmp && uv pip install --python "$VENV_PATH/bin/python" \
"flash-attn==2.8.3" --no-build-isolation --no-binary flash-attn --no-cache --reinstall-package flash-attn)
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
uv pip install --python "$VENV_PATH/bin/python" --reinstall --no-deps \
"flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
-10
View File
@@ -143,16 +143,6 @@ main() {
log_info "Installing pre-commit hooks..."
uv run pre-commit install
# aarch64 has no prebuilt flash-attn wheel; build it from source for the local GPU.
# Without this, `import flash_attn` fails with `ModuleNotFoundError: flash_attn_2_cuda`.
# Run last so no subsequent uv operation (which implicitly syncs against the lockfile)
# rebuilds flash-attn from PyPI with FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and undoes this.
if [ "$(uname -m)" = "aarch64" ]; then
log_info "aarch64 detected: building flash-attn from source (this takes 20-30 minutes)..."
log_warn "Future 'uv sync --all-extras' or 'uv run' will remove this build. Use 'uv sync --inexact' or 'uv run --no-sync' to keep it."
bash scripts/docker-arm64-post-install.sh
fi
log_info "Installation completed!"
}
+35 -11
View File
@@ -19,41 +19,65 @@ uv run rl @ base.toml --trainer @ trainer.toml --trainer.lr 1e-3 # mix
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base.
Naming: CLI uses kebab-case (`--model.max-model-len`); TOML uses snake_case (`max_model_len`).
Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max_model_len`).
## Inspect & validate
```bash
uv run rl --help # all fields and defaults
uv run rl @ rl.toml --dry-run --output-dir /tmp/x # write resolved TOML to /tmp/x/configs
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved configs (JSON) to /tmp/x/check/configs
```
## Validators
Incompatible combinations (e.g. CP requires flash attention) must raise in a `model_validator` at resolve time, not at runtime. When renaming a field, emit a deprecation warning with a migration hint — never silently drop.
Incompatible combinations (e.g. CP requires flash attention) must raise in a `model_validator` at resolve time, not at runtime. When renaming a field, remove the old spelling: no `validation_alias`, no auto-translating `mode="before"` validator. The old key then fails as an unknown key, which is the signal. An alias that stays forever is worse than a break — it never gets retired, and a key whose *meaning* changed silently misconfigures the run.
## Special syntax
**No inline tables** — checked-in configs use `[section]` headers, never `key = { ... }`. Expand `env.taskset = { id = "..." }` to a full-path header (`[orchestrator.train.source.env.taskset]` — subtable headers after a `[[...]]` entry attach to that entry).
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--model.max-model-len None`.
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--vllm.max-model-len None`.
**Lists** — TOML uses array of tables; later config files replace lists wholesale, so overlays must include the full desired list:
```toml
[[orchestrator.train.env]]
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.eval.source]]
name = "reverse-text-eval"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
split = "test"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
```
CLI: `--orchestrator.train.env.0.env.taskset.id reverse-text-v1`.
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text` or `--orchestrator.eval.source.0.env.taskset.id reverse-text`.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--vllm-extra '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
**vLLM pass-through** — `[inference.vllm]` uses vLLM's own argument names (`model`, `tensor_parallel_size`, `data_parallel_size`, `max_model_len`, ...) and forwards *any* key to the vLLM server, typed by prime-rl or not: `[inference.vllm] max_num_seqs = 256`, or `--inference.vllm.max-num-seqs 256` on the CLI. CLI values are JSON-coerced, so dict-valued vLLM args work as `--inference.vllm.compilation-config '{"cudagraph_mode": "NONE"}'`. Non-vLLM knobs (router, deployment, weight broadcast, kv-cache offload, env vars) stay on `[inference]` itself.
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-env override: `[orchestrator.train.env.algo] type = "opd"` (the env assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
@@ -66,7 +90,7 @@ In TOML, an empty section header (`[ckpt]`) does the same.
## RL trainer token exports
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `<run_dir>/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
```toml
enable_token_export = true

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