Compare commits

...
Author SHA1 Message Date
de626e934e chore: bump vllm-router wheel to v0.2.0 (#3274)
First release from the router's rebase onto upstream vllm-project/router
(PrimeIntellect-ai/router#51): upstream v0.1.15+18 with the re-ported
fork features (P/D routed-experts merge validated byte-identical against
a single-engine baseline, model-aware routing, phantom-load fixes,
validation 500->400 rewrite incl. vLLM 0.26 wording, per-run usage
metrics, JWT auth).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 12:36:30 -07:00
e56a8df198 feat!: remove the benchmark mode (#3272)
Remove the --bench flag from all entrypoints (RLConfig, SFTConfig,
TrainerConfig, OrchestratorConfig) along with BenchConfig, the
auto_setup_bench validators, the bench branches in the trainers and
orchestrator, and the rich benchmark table / JSON export helpers.

The benchmark CI keeps working: run_single_benchmark.py now runs a
normal short training (--max-steps, fake data) with the file monitor
enabled and aggregates throughput / MFU / step time / peak memory
from the run's metrics.jsonl. The output JSON schema is unchanged, so
the regression test, the aggregation script, and the stored baselines
are untouched.

Monitors no longer retain metric history: keep_full_history and the
history list are gone. The file and prime monitors keep only the last
metrics dict for the final summary, and the trainers track the peak
memory maximum locally for the end-of-run log.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 10:58:20 -07:00
68e0c50f6c feat: per-attempt log directories (#3271)
* never overwrite logs across launch attempts

Every launch of a run — fresh or resumed — writes its logs to its own
logs/attempt_<n>/ directory, with logs/latest symlinked to the current
attempt. Previously a resume reopened the same log files with mode "w"
and destroyed the previous attempt's logs. The SLURM templates compute
the attempt in bash the same way; readers (tmux.sh, log hints, tests)
go through logs/latest. Logs are the only clobbered artifact: the
step-keyed dirs are pruned deliberately on resume, and configs/ holds
the current attempt's resolved configs by design.

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

* route all template log paths through the attempt dir

The shared _launch_rank/_launch_router snippets and the multi-node SFT
template still wrote under $OUTPUT_DIR/logs/, so per-rank vLLM tees
targeted a directory that no longer exists and SFT resumes kept
overwriting trainer logs. Every sbatch template now computes the same
attempt block and writes only through $LOG_DIR; verified by rendering
all four entrypoint scripts and grepping for stale paths.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 21:53:06 -07:00
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
189 changed files with 2821 additions and 7158 deletions
+1 -1
View File
@@ -174,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
+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
+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
+2 -2
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/)
@@ -218,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
+68 -11
View File
@@ -2,15 +2,18 @@
"""
Run a single benchmark configuration and output JSON results.
This script wraps the prime-rl training with --bench.output-json to get
metrics directly without parsing console output.
This script runs a normal short training (--max-steps) with the file monitor
enabled and aggregates throughput / MFU / step time / peak memory from the
run's metrics.jsonl.
"""
from __future__ import annotations
import json
import statistics
import subprocess
import sys
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
@@ -83,6 +86,8 @@ class BenchmarkConfig(BaseConfig):
timeout: Annotated[int, Field(description="Timeout in seconds")] = 3600
max_steps: Annotated[int, Field(ge=2, description="Training steps to run. The first step is warmup.")] = 4
micro_batches: Annotated[int, Field(ge=1, description="Number of micro batches")] = 2
ep: Annotated[int, Field(ge=1, description="Expert parallelism size (1 = no EP)")] = 1
@@ -115,7 +120,7 @@ class BenchmarkConfig(BaseConfig):
] = None
def build_command(config: BenchmarkConfig) -> list[str]:
def build_command(config: BenchmarkConfig, output_dir: Path) -> list[str]:
"""Build the benchmark command from config."""
# Determine training script
if config.type == "rl":
@@ -137,12 +142,18 @@ def build_command(config: BenchmarkConfig) -> list[str]:
str(config.seq_len),
"--model.attn",
config.attention,
"--bench.output-json",
str(config.output),
"--max-steps",
str(config.max_steps),
"--output-dir",
str(output_dir),
"--file-monitor.filename",
"metrics.jsonl",
"--model.compile",
"--dist-timeout-seconds",
str(config.timeout),
]
if config.type == "sft":
cmd.extend(["--run.name", "bench"])
# Add activation checkpointing if enabled
if config.ac == "Recompute":
@@ -198,14 +209,61 @@ def dummy_metrics() -> dict:
}
def aggregate_metrics(metrics_path: Path) -> dict:
"""Aggregate per-step metrics from a run's metrics.jsonl.
Each metrics.jsonl line is one monitor.log call (``{"step": N, ...}``);
merge the lines per step, drop the first (warmup) step, and compute
mean/std/min/max per metric like the old --bench JSON export did.
"""
per_step: dict[int, dict] = {}
with open(metrics_path) as f:
for line in f:
row = json.loads(line)
per_step.setdefault(row["step"], {}).update(row)
steps = sorted(per_step)[1:] # Exclude first warmup step
columns = {
"perf/mfu": "mfu",
"perf/throughput": "throughput",
"time/step": "step_time",
"perf/peak_memory": "peak_memory",
}
series = {name: [per_step[step][key] for step in steps] for key, name in columns.items()}
def stats(values: list[float]) -> dict:
return {
"mean": statistics.mean(values),
"std": statistics.stdev(values) if len(values) > 1 else 0.0,
"min": min(values),
"max": max(values),
}
total_memory_gib = torch.cuda.mem_get_info()[1] / 1024**3
peak_memory_gib = statistics.mean(series["peak_memory"])
return {
"mfu": stats(series["mfu"]),
"throughput": stats(series["throughput"]),
"step_time": stats(series["step_time"]),
"peak_memory": {
"gib": peak_memory_gib,
"pct": peak_memory_gib / total_memory_gib * 100,
},
}
def run_benchmark(config: BenchmarkConfig) -> None:
"""Run a single benchmark and write results to output path."""
cmd = build_command(config)
output_dir = Path(tempfile.mkdtemp(prefix="benchmark-run-"))
cmd = build_command(config, output_dir)
print(f"Running: {' '.join(cmd)}")
if config.dry_run:
return
# The SFT entrypoint writes to output_dir/<run.name>, the RL trainer to output_dir directly
metrics_path = output_dir / "bench" / "metrics.jsonl" if config.type == "sft" else output_dir / "metrics.jsonl"
start_time = time.perf_counter()
try:
config.output.parent.mkdir(parents=True, exist_ok=True)
@@ -221,14 +279,13 @@ def run_benchmark(config: BenchmarkConfig) -> None:
config.success = False
config.error_reason = extract_oom_error_reason(output) or f"Non-zero exit code: {result.returncode}"
print(f"Process exited with code {result.returncode}: {output}")
if not config.output.exists():
if not metrics_path.exists():
config.success = False
config.error_reason = config.error_reason or extract_oom_error_reason(output) or "No JSON output written"
config.error_reason = config.error_reason or extract_oom_error_reason(output) or "No metrics.jsonl written"
print(f"Process exited with code {result.returncode}: {output}")
print("Benchmark completed but no JSON output was written")
print("Benchmark completed but no metrics.jsonl was written")
else:
with open(config.output) as f:
metrics = json.load(f)
metrics = aggregate_metrics(metrics_path)
lines = output.splitlines()
print("\n".join(lines))
except subprocess.TimeoutExpired:
+1 -1
View File
@@ -36,7 +36,7 @@ max_completion_tokens = 768
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
id = "alphabet-sort"
min_turns = 3
max_turns = 5
+1 -1
View File
@@ -23,7 +23,7 @@ seq_len = 8192
name = "hendrycks-math"
[orchestrator.train.source.env.taskset]
id = "math-env-v1"
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
+1 -1
View File
@@ -26,7 +26,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
+1 -1
View File
@@ -44,7 +44,7 @@ max_completion_tokens = 512
name = "wiki-search"
[orchestrator.train.source.env.taskset]
id = "wiki-search-v1"
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
+1 -1
View File
@@ -25,7 +25,7 @@ group_size = 8
name = "wordle"
[orchestrator.train.source.env.taskset]
id = "wordle-v1"
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
+1 -1
View File
@@ -26,7 +26,7 @@ max_completion_tokens = 384
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
id = "alphabet-sort"
min_turns = 2
max_turns = 2
min_names_per_turn = 1
@@ -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"
@@ -30,7 +32,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -29,7 +29,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -29,7 +29,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -1,10 +0,0 @@
# Env server for the multi-run RL integration test: one per orchestrator, each bound at
# its run's base port (the test passes --serve.address).
[env.taskset]
id = "reverse-text-v1"
[env.agent.harness]
id = "null"
[env.agent.runtime]
type = "subprocess"
@@ -1,11 +0,0 @@
# Inference config for multi-run RL integration test
[vllm]
model = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
max_model_len = 2048
enable_lora = true
max_lora_rank = 8
max_loras = 4
gpu_memory_utilization = 0.7
[weight_broadcast]
type = "filesystem"
@@ -1,39 +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.source]]
name = "reverse-text"
[train.source.env.taskset]
id = "reverse-text-v1"
[train.source.env.agent.harness]
id = "null"
[train.source.env.agent.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"
@@ -41,7 +41,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -60,7 +60,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
@@ -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
@@ -47,7 +47,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -66,7 +66,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
@@ -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"
@@ -27,7 +29,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -26,7 +26,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
+1 -1
View File
@@ -22,7 +22,7 @@ group_size = 16
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
id = "alphabet-sort"
min_turns = 3
max_turns = 5
+2 -2
View File
@@ -22,7 +22,7 @@ seq_len = 8192
name = "hendrycks-math"
[orchestrator.train.source.env.taskset]
id = "math-env-v1"
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
@@ -40,7 +40,7 @@ name = "aime2024"
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24-v1"
id = "aime24"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+1 -1
View File
@@ -22,7 +22,7 @@ group_size = 16
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
+1 -1
View File
@@ -27,7 +27,7 @@ enforce = true
name = "wiki-search"
[orchestrator.train.source.env.taskset]
id = "wiki-search-v1"
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
+1 -1
View File
@@ -22,7 +22,7 @@ group_size = 16
name = "wordle"
[orchestrator.train.source.env.taskset]
id = "wordle-v1"
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
@@ -24,7 +24,7 @@ max_completion_tokens = 64
name = "color-codeword"
[orchestrator.train.source.env.taskset]
id = "color-codeword-v1"
id = "color-codeword"
images_per_turn = 1
[orchestrator.train.source.env.agent.harness]
+1 -1
View File
@@ -32,7 +32,7 @@ CUDA_VISIBLE_DEVICES=1 uv run inference \
## 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)
+1 -1
View File
@@ -28,7 +28,7 @@ alpha = 0.1
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
id = "alphabet-sort"
min_turns = 3
max_turns = 5
+2 -2
View File
@@ -25,7 +25,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -44,7 +44,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+2 -2
View File
@@ -25,7 +25,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -44,7 +44,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+4 -4
View File
@@ -35,7 +35,7 @@ max_completion_tokens = 128
name = "reverse-text-grpo"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -47,7 +47,7 @@ type = "subprocess"
name = "reverse-text-opd"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -60,7 +60,7 @@ type = "opd"
[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
@@ -73,7 +73,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+3 -3
View File
@@ -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]
@@ -37,7 +37,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -56,7 +56,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+3 -3
View File
@@ -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]
@@ -37,7 +37,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -56,7 +56,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+2 -2
View File
@@ -25,7 +25,7 @@ max_completion_tokens = 512
name = "kuhn-poker"
[orchestrator.train.source.env.taskset]
id = "kuhn-poker-v1"
id = "kuhn-poker"
[orchestrator.train.source.env.player0.harness]
id = "null"
@@ -50,7 +50,7 @@ max_completion_tokens = 512
name = "kuhn-poker"
[orchestrator.eval.source.env.taskset]
id = "kuhn-poker-v1"
id = "kuhn-poker"
[orchestrator.eval.source.env.player0.harness]
id = "null"
+2 -2
View File
@@ -33,7 +33,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -52,7 +52,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+3 -3
View File
@@ -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
@@ -42,7 +42,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -61,7 +61,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+3 -3
View File
@@ -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
@@ -42,7 +42,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -61,7 +61,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+3 -3
View File
@@ -21,7 +21,7 @@ max_completion_tokens = 128
name = "reverse-text-a"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -33,7 +33,7 @@ type = "subprocess"
name = "reverse-text-b"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -52,7 +52,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
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:
+9 -9
View File
@@ -35,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
@@ -47,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.
@@ -126,7 +126,7 @@ type = "grpo"
name = "math" # inherits the top-level grpo
[orchestrator.train.source.env.taskset]
id = "math-v1"
id = "math"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -138,7 +138,7 @@ type = "subprocess"
name = "terminal"
[orchestrator.train.source.env.taskset]
id = "terminal-v1"
id = "terminal"
[orchestrator.train.source.env.agent.harness]
id = "bash"
@@ -354,7 +354,7 @@ The solver attempts for A should not be compared with the solver attempts for B:
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-v1`, that role is `solver`:
Configure which roles are compared within a single proposed problem with `episode_agents`. For `proposer-solver`, that role is `solver`:
```toml
[orchestrator.algo]
@@ -367,7 +367,7 @@ group_size = 4 # proposed problems per source task
env.n = 4 # solver attempts per proposed problem
[orchestrator.train.source.env.taskset]
id = "proposer-solver-v1"
id = "proposer-solver"
[orchestrator.train.source.env.proposer.harness]
id = "null"
@@ -401,7 +401,7 @@ decay = 0.95
name = "kuhn-poker"
[orchestrator.train.source.env.taskset]
id = "kuhn-poker-v1"
id = "kuhn-poker"
[orchestrator.train.source.env.player0.harness]
id = "null"
@@ -416,7 +416,7 @@ id = "null"
type = "subprocess"
```
Both of `kuhn-poker-v1`'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.
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
@@ -481,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
+11 -10
View File
@@ -61,7 +61,7 @@ CLI flags mirror the TOML tree using dots:
```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
@@ -155,7 +155,7 @@ name = "gsm8k"
ratio = 3 # 75% of batches
[orchestrator.train.source.env.taskset]
id = "gsm8k-v1"
id = "gsm8k"
split = "train"
[orchestrator.train.source.env.agent.harness]
@@ -169,7 +169,7 @@ name = "reverse-text"
ratio = 1 # default — 25% of batches
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -181,7 +181,7 @@ type = "subprocess"
name = "gsm8k-eval"
[orchestrator.eval.source.env.taskset]
id = "gsm8k-v1"
id = "gsm8k"
split = "test"
[orchestrator.eval.source.env.agent.harness]
@@ -260,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.
+1 -1
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.
+4 -4
View File
@@ -10,7 +10,7 @@ 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 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.
@@ -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.
+8 -16
View File
@@ -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/latest/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
@@ -245,22 +245,14 @@ The default templates live under [`src/prime_rl/templates/`](https://github.com/
## Benchmarking
Every entrypoint supports a `--bench` flag that runs a few warm-up + measurement steps with fake data and prints a rich-formatted throughput / MFU table:
To benchmark a parallelism config before committing a multi-day run, run a short training with fake data and a step cap, and read throughput / MFU / step time / peak memory from the logs:
```bash
# SFT trainer alone
uv run sft @ sft.toml --bench
uv run sft ... --data.type fake --data.length variable --bench # variable-length fake data
uv run sft @ sft.toml --data.type fake --max-steps 4
# RL trainer alone (no inference involved)
uv run trainer @ train.toml --data.fake --bench
# Inference alone — start the server normally, then bench the orchestrator
uv run inference @ infer.toml
uv run orchestrator @ orch.toml --bench
# Full RL stack (trainer with fake data, inference with real data from orchestrator)
uv run rl @ rl.toml --bench
uv run trainer @ train.toml --data.fake --max-steps 4
```
Persist results with `--bench.output-json`. Use this to compare parallelism configs before committing a multi-day run.
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, enable the file monitor (`--file-monitor.filename metrics.jsonl`) and aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
+31 -23
View File
@@ -77,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
@@ -90,7 +91,7 @@ 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-v1`) |
| `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 |
@@ -199,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:**
@@ -217,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 | Progress, per-env data state | `<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
@@ -235,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.
@@ -259,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 — there the router logs into `inference.log`):
The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>/` — every launch (fresh or resumed) gets its own numbered attempt directory, and `logs/latest` symlinks to the current one. 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/latest/ # symlink -> attempt_<n>, one per launch
├── 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
@@ -280,9 +288,9 @@ Env logs are the first place to look for env-side errors (most user code lives t
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/latest/{trainer,orchestrator,inference}.log
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
```
### Console Output
@@ -290,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
@@ -341,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.
+8 -16
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"
@@ -103,13 +104,10 @@ forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "openseeker-v1"
id = "openseeker"
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
@@ -122,7 +120,7 @@ choices = ["A", "B"]
# [[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
@@ -136,13 +134,10 @@ forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
@@ -155,7 +150,7 @@ choices = ["A", "B"]
# [[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
@@ -175,16 +170,13 @@ forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-search"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "browsecomp-v1"
id = "browsecomp"
[orchestrator.eval.source.env.taskset.task.judge]
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
@@ -193,7 +185,7 @@ model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
# [[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
+5 -10
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"
@@ -101,16 +102,13 @@ thinking_retention = "all"
name = "scaleswe"
[orchestrator.train.source.env.taskset]
id = "scaleswe-v1"
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-swe"]
[orchestrator.prime_monitor]
@@ -124,16 +122,13 @@ interval = 20
name = "swebench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-swe"]
[orchestrator.eval.source.env.agent.timeout]
+11 -19
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"
@@ -99,26 +100,23 @@ id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-terminal"]
[orchestrator.train.source.env.taskset]
id = "tmax-v1"
id = "tmax"
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
# [[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.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
@@ -135,28 +133,25 @@ id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-terminal"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
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.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
@@ -169,28 +164,25 @@ id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-terminal"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "terminal-bench-2-v1"
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.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
+6 -4
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"
@@ -131,13 +134,12 @@ clear_thinking = false
name = "r2e"
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["glm5-llmd"]
[inference]
+1 -2
View File
@@ -79,13 +79,12 @@ interval = 20
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
labels = ["glm5-pd-disag", "swe-bench-verified"]
[[orchestrator.post_batch_filters]]
+7 -10
View File
@@ -52,13 +52,12 @@ name = "swe"
ratio = 0.3
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["intellect-3.1", "swe"]
[[orchestrator.train.source]]
@@ -66,7 +65,7 @@ name = "deepdive"
ratio = 0.2
[orchestrator.train.source.env.taskset]
id = "deepdive-v1"
id = "deepdive"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
@@ -74,7 +73,6 @@ skills = ["search"]
forward_env = ["SERPER_API_KEY"]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["intellect-3.1", "deepdive"]
[[orchestrator.train.source]]
@@ -82,7 +80,7 @@ name = "math"
ratio = 0.3
[orchestrator.train.source.env.taskset]
id = "i3_math_v1"
id = "i3_math"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -95,7 +93,7 @@ name = "logic"
ratio = 0.2
[orchestrator.train.source.env.taskset]
id = "i3_logic_v1"
id = "i3_logic"
[orchestrator.train.source.env.taskset.filter]
max = 0.874
@@ -111,7 +109,7 @@ name = "code"
ratio = 0.2
[orchestrator.train.source.env.taskset]
id = "i3_code_v1"
id = "i3_code"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -130,20 +128,19 @@ interval = 25
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
labels = ["intellect-3.1", "swe-bench-verified"]
[[orchestrator.eval.source]]
name = "aime2025"
[orchestrator.eval.source.env.taskset]
id = "aime25-v1"
id = "aime25"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+2 -4
View File
@@ -52,13 +52,12 @@ max_off_policy_steps = 16
name = "swe"
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["minimax-swe", "swe"]
[orchestrator.eval]
@@ -68,13 +67,12 @@ interval = 25
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
labels = ["minimax-swe", "swe-bench-verified"]
[inference.vllm]
+4 -9
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"
@@ -85,16 +86,13 @@ truncate_history_thinking = false
name = "scaleswe"
[orchestrator.train.source.env.taskset]
id = "scaleswe-v1"
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["nemotron-3-super-swe"]
[orchestrator.prime_monitor]
@@ -106,16 +104,13 @@ interval = 20
name = "swebench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["nemotron-3-super-swe"]
[orchestrator.eval.source.env.agent.timeout]
+2 -2
View File
@@ -52,7 +52,7 @@ max_completion_tokens = 32768
name = "math"
[orchestrator.train.source.env.taskset]
id = "i3_math_v1"
id = "i3_math"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -67,7 +67,7 @@ interval = 25
name = "aime2025"
[orchestrator.eval.source.env.taskset]
id = "aime25-v1"
id = "aime25"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+2 -4
View File
@@ -50,13 +50,12 @@ max_off_policy_steps = 16
name = "swe"
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["qwen30b-swe", "swe"]
[orchestrator.eval]
@@ -66,13 +65,12 @@ interval = 25
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
labels = ["qwen30b-swe", "swe-bench-verified"]
[inference.vllm]
+1 -1
View File
@@ -38,7 +38,7 @@ max_off_policy_steps = 32
[[orchestrator.train.source]]
[orchestrator.train.source.env.taskset]
id = "general-agent-v1"
id = "general-agent"
min_tier = 1
[orchestrator.train.source.env.taskset.task.tools]
+7 -6
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:
@@ -38,7 +38,7 @@ 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).
@@ -115,7 +116,7 @@ uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruc
```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 \
+1 -1
View File
@@ -35,7 +35,7 @@ max_completion_tokens = 768
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
id = "alphabet-sort"
min_turns = 3
max_turns = 5
+2 -2
View File
@@ -20,7 +20,7 @@ seq_len = 8192
name = "hendrycks-math"
[orchestrator.train.source.env.taskset]
id = "math-env-v1"
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
@@ -38,7 +38,7 @@ name = "aime2024"
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24-v1"
id = "aime24"
[orchestrator.eval.source.env.agent.harness]
id = "null"
+18 -16
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.
@@ -27,7 +27,7 @@ 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).
@@ -100,7 +102,7 @@ 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
@@ -213,7 +215,7 @@ kubectl exec -it my-exp-inference-0 -- bash
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:**
+1 -1
View File
@@ -19,7 +19,7 @@ max_completion_tokens = 128
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
+7 -6
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:
@@ -77,7 +77,7 @@ 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
@@ -119,7 +120,7 @@ uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSe
```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 \
@@ -135,7 +136,7 @@ The V1 taskset fixes the question bank and searchable corpus. You can replace it
```toml
[[orchestrator.train.source]]
name = "wiki-search"
taskset = { id = "wiki-search-v1", task = { judges = [{ id = "reference", model = "openai/gpt-5.4-nano" }] } }
taskset = { id = "wiki-search", task = { judges = [{ id = "reference", model = "openai/gpt-5.4-nano" }] } }
harness = { id = "null" }
runtime = { type = "subprocess" }
```
+1 -1
View File
@@ -44,7 +44,7 @@ max_completion_tokens = 512
name = "wiki-search"
[orchestrator.train.source.env.taskset]
id = "wiki-search-v1"
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
+10 -8
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
@@ -29,7 +29,7 @@ Then, use the `eval` entrypoint to evaluate the model in the `wordle` environmen
```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).
@@ -103,7 +105,7 @@ 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**.
+1 -1
View File
@@ -22,7 +22,7 @@ group_size = 16
name = "wordle"
[orchestrator.train.source.env.taskset]
id = "wordle-v1"
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
+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"
+1 -1
View File
@@ -17,7 +17,7 @@ max_completion_tokens = 128
name = "reverse-text"
[train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[train.source.env.agent.harness]
id = "null"
+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:
@@ -58,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."
@@ -246,7 +246,7 @@ class RAEAlgoConfig(BaseAlgoConfig):
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-v1`` and friends): in a zero-sum game the group mean is ~0
(``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
@@ -274,16 +274,16 @@ class HierarchicalGRPOAlgoConfig(BaseAlgoConfig):
episode_agents: list[str] = Field(min_length=1)
"""Roles compared within one proposed problem. Use ``["solver"]`` for
``proposer-solver-v1``."""
``proposer-solver``."""
def validate_env(self, env_config: vf.EnvConfig) -> None:
"""Require the proposer-solver structure used by the comparisons."""
try:
from proposer_solver_v1 import ProposerSolverEnvConfig
from proposer_solver import ProposerSolverEnvConfig
except ImportError as e:
raise ValueError(
"algorithm 'hierarchical_grpo' requires a proposer-solver env, but the "
"proposer-solver-v1 package is not installed (`uv sync --all-packages`)."
"proposer-solver package is not installed (`uv sync --all-packages`)."
) from e
if not isinstance(env_config, ProposerSolverEnvConfig):
raise ValueError(
@@ -8,9 +8,9 @@ from prime_rl.utils.config import BaseConfig
class EnvServerConfig(BaseConfig):
"""``uv run env-server``: what to serve (``[env]``, or ``[legacy]`` for a classic v0
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."""
"""``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."""
@@ -18,9 +18,6 @@ class EnvServerConfig(BaseConfig):
serve: vf.ServeConfig = vf.ServeConfig()
"""How it's served: the worker pool, the bind address, each worker's episode bound."""
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
"""A classic (v0) environment to serve through the bridge instead of ``env``."""
log: LogConfig = LogConfig()
output_dir: Path = Path("outputs")
@@ -32,35 +29,12 @@ class EnvServerConfig(BaseConfig):
"""Narrow ``env`` to the selected env's config class."""
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
@property
def is_legacy(self) -> bool:
"""Whether this serves the v0 bridge: a legacy id and no v1 taskset."""
return self.legacy.id is not None and not self.env.taskset.id
@property
def env_id(self) -> str:
"""The served env's identifier: the v1 env's, else the v0 env id."""
return self.env.env_id or self.legacy.id or ""
return self.env.env_id or ""
@model_validator(mode="after")
def validate_env(self):
# A v0 id next to any v1 env identity leaves one of the two going nowhere, and
# which one depends on `is_legacy`: a taskset makes it False, so the v0 env never
# loads; a bare `env.id` leaves it True, so the v0 env runs under the v1 name.
if self.legacy.id is not None and self.env.env_id:
if self.env.taskset.id:
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with "
f"the v1 taskset {self.env.taskset.id!r}. Pairing a reusable env with a taskset "
f"is env.id = {self.legacy.id!r}; to run the v0 env instead, drop the taskset."
)
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with the "
f"v1 env.id {self.env.id!r}: the v0 env is what would run, stamped with the v1 "
"env's name. Keep whichever one you meant to run."
)
if not self.env_id:
raise ValueError(
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or legacy = { id = "<id>" } (v0)'
)
raise ValueError('no env configured — set env = { taskset = { id = "<id>" } }')
return self
@@ -17,6 +17,7 @@ from prime_rl.configs.shared import (
HeartbeatConfig,
LogConfig,
PrimeMonitorConfig,
ResumeConfig,
TransportConfig,
WandbWithExtrasConfig,
ZMQTransportConfig,
@@ -25,11 +26,6 @@ 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."""
@@ -124,8 +120,7 @@ class EvalSamplingConfig(BaseConfig):
class EnvConfig(BaseConfig):
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
runs, ``serve`` — how it's hosted, ``legacy`` — a classic v0 env instead) plus this
orchestrator's own per-env knobs."""
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."""
@@ -133,9 +128,6 @@ class EnvConfig(BaseConfig):
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."""
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
"""A classic (v0) environment to run through the bridge instead of ``env``."""
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."""
@@ -148,15 +140,9 @@ class EnvConfig(BaseConfig):
"""Narrow ``env`` to the selected env's config class."""
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
@property
def is_legacy(self) -> bool:
"""A classic (v0) env run through the bridge: a legacy id and no v1 taskset."""
return self.legacy.id is not None and not self.env.taskset.id
@property
def env_id(self) -> str:
"""The env's identifier: the v1 env's, else the v0 env id."""
return self.env.env_id or self.legacy.id or ""
return self.env.env_id or ""
@property
def resolved_name(self) -> str:
@@ -164,47 +150,14 @@ class EnvConfig(BaseConfig):
@model_validator(mode="after")
def validate_env(self):
# A v0 id next to any v1 env identity leaves one of the two going nowhere, and
# which one depends on `is_legacy`: a taskset makes it False, so the v0 env never
# loads; a bare `env.id` leaves it True, so the v0 env runs under the v1 name.
if self.legacy.id is not None and self.env.env_id:
if self.env.taskset.id:
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with "
f"the v1 taskset {self.env.taskset.id!r}. Pairing a reusable env with a taskset "
f"is env.id = {self.legacy.id!r}; to run the v0 env instead, drop the taskset."
)
raise ValueError(
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with the "
f"v1 env.id {self.env.id!r}: the v0 env is what would run, stamped with the v1 "
"env's name. Keep whichever one you meant to run."
)
if not self.env_id:
raise ValueError(
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or legacy = { id = "<id>" } (v0)'
)
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
``legacy.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.legacy.extra_env_kwargs["timeout_seconds"] = agent.timeout.rollout
if agent.max_output_tokens is not None:
self.legacy.extra_env_kwargs["max_total_completion_tokens"] = agent.max_output_tokens
return self
class TrainSourceConfig(EnvConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
@@ -334,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."""
@@ -461,9 +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."""
optim: OptimizerConfig = OptimizerConfig()
"""Per-run optimizer configuration for multi-run training."""
eval: EvalConfig | None = None
"""Evaluation configuration."""
@@ -504,6 +451,9 @@ 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()
@@ -512,11 +462,11 @@ class OrchestratorConfig(BaseConfig):
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)."""
@@ -539,9 +489,11 @@ class OrchestratorConfig(BaseConfig):
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."""
@@ -549,9 +501,6 @@ class OrchestratorConfig(BaseConfig):
max_off_policy_steps: int = Field(8, ge=0)
"""Maximum policies allowed to generate a single rollout. Rollouts generated more than ``max_off_policy_steps`` ahead of training are discarded. Higher values yield better throughput at the cost of off-policy noise."""
bench: bool = False
"""Benchmark mode. Sets ``max_steps`` to 5 and disables W&B."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
@@ -687,23 +636,9 @@ class OrchestratorConfig(BaseConfig):
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench:
self.max_steps = 4 # Run for 1 warmup step + 3 evaluation steps
# Disable evaluation
self.eval = None
if self.wandb:
self.wandb.log_extras = None
if self.prime_monitor:
self.prime_monitor.log_extras = None
return self
@model_validator(mode="after")
def resolve_env_config(self):
"""Set vLLM sampling defaults + legacy env kwargs on each train env from top-level fields."""
"""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.
@@ -712,10 +647,6 @@ 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 legacy.extra_env_kwargs via env.set_kwargs).
env.legacy.extra_env_kwargs["max_seq_len"] = self.seq_len
return self
@property
@@ -1,3 +1,4 @@
import uuid
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
@@ -21,16 +22,12 @@ 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 (
BenchConfig,
FakeDataLoaderConfig,
TokenizerConfig,
TrainerConfig,
)
from prime_rl.configs.trainer import (
FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig,
)
@@ -40,13 +37,16 @@ from prime_rl.configs.trainer import (
from prime_rl.configs.trainer import (
NIXLWeightBroadcastConfig as TrainerNIXLWeightBroadcastConfig,
)
from prime_rl.configs.trainer import (
TokenizerConfig,
TrainerConfig,
)
from prime_rl.utils.config import BaseConfig, find_package_resource
from prime_rl.utils.validation import (
propagate_shared_fields,
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,
@@ -100,9 +100,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."""
@@ -222,16 +219,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
@@ -241,6 +256,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."""
@@ -263,9 +281,6 @@ class RLConfig(BaseConfig):
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``."""
deployment: DeploymentConfig = SingleNodeDeploymentConfig()
slurm: SlurmConfig | None = None
@@ -316,9 +331,9 @@ class RLConfig(BaseConfig):
"Cannot configure inference with num_infer_nodes = 0. "
"Either set num_infer_nodes > 0 or remove the inference config."
)
if num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
if num_infer_nodes == 0 and not self.trainer.data.fake:
raise ValueError(
"Must use fake data (trainer.data.fake or bench = true) when num_infer_nodes = 0, "
"Must use fake data (trainer.data.fake) when num_infer_nodes = 0, "
"since no orchestrator or inference server will be running."
)
return self
@@ -360,12 +375,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)
@@ -463,24 +524,6 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench:
self.trainer.bench = BenchConfig()
self.orchestrator.bench = True
self.trainer.data.fake = FakeDataLoaderConfig(
batch_size=self.orchestrator.batch_size or 32,
)
trainer_bench_enabled = self.trainer.bench is not None
if trainer_bench_enabled != self.orchestrator.bench:
raise ValueError(
f"Trainer benchmark mode ({self.trainer.bench}) and orchestrator benchmark mode "
f"({self.orchestrator.bench}) must match. Use the top-level bench = true to set both."
)
return self
@model_validator(mode="after")
def auto_setup_lora(self):
if self.trainer.model.lora is not None:
@@ -603,6 +646,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
@@ -625,7 +669,9 @@ class RLConfig(BaseConfig):
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:
@@ -756,7 +802,7 @@ class RLConfig(BaseConfig):
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
@@ -1,3 +1,4 @@
import uuid
import warnings
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
@@ -10,13 +11,14 @@ from prime_rl.configs.shared import (
EnvVars,
FileMonitorConfig,
HeartbeatConfig,
ResumeConfig,
RunConfig,
SlurmConfig,
TrainerLogConfig,
WandbConfig,
)
from prime_rl.configs.trainer import (
AdamWConfig,
BenchConfig,
CheckpointConfig,
ConstantSchedulerConfig,
GCConfig,
@@ -188,6 +190,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 +200,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``."""
@@ -210,9 +238,6 @@ class SFTConfig(BaseConfig):
memory_profiler_path: Path | None = None
"""Path to write the memory profile to."""
bench: BenchConfig | None = None
"""Benchmark-mode configuration. When set, ``max_steps`` is forced to 4 and fake data is used."""
gc: GCConfig | None = GCConfig()
"""Garbage collection config. Disables automatic GC and runs deterministic collections every N steps to avoid stragglers. Set to null to use Python's default GC behavior."""
@@ -365,14 +390,6 @@ class SFTConfig(BaseConfig):
### Auto-setup and validate shared configs
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench is not None:
self.max_steps = 4 # 1 Warmup + 3 Benchmark
if self.ckpt: # Do not checkpoint
self.ckpt = None
return self
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
@@ -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."""
@@ -142,18 +167,7 @@ class ClientConfig(BaseConfig):
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
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):
@@ -10,6 +10,7 @@ from prime_rl.configs.shared import (
FileMonitorConfig,
HeartbeatConfig,
MetricsServerConfig,
ResumeConfig,
TrainerLogConfig,
TransportConfig,
WandbConfig,
@@ -59,11 +60,6 @@ class CompileConfig(BaseConfig):
"""Compile transformer blocks with ``fullgraph=True``."""
class BenchConfig(BaseConfig):
output_json: Path | None = None
"""Path to write benchmark results as JSON. If unset, results are only printed to the console."""
class IndexCacheConfig(BaseConfig):
topk_freq: int = Field(1, ge=1)
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
@@ -431,9 +427,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,6 +570,9 @@ 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()
@@ -607,9 +603,6 @@ class TrainerConfig(BaseConfig):
memory_profiler_path: Path | None = None
"""Path to write the memory profile to."""
bench: BenchConfig | None = None
"""Benchmark-mode configuration. When set, ``max_steps`` is forced to 4 and fake data is used."""
gc: GCConfig | None = GCConfig()
"""Garbage collection config. Disables automatic GC and runs deterministic collections every N steps to avoid stragglers. Set to null to use Python's default GC behavior."""
@@ -625,9 +618,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."""
@@ -664,16 +654,6 @@ class TrainerConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench is not None:
self.max_steps = 4 # 1 Warmup + 3 Benchmark
if not self.data.fake:
self.data.fake = FakeDataLoaderConfig()
if self.ckpt: # Do not checkpoint
self.ckpt = None
return self
@model_validator(mode="after")
def dont_do_massive_traces(self):
if self.trace_path:
@@ -702,12 +682,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:
@@ -33,6 +33,7 @@ REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
(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"),
@@ -90,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")
@@ -138,22 +137,6 @@ 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.vllm.chat_template
# (vLLM ``--chat-template``). Read trainer's value *after* the shared
# propagation above so we cover both:
@@ -211,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."
)
@@ -239,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,
+20 -21
View File
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.3.0",
"verifiers[harbor]>=0.3.1.dev14",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -128,28 +128,28 @@ override-dependencies = [
"openenv-core",
]
# research-environments packages are auto-discovered as workspace members, so new
# 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/alphabet_sort_v1",
"deps/verifiers/environments/color_codeword_v1",
"deps/verifiers/environments/gsm8k_v1",
"deps/verifiers/environments/kuhn_poker_v1",
"deps/verifiers/environments/proposer_solver_v1",
"deps/verifiers/environments/reverse_text_v1",
"deps/verifiers/environments/wiki_search_v1",
"deps/verifiers/environments/wordle_v1",
"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
@@ -195,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 }
@@ -210,8 +208,8 @@ torchao = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/downlo
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ 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'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ 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'" },
@@ -263,6 +261,7 @@ select = ["F", "I"]
# 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
+1 -1
View File
@@ -60,7 +60,7 @@ if [[ ${#POSITIONAL[@]} -ge 2 ]]; then
OUTPUT_DIR="${POSITIONAL[1]}"
fi
LOG_DIR="${OUTPUT_DIR}/logs"
LOG_DIR="${OUTPUT_DIR}/logs/latest"
if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
echo "Attaching to tmux session: $SESSION_NAME"
+5 -5
View File
@@ -25,7 +25,7 @@ Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max
```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
@@ -47,7 +47,7 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -59,7 +59,7 @@ type = "subprocess"
name = "reverse-text-eval"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
id = "reverse-text"
split = "test"
[orchestrator.eval.source.env.agent.harness]
@@ -69,7 +69,7 @@ id = "null"
type = "subprocess"
```
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text-v1` or `--orchestrator.eval.source.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: `--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.
@@ -90,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
+2 -2
View File
@@ -26,10 +26,10 @@ uv sync # core only
uv sync --group dev # + pytest, ruff, pre-commit
uv sync --all-extras # + extras (flash-attn, flash-attn-cute, …)
uv sync --all-extras --all-packages # + all env packages (needed to train on them)
uv sync --package prime-rl --package gsm8k-v1 # core + just one env
uv sync --package prime-rl --package gsm8k # core + just one env
```
Environment packages are uv **workspace members**. Those under `deps/research-environments/environments/*/*` are auto-discovered — adding a new env there needs no `pyproject.toml` change. verifiers' example envs are enumerated explicitly in `[tool.uv.workspace].members` (only the ones prime-rl trains or tests on) — to use another, add its path to the list. Members are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
Environment packages are uv **workspace members**. Those under `deps/prime-envs/environments/*/*` are auto-discovered — adding a new env there needs no `pyproject.toml` change. verifiers' example envs are enumerated explicitly in `[tool.uv.workspace].members` (only the ones prime-rl trains or tests on) — to use another, add its path to the list. Members are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
+16 -16
View File
@@ -9,9 +9,9 @@ description: Monitor an ongoing prime-rl training run — find the output direct
### On launch
1. Find the output dir and read the resolved configs at `{output_dir}/configs/` (start with `rl.toml`).
1. Find the run dir and read the resolved configs at `{run_dir}/configs/` (start with `rl.json`). The run dir is `{output_dir}/{run_name}` — `run.name` auto-generates as `<envs>--<model>--<short-id>`, so if you only know the output dir, pick the most recently modified subdirectory (`ls -t {output_dir} | head -1`) or read `run.name` from the launch command.
2. Confirm all processes are alive and the run is making progress.
3. Write the initial summary into `{output_dir}/STATUS.md`.
3. Write the initial summary into `{run_dir}/STATUS.md`.
### Recurring check-ins
@@ -19,7 +19,7 @@ Default cadence: **1 hour** (researcher can override). At each check-in:
1. Confirm processes are alive.
2. Grep logs for errors/warnings; note current step and key metrics.
3. **Append** an entry to `{output_dir}/STATUS.md` (never overwrite):
3. **Append** an entry to `{run_dir}/STATUS.md` (never overwrite):
```markdown
## YYYY-MM-DD HH:MM UTC
@@ -55,15 +55,15 @@ After a restart, verify all processes are back up and progress resumed before th
### Where to find things
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the output dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
- `{output_dir}/configs/` — resolved TOMLs (`rl.toml` has the full picture).
- `{output_dir}/logs/` — see below.
- `{output_dir}/rollouts/step_N/{train,eval}/` — saved rollout traces (see Traces below).
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the run dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
- `{run_dir}/configs/` — resolved configs, written as JSON so explicit None settings round-trip (`rl.json` has the full picture).
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved rollout traces (see Traces below).
### Logs
```
{output_dir}/logs/
{run_dir}/logs/latest/
├── trainer.log # rank 0 stdout
├── orchestrator.log # orchestrator stdout
├── inference.log # vLLM stdout
@@ -81,8 +81,8 @@ Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough
Scan for problems:
```bash
grep -E "WARNING|ERROR" {output_dir}/logs/{trainer,orchestrator,inference}.log
grep -E "WARNING|ERROR" {output_dir}/logs/envs/{train,eval}/*.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
```
### Metrics
@@ -141,8 +141,8 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
### Traces
```
{output_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per rollout as it completes
{output_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
{run_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per rollout as it completes
{run_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
```
JSONL files of `vf.Trace` records (training tensors excluded), one line per trace — a
@@ -157,12 +157,12 @@ share the step file) — untrainable traces (a frozen judge's) appear only in `a
`group_id`, `episode_id`, and `policy_version` under `info`.
```bash
wc -l {output_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.ok | not) | {id, env: .info.env_name, runtime}' {output_dir}/rollouts/step_*/train/all/traces.jsonl
wc -l {run_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
jq '.rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.ok | not) | {id, env: .info.env_name, runtime}' {run_dir}/rollouts/step_*/train/all/traces.jsonl
```
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the trace subtrees.
### Common failure modes
+6 -2
View File
@@ -7,6 +7,10 @@ description: How to launch prime-rl training runs — the `rl`, `sft`, and `infe
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
## Run directories
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, weights, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
## Config system at a glance
[`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config) — Pydantic-based TOML + CLI loader. Highlights (see the `configs` skill for full mechanics):
@@ -35,8 +39,8 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
- SLURM: single- and multi-node
- Environment packages: before launching a config with a non-core verifier env id,
verify the package imports under `uv run` (for example
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym_v1'))"`).
If a local env exists under `deps/research-environments/environments/` or
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
If a local env exists under `deps/prime-envs/environments/` or
`deps/verifiers/environments/` but does not import, install the env workspace
members with `uv sync --all-packages` (all) or `uv sync --package prime-rl
--package <env>` (one) — they're auto-discovered, no `pyproject.toml` edit needed.
+14 -12
View File
@@ -1,6 +1,8 @@
import os
from functools import partial
from verifiers.v1 import pool_serve_kwargs
from verifiers.v1.runtimes import set_base_sandbox_labels
from verifiers.v1.serve import env_config_data, serve_env
from prime_rl.configs.env_server import EnvServerConfig
@@ -10,23 +12,23 @@ from prime_rl.utils.process import set_proc_title
from prime_rl.utils.utils import clean_exit
def setup_worker(log_level: str | None, json_logging: bool, sandbox_labels: list[str]) -> None:
setup_env_server_logging(log_level, json_logging)
set_base_sandbox_labels(sandbox_labels)
@clean_exit
def run_server(config: EnvServerConfig):
# ``serve.pool`` (static or elastic) sizes the server; a v0/legacy env runs through
# the bridge, a v1 env is a native env block — both speak the same serve protocol,
# so the orchestrator is agnostic. serve_env applies the logging setup in this process
# and in every spawned worker.
server_kwargs = (
{"env_id": config.env_id, "env_args": config.legacy.args, "extra_env_kwargs": config.legacy.extra_env_kwargs}
if config.is_legacy
else {"config_data": env_config_data(config.env), "max_concurrent": config.serve.max_concurrent}
)
run_name = os.environ.get("PRL_RUN_NAME")
sandbox_labels = [run_name] if run_name else []
# ``serve.pool`` (static or elastic) sizes the server. serve_env applies the worker
# setup in this process and in every spawned worker.
serve_env(
**pool_serve_kwargs(config.serve.pool),
legacy=config.is_legacy,
address=config.serve.address,
log_setup=partial(setup_env_server_logging, config.log.level, config.log.json_logging),
**server_kwargs,
log_setup=partial(setup_worker, config.log.level, config.log.json_logging, sandbox_labels),
config_data=env_config_data(config.env),
max_concurrent=config.serve.max_concurrent,
)
+9 -11
View File
@@ -7,12 +7,10 @@ from pathlib import Path
from threading import Event, Thread
from typing import Any
import tomli_w
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli, to_toml_dict
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir
from prime_rl.utils.pathing import format_log_message, get_config_dir, latest_log_dir
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
@@ -20,7 +18,7 @@ from prime_rl.utils.process import (
set_proc_title,
)
INFERENCE_TOML = "inference.toml"
INFERENCE_CONFIG = "inference.json"
INFERENCE_SBATCH = "inference.sbatch"
@@ -44,12 +42,12 @@ def write_config(
engines — the sbatch script starts the single global router.
"""
output_dir.mkdir(parents=True, exist_ok=True)
config_path = output_dir / INFERENCE_TOML
toml_dict = to_toml_dict(config, exclude=exclude)
config_path = output_dir / INFERENCE_CONFIG
config_dict = dump_resolved_config(config, exclude=exclude)
if engine_only:
toml_dict["router"] = "None"
with open(config_path, "wb") as f:
tomli_w.dump(toml_dict, f)
config_dict["router"] = None
with open(config_path, "w") as f:
json.dump(config_dict, f, indent=2)
return config_path
@@ -137,7 +135,7 @@ def inference_slurm(config: InferenceConfig):
write_slurm_script(config, config_path, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
log_dir = get_log_dir(config.output_dir)
log_dir = latest_log_dir(config.output_dir)
num_nodes = getattr(config.deployment, "num_nodes", 1)
log_message = format_log_message(log_dir=log_dir, inference=True, job_log=True, num_infer_nodes=num_nodes)
+74 -62
View File
@@ -11,22 +11,23 @@ from threading import Event, Thread
from urllib.parse import urlparse
import pynvml
import tomli_w
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.inference import vllm_overrides_fragment
from prime_rl.utils.config import cli, to_toml_dict
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import (
clean_future_steps,
create_attempt_log_dir,
format_log_message,
get_ckpt_dir,
get_log_dir,
get_config_dir,
latest_log_dir,
resolve_latest_ckpt_step,
validate_output_dir,
validate_run_dir,
)
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
@@ -38,12 +39,12 @@ from prime_rl.utils.process import (
set_proc_title,
)
RL_TOML = "rl.toml"
RL_CONFIG = "rl.json"
RL_SBATCH = "rl.sbatch"
TRAINER_TOML = "trainer.toml"
ORCHESTRATOR_TOML = "orchestrator.toml"
INFERENCE_TOML = "inference.toml"
TRAINER_CONFIG = "trainer.json"
ORCHESTRATOR_CONFIG = "orchestrator.json"
INFERENCE_CONFIG = "inference.json"
ENVS_DIR = "envs"
@@ -79,46 +80,45 @@ def get_physical_gpu_ids() -> list[int]:
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
"""Write resolved config to disk, excluding launcher-only fields."""
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_dir / RL_TOML, "wb") as f:
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
with open(output_dir / RL_CONFIG, "w") as f:
json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2)
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
"""Write resolved subconfigs to disk as TOML files."""
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_dir / TRAINER_TOML, "wb") as f:
tomli_w.dump(to_toml_dict(config.trainer), f)
with open(output_dir / TRAINER_CONFIG, "w") as f:
json.dump(dump_resolved_config(config.trainer), f, indent=2)
with open(output_dir / ORCHESTRATOR_TOML, "wb") as f:
tomli_w.dump(to_toml_dict(config.orchestrator), f)
with open(output_dir / ORCHESTRATOR_CONFIG, "w") as f:
json.dump(dump_resolved_config(config.orchestrator), f, indent=2)
if config.inference is not None:
# Exclude launcher-only fields that are not needed by the vLLM server
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
inference_dict = to_toml_dict(config.inference, exclude=exclude_inference)
inference_dict = dump_resolved_config(config.inference, exclude=exclude_inference)
if config.deployment.type == "multi_node":
# Per-rank processes run bare engines; the sbatch starts the single global router.
inference_dict["router"] = "None"
with open(output_dir / INFERENCE_TOML, "wb") as f:
tomli_w.dump(inference_dict, f)
inference_dict["router"] = None
with open(output_dir / INFERENCE_CONFIG, "w") as f:
json.dump(inference_dict, f, indent=2)
# One EnvServerConfig TOML per launcher-managed source: `env-server @ <path>` binds
# at the source's deterministic address, where the orchestrator connects. The source's
# env/serve/legacy blocks carry over; its other knobs (sampling, algo, name, ...) are
# env/serve blocks carry over; its other knobs (sampling, algo, name, ...) are
# orchestrator-side.
for split, source, address in env_servers(config):
env_dir = output_dir / ENVS_DIR / split
env_dir.mkdir(parents=True, exist_ok=True)
source_dict = to_toml_dict(source)
source_dict = dump_resolved_config(source)
env_server_dict = {
"env": source_dict["env"],
"serve": {**source_dict.get("serve", {}), "address": address},
"legacy": source_dict.get("legacy", {}),
"log": {"level": config.orchestrator.log.vf_level, "json_logging": config.orchestrator.log.json_logging},
}
with open(env_dir / f"{source.resolved_name}.toml", "wb") as f:
tomli_w.dump(env_server_dict, f)
with open(env_dir / f"{source.resolved_name}.json", "w") as f:
json.dump(env_server_dict, f, indent=2)
def rl_local(config: RLConfig):
@@ -129,7 +129,7 @@ def rl_local(config: RLConfig):
json_logging=config.log.json_logging,
)
config_dir = config.output_dir / "configs"
config_dir = get_config_dir(config.run_dir)
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
@@ -162,17 +162,17 @@ def rl_local(config: RLConfig):
logger.debug(f"RL start command: {' '.join(start_command)}")
# Build shared W&B env vars for subprocesses. Shared mode is always on for
# the rl entrypoint — trainer and orchestrator log to a single W&B run.
# The monitor short-circuits when WANDB_MODE=disabled/offline is also set.
# the rl entrypoint — trainer and orchestrator log to a single W&B run whose
# id ($WANDB_RUN_ID) equals $PRL_RUN_ID. The monitor short-circuits when
# WANDB_MODE=disabled/offline is also set.
wandb_shared_env: dict[str, str] = {
"WANDB_SHARED_MODE": "1",
"WANDB_SHARED_RUN_ID": os.environ.get("WANDB_SHARED_RUN_ID", uuid.uuid4().hex),
"WANDB_RUN_ID": os.environ["PRL_RUN_ID"],
}
# Validate client port matches inference server port
if config.inference is not None and not config.orchestrator.model.client.is_elastic:
base_url = config.orchestrator.model.client.base_url[0]
parsed = urlparse(base_url)
if config.inference is not None:
parsed = urlparse(config.orchestrator.model.client.base_url)
client_port = parsed.port
expected_port = config.inference.server.port
if client_port != expected_port:
@@ -182,9 +182,8 @@ def rl_local(config: RLConfig):
f"Update the base_url to use port {expected_port} to match the inference server."
)
# Prepare paths to communicate with the trainer
log_dir = get_log_dir(config.output_dir)
log_dir.mkdir(parents=True, exist_ok=True)
# Per-attempt log dir: a resume never overwrites an earlier attempt's logs
log_dir = create_attempt_log_dir(config.run_dir)
# Start processes
processes: list[Popen] = []
@@ -203,7 +202,7 @@ def rl_local(config: RLConfig):
try:
# Optionally, start inference process
if config.inference:
inference_cmd = ["inference", "@", (config_dir / INFERENCE_TOML).as_posix()]
inference_cmd = ["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()]
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
# If we don't log stdout, the server hangs
@@ -238,7 +237,7 @@ def rl_local(config: RLConfig):
"No [inference] block configured - the policy inference server will not be started here. "
"Every algorithm requires a policy inference pool for evals + weight sync; "
"make sure one is running at orchestrator.model.client.base_url "
f"({', '.join(config.orchestrator.model.client.base_url)}), otherwise the orchestrator "
f"({config.orchestrator.model.client.base_url}), otherwise the orchestrator "
"will hang waiting for it."
)
@@ -248,7 +247,7 @@ def rl_local(config: RLConfig):
assert algo is not None, "TrainSourceConfig.algo must be resolved before launch (inherit_env_algorithms)"
for ref in (algo.sampling.source, getattr(algo, "teacher", None)):
if isinstance(ref, FrozenModelConfig):
frozen_endpoints.append(f"{ref.name} ({', '.join(ref.base_url)})")
frozen_endpoints.append(f"{ref.name} ({ref.base_url})")
if frozen_endpoints:
endpoints = ", ".join(dict.fromkeys(frozen_endpoints))
logger.info(
@@ -262,7 +261,7 @@ def rl_local(config: RLConfig):
# orchestrator start in parallel.
for split, source, address in env_servers(config):
name = source.resolved_name
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.toml").as_posix()]
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
logger.info(f"Starting {split} env server {name} at {address}")
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
@@ -292,7 +291,7 @@ def rl_local(config: RLConfig):
monitor_thread.start()
monitor_threads.append(monitor_thread)
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_TOML).as_posix()]
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()]
logger.info("Starting orchestrator process")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
with open(log_dir / "orchestrator.log", "w") as log_file:
@@ -342,7 +341,7 @@ def rl_local(config: RLConfig):
"-m",
"prime_rl.trainer.rl.train",
"@",
(config_dir / TRAINER_TOML).as_posix(),
(config_dir / TRAINER_CONFIG).as_posix(),
]
logger.info(f"Starting trainer on GPU(s) {' '.join(map(str, trainer_gpu_ids))}")
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
@@ -471,8 +470,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
config_path=config_dir / RL_TOML,
output_dir=config.output_dir,
config_path=config_dir / RL_CONFIG,
output_dir=config.run_dir,
gpus_per_node=config.deployment.gpus_per_node,
)
elif config.inference is not None and config.inference.deployment.type == "disaggregated":
@@ -481,9 +480,9 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
script = template.render(
**config.slurm.template_vars,
is_disaggregated=True,
run_name=config.run.name,
config_dir=config_dir,
output_dir=config.output_dir,
orchestrator_output_dir=config.orchestrator.output_dir,
output_dir=config.run_dir,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
nodes_per_infer_replica=infer_deploy.num_nodes,
@@ -522,9 +521,9 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
script = template.render(
**config.slurm.template_vars,
is_disaggregated=False,
run_name=config.run.name,
config_dir=config_dir, # TODO: should prob have each subconfig path separately
output_dir=config.output_dir,
orchestrator_output_dir=config.orchestrator.output_dir,
output_dir=config.run_dir,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.total_infer_nodes,
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
@@ -567,12 +566,12 @@ def rl_slurm(config: RLConfig):
config.log.level or os.environ.get("PRIME_LOG_LEVEL", "info"), json_logging=config.log.json_logging
)
config_dir = config.output_dir / "configs"
log_dir = get_log_dir(config.output_dir)
config_dir = get_config_dir(config.run_dir)
log_dir = latest_log_dir(config.run_dir)
if config.deployment.type == "single_node":
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean_output_dir"})
logger.info(f"Wrote config to {config_dir / RL_TOML}")
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean"})
logger.info(f"Wrote config to {config_dir / RL_CONFIG}")
train_env_names = env_server_names(config, "train")
eval_env_names = env_server_names(config, "eval")
@@ -604,7 +603,7 @@ def rl_slurm(config: RLConfig):
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
)
script_path = config.output_dir / RL_SBATCH
script_path = config.run_dir / RL_SBATCH
write_slurm_script(config, config_dir, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
@@ -622,36 +621,49 @@ def rl_slurm(config: RLConfig):
def rl(config: RLConfig):
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
# The run identity is runtime-only, never sub-config: $PRL_RUN_ID / $PRL_RUN_NAME are
# the vehicle for runtime info between processes, and every spawned process inherits
# them. Components launched standalone have no run identity. TODO: fetch the id from
# the Prime SDK once runs are registered there.
os.environ.setdefault("PRL_RUN_ID", uuid.uuid4().hex)
assert config.run.name is not None # resolved at construction
os.environ["PRL_RUN_NAME"] = config.run.name
resuming = config.resume is not None
clean = config.clean and not os.environ.get("NEVER_CLEAN")
ckpt_output_dir = config.ckpt.output_dir if config.ckpt else None
validate_output_dir(config.output_dir, resuming=resuming, clean=clean, ckpt_output_dir=ckpt_output_dir)
config.output_dir.mkdir(parents=True, exist_ok=True)
validate_run_dir(
config.run_dir, output_dir=config.output_dir, resuming=resuming, clean=clean, ckpt_output_dir=ckpt_output_dir
)
config.run_dir.mkdir(parents=True, exist_ok=True)
if ckpt_output_dir is not None:
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
# Clean stale rollouts and broadcasts. When resuming, anything past the resume
# step is stale. When training from scratch, every existing step directory is
# stale — without this, a fresh run in a dirty output_dir would pick up rollouts
# stale — without this, a fresh run in a dirty run dir would pick up rollouts
# from a previous run and the orchestrator would see a negative async level.
resume_step: int | None = None
if resuming:
resume_step = config.ckpt.resume_step
if resume_step == -1:
ckpt_base = ckpt_output_dir if ckpt_output_dir is not None else config.output_dir
resume_step = resolve_latest_ckpt_step(get_ckpt_dir(ckpt_base))
if config.resume.dir is not None:
resume_step = config.resume.dir_step
else:
resume_step = config.resume.step
if resume_step is None:
ckpt_base = ckpt_output_dir if ckpt_output_dir is not None else config.run_dir
resume_step = resolve_latest_ckpt_step(get_ckpt_dir(ckpt_base))
if resume_step is not None:
get_logger().info(f"Resuming from step {resume_step}, cleaning future rollouts and broadcasts")
clean_future_steps(config.output_dir, resume_step)
clean_future_steps(config.run_dir, resume_step)
else:
get_logger().info("Training from scratch, cleaning any stale rollouts and broadcasts")
clean_future_steps(config.output_dir, -1)
clean_future_steps(config.run_dir, -1)
if not config.dry_run:
from prime_rl.trainer.model import pre_download_model
pre_download_model(config.trainer.model.name)
pre_download_model(config.trainer.model.name, skip_weights=config.trainer.model.debug.random_init)
if config.slurm is not None:
rl_slurm(config)
+30 -26
View File
@@ -1,3 +1,4 @@
import json
import os
import subprocess
import sys
@@ -6,12 +7,16 @@ from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
import tomli_w
from prime_rl.configs.sft import SFTConfig
from prime_rl.utils.config import cli, to_toml_dict
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir, validate_output_dir
from prime_rl.utils.pathing import (
create_attempt_log_dir,
format_log_message,
get_config_dir,
latest_log_dir,
validate_run_dir,
)
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_TRAINER_ENV_VARS,
@@ -21,15 +26,15 @@ from prime_rl.utils.process import (
set_proc_title,
)
SFT_TOML = "sft.toml"
SFT_CONFIG = "sft.json"
SFT_SBATCH = "sft.sbatch"
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
"""Write resolved config to disk, excluding launcher-only fields."""
config_path.parent.mkdir(parents=True, exist_ok=True)
with open(config_path, "wb") as f:
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
with open(config_path, "w") as f:
json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2)
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path) -> None:
@@ -52,14 +57,14 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path)
script = template.render(
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.output_dir,
output_dir=config.run_dir,
gpus_per_node=config.deployment.gpus_per_node,
)
else:
script = template.render(
**config.slurm.template_vars,
config_path=config_path,
output_dir=config.output_dir,
output_dir=config.run_dir,
trainer_env_vars=trainer_env_vars,
num_nodes=config.deployment.num_nodes,
gpus_per_node=config.deployment.gpus_per_node,
@@ -76,21 +81,21 @@ def sft_slurm(config: SFTConfig):
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = get_config_dir(config.output_dir)
config_path = config_dir / SFT_TOML
config_dir = get_config_dir(config.run_dir)
config_path = config_dir / SFT_CONFIG
exclude = (
{"deployment", "slurm", "dry_run", "clean_output_dir"}
{"deployment", "slurm", "dry_run", "clean"}
if config.deployment.type == "multi_node"
else {"slurm", "dry_run", "clean_output_dir"}
else {"slurm", "dry_run", "clean"}
)
write_config(config, config_path, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
script_path = config.output_dir / SFT_SBATCH
script_path = config.run_dir / SFT_SBATCH
write_slurm_script(config, config_path, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
log_dir = get_log_dir(config.output_dir)
log_dir = latest_log_dir(config.run_dir)
num_nodes = config.deployment.num_nodes if config.deployment.type == "multi_node" else 1
log_message = format_log_message(log_dir=log_dir, trainer=True, num_train_nodes=num_nodes)
@@ -113,8 +118,8 @@ def sft_local(config: SFTConfig):
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = get_config_dir(config.output_dir)
config_path = config_dir / SFT_TOML
config_dir = get_config_dir(config.run_dir)
config_path = config_dir / SFT_CONFIG
write_config(config, config_path)
logger.info(f"Wrote config to {config_path}")
@@ -122,8 +127,7 @@ def sft_local(config: SFTConfig):
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
return
log_dir = config.output_dir / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
log_dir = create_attempt_log_dir(config.run_dir)
from prime_rl.utils.utils import get_free_port
@@ -132,7 +136,7 @@ def sft_local(config: SFTConfig):
"--role=trainer",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
f"--log-dir={config.output_dir / 'logs' / 'trainer' / 'torchrun'}",
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
"--redirect=3",
"--tee=3",
@@ -140,7 +144,7 @@ def sft_local(config: SFTConfig):
"-m",
"prime_rl.trainer.sft.train",
"@",
(config_dir / SFT_TOML).as_posix(),
(config_dir / SFT_CONFIG).as_posix(),
]
logger.info(f"Starting SFT trainer with {config.deployment.num_gpus} GPU(s)")
@@ -206,15 +210,15 @@ def sft_local(config: SFTConfig):
def sft(config: SFTConfig):
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
config.output_dir.mkdir(parents=True, exist_ok=True)
resuming = config.resume is not None
clean = config.clean and not os.environ.get("NEVER_CLEAN")
validate_run_dir(config.run_dir, output_dir=config.output_dir, resuming=resuming, clean=clean)
config.run_dir.mkdir(parents=True, exist_ok=True)
if not config.dry_run:
from prime_rl.trainer.model import pre_download_model
pre_download_model(config.model.name)
pre_download_model(config.model.name, skip_weights=config.model.debug.random_init)
if config.slurm is not None:
sft_slurm(config)

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