Compare commits

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

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

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

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

* Repoint verifiers submodule to merged main

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

---------

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

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

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

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

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

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

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

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

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

* test: drop NVFP4 expectation, BF16 only

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

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

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

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

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

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

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

* chore: bump verifiers pin to the reworked branch head

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

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

* chore: bump verifiers pin (v1 CLI simplifications)

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

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

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

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

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

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

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

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

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

* chore: bump verifiers pin (ruff fixes)

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

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

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

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

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

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

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

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

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

* chore: pin verifiers to the merged main commit

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

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

* chore: floor verifiers at 0.3.1.dev12

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Removes the multi-tenant infrastructure:

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

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

* feat: always broadcast step-0 weights at startup

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

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

* fix: assign base_url as str in auto_setup_inference_client

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

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

---------

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

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

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

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

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

* refactor: consume vf.ServeConfig as-is

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* chore: verifiers floors to 0.3.0 (released)

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

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

* chore: relock for the 0.3.0 floors

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

* chore: renderers floor to 0.1.9 (released)

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

---------

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

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

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

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

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

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

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

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

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

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

Measured on the first green build of this branch:

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

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

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

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

Splitting also lets cluster nodes pull these layers in parallel.
2026-08-06 16:01:26 -07:00
168 changed files with 2139 additions and 7092 deletions
+6 -2
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
@@ -193,7 +193,11 @@ jobs:
with:
context: .
file: ./Dockerfile.cuda
push: true
# zstd compresses the multi-GB venv layers several times faster than gzip at a
# comparable ratio. No `force-compression`, so base-image layers are reused as-is
# rather than needlessly recompressed. Pulling zstd layers needs containerd >= 1.5
# or Docker >= 23.
outputs: type=image,push=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
with:
+2 -5
View File
@@ -32,7 +32,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Install dependencies
@@ -84,9 +84,6 @@ jobs:
- test: reverse_text_moe
runner: vm
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: reverse_text_multi_run
runner: 4xa6000
pytest_args: "tests/integration/test_reverse_text_multi_run.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py"
@@ -103,7 +100,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Install dependencies
+1 -1
View File
@@ -79,7 +79,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
with:
+3 -3
View File
@@ -4,9 +4,9 @@
[submodule "renderers"]
path = deps/renderers
url = git@github.com:PrimeIntellect-ai/renderers.git
[submodule "research-environments"]
path = deps/research-environments
url = git@github.com:PrimeIntellect-ai/research-environments.git
[submodule "prime-envs"]
path = deps/prime-envs
url = git@github.com:PrimeIntellect-ai/prime-envs.git
[submodule "pydantic-config"]
path = deps/pydantic-config
url = https://github.com/PrimeIntellect-ai/pydantic-config
+21 -7
View File
@@ -1,3 +1,7 @@
# syntax=docker/dockerfile:1
# ^ `COPY --exclude` (used to split the venv into parallel-compressible layers) needs
# Dockerfile syntax >= 1.19; `docker/dockerfile:1` resolves to the latest stable 1.x.
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
# Build stage - multi-arch base (supports amd64 + arm64)
@@ -128,11 +132,6 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
&& rm -rf /tmp/nixl /app/deps/nixl_cu12-*.whl; \
fi
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
ARG TARGETARCH
COPY scripts/docker-arm64-post-install.sh /app/scripts/docker-arm64-post-install.sh
RUN if [ "$TARGETARCH" = "arm64" ]; then /app/scripts/docker-arm64-post-install.sh; fi
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
# COPY ships only the trimmed result (~1.5 GB) instead of the full ~6.6 GB. Drops the math
# runtime libs (cublas/cusparse/cufft/cusolver/curand/npp/nvjpeg) and big static .a
@@ -217,8 +216,23 @@ RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.
USER appuser
ENV PATH="/usr/local/bin:$PATH"
WORKDIR /app
# Copy the application from the builder
COPY --from=builder --chown=appuser:appuser /app /app
# Copy the application from the builder, splitting the venv's largest trees into their
# own layers. BuildKit compresses and pushes layers in parallel, so shipping the whole
# ~20 GB venv as one layer serialized the export behind a single compressor. Splitting
# also lets nodes pull the image in parallel. Keep the excludes below in sync with the
# per-tree copies that follow, or the data lands in the image twice.
COPY --from=builder --chown=appuser:appuser \
--exclude=.venv/lib/python3.12/site-packages/nvidia \
--exclude=.venv/lib/python3.12/site-packages/torch \
--exclude=.venv/lib/python3.12/site-packages/vllm \
--exclude=.venv/lib/python3.12/site-packages/flash_attn \
--exclude=.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so \
/app /app
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/nvidia /app/.venv/lib/python3.12/site-packages/nvidia
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/torch /app/.venv/lib/python3.12/site-packages/torch
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/vllm /app/.venv/lib/python3.12/site-packages/vllm
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn /app/.venv/lib/python3.12/site-packages/flash_attn
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so /app/.venv/lib/python3.12/site-packages/
COPY --from=builder /opt/ucx /opt/ucx
# Copy and set up entrypoint script
+3 -12
View File
@@ -95,7 +95,7 @@ cd prime-rl
2. Initialize submodules
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
```
3. Install [uv](https://docs.astral.sh/uv/)
@@ -113,15 +113,6 @@ uv sync --all-extras
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
4.1. On aarch64 hosts: build flash-attn from source for your GPU
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`.
```bash
bash scripts/docker-arm64-post-install.sh
```
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
@@ -166,7 +157,7 @@ uv run trainer @ configs/debug/fake/rl.toml
5. Check that you can run the inference server (*this requires 1 GPU*)
```bash
uv run inference --model.name Qwen/Qwen3-0.6B
uv run inference --vllm.model Qwen/Qwen3-0.6B
```
6. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
@@ -227,7 +218,7 @@ Check out the [docs](docs) directory for in-depth guides on how to use prime-rl.
- [**Training**](docs/training.md) - RL, SFT, evals, checkpointing, observability, rules of thumb
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA, multi-tenant training
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA
- [**Development**](docs/development.md) - Test suite, pre-commit hooks, adding a new model
## Contributing
+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
+2 -4
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"
@@ -36,10 +36,8 @@ type = "subprocess"
[trainer.model]
seq_len = 16384
[inference.model]
[inference.vllm]
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+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"
+2 -2
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"
@@ -54,5 +54,5 @@ type = "subprocess"
[ckpt] # Checkpoint at the end of training
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
+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
@@ -30,7 +30,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"
@@ -39,10 +39,12 @@ id = "null"
type = "subprocess"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[inference.vllm]
enable_lora = true
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "prime-qwen3"
@@ -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"
@@ -38,10 +38,12 @@ id = "null"
type = "subprocess"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[inference.vllm]
enable_lora = true
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "prime-qwen3"
@@ -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"
@@ -38,11 +38,9 @@ id = "null"
type = "subprocess"
[inference]
gpu_memory_utilization = 0.7
[inference.model]
[inference.vllm]
max_model_len = 2048
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "default"
@@ -1,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,13 +0,0 @@
# Inference config for multi-run RL integration test
enable_lora = true
max_lora_rank = 8
max_loras = 4
gpu_memory_utilization = 0.7
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
max_model_len = 2048
[weight_broadcast]
type = "filesystem"
@@ -1,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"
@@ -72,4 +72,6 @@ type = "subprocess"
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.4
@@ -30,7 +30,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -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"
@@ -78,4 +78,6 @@ type = "subprocess"
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.4
@@ -27,7 +27,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"
+3 -3
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
@@ -40,5 +40,5 @@ max_completion_tokens = 768
[trainer]
[inference.parallel]
dp = 4
[inference.vllm]
data_parallel_size = 4
+4 -7
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"
@@ -54,12 +54,9 @@ type = "subprocess"
seq_len = 16384
attn = "flash_attention_2"
[inference.parallel]
dp = 4
[inference.model]
[inference.vllm]
max_model_len = 8192
data_parallel_size = 4
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+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"
+3 -5
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"
@@ -40,8 +40,6 @@ max_completion_tokens = 512
[trainer]
[inference.parallel]
dp = 4
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
data_parallel_size = 4
+3 -4
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"
@@ -35,8 +35,7 @@ max_completion_tokens = 1024
[trainer]
[inference.parallel]
dp = 6
[inference.vllm]
data_parallel_size = 6
[orchestrator.renderer]
name = "prime-qwen3"
@@ -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]
+3 -3
View File
@@ -24,10 +24,10 @@ Needed for `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--server.port 8001 \
--gpu-memory-utilization 0.5 \
--model.enforce-eager
--vllm.gpu-memory-utilization 0.5 \
--vllm.enforce-eager
```
## Run the debug configs
+3 -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
@@ -58,4 +58,6 @@ name = "prime-qwen3"
lr = 1e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+4 -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"
@@ -58,4 +58,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+4 -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"
@@ -58,4 +58,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+8 -6
View File
@@ -3,8 +3,8 @@
# ref_logprobs, GRPO samples don't, and both pack into the same micro batches.
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/mixed_grpo_opd.toml
@@ -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"
@@ -85,4 +85,6 @@ type = "subprocess"
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+7 -5
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/opd.toml
@@ -24,7 +24,7 @@ type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
@@ -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"
@@ -70,4 +70,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+7 -5
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/opd_lora.toml
@@ -24,7 +24,7 @@ type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
@@ -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"
@@ -76,4 +76,6 @@ save_adapter_separately = true
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+4 -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"
@@ -70,4 +70,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+4 -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"
@@ -64,4 +64,6 @@ type = "subprocess"
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+7 -5
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/sft_distill.toml
@@ -25,7 +25,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -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"
@@ -75,4 +75,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+7 -5
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/sft_distill_lora.toml
@@ -25,7 +25,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -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"
@@ -81,4 +81,6 @@ save_adapter_separately = true
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+5 -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"
@@ -64,4 +64,6 @@ type = "subprocess"
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
Vendored Submodule
+1
Submodule deps/prime-envs added at b30aad3637
+1 -1
+1 -1
+1 -8
View File
@@ -1,6 +1,6 @@
# Advanced
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, multi-tenant training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
## Table of Contents
@@ -11,7 +11,6 @@ This page covers the specialized features layered on top of the core training st
- [Enabling VLM Mode](#enabling-vlm-mode)
- [Limitations](#limitations)
- [LoRA Training](#lora-training)
- [Multi-Tenant Training](#multi-tenant-training)
- [Disaggregated Prefill/Decode Inference](#disaggregated-prefilldecode-inference)
## Custom Modeling
@@ -123,12 +122,6 @@ LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** su
save_adapter_separately = true
```
LoRA pairs naturally with [multi-tenant training](#multi-tenant-training) — each tenant gets its own adapter and the backbone is shared across all of them in trainer memory.
## Multi-Tenant Training
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/src/prime_rl/trainer/runs.py).
## Disaggregated Prefill/Decode Inference
For large MoE serving, splitting prefill and decode onto separate vLLM groups can substantially improve throughput. Pick the prefill:decode ratio based on workload shape:
+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
+6 -6
View File
@@ -50,7 +50,7 @@ CLI flags mirror the TOML tree using dots:
--max-steps 50 # top-level
--model.name Qwen/Qwen3-4B # nested
--trainer.optim.lr 1e-5 # double-nested
--inference.parallel.tp 4
--inference.vllm.tensor-parallel-size 4
```
> Field names are snake_case in TOML (`max_model_len`) and kebab-case on the CLI (`--max-model-len`).
@@ -126,11 +126,11 @@ To **disable** a sub-config that's on by default, use `--no-<name>` on the CLI o
TOML has no `null`. Use the string `"None"`, which the loader coerces:
```toml
[inference.model]
[inference.vllm]
max_model_len = "None"
```
On the CLI: `--inference.model.max-model-len None`.
On the CLI: `--inference.vllm.max-model-len None`.
### Discriminated Unions
@@ -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]
+3 -3
View File
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
| Workflow | Trigger | What runs | Where |
|---|---|---|---|
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_multi_run`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
@@ -118,8 +118,8 @@ Then run the full RL stack on reverse-text:
uv run rl @ configs/ci/integration/reverse-text-moe/start.toml \
--model.name samsja/mini-glm-moe \
--trainer.model.impl custom \
--inference.gpu-memory-utilization 0.7 \
--inference.model.max-model-len 2048
--inference.vllm.gpu-memory-utilization 0.7 \
--inference.vllm.max-model-len 2048
```
What to look for:
+23 -26
View File
@@ -42,7 +42,7 @@ type = "single_node" # or "multi_node" or "disaggregated"
To configure the inference server, you can use the `InferenceConfig` field. This is a config-field that allows you to set the inference server-specific knobs. Most of these are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
```toml
[inference]
[inference.vllm]
model = "PrimeIntellect/INTELLECT-3"
...
```
@@ -63,12 +63,10 @@ The launcher starts a `vllm-router` on `inference.server.port` (default `8000`)
This deployment shape runs the inference server on a single node, if configured with NVLink enabled, it allows you more freedom in terms of parallelism configurations.
```toml
[inference]
[inference.vllm]
enable_expert_parallel = true # defaults to False
[inference.parallel]
tp = 2
dp = 4
tensor_parallel_size = 2
data_parallel_size = 4
[inference.deployment]
type = "single_node"
@@ -76,7 +74,7 @@ type = "single_node"
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required `orchestrator.max_inflight_requests`. Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.enable_expert_parallel` or `inference.parallel.tp` to maximize the available GPU memory.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.vllm.enable_expert_parallel` or `inference.vllm.tensor_parallel_size` to maximize the available GPU memory.
You can also increase the available KV cache memory by enabling `inference.kv_cache_offload`. More details in the [Advanced Configuration](#advanced-configuration) section.
@@ -86,7 +84,7 @@ You can also increase the available KV cache memory by enabling `inference.kv_ca
This deployment shape branches into 2 sub-shapes:
- [Multi-replica](#multi-replica) - Runs the inference server on multiple nodes, but each node runs an independent vLLM replica. You can think of this as a for-loop over single-node deployments.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.vllm.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
### Multi-replica
@@ -98,35 +96,31 @@ Parallelism configuration is the same as the single-node deployment. The shape i
type = "multi_node"
num_nodes = 2
[inference]
[inference.vllm]
model = "PrimeIntellect/INTELLECT-3"
[inference.parallel]
tp = 2
dp = 4
tensor_parallel_size = 2
data_parallel_size = 4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a single global router running on the first inference node, fronting the per-rank endpoints of all replicas — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[inference.router]` block. You can read more about the supported routing options in the [router](#router) section.
This configuration will run 2 independent vLLM replicas, each with `tensor_parallel_size=2` and `data_parallel_size=4`. Routing is handled by a single global router running on the first inference node, fronting the per-rank endpoints of all replicas — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[inference.router]` block. You can read more about the supported routing options in the [router](#router) section.
### Wide-EP
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.enable_expert_parallel = true`.
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.vllm.enable_expert_parallel = true`.
```toml
[inference.deployment]
type = "multi_node"
num_nodes = 2
[inference]
[inference.vllm]
model = "PrimeIntellect/INTELLECT-3"
enable_expert_parallel = true
[inference.parallel]
tp = 2
dp = 8
tensor_parallel_size = 2
data_parallel_size = 8
```
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tp = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tensor_parallel_size = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
## P/D Disaggregation
@@ -272,24 +266,27 @@ type = "disaggregated"
These are role-specific and layer on top of [`env_vars`](configuration.md#environment-variables) shared by all inference processes regardless of role.
### Other vLLM features
We support various other vLLM features. Some of those, such as `enable_dbo`, `enable_eplb` are exposed as a top-level config fields. For those that are not, you can configure them by setting `inference.vllm_extra` to the desired value.
The `[inference.vllm]` section is a pass-through: every key is forwarded to the vLLM server under vLLM's own argument name, whether prime-rl types it or not. Anything `vllm serve` accepts can be set here.
```toml
[inference.vllm_extra]
[inference.vllm]
headless = true
max_num_seqs = 256
```
On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (or `--vllm.max-num-seqs 256` for the standalone inference entrypoint); dict-valued arguments take a JSON string, e.g. `--vllm.compilation-config '{"cudagraph_mode": "NONE"}'`.
### Router Replay
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.enable_return_routed_experts = true`.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`.
```toml
[trainer]
enable_router_replay = true # this will also auto-set the inference.enable_return_routed_experts = true
enable_router_replay = true # this will also auto-set inference.vllm.enable_return_routed_experts = true
[inference]
[inference.vllm]
enable_return_routed_experts = true
```
+3 -3
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.
@@ -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.
+2 -2
View File
@@ -38,7 +38,7 @@ The `rl`, `sft`, and `inference` entrypoints all accept a `[deployment]` block (
uv run rl @ rl.toml \
--deployment.num-infer-gpus 6 \
--deployment.num-train-gpus 2 \
--inference.parallel.dp 6
--inference.vllm.data-parallel-size 6
```
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
@@ -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
+3 -3
View File
@@ -37,7 +37,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at the source's derived `serve.address`); only needed when running the orchestrator standalone. |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at a derived loopback address); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
## RL Trainer
@@ -90,7 +90,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 |
@@ -103,7 +103,7 @@ Frozen models are declared inline on the algorithm, named where the model is use
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name <frozen-model> --server.port 8001
--vllm.model <frozen-model> --server.port 8001
```
The standalone `uv run sft` entrypoint is the more traditional SFT path — pure dataset-based, no orchestrator. Use the `sft` algorithm only when you want a frozen model to generate the supervision on the fly.
+9 -11
View File
@@ -109,7 +109,7 @@ 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 +122,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
@@ -142,7 +142,7 @@ 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 +155,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
@@ -184,7 +184,7 @@ labels = ["glm45air-search"]
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,22 +193,20 @@ 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
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
[inference.vllm]
max_model_len = 131072
[inference.parallel]
tp = 8
tensor_parallel_size = 8
enable_return_routed_experts = true
+6 -8
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.
@@ -101,7 +101,7 @@ thinking_retention = "all"
name = "scaleswe"
[orchestrator.train.source.env.taskset]
id = "scaleswe-v1"
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
@@ -124,7 +124,7 @@ 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"
@@ -142,15 +142,13 @@ rollout = 3600
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
[inference.vllm]
max_model_len = 131072
[inference.parallel]
tp = 8
tensor_parallel_size = 8
enable_return_routed_experts = true
+12 -14
View File
@@ -105,20 +105,20 @@ 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
@@ -144,19 +144,19 @@ labels = ["glm45air-terminal"]
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
@@ -178,34 +178,32 @@ labels = ["glm45air-terminal"]
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
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
[inference.vllm]
max_model_len = 131072
[inference.parallel]
tp = 8
tensor_parallel_size = 8
enable_return_routed_experts = true
+11 -13
View File
@@ -6,22 +6,9 @@
output_dir = "/shared/outputs/glm5.2-16node-llmd"
enable_expert_parallel = true
gpu_memory_utilization = 0.75
enable_eplb = false
use_deep_gemm = true
enable_fp32_lm_head = true
[model]
name = "zai-org/GLM-5.2-FP8"
max_model_len = 91000
tool_call_parser = "glm47"
reasoning_parser = "glm45"
[vllm_extra]
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[kv_cache_offload]
type = "mooncake"
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
@@ -64,3 +51,14 @@ non_cached_tokens = 128
[slurm]
job_name = "glm5.2-16node-llmd"
partition = "all"
[vllm]
model = "zai-org/GLM-5.2-FP8"
max_model_len = 91000
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
+8 -8
View File
@@ -1,12 +1,4 @@
enable_expert_parallel = true
enable_eplb = false
use_deep_gemm = true
gpu_memory_utilization = 0.85
[model]
name = "zai-org/GLM-5-FP8"
tool_call_parser = "auto"
reasoning_parser = "glm45"
[deployment]
type = "disaggregated"
@@ -17,3 +9,11 @@ gpus_per_node = 8
[slurm]
job_name = "glm5"
partition = "cluster"
[vllm]
model = "zai-org/GLM-5-FP8"
tool_call_parser = "auto"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.85
enable_expert_parallel = true
enable_eplb = false
+11 -18
View File
@@ -48,7 +48,6 @@ num_decode_replicas = 1
"max_num_batched_tokens" = 96
"max_num_seqs" = 96
[inference.router]
type = "llm-d"
@@ -66,6 +65,16 @@ non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[inference.vllm]
model = "zai-org/GLM-5.1-FP8"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[slurm]
job_name = "glm5-llmd"
partition = "all" # FILL IN: set to your cluster's partition
@@ -118,12 +127,11 @@ temperature = 1.0
[orchestrator.train.sampling.extra_body.chat_template_kwargs]
clear_thinking = false
[[orchestrator.train.source]]
name = "r2e"
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
@@ -133,25 +141,10 @@ type = "prime"
labels = ["glm5-llmd"]
[inference]
enable_expert_parallel = true
# <0.80 because glm5 layers are too large for 0.85
gpu_memory_utilization = 0.75
enable_eplb = false
use_deep_gemm = true
enable_fp32_lm_head = true
[inference.model]
name = "zai-org/GLM-5.1-FP8"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
# Speed up GLM-5.1 weight load: EP weight filtering + safetensors prefetch.
[inference.vllm_extra]
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
# Mooncake distributed CPU KV store: 1TB/node shared pool across all inference nodes.
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
+7 -9
View File
@@ -23,10 +23,15 @@ type = "disaggregated"
prefill_nodes_per_replica = 4
decode_nodes_per_replica = 4
[inference.vllm]
model = "zai-org/GLM-5-FP8"
tool_call_parser = "glm47"
gpu_memory_utilization = 0.80
enable_expert_parallel = true
enable_eplb = false
[slurm]
job_name = "glm5-pd-disag"
[ckpt]
interval = 100
@@ -58,7 +63,6 @@ type = "adamw"
lr = 1e-6
weight_decay = 0.1
[orchestrator]
batch_size = 4096
group_size = 16
@@ -75,7 +79,7 @@ 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"
@@ -89,12 +93,6 @@ type = "gibberish"
enforce = true
[inference]
enable_expert_parallel = true
# we need <0.85 bc glm5 layers are too large for 0.85
gpu_memory_utilization = 0.80
enable_eplb = false
use_deep_gemm = true
[inference.model]
name = "zai-org/GLM-5-FP8"
tool_call_parser = "glm47"
+9 -11
View File
@@ -52,7 +52,7 @@ 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"
@@ -66,7 +66,7 @@ name = "deepdive"
ratio = 0.2
[orchestrator.train.source.env.taskset]
id = "deepdive-v1"
id = "deepdive"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
@@ -82,7 +82,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 +95,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 +111,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,7 +130,7 @@ 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"
@@ -143,7 +143,7 @@ labels = ["intellect-3.1", "swe-bench-verified"]
name = "aime2025"
[orchestrator.eval.source.env.taskset]
id = "aime25-v1"
id = "aime25"
[orchestrator.eval.source.env.agent.harness]
id = "null"
@@ -151,9 +151,7 @@ id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[inference.parallel]
tp = 8
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[inference.vllm]
tensor_parallel_size = 8
[orchestrator.renderer]
name = "default"
+4 -7
View File
@@ -48,12 +48,11 @@ batch_size = 2048
oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.train.source]]
name = "swe"
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
@@ -69,7 +68,7 @@ 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"
@@ -78,9 +77,7 @@ id = "bash"
type = "prime"
labels = ["minimax-swe", "swe-bench-verified"]
[inference.parallel]
tp = 8
# PrimeIntellect/MiniMax-M2.5-bf16 — template-identical to MiniMaxAI/MiniMax-M2.5 (mapped).
[inference.vllm]
tensor_parallel_size = 8
[orchestrator.renderer]
name = "minimax-m2"
+8 -10
View File
@@ -85,7 +85,7 @@ truncate_history_thinking = false
name = "scaleswe"
[orchestrator.train.source.env.taskset]
id = "scaleswe-v1"
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
@@ -106,7 +106,7 @@ 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"
@@ -122,13 +122,11 @@ labels = ["nemotron-3-super-swe"]
rollout = 3600
[inference]
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
enable_prefix_caching = true
enable_expert_parallel = true
enable_return_routed_experts = true
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
enable_prefix_caching = true
[inference.model]
max_model_len = 131072
[inference.parallel]
tp = 8
+4 -4
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"
@@ -75,5 +75,5 @@ id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[inference.parallel]
tp = 8
[inference.vllm]
tensor_parallel_size = 8
+4 -4
View File
@@ -50,7 +50,7 @@ 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"
@@ -66,7 +66,7 @@ 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"
@@ -75,5 +75,5 @@ id = "bash"
type = "prime"
labels = ["qwen30b-swe", "swe-bench-verified"]
[inference.parallel]
tp = 8
[inference.vllm]
tensor_parallel_size = 8
+5 -7
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]
@@ -51,11 +51,9 @@ id = "null"
type = "modal"
[inference]
gpu_memory_utilization = 0.85
[inference.model]
[inference.vllm]
max_model_len = 32768
[inference.parallel]
dp = 2
tp = 4
data_parallel_size = 2
tensor_parallel_size = 4
gpu_memory_utilization = 0.85
+6 -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:
@@ -32,13 +32,13 @@ We use non-default settings to balance the difficulty: 3 fixed turns (instead of
Start the inference server:
```bash
# In the `Inference` pane
uv run inference --enable-lora --model.name Qwen/Qwen3-4B-Instruct-2507
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507
```
Evaluate the base model:
```bash
# In the `Trainer` pane
uv run eval alphabet-sort-v1 --harness.id null \
uv run eval alphabet-sort --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
-n 20 \
@@ -110,12 +110,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetS
Let's see how our final RL checkpoint performs on the eval set.
```bash
# In the `Inference` pane
uv run inference --enable-lora --model.name PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
```
```bash
# In the `Trainer` pane
uv run eval alphabet-sort-v1 --harness.id null \
uv run eval alphabet-sort --harness.id null \
-m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL \
--client.base-url http://localhost:8000/v1 \
-n 20 \
+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
+3 -5
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"
@@ -49,10 +49,8 @@ type = "subprocess"
[trainer.model]
seq_len = 16384
[inference.model]
[inference.vllm]
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+11 -11
View File
@@ -1,15 +1,15 @@
# Reverse Text
We demonstrate how to train `Qwen3-0.6B` to reverse a small chunk of text. We will use a SFT warmup to learn the skill of text reversal on longer documents and then a quick RL run on the `reverse-text-v1` taskset. We use a similar setup in our CI and for development.
We demonstrate how to train `Qwen3-0.6B` to reverse a small chunk of text. We will use a SFT warmup to learn the skill of text reversal on longer documents and then a quick RL run on the `reverse-text` taskset. We use a similar setup in our CI and for development.
> The commands in this example were designed to be run on 2 GPUs (one trainer and one inference GPU). It is possible to run on less or more GPUs using different deployment strategies. If you run on a different setup, you may need to adjust the start commands.
## Setup
The `reverse-text-v1` taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
The `reverse-text` taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import reverse_text_v1"
uv run python -c "import reverse_text"
```
First, let's start a `tmux` session which we will use throughout the experiment.
@@ -22,12 +22,12 @@ Let's check how well `Qwen3-0.6B` does out-of-the-box on the `reverse-text` envi
```bash
# Run this in the `Inference` pane
uv run inference --model.name Qwen/Qwen3-0.6B
uv run inference --vllm.model Qwen/Qwen3-0.6B
```
```bash
# Run this in the `Trainer` pane
uv run eval reverse-text-v1 --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval reverse-text --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
This is of course just a quick vibe check and no full-fledged evaluation, but we can see that the model struggles with this task. In this specific instance, we got an **average reward of ~0.05** across the 20x3 rollouts. Let's do some training!
@@ -95,12 +95,12 @@ Let's see how our final RL checkpoints perform on the `reverse-text` environment
```bash
# Run this in the `Inference` pane
uv run inference --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
uv run inference --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
```
```bash
# Run this in the `Trainer` pane
uv run eval reverse-text-v1 --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval reverse-text --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
Way better! Now we get an **average reward of ~0.8**.
@@ -210,10 +210,10 @@ kubectl exec -it my-exp-trainer-0 -- bash
# If inference server isn't running with the RL model, start it in another terminal:
kubectl exec -it my-exp-inference-0 -- bash
uv run inference --model.name /data/outputs/weights/step_20
uv run inference --vllm.model /data/outputs/weights/step_20
# Back in trainer pod, run evaluation
uv run eval reverse-text-v1 --harness.id null \
uv run eval reverse-text --harness.id null \
-m /data/outputs/weights/step_20 \
--client.base-url $INFERENCE_URL \
-n 20 -r 3 --sampling.max-tokens 1024 --no-push
@@ -223,8 +223,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"
+6 -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:
@@ -70,14 +70,14 @@ Start the inference server:
```bash
# In the `Inference` pane
uv run inference --enable-lora --model.name Qwen/Qwen3-4B-Instruct-2507 --model.tool_call_parser hermes
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507 --vllm.tool-call-parser hermes
```
Evaluate the base model:
```bash
# In the `Trainer` pane
uv run eval wiki-search-v1 --harness.id null \
uv run eval wiki-search --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
-n 20 \
@@ -114,12 +114,12 @@ Evaluate your trained model:
```bash
# In the `Inference` pane
uv run inference --enable-lora --model.name <user>/Qwen3-4B-Instruct-WikiSearch-RL --model.tool_call_parser hermes
uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSearch-RL --vllm.tool-call-parser hermes
```
```bash
# In the `Trainer` pane
uv run eval wiki-search-v1 --harness.id null \
uv run eval wiki-search --harness.id null \
-m <user>/Qwen3-4B-Instruct-WikiSearch-RL \
--client.base-url http://localhost:8000/v1 \
-n 20 \
@@ -135,7 +135,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" }
```
+6 -6
View File
@@ -40,15 +40,11 @@ name = "qwen3-4b-wiki-search"
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[[orchestrator.train.source]]
name = "wiki-search"
[orchestrator.train.source.env.taskset]
id = "wiki-search-v1"
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
@@ -56,7 +52,11 @@ id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[ckpt] # Checkpoint at the end of training
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
+6 -6
View File
@@ -1,6 +1,6 @@
# Wordle
In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This will require a SFT warmup to learn the format and, finally, multi-turn RL against the `wordle-v1` taskset to improve performance.
In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This will require a SFT warmup to learn the format and, finally, multi-turn RL against the `wordle` taskset to improve performance.
> The commands in this example were designed to be run on 2 GPUs (one trainer and one inference GPU). It is possible to run on less or more GPUs using different deployment strategies. If you run on a different setup, you may need to adjust the start commands.
@@ -9,7 +9,7 @@ In this example, we demonstrate how to train `Qwen3-1.7B` to play Wordle. This w
The taskset is included through the Verifiers workspace. After syncing the repository, verify it with:
```bash
uv run python -c "import wordle_v1"
uv run python -c "import wordle"
```
Start the pre-layouted `tmux` session which we will use to run all experiments and view logs conveniently
@@ -22,14 +22,14 @@ Before training, we want to get a baseline score and test how well `Qwen3-1.7B`
```bash
# Run this in the `Inference` pane
uv run inference --model.name Qwen/Qwen3-1.7B
uv run inference --vllm.model Qwen/Qwen3-1.7B
```
Then, use the `eval` entrypoint to evaluate the model in the `wordle` environment. We evaluate on the 20 evaluation examples which are distinct words not appearing in the training set of the environment. We constrain the response length to 1024 tokens as this should be more than enough to play a full game.
```bash
# Run this in the `Trainer` pane
uv run eval wordle-v1 --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval wordle --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
We got an **average reward of ~0.2** across the 20x3 rollouts. From the summary, we can see that the most of the reward is coming from format and partial rewards. In fact, the model does not guess the correct word within any game, leading to a win rate of **0%**. Looking at some samples, it is evident repeatedly submitting guesses in the wrong format and is not able to revise its strategy from the environment feedback. Let's do some SFT warmup to get the model to learn the format of the environment.
@@ -98,12 +98,12 @@ Let's see how our final RL checkpoint performs on the eval set.
```bash
# Run this in the `Inference` pane
uv run inference --model.name PrimeIntellect/Qwen3-1.7B-Wordle-RL
uv run inference --vllm.model PrimeIntellect/Qwen3-1.7B-Wordle-RL
```
```bash
# Run this in the `Trainer` pane
uv run eval wordle-v1 --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
uv run eval wordle --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
Way better! Our model now wins **~60%** and gets an average reward of **~1.5**.
+3 -5
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"
@@ -35,9 +35,7 @@ max_completion_tokens = 1024
[trainer] # Default trainer config
[inference.parallel]
dp = 6
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
[inference.vllm]
data_parallel_size = 6
[orchestrator.renderer]
name = "prime-qwen3"
+4 -6
View File
@@ -2,8 +2,6 @@
This directory contains a Helm chart for deploying prime-rl training infrastructure on Kubernetes clusters.
For complete documentation, see the [Kubernetes guide](https://docs.primeintellect.ai/prime-rl/kubernetes).
## Quick Start
```bash
@@ -64,11 +62,11 @@ helm install my-exp ./prime-rl \
```bash
helm uninstall my-exp
kubectl delete pvc prime-rl-shared-data # Warning: deletes data!
# The PVC is named <release-name>-shared-data (see templates/pvc.yaml)
kubectl delete pvc my-exp-shared-data # Warning: deletes data!
```
## Learn More
- [Full Kubernetes documentation](https://docs.primeintellect.ai/prime-rl/kubernetes) - Architecture, configuration, distributed training
- [Deployment guide](https://docs.primeintellect.ai/prime-rl/deployment) - Non-Kubernetes deployments
- [Troubleshooting](https://docs.primeintellect.ai/prime-rl/troubleshooting) - Common issues
- [Scaling guide](https://docs.primeintellect.ai/prime-rl/scaling) - Non-Kubernetes multi-node deployment (SLURM), parallelism, benchmarking
+1 -1
View File
@@ -11,7 +11,7 @@ image:
orchestrator:
enabled: true
autoStart: true
command: "uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs/run_default --client.base-url $INFERENCE_URL ; sleep infinity"
command: "uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL ; sleep infinity"
resources:
requests:
memory: "1Gi"
+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:
+2 -2
View File
@@ -7,10 +7,10 @@ requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.4.2",
"renderers>=0.1.9.dev10",
"renderers>=0.1.9",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.2.2.dev76",
"verifiers>=0.3.0",
]
[build-system]
@@ -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
@@ -1,12 +1,13 @@
import json
from argparse import Namespace
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import Field, model_validator
from pydantic import ConfigDict, Field, model_validator
from pydantic_config import BaseConfig
from prime_rl.configs.shared import BaseModelConfig, EnvVars, LogConfig, SlurmConfig
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
from prime_rl.configs.shared import EnvVars, LogConfig, SlurmConfig
from prime_rl.utils.config import find_package_resource
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
# TODO: Set thinking/ solution budget
@@ -23,61 +24,192 @@ class ServerConfig(BaseConfig):
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. With Kubernetes liveness probes, keep the probe ``timeoutSeconds`` at least this high."""
class ParallelConfig(BaseConfig):
tp: int = 1
"""Tensor parallel size. Forwarded to vLLM as ``--tensor-parallel-size``."""
# Valid vLLM max_lora_rank values (`vllm.config.lora.MaxLoRARanks`), excluding 1 so
# tiny adapters round up to 8. Hardcoded rather than imported: prime-rl-configs does
# not depend on vLLM, and importing it costs seconds in every config-parsing process.
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
dp: int = Field(1, ge=1)
"""Data parallel size. Forwarded to vLLM as ``--data-parallel-size``."""
def __str__(self) -> str:
return f"tp={self.tp} dp={self.dp}"
# vLLM all2all backend options for expert-parallel deployments.
All2AllBackend = Literal[
"allgather_reducescatter",
"deepep_high_throughput",
"deepep_low_latency",
"flashinfer_nvlink_one_sided",
"flashinfer_nvlink_two_sided",
]
class ModelConfig(BaseModelConfig):
"""Configures the inference model. Most arguments are passed directly to the vLLM LLM class (https://docs.vllm.ai/en/latest/api/vllm.LLM.html).
class VllmConfig(BaseConfig):
"""Arguments forwarded to the vLLM server, under vLLM's own argument names
(https://docs.vllm.ai/en/latest/configuration/engine_args.html).
The fields below are the arguments prime-rl types, defaults, or reads back;
any other vLLM argument can be set as well (``[inference.vllm] max_num_seqs = 256``
or ``--vllm.max-num-seqs 256``) and passes through to the server verbatim.
Parser fields (``tool_call_parser``, ``reasoning_parser``) default to ``"auto"``,
which resolves to a concrete parser name at validation time from the model name.
Set to ``None`` to disable.
"""
model_config = ConfigDict(extra="allow")
model: str = "Qwen/Qwen3-0.6B"
"""HF model name or local path."""
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models. Forwarded as ``--dtype``."""
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models."""
max_model_len: int | None = None
"""Maximum model context length. If None, uses the model config's value. Forwarded as ``--max-model-len``."""
"""Maximum model context length. If None, uses the model config's value."""
enforce_eager: bool = False
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance. Forwarded as ``--enforce-eager``."""
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance."""
trust_remote_code: bool = False
"""Trust remote code. Forwarded to vLLM engine init."""
"""Trust remote code when loading the model."""
chat_template: str | None = None
"""Chat template — a Jinja2 template string or path to a template file. Forwarded as ``--chat-template``. If None, uses the model's default."""
"""Chat template — a Jinja2 template string or path to a template file. If None, uses the model's default."""
tool_call_parser: str | None = "auto"
"""Tool-call parser. Forwarded as ``--tool-call-parser``. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
"""Tool-call parser. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
reasoning_parser: str | None = "auto"
"""Parser for extracting reasoning content from model outputs. Forwarded as ``--reasoning-parser``. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
"""Parser for extracting reasoning content from model outputs. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
rope_scaling: dict[str, Any] | str | None = None
"""RoPE scaling configuration as a dict (e.g. ``{rope_type="yarn", factor=4.0, original_max_position_embeddings=32768}``). Forwarded as ``--rope-scaling``."""
"""RoPE scaling configuration as a dict (e.g. ``{rope_type="yarn", factor=4.0, original_max_position_embeddings=32768}``)."""
tensor_parallel_size: int = 1
"""Tensor parallel size."""
data_parallel_size: int = Field(1, ge=1)
"""Data parallel size."""
data_parallel_size_local: int | None = Field(None, ge=1)
"""Data parallel replicas to run on this node."""
data_parallel_rpc_port: int = Field(13345, ge=1, le=65535)
"""RPC port for data parallel communication."""
api_server_count: int = Field(1, ge=0)
"""API servers to run. Set to 0 for headless mode."""
seed: int = 0
"""Seed the inference components."""
gpu_memory_utilization: float = 0.9
"""GPU memory utilization."""
enable_prefix_caching: bool | None = None
"""Enable prefix caching."""
quantization: str | None = None
"""Online inference quantization method. If None, vLLM infers it from the checkpoint."""
enable_lora: bool = False
"""Enable LoRA."""
max_loras: int = 8
"""Maximum number of LoRAs."""
# TODO: The default value is very high because our areal impl for lora isn't ideal
# We add a lora with the same name instead of changing weights inplace
# Because we dont cancel requests that are past max_async, these requests could be using a LoRA that gets unloaded which will crash the inference server
max_cpu_loras: int = 100
"""Maximum number of LoRAs on CPU."""
max_lora_rank: int | None = None
"""Maximum LoRA rank. Rounded up to the nearest value vLLM accepts."""
lora_target_modules: list[str] | None = None
"""LoRA target modules."""
enable_expert_parallel: bool = False
"""Enable expert parallelism for MoE models."""
all2all_backend: All2AllBackend = "allgather_reducescatter"
"""All-to-all backend for expert-parallel communication."""
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB)."""
enable_dbo: bool = False
"""Enable dual batch overlap (DBO)."""
enable_return_routed_experts: bool = False
"""Return routed experts in responses."""
@model_validator(mode="before")
@classmethod
def parse_extra_values(cls, data: dict) -> dict:
"""Normalize pass-through (untyped) entries: kebab-case keys become snake_case,
and string values — which is how CLI overrides arrive — are JSON-parsed so
``--vllm.max-num-seqs 256`` lands as an int and ``--vllm.compilation-config
'{"cudagraph_mode": "NONE"}'`` as a dict. Non-JSON strings stay strings."""
if not isinstance(data, dict):
return data
for key in [k for k in data if k not in cls.model_fields]:
value = data.pop(key)
if isinstance(value, str):
try:
value = json.loads(value)
except json.JSONDecodeError:
pass
data[key.replace("-", "_")] = value
return data
@model_validator(mode="after")
def auto_resolve_parsers(self):
"""Resolve ``"auto"`` parser values to concrete parser names from the model name.
Runs after ``RLConfig.auto_setup_shared_configs`` (mode=before) has
propagated the shared ``[model] name`` into ``inference.model``, so the
propagated the shared ``[model] name`` into ``inference.vllm``, so the
name is set even when only the shared block specifies it.
"""
if self.tool_call_parser == "auto":
self.tool_call_parser = resolve_tool_call_parser(self.name)
self.tool_call_parser = resolve_tool_call_parser(self.model)
if self.reasoning_parser == "auto":
self.reasoning_parser = resolve_reasoning_parser(self.name)
self.reasoning_parser = resolve_reasoning_parser(self.model)
return self
@model_validator(mode="after")
def auto_setup_max_lora_rank(self):
"""Auto-setup max_lora_rank by rounding up to the nearest valid vLLM value.
vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512).
This validator ensures that any configured rank is rounded up to the minimum valid value
that can serve adapters of the requested rank.
"""
if self.max_lora_rank is not None:
original_rank = self.max_lora_rank
for valid_rank in VALID_VLLM_LORA_RANKS:
if valid_rank >= self.max_lora_rank:
self.max_lora_rank = valid_rank
break
else:
raise ValueError(f"max_lora_rank={original_rank} exceeds vLLM maximum of {VALID_VLLM_LORA_RANKS[-1]}")
return self
@model_validator(mode="after")
def auto_setup_api_server_count(self):
"""
Ensures that we have at least as many API servers as data parallel
size. Unless LoRA is enabled, in which case only one API server is
supported (vLLM limitation).
"""
if self.model_extra and self.model_extra.get("headless", False):
self.api_server_count = 0
return self
if "api_server_count" not in self.model_fields_set:
min_api_server_count = self.data_parallel_size_local or self.data_parallel_size
if self.api_server_count < min_api_server_count:
self.api_server_count = min_api_server_count
if self.enable_lora:
self.api_server_count = 1 # LoRA requires only one API server
return self
@@ -153,20 +285,6 @@ KVCacheOffloadConfig: TypeAlias = Annotated[
]
# Valid vLLM max_lora_rank values (from vllm/config/lora.py)
# TODO: on newer vLLM, can import via `get_args(vllm.config.lora.MaxLoRARanks)`
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
# vLLM all2all backend options for expert-parallel deployments.
All2AllBackend = Literal[
"allgather_reducescatter",
"deepep_high_throughput",
"deepep_low_latency",
"flashinfer_nvlink_one_sided",
"flashinfer_nvlink_two_sided",
]
# Known llm-d EPP scorer plugins (used to guard the ``scorers`` map against typos).
KNOWN_SCORERS = frozenset(
{
@@ -325,10 +443,8 @@ class InferenceConfig(BaseConfig):
backend_port: int = 8100
"""Port for the vLLM engine(s) behind the router. Defaults to ``server.port + 100``. Multi-node deployments start one engine per local DP rank at ``backend_port + rank``."""
model: ModelConfig = Field(default_factory=ModelConfig)
parallel: ParallelConfig = ParallelConfig()
"""Multi-node and multi-GPU parallelism (TP, DP, PP)."""
vllm: VllmConfig = Field(default_factory=VllmConfig)
"""vLLM server arguments, under vLLM's own argument names. Unknown fields pass through verbatim."""
log: LogConfig = LogConfig()
"""Logging configuration."""
@@ -336,57 +452,6 @@ class InferenceConfig(BaseConfig):
env_vars: EnvVars = {}
"""Extra environment variables for the inference server process(es). Merged on top of the launcher defaults."""
enable_lora: bool = False
"""Enable LoRA. Forwarded as ``--enable-lora``."""
max_loras: int = 8
"""Maximum number of LoRAs. Forwarded as ``--max-loras``."""
# TODO: The default value is very high because our areal impl for lora isn't ideal
# We add a lora with the same name instead of changing weights inplace
# Because we dont cancel requests that are past max_async, these requests could be using a LoRA that gets unloaded which will crash the inference server
max_cpu_loras: int = 100
"""Maximum number of LoRAs on CPU. Forwarded as ``--max-cpu-loras``."""
max_lora_rank: int | None = None
"""Maximum LoRA rank. Forwarded as ``--max-lora-rank``."""
lora_target_modules: list[str] | None = None
"""LoRA target modules. Forwarded as ``--lora-target-modules``."""
enable_prefix_caching: bool | None = None
"""Enable prefix caching. Forwarded as ``--enable-prefix-caching``."""
gpu_memory_utilization: float = 0.9
"""GPU memory utilization. Forwarded as ``--gpu-memory-utilization``."""
quantization: str | None = None
"""Online inference quantization method. Forwarded as ``--quantization``."""
api_server_count: int = Field(1, ge=0)
"""API servers to run. Forwarded as ``--api-server-count``. Set to 0 for headless mode."""
data_parallel_size_local: int | None = Field(None, ge=1)
"""Data parallel replicas to run on this node. Forwarded as ``--data-parallel-size-local``."""
data_parallel_rpc_port: int = Field(13345, ge=1, le=65535)
"""RPC port for data parallel communication. Forwarded as ``--data-parallel-rpc-port``."""
seed: int = 0
"""Seed the inference components. Forwarded as ``--seed``."""
enable_expert_parallel: bool = False
"""Enable expert parallelism for MoE models. Forwarded as ``--enable-expert-parallel``."""
all2all_backend: All2AllBackend = "allgather_reducescatter"
"""All-to-all backend for expert-parallel communication. Forwarded as ``--all2all-backend``."""
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB). Forwarded as ``--enable-eplb``."""
enable_dbo: bool = False
"""Enable dual batch overlap (DBO). Forwarded as ``--enable-dbo``."""
use_deep_gemm: bool = False
"""Enable vLLM DeepGEMM FP8 kernels ``VLLM_USE_DEEP_GEMM=1``. Only works with block-wise FP8 quantization (e.g. GLM-5-FP8)."""
@@ -398,18 +463,12 @@ class InferenceConfig(BaseConfig):
use_pd_kv_transfer: bool = False
"""Auto-set for disaggregated P/D: emit the NIXL transfer connector. Persisted into the per-node config (which drops ``deployment``) so the connector is still built per worker. Not meant to be set by hand."""
enable_return_routed_experts: bool = False
"""Return routed experts in responses. Forwarded as ``--enable-return-routed-experts``."""
enable_fp32_lm_head: bool = True
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
enable_fp32_router_logits: bool = True
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
vllm_extra: dict[str, Any] = {}
"""Extra arguments forwarded to vLLM. Applied as attributes on the vLLM namespace after config translation."""
# Launcher-only fields
deployment: InferenceDeploymentConfig = SingleNodeInferenceDeploymentConfig()
@@ -432,7 +491,7 @@ class InferenceConfig(BaseConfig):
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
if self.router is not None and self.router.type == "llm-d" and self.enable_return_routed_experts:
if self.router is not None and self.router.type == "llm-d" and self.vllm.enable_return_routed_experts:
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(enable_return_routed_experts): it breaks P/D and is unverified for multi-node. "
@@ -458,10 +517,10 @@ class InferenceConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_kv_cache_offload(self):
if self.kv_cache_offload is not None:
if self.enable_prefix_caching is False:
raise ValueError("KV cache offloading requires inference.enable_prefix_caching to be true.")
if "enable_prefix_caching" not in self.model_fields_set:
self.enable_prefix_caching = True
if self.vllm.enable_prefix_caching is False:
raise ValueError("KV cache offloading requires inference.vllm.enable_prefix_caching to be true.")
if "enable_prefix_caching" not in self.vllm.model_fields_set:
self.vllm.enable_prefix_caching = True
return self
@@ -470,19 +529,19 @@ class InferenceConfig(BaseConfig):
"""Auto-configure inference for disaggregated P/D: enable EP and compute DP."""
if self.deployment.type == "disaggregated":
self.use_pd_kv_transfer = True
if "enable_expert_parallel" not in self.model_fields_set:
self.enable_expert_parallel = True
if "enable_eplb" not in self.model_fields_set:
self.enable_eplb = False
if "enable_expert_parallel" not in self.vllm.model_fields_set:
self.vllm.enable_expert_parallel = True
if "enable_eplb" not in self.vllm.model_fields_set:
self.vllm.enable_eplb = False
gpus_per_node = self.deployment.gpus_per_node
tp = self.parallel.tp
tp = self.vllm.tensor_parallel_size
dp_per_node = gpus_per_node // tp
if self.data_parallel_size_local is None:
self.data_parallel_size_local = dp_per_node
if self.parallel.dp == 1:
self.parallel.dp = dp_per_node
if self.api_server_count == 1:
self.api_server_count = dp_per_node
if self.vllm.data_parallel_size_local is None:
self.vllm.data_parallel_size_local = dp_per_node
if self.vllm.data_parallel_size == 1:
self.vllm.data_parallel_size = dp_per_node
if self.vllm.api_server_count == 1:
self.vllm.api_server_count = dp_per_node
return self
@model_validator(mode="after")
@@ -493,44 +552,6 @@ class InferenceConfig(BaseConfig):
self.slurm.template_path = templates_dir / "inference.sbatch.j2"
return self
@model_validator(mode="after")
def auto_setup_max_lora_rank(self):
"""Auto-setup max_lora_rank by rounding up to the nearest valid vLLM value.
vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512).
This validator ensures that any configured rank is rounded up to the minimum valid value
that can serve adapters of the requested rank.
"""
if self.max_lora_rank is not None:
original_rank = self.max_lora_rank
for valid_rank in VALID_VLLM_LORA_RANKS:
if valid_rank >= self.max_lora_rank:
self.max_lora_rank = valid_rank
break
else:
raise ValueError(f"max_lora_rank={original_rank} exceeds vLLM maximum of {VALID_VLLM_LORA_RANKS[-1]}")
return self
@model_validator(mode="after")
def auto_setup_api_server_count(self):
"""
Ensures that we have at least as many API servers as data parallel
size. Unless LoRA is enabled, in which case only one API server is
supported (vLLM limitation).
"""
if self.vllm_extra.get("headless", False):
self.api_server_count = 0
return self
if "api_server_count" not in self.model_fields_set:
min_api_server_count = self.data_parallel_size_local or self.parallel.dp
if self.api_server_count < min_api_server_count:
self.api_server_count = min_api_server_count
if self.enable_lora:
self.api_server_count = 1 # LoRA requires only one API server
return self
def build_kv_transfer_config(self) -> dict[str, Any] | None:
"""Build the single vLLM ``kv_transfer_config`` from the transfer + offload connectors.
@@ -560,90 +581,49 @@ class InferenceConfig(BaseConfig):
"kv_connector_extra_config": {"connectors": connectors},
}
def to_vllm(self) -> Namespace:
"""Convert InferenceConfig to vLLM-compatible Namespace."""
namespace = Namespace()
to_vllm = {
"server.host": "host",
"server.port": "port",
"server.liveness_timeout_seconds": "liveness_timeout_seconds",
"model.name": "model",
"model.dtype": "dtype",
"model.max_model_len": "max_model_len",
"model.enforce_eager": "enforce_eager",
"model.trust_remote_code": "trust_remote_code",
"model.chat_template": "chat_template",
"model.tool_call_parser": "tool_call_parser",
"model.reasoning_parser": "reasoning_parser",
"model.rope_scaling": "rope_scaling",
"parallel.tp": "tensor_parallel_size",
"parallel.dp": "data_parallel_size",
"data_parallel_size_local": "data_parallel_size_local",
"data_parallel_rpc_port": "data_parallel_rpc_port",
"enable_lora": "enable_lora",
"enable_prefix_caching": "enable_prefix_caching",
"max_loras": "max_loras",
"max_cpu_loras": "max_cpu_loras",
"max_lora_rank": "max_lora_rank",
"lora_target_modules": "lora_target_modules",
"gpu_memory_utilization": "gpu_memory_utilization",
"quantization": "quantization",
"api_server_count": "api_server_count",
"enable_return_routed_experts": "enable_return_routed_experts",
"enable_expert_parallel": "enable_expert_parallel",
"all2all_backend": "all2all_backend",
"enable_eplb": "enable_eplb",
"enable_dbo": "enable_dbo",
"seed": "seed",
}
# Fields vLLM rejects as None — omitted from the namespace so vLLM applies its
# own default (e.g. quantization is inferred from the checkpoint).
_OMIT_IF_NONE = frozenset(
{"chat_template", "tool_call_parser", "reasoning_parser", "lora_target_modules", "quantization", "rope_scaling"}
)
for config_key, vllm_key in to_vllm.items():
value = rgetattr(self, config_key.replace("-", "_"))
rsetattr(namespace, vllm_key, value)
def to_namespace(self) -> Namespace:
"""Dump the server + vllm sections into a vLLM-compatible Namespace."""
namespace = Namespace(
host=self.server.host,
port=self.server.port,
liveness_timeout_seconds=self.server.liveness_timeout_seconds,
)
# Set `logprobs_mode` to `processed_logprobs` by default
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
extra_fields = self.vllm.model_extra or {}
for key in (*type(self.vllm).model_fields, *extra_fields):
value = getattr(self.vllm, key)
# None extras are dropped too: `--vllm.foo None` means "use vLLM's default".
if value is None and (key in self._OMIT_IF_NONE or key in extra_fields):
continue
setattr(namespace, key, value)
# Auto tool choice is gated on a tool-call parser being resolved, unless
# explicitly overridden.
if "enable_auto_tool_choice" not in extra_fields:
namespace.enable_auto_tool_choice = hasattr(namespace, "tool_call_parser")
# Default `logprobs_mode` to `processed_logprobs`
if not hasattr(namespace, "logprobs_mode"):
namespace.logprobs_mode = "processed_logprobs"
kv_transfer_config = self.build_kv_transfer_config()
if kv_transfer_config is not None:
rsetattr(namespace, "kv_transfer_config", kv_transfer_config)
namespace.kv_transfer_config = kv_transfer_config
# Pass prime-rl-specific flags through vLLM's additional_config dict;
# workers read these via get_current_vllm_config().additional_config.
additional_config = getattr(namespace, "additional_config", None) or {}
if self.enable_fp32_lm_head:
existing = getattr(namespace, "additional_config", None) or {}
existing["fp32_lm_head"] = True
rsetattr(namespace, "additional_config", existing)
additional_config["fp32_lm_head"] = True
if self.enable_fp32_router_logits:
existing = getattr(namespace, "additional_config", None) or {}
existing["fp32_router_logits"] = True
rsetattr(namespace, "additional_config", existing)
# Remove chat_template if not set (vLLM doesn't accept None)
if namespace.chat_template is None:
delattr(namespace, "chat_template")
# Remove tool_call_parser if not set (vLLM doesn't accept None) and gate
# `enable_auto_tool_choice` on its presence.
if namespace.tool_call_parser is None:
delattr(namespace, "tool_call_parser")
namespace.enable_auto_tool_choice = hasattr(namespace, "tool_call_parser")
# Remove reasoning_parser if not set (vLLM doesn't accept None)
if namespace.reasoning_parser is None:
delattr(namespace, "reasoning_parser")
# Remove lora_target_modules if not set (vLLM doesn't accept None)
if hasattr(namespace, "lora_target_modules") and namespace.lora_target_modules is None:
delattr(namespace, "lora_target_modules")
# Remove quantization if not set so vLLM can infer it from the checkpoint.
if namespace.quantization is None:
delattr(namespace, "quantization")
# Remove rope_scaling if not set (vLLM doesn't accept None)
if hasattr(namespace, "rope_scaling"):
if namespace.rope_scaling is None:
delattr(namespace, "rope_scaling")
additional_config["fp32_router_logits"] = True
if additional_config:
namespace.additional_config = additional_config
return namespace
@@ -4,7 +4,6 @@ from typing import Annotated, Any, Literal, TypeAlias
import verifiers.v1 as vf
from pydantic import Field, SerializeAsAny, model_validator
from renderers import AutoRendererConfig, RendererConfig
from verifiers.v1.configs.serve import PoolConfig
from prime_rl.configs.algorithm import (
AlgoConfig,
@@ -26,11 +25,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."""
@@ -123,34 +117,15 @@ class EvalSamplingConfig(BaseConfig):
return args
class ServeConfig(BaseConfig):
"""The subset of verifiers' ``ServeConfig`` a source configures — the worker pool
and the per-worker bound. The launcher materializes it into the env server's full
``[serve]`` block, filling in the source's derived address
(``OrchestratorConfig.env_addresses``)."""
pool: PoolConfig = Field(default_factory=vf.ElasticPoolConfig)
"""Worker-pool sizing. ``elastic`` (default) starts at one worker and scales up on
demand; ``static`` pre-spawns a fixed ``num_workers``."""
max_concurrent: int | None = Field(None, ge=1)
"""Episodes in flight per worker (None = unbounded; the dispatcher's
``max_inflight_episodes`` is the run's bound)."""
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."""
serve: ServeConfig = ServeConfig()
"""How this source's env server is sized. Consumed by the launcher (which writes each source's env-server config), not by the orchestrator — the orchestrator only connects."""
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
"""A classic (v0) environment to run through the bridge instead of ``env``."""
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."""
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."""
@@ -164,15 +139,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:
@@ -180,47 +149,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()
@@ -354,7 +290,7 @@ class CheckpointConfig(BaseConfig):
"""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, v{resume_step} 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."""
@@ -477,9 +413,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."""
@@ -528,14 +461,14 @@ 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>``. Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
"""First port of the env-server port range: the source at position ``i`` (train, then eval) is served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address`` keep it instead, without shifting the other sources' ports (indices stay positional). Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
batch_size: int | None = Field(None, ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
@@ -555,9 +488,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."""
@@ -719,7 +654,7 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_config(self):
"""Set vLLM sampling defaults + legacy env kwargs on each train env from top-level fields."""
"""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.
@@ -728,10 +663,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
@@ -746,11 +677,13 @@ class OrchestratorConfig(BaseConfig):
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each source's env server lives, keyed by ``(split, resolved_name)``:
the source's own ``serve.address`` when set (an externally managed server), else
``tcp://127.0.0.1:<port>`` with ports from ``env_server_base_port`` in
``env_sources`` order. The launcher binds env servers at exactly these addresses
and the orchestrator connects to them, so both sides agree from the config
alone."""
return {
(split, source.resolved_name): f"tcp://127.0.0.1:{self.env_server_base_port + index}"
(split, source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, (split, source) in enumerate(self.env_sources)
}
@@ -222,7 +222,7 @@ 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."""
@@ -393,7 +393,11 @@ class RLConfig(BaseConfig):
"Set weight_broadcast.type = 'filesystem'."
)
if self.weight_broadcast.type in ("nccl", "nixl"):
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
inference_world_size = (
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
if self.inference
else 1
)
common_config = dict(
host=self.weight_broadcast.host,
port=self.weight_broadcast.port,
@@ -446,14 +450,14 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def validate_eplb_requires_quantized_weight_transfer(self):
if self.inference is None or not self.inference.enable_eplb:
if self.inference is None or not self.inference.vllm.enable_eplb:
return self
# TODO(matej): check if weight reloading works itself before supporting EPLB without quantized transfer.
trainer_weight_broadcast = self.trainer.weight_broadcast
if trainer_weight_broadcast.type != "nccl" or not trainer_weight_broadcast.quantize_in_weight_transfer:
raise ValueError(
"inference.enable_eplb requires weight_broadcast.type = 'nccl' and "
"inference.vllm.enable_eplb requires weight_broadcast.type = 'nccl' and "
"weight_broadcast.quantize_in_weight_transfer = true."
)
@@ -517,8 +521,8 @@ class RLConfig(BaseConfig):
)
if self.inference is not None:
self.inference.enable_lora = True
self.inference.max_lora_rank = self.trainer.model.lora.rank
self.inference.vllm.enable_lora = True
self.inference.vllm.max_lora_rank = self.trainer.model.lora.rank
else:
warnings.warn(
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
@@ -532,12 +536,12 @@ class RLConfig(BaseConfig):
def auto_setup_router_replay(self):
if self.trainer.enable_router_replay:
if self.inference is not None:
if self.inference.enable_return_routed_experts is False:
if self.inference.vllm.enable_return_routed_experts is False:
warnings.warn(
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True.",
"Router replay is enabled, but inference.vllm.enable_return_routed_experts is False. Setting to True.",
stacklevel=2,
)
self.inference.enable_return_routed_experts = True
self.inference.vllm.enable_return_routed_experts = True
else:
warnings.warn(
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server.",
@@ -553,12 +557,12 @@ class RLConfig(BaseConfig):
``trainer.enable_router_replay`` path, which sets the inference flag here
(after InferenceConfig's own validators, which therefore miss it).
"""
if self.inference is not None and self.inference.enable_return_routed_experts:
if self.inference is not None and self.inference.vllm.enable_return_routed_experts:
router = self.inference.router
if router is not None and router.type == "llm-d":
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(inference.enable_return_routed_experts / trainer.enable_router_replay): it "
"(inference.vllm.enable_return_routed_experts / trainer.enable_router_replay): it "
"breaks P/D and is unverified for multi-node. Use router type 'vllm-router' "
"for router-replay runs."
)
@@ -599,6 +603,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
@@ -608,20 +613,22 @@ class RLConfig(BaseConfig):
# fill up inference capacity with dp ranks
if self.inference is not None:
num_infer_gpus = self.deployment.num_infer_gpus
if num_infer_gpus != self.inference.parallel.dp * self.inference.parallel.tp:
assert num_infer_gpus % self.inference.parallel.tp == 0, (
if num_infer_gpus != self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size:
assert num_infer_gpus % self.inference.vllm.tensor_parallel_size == 0, (
"Number of inference GPUs must be divisible by the tensor parallel size"
)
self.inference.parallel.dp = num_infer_gpus // self.inference.parallel.tp
self.inference.vllm.data_parallel_size = num_infer_gpus // self.inference.vllm.tensor_parallel_size
# Ensure api_server_count matches DP so all workers are created.
# Without this, in-memory weight transfer expects dp*tp workers
# but only api_server_count*tp exist, causing a deadlock.
dp = self.inference.parallel.dp
if self.inference.api_server_count < dp and not self.inference.enable_lora:
self.inference.api_server_count = dp
dp = self.inference.vllm.data_parallel_size
if self.inference.vllm.api_server_count < dp and not self.inference.vllm.enable_lora:
self.inference.vllm.api_server_count = dp
elif self.deployment.type == "multi_node": # multi-node
self.orchestrator.num_train_workers = self.deployment.num_train_nodes * self.deployment.gpus_per_node
self.orchestrator.num_train_workers = (
self.deployment.num_train_nodes * self.deployment.gpus_per_node // self.trainer.model.cp
)
if self.deployment.nodes_per_fsdp_group is not None:
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
@@ -635,35 +642,38 @@ class RLConfig(BaseConfig):
if (
self.inference is not None
and self.inference.enable_expert_parallel
and self.inference.vllm.enable_expert_parallel
and self.inference.deployment.type != "disaggregated"
):
inference_tp = self.inference.parallel.tp
inference_tp = self.inference.vllm.tensor_parallel_size
if self.deployment.gpus_per_node % inference_tp != 0:
raise ValueError(
"deployment.gpus_per_node must be divisible by inference.parallel.tp "
"when inference.enable_expert_parallel is enabled in multi-node deployment."
"deployment.gpus_per_node must be divisible by inference.vllm.tensor_parallel_size "
"when inference.vllm.enable_expert_parallel is enabled in multi-node deployment."
)
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
total_infer_gpus = self.deployment.infer_nodes_per_replica * self.deployment.gpus_per_node
expected_global_world_size = self.inference.parallel.dp * inference_tp
expected_global_world_size = self.inference.vllm.data_parallel_size * inference_tp
if expected_global_world_size != total_infer_gpus:
raise ValueError(
"For multi-node expert parallel inference, inference.parallel.dp * inference.parallel.tp "
"For multi-node expert parallel inference, inference.vllm.data_parallel_size * inference.vllm.tensor_parallel_size "
f"must match total inference GPUs ({total_infer_gpus}), got {expected_global_world_size}."
)
if self.inference.data_parallel_size_local is None:
self.inference.data_parallel_size_local = inferred_dp_local
elif self.inference.data_parallel_size_local != inferred_dp_local:
if self.inference.vllm.data_parallel_size_local is None:
self.inference.vllm.data_parallel_size_local = inferred_dp_local
elif self.inference.vllm.data_parallel_size_local != inferred_dp_local:
raise ValueError(
"inference.data_parallel_size_local must equal deployment.gpus_per_node / inference.parallel.tp "
f"({inferred_dp_local}) when inference.enable_expert_parallel is enabled in multi-node deployment."
"inference.vllm.data_parallel_size_local must equal deployment.gpus_per_node / inference.vllm.tensor_parallel_size "
f"({inferred_dp_local}) when inference.vllm.enable_expert_parallel is enabled in multi-node deployment."
)
if not self.inference.enable_lora and self.inference.api_server_count == self.inference.parallel.dp:
self.inference.api_server_count = inferred_dp_local
if (
not self.inference.vllm.enable_lora
and self.inference.vllm.api_server_count == self.inference.vllm.data_parallel_size
):
self.inference.vllm.api_server_count = inferred_dp_local
# Auto-infer DP and api_server_count for standard multi-node inference.
# Without EP, vLLM only creates api_server_count * tp workers per node,
@@ -671,16 +681,16 @@ class RLConfig(BaseConfig):
# more workers than exist, deadlocking in-memory transfer initialization.
if (
self.inference is not None
and not self.inference.enable_expert_parallel
and not self.inference.vllm.enable_expert_parallel
and self.inference.deployment.type != "disaggregated"
):
dp_per_node = self.deployment.gpus_per_node // self.inference.parallel.tp
if self.inference.parallel.dp == 1 and dp_per_node > 1:
self.inference.parallel.dp = dp_per_node
if self.inference.data_parallel_size_local is None and dp_per_node > 1:
self.inference.data_parallel_size_local = dp_per_node
if self.inference.api_server_count == 1 and dp_per_node > 1:
self.inference.api_server_count = dp_per_node
dp_per_node = self.deployment.gpus_per_node // self.inference.vllm.tensor_parallel_size
if self.inference.vllm.data_parallel_size == 1 and dp_per_node > 1:
self.inference.vllm.data_parallel_size = dp_per_node
if self.inference.vllm.data_parallel_size_local is None and dp_per_node > 1:
self.inference.vllm.data_parallel_size_local = dp_per_node
if self.inference.vllm.api_server_count == 1 and dp_per_node > 1:
self.inference.vllm.api_server_count = dp_per_node
if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "nixl"):
# Every allocated inference GPU is an in-memory transfer worker.
@@ -721,7 +731,7 @@ class RLConfig(BaseConfig):
# External-LB: one admin client per DP rank, so roles expand per rank
# (stride = dp_local = gpus_per_node / tp). ADMIN_URLS lists all prefill
# ranks, then all decode ranks, per replica — match that order.
stride = self.deployment.gpus_per_node // self.inference.parallel.tp
stride = self.deployment.gpus_per_node // self.inference.vllm.tensor_parallel_size
role_order = ["prefill"] * (infer_deploy.num_prefill_nodes * stride) + ["decode"] * (
infer_deploy.num_decode_nodes * stride
)
@@ -749,7 +759,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
@@ -108,23 +108,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 +131,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):
@@ -625,9 +625,6 @@ class TrainerConfig(BaseConfig):
metrics_server: MetricsServerConfig | None = None
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
max_concurrent_runs: int = Field(1, ge=1)
"""Maximum number of concurrent runs to allow. If 1, only one run may run at a time."""
enable_token_export: bool = False
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
@@ -702,12 +699,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"):
@@ -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"),
@@ -68,13 +68,12 @@ def propagate_shared_fields(data: Any) -> Any:
propagate(
"model.name",
"trainer.model.name",
"inference.model.name",
"inference.vllm.model",
"orchestrator.model.name",
)
propagate(
"model.vlm",
"trainer.model.vlm",
"inference.model.vlm",
"orchestrator.model.vlm",
)
@@ -109,7 +108,7 @@ def propagate_shared_fields(data: Any) -> Any:
# [file_monitor] leaf. (Bare empty ``[file_monitor]`` block enablement is at the end.)
propagate("file_monitor.filename", "trainer.file_monitor.filename", "orchestrator.file_monitor.filename")
# [tokenizer]. ``chat_template`` also flows to ``inference.model`` (vLLM's
# [tokenizer]. ``chat_template`` also flows to ``inference.vllm`` (vLLM's
# ``--chat-template``); ``name`` and ``trust_remote_code`` can legitimately
# differ between sub-configs (auto-derived from model names, which may
# differ for FP8-quantized inference variants).
@@ -123,7 +122,7 @@ def propagate_shared_fields(data: Any) -> Any:
"tokenizer.chat_template",
"trainer.tokenizer.chat_template",
"orchestrator.tokenizer.chat_template",
"inference.model.chat_template",
"inference.vllm.chat_template",
)
# [rollout_transport] → both sub-configs (host is launcher-injected for zmq multi-node).
@@ -139,23 +138,9 @@ 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)
propagate("output_dir", "trainer.output_dir", "orchestrator.output_dir")
# Cascade trainer.tokenizer.chat_template → inference.model.chat_template
# Cascade trainer.tokenizer.chat_template → inference.vllm.chat_template
# (vLLM ``--chat-template``). Read trainer's value *after* the shared
# propagation above so we cover both:
# - shared ``[tokenizer] chat_template`` (already filled all three above,
@@ -165,7 +150,7 @@ def propagate_shared_fields(data: Any) -> Any:
# would otherwise complain about the missing inference value).
trainer_chat_template = get("trainer.tokenizer.chat_template")
if trainer_chat_template is not None:
fill("inference.model.chat_template", trainer_chat_template)
fill("inference.vllm.chat_template", trainer_chat_template)
# Bare ``[ckpt]`` / ``[wandb]`` block: presence-only signal that enables
# the section with defaults on both sub-configs. Necessary because
@@ -225,9 +210,9 @@ def validate_shared_model_name(
) -> None:
# Orchestrator must match inference (it queries the inference server)
if inference is not None:
if inference.model.name != orchestrator.model.name:
if inference.vllm.model != orchestrator.model.name:
raise ValueError(
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
f"Inference model name ({inference.vllm.model}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
"The orchestrator queries the inference server and must use the same model name."
)
return
@@ -244,9 +229,10 @@ def validate_shared_output_dir(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.output_dir != orchestrator.output_dir.parent:
if trainer.output_dir != orchestrator.output_dir:
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."
f"Trainer outputs directory ({trainer.output_dir}) and orchestrator outputs directory ({orchestrator.output_dir}) are not the same. "
"Please specify the same outputs directory for both (the orchestrator no longer nests under a run_default subdirectory)."
)
@@ -310,9 +296,9 @@ def validate_shared_tokenizer(
f"Use the shared [tokenizer] config to set chat_template for both."
)
if inference is not None:
if trainer.tokenizer.chat_template != inference.model.chat_template:
if trainer.tokenizer.chat_template != inference.vllm.chat_template:
raise ValueError(
f"Inference chat_template ({inference.model.chat_template!r}) does not match "
f"Inference chat_template ({inference.vllm.chat_template!r}) does not match "
f"the shared tokenizer chat_template ({trainer.tokenizer.chat_template!r}). "
f"Use the shared [tokenizer] config to set chat_template for all components."
)
+28 -15
View File
@@ -1,6 +1,6 @@
[project]
name = "prime-rl"
version = "0.7.0"
version = "0.8.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.2.2.dev76",
"verifiers[harbor]>=0.3.1.dev14",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -59,8 +59,13 @@ env-server = "prime_rl.entrypoints.env_server:main"
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
[project.optional-dependencies]
# Both wheels are the same flash-attn 2.8.3 / cu128 / torch 2.11 / cp312 build and carry
# sm_80 / sm_90 / sm_100 / sm_120 cubins. `attn="auto"` picks FA4 on sm_100 and FA3 on
# sm_90, so FA2 is the resolved backend on sm_120 (see `_resolve_attn_impl` in
# trainer/model.py).
flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.22/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
]
flash-attn-3 = ["flash_attn_3"]
@@ -123,19 +128,28 @@ override-dependencies = [
"openenv-core",
]
# Environment packages (research-environments + verifiers) are auto-discovered as
# workspace members, so new envs need no per-package registration. Install them
# with `uv sync --all-packages`.
# prime-envs packages are auto-discovered as workspace members, so new
# envs there need no per-package registration. verifiers' example envs are opt-in:
# only the ones prime-rl trains or tests on are listed, so an upstream example with
# conflicting pins can't break the shared lock. Install them with
# `uv sync --all-packages`.
[tool.uv.workspace]
members = [
"deps/research-environments/environments/*/*",
"deps/verifiers/environments/*",
"deps/prime-envs/environments/*/*",
"deps/verifiers/environments/alphabet_sort",
"deps/verifiers/environments/color_codeword",
"deps/verifiers/environments/gsm8k",
"deps/verifiers/environments/kuhn_poker",
"deps/verifiers/environments/proposer_solver",
"deps/verifiers/environments/reverse_text",
"deps/verifiers/environments/wiki_search",
"deps/verifiers/environments/wordle",
]
# tau2-synth-v1 and tau3-bench-v1 pin `tau2` forks/revs that conflict with the
# canonical tau2-bench-v1; a workspace shares one lock, so these can't coexist.
# tau2-synth and tau3-bench pin `tau2` forks/revs that conflict with the
# canonical tau2-bench; a workspace shares one lock, so these can't coexist.
exclude = [
"deps/research-environments/environments/tool_use/tau2_synth_v1",
"deps/research-environments/environments/tool_use/tau3_bench_v1",
"deps/prime-envs/environments/tool_use/tau2_synth",
"deps/prime-envs/environments/tool_use/tau3_bench",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -181,10 +195,8 @@ torchao = false
[tool.uv.sources]
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
# prime-rl depends on the one `verifiers` package (v0 + v1 + the legacy bridge + the built-in v1
# harnesses/tasksets, now bundled in verifiers.v1). v0 envs resolve from
# deps/{verifiers,research-environments}/environments; v1 tasksets (`-v1`) and the `compact`
# example live under deps/{verifiers,research-environments}/environments.
# prime-rl consumes `verifiers.v1` (incl. the built-in harnesses/tasksets); env tasksets
# live under deps/{verifiers,prime-envs}/environments.
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
@@ -249,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
-44
View File
@@ -1,44 +0,0 @@
#!/bin/bash
# arm64 post-install fixups: rebuild flash-attn from source for the target GPU.
#
# Why this exists: pyproject.toml sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE to keep
# `uv sync` fast; on x86_64 it pins a prebuilt wheel to fill in the binary, but no
# such wheel exists for aarch64. Without this script, `import flash_attn` fails on
# aarch64 with `ModuleNotFoundError: No module named 'flash_attn_2_cuda'`.
#
# Defaults preserve the existing Docker behavior (sm_100 / GB200). On a host with
# `nvidia-smi` available, the compute capability is auto-detected from the local
# GPU. Override via env vars if needed:
# TORCH_CUDA_ARCH_LIST e.g. 9.0 (Hopper), 10.0 (Blackwell)
# VENV_PATH path to the venv (default: $(pwd)/.venv)
# MAX_JOBS parallel nvcc jobs (default: 4)
set -euo pipefail
if [ -z "${TORCH_CUDA_ARCH_LIST:-}" ]; then
# Try to detect from the local GPU. Tolerate any failure mode (binary missing,
# driver not loaded, Docker buildx without --gpus) and fall back to GB200.
TORCH_CUDA_ARCH_LIST="$(nvidia-smi --query-gpu=compute_cap --format=csv,noheader 2>/dev/null | head -1 | tr -d ' ' || true)"
: "${TORCH_CUDA_ARCH_LIST:=10.0}"
fi
export TORCH_CUDA_ARCH_LIST
VENV_PATH="${VENV_PATH:-$(pwd)/.venv}"
if [ ! -x "$VENV_PATH/bin/python" ]; then
echo "ERROR: no python at $VENV_PATH/bin/python. Run from the project root or set VENV_PATH." >&2
exit 1
fi
export MAX_JOBS="${MAX_JOBS:-4}"
export FLASH_ATTENTION_FORCE_BUILD=TRUE
export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
echo "=== building flash-attn from source (TORCH_CUDA_ARCH_LIST=$TORCH_CUDA_ARCH_LIST, MAX_JOBS=$MAX_JOBS) ==="
echo " target venv: $VENV_PATH"
# Run from /tmp so uv ignores the project's [tool.uv.extra-build-variables],
# which sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and would prevent kernel compilation.
(cd /tmp && uv pip install --python "$VENV_PATH/bin/python" \
"flash-attn==2.8.3" --no-build-isolation --no-binary flash-attn --no-cache --reinstall-package flash-attn)
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
uv pip install --python "$VENV_PATH/bin/python" --reinstall --no-deps \
"flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
-10
View File
@@ -143,16 +143,6 @@ main() {
log_info "Installing pre-commit hooks..."
uv run pre-commit install
# aarch64 has no prebuilt flash-attn wheel; build it from source for the local GPU.
# Without this, `import flash_attn` fails with `ModuleNotFoundError: flash_attn_2_cuda`.
# Run last so no subsequent uv operation (which implicitly syncs against the lockfile)
# rebuilds flash-attn from PyPI with FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and undoes this.
if [ "$(uname -m)" = "aarch64" ]; then
log_info "aarch64 detected: building flash-attn from source (this takes 20-30 minutes)..."
log_warn "Future 'uv sync --all-extras' or 'uv run' will remove this build. Use 'uv sync --inexact' or 'uv run --no-sync' to keep it."
bash scripts/docker-arm64-post-install.sh
fi
log_info "Installation completed!"
}
+9 -7
View File
@@ -19,7 +19,7 @@ uv run rl @ base.toml --trainer @ trainer.toml --trainer.lr 1e-3 # mix
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base.
Naming: CLI uses kebab-case (`--model.max-model-len`); TOML uses snake_case (`max_model_len`).
Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max_model_len`).
## Inspect & validate
@@ -38,7 +38,7 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--model.max-model-len None`.
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--vllm.max-model-len None`.
**Lists** — TOML uses array of tables; later config files replace lists wholesale, so overlays must include the full desired list:
@@ -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,9 +69,11 @@ 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: `--vllm-extra '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
**vLLM pass-through** — `[inference.vllm]` uses vLLM's own argument names (`model`, `tensor_parallel_size`, `data_parallel_size`, `max_model_len`, ...) and forwards *any* key to the vLLM server, typed by prime-rl or not: `[inference.vllm] max_num_seqs = 256`, or `--inference.vllm.max-num-seqs 256` on the CLI. CLI values are JSON-coerced, so dict-valued vLLM args work as `--inference.vllm.compilation-config '{"cudagraph_mode": "NONE"}'`. Non-vLLM knobs (router, deployment, weight broadcast, kv-cache offload, env vars) stay on `[inference]` itself.
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
@@ -88,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 `output_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 under `deps/research-environments/environments/*/*` and `deps/verifiers/environments/*` are uv **workspace members**, auto-discovered — adding a new env needs no `pyproject.toml` change. They 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`.
+1 -1
View File
@@ -162,7 +162,7 @@ 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
```
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 `{output_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the trace subtrees.
### Common failure modes
+4 -4
View File
@@ -35,8 +35,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.
@@ -60,8 +60,8 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly.
```bash
uv run inference --model.name Qwen/Qwen3-0.6B
uv run inference --model.name Qwen/Qwen3-0.6B --model.enforce-eager
uv run inference --vllm.model Qwen/Qwen3-0.6B
uv run inference --vllm.model Qwen/Qwen3-0.6B --vllm.enforce-eager
```
Smoke checks:
+4 -11
View File
@@ -12,21 +12,14 @@ from prime_rl.utils.utils import clean_exit
@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}
)
# ``serve.pool`` (static or elastic) sizes the server. serve_env applies the logging
# 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,
config_data=env_config_data(config.env),
max_concurrent=config.serve.max_concurrent,
)
+6 -6
View File
@@ -64,7 +64,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
template = env.get_template(config.slurm.template_path.name)
is_disaggregated = config.deployment.type == "disaggregated"
dp_per_node = config.deployment.gpus_per_node // config.parallel.tp
dp_per_node = config.deployment.gpus_per_node // config.vllm.tensor_parallel_size
offload = config.kv_cache_offload
is_mooncake = offload is not None and offload.type == "mooncake"
@@ -100,7 +100,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
num_decode_replicas=config.deployment.num_decode_replicas,
prefill_port=config.deployment.prefill_port,
decode_port=config.deployment.decode_port,
data_parallel_rpc_port=config.data_parallel_rpc_port,
data_parallel_rpc_port=config.vllm.data_parallel_rpc_port,
use_deep_gemm=config.use_deep_gemm,
prefill_env_vars=config.deployment.prefill_env_vars,
decode_env_vars=config.deployment.decode_env_vars,
@@ -110,8 +110,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
elif is_multi_node:
template_vars.update(
backend_port=config.backend_port,
data_parallel_rpc_port=config.data_parallel_rpc_port,
enable_expert_parallel=config.enable_expert_parallel,
data_parallel_rpc_port=config.vllm.data_parallel_rpc_port,
enable_expert_parallel=config.vllm.enable_expert_parallel,
infer_nodes_per_replica=config.deployment.num_nodes,
)
@@ -170,7 +170,7 @@ def start_router(config: InferenceConfig) -> subprocess.Popen:
"--worker-urls",
f"http://{worker_host}:{config.backend_port}",
"--intra-node-data-parallel-size",
str(config.data_parallel_size_local or config.parallel.dp),
str(config.vllm.data_parallel_size_local or config.vllm.data_parallel_size),
"--request-id-headers",
"x-session-id",
"--worker-startup-timeout-secs",
@@ -222,7 +222,7 @@ def inference_local(config: InferenceConfig):
from prime_rl.inference.vllm.server import server # pyright: ignore
try:
server(config, vllm_extra=config.vllm_extra)
server(config)
finally:
if router_process is not None:
router_stopping.set()

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