Compare commits

...
Author SHA1 Message Date
6e33f3f82f chore: bump verifiers for the unbounded model-call timeout (#3227)
Bumps deps/verifiers 29e3a0f7 -> a298bcfe, picking up two commits:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Removes the multi-tenant infrastructure:

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

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

* feat: always broadcast step-0 weights at startup

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

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

* fix: assign base_url as str in auto_setup_inference_client

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

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

---------

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

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

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

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

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

* refactor: consume vf.ServeConfig as-is

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* chore: verifiers floors to 0.3.0 (released)

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

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

* chore: relock for the 0.3.0 floors

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

* chore: renderers floor to 0.1.9 (released)

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

---------

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

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

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

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

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

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

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

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

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

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

Measured on the first green build of this branch:

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

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

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

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

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

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

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

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

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

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

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

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

* review: drop inline comment above seq_lens kwargs

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

---------

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

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

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

* chore: docstring + test tidy

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

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

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

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

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

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

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

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

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

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

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

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

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

* refactor: rename env server naming to env throughout

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

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

* docs: trim env entrypoint row

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

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

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

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

* docs: drop the removed serve CLI reference from EnvConfig

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

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

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

* ci: slim install imports configs.env

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

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

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

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

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

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

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

---------

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

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

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

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

* chore: trim the ignore comment

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

---------

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

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

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

* ci: restrict manual image builds to maintain/admin

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

* ci: gate only manual dispatches in authorize job

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

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

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

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

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

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

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

This reverts commit b054923274aecb39f82671b2f9eae22ef0590fb9.

---------

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* chore: bump verifiers to vf#2187 head

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

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

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

* chore: bump verifiers pin

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

* chore: bump verifiers pin

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

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

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

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

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

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

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

* chore: bump research-environments to latest main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

* chore: bump verifiers submodule

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

* chore: bump verifiers submodule

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

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

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

* chore: bump verifiers to main

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

---------

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

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

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

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

* chore: bump research-environments to latest main

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

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

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

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

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

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

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

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

* fix(orchestrator): read the agent timing span

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

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

---------

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

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

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

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

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

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

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

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

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

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

* docs: simplify orchestrator checkpoint table row

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

* refactor(orchestrator): simplify TrainSource surface

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

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

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

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

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

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

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

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

---------

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

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

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

* fix CPU test config fixtures

* rename evaluation environments to sources

* chore(orchestrator)!: rename max_inflight_rollouts to max_inflight_episodes

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

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

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

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

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

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

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

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

* fix the source-config readers the compose commit missed

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

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

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

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

* spell the env annotation out instead of vf.EnvField

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

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

* declare the env default with the factory verifiers exports

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

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

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

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

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

* drop the serving-key pointers here too

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

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

* bump verifiers: no max_concurrent alias on the env block

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

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

* bump verifiers to 0.2.2.dev43 (merged main)

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

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

Replaces the temporary branch pin this PR carried.

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

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

Two CI failures from the compose commit.

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

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

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

* chore: adapt to the verifiers trace record cleanups

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

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

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

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

---------

Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 10:34:53 -07:00
176 changed files with 3593 additions and 7347 deletions
+55 -14
View File
@@ -34,8 +34,42 @@ concurrency:
cancel-in-progress: false
jobs:
authorize:
name: Authorize dispatcher
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Require maintain or admin
# Gate MANUAL dispatches only; other events (e.g. release) are
# already privileged and pass through. Guard the step, not the job —
# a skipped job would skip `prepare` via `needs: authorize`.
if: github.event_name == 'workflow_dispatch'
env:
GH_TOKEN: ${{ github.token }}
ACTOR: ${{ github.triggering_actor }}
REPO: ${{ github.repository }}
run: |
# Restricted to repo members with maintain or admin. Automated
# in-repo dispatches (devx_tag dev-image builds, the release build)
# run as github-actions[bot] via GITHUB_TOKEN — allow those through.
if [ "$ACTOR" = "github-actions[bot]" ]; then
echo "Dispatcher is repo automation ($ACTOR); allowed."
exit 0
fi
role=$(gh api "repos/${REPO}/collaborators/${ACTOR}/permission" --jq '.role_name' 2>/dev/null || true)
echo "Dispatcher $ACTOR has repo role: ${role:-<none>}"
case "$role" in
admin|maintain)
echo "Authorized." ;;
*)
echo "::error::$ACTOR (role: ${role:-none}) is not allowed to trigger image builds; requires maintain or admin." >&2
exit 1 ;;
esac
prepare:
name: Prepare build
needs: authorize
runs-on: ubuntu-latest
permissions:
contents: read
@@ -81,27 +115,30 @@ jobs:
INPUT_TAG: ${{ env.BUILD_TAG }}
PLATFORMS: ${{ env.BUILD_PLATFORMS }}
run: |
case "$INPUT_REF" in
main|v[0-9]*|*.dev[0-9]*) ;;
*)
echo "ref '${INPUT_REF}' not allowed for ghcr publish (must be main, v*, or *.dev*)" >&2
exit 1
;;
esac
if [ -n "$INPUT_TAG" ] && [ "$INPUT_TAG" != "$INPUT_REF" ] && [ "$INPUT_REF" != "main" ]; then
echo "custom 'tag' that differs from 'ref' is only allowed when ref=main; got ref='${INPUT_REF}' tag='${INPUT_TAG}'" >&2
exit 1
fi
raw_tag="$INPUT_TAG"
if [ -z "$raw_tag" ]; then
raw_tag="$INPUT_REF"
sanitize() {
echo "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//' | cut -c1-50
}
# A ref that is exactly a git tag builds under that tag verbatim;
# any other ref (branch / arbitrary commit) is prefixed with
# `git describe` so the tag carries the nearest release, commit
# distance and short sha (e.g. v0.7.0-42-g1a2b3c4d5-fix-my-branch)
# and can't collide with a clean release tag.
if [ -n "$INPUT_TAG" ]; then
tag=$(sanitize "$INPUT_TAG")
elif tag=$(git describe --tags --exact-match 2>/dev/null); then
:
else
tag="$(git describe --tags --always)-$(sanitize "$INPUT_REF")"
fi
tag=$(echo "$raw_tag" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | cut -c1-50 | sed 's/^-//;s/-$//')
if [ -z "$tag" ]; then
echo "Could not derive a valid image tag from '${raw_tag}'." >&2
echo "Could not derive a valid image tag from ref='${INPUT_REF}' tag='${INPUT_TAG}'." >&2
exit 1
fi
@@ -156,7 +193,11 @@ jobs:
with:
context: .
file: ./Dockerfile.cuda
push: true
# zstd compresses the multi-GB venv layers several times faster than gzip at a
# comparable ratio. No `force-compression`, so base-image layers are reused as-is
# rather than needlessly recompressed. Pulling zstd layers needs containerd >= 1.5
# or Docker >= 23.
outputs: type=image,push=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
-3
View File
@@ -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"
+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
+2 -11
View File
@@ -113,15 +113,6 @@ uv sync --all-extras
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
4.1. On aarch64 hosts: build flash-attn from source for your GPU
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`.
```bash
bash scripts/docker-arm64-post-install.sh
```
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
@@ -166,7 +157,7 @@ uv run trainer @ configs/debug/fake/rl.toml
5. Check that you can run the inference server (*this requires 1 GPU*)
```bash
uv run inference --model.name Qwen/Qwen3-0.6B
uv run inference --vllm.model Qwen/Qwen3-0.6B
```
6. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
@@ -227,7 +218,7 @@ Check out the [docs](docs) directory for in-depth guides on how to use prime-rl.
- [**Training**](docs/training.md) - RL, SFT, evals, checkpointing, observability, rules of thumb
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA, multi-tenant training
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA
- [**Development**](docs/development.md) - Test suite, pre-commit hooks, adding a new model
## Contributing
+3 -2
View File
@@ -8,8 +8,9 @@ Configurations for running prime-rl.
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
- **`ci/`** — integration and nightly configs used by CI.
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
(per-algorithm smokes) and `fake/` (fake-data trainer/SFT smokes). Not guaranteed
functional or up to date.
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
(two reverse-text train sources + one eval source, one env server per source). Not
guaranteed functional or up to date.
```bash
uv run rl @ configs/basic/<env>/rl.toml
+14 -3
View File
@@ -34,9 +34,20 @@ max_completion_tokens = 768
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[ckpt] # Checkpoint at the end of training
+12 -6
View File
@@ -21,17 +21,23 @@ seq_len = 8192
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "math-env-v1"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[trainer.model]
seq_len = 16384
[inference.model]
[inference.vllm]
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+9 -3
View File
@@ -24,9 +24,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
+10 -4
View File
@@ -42,11 +42,17 @@ max_completion_tokens = 512
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "wiki-search-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[ckpt] # Checkpoint at the end of training
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
+9 -3
View File
@@ -23,9 +23,15 @@ group_size = 8
[[orchestrator.train.source]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.player.harness = { id = "null" }
env.player.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "wordle-v1"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
+17 -3
View File
@@ -24,9 +24,23 @@ max_completion_tokens = 384
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, task = { similarity_power = 4, power_per_turn = false } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
min_turns = 2
max_turns = 2
min_names_per_turn = 1
max_names_per_turn = 3
[orchestrator.train.source.env.taskset.task]
similarity_power = 4
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
@@ -28,15 +28,23 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[inference.vllm]
enable_lora = true
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "prime-qwen3"
@@ -27,15 +27,23 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[inference.vllm]
enable_lora = true
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "prime-qwen3"
@@ -27,16 +27,20 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
gpu_memory_utilization = 0.7
[inference.model]
[inference.vllm]
max_model_len = 2048
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "default"
@@ -1,13 +0,0 @@
# Inference config for multi-run RL integration test
enable_lora = true
max_lora_rank = 8
max_loras = 4
gpu_memory_utilization = 0.7
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
max_model_len = 2048
[weight_broadcast]
type = "filesystem"
@@ -1,33 +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"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
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"
@@ -39,9 +39,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -52,12 +58,20 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.4
@@ -30,7 +30,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -45,9 +45,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -58,12 +64,20 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.4
@@ -25,9 +25,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
@@ -24,9 +24,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference]
+16 -5
View File
@@ -20,14 +20,25 @@ group_size = 16
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 768
[trainer]
[inference.parallel]
dp = 4
[inference.vllm]
data_parallel_size = 4
+22 -11
View File
@@ -20,32 +20,43 @@ seq_len = 8192
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "math-env-v1"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 50
[[orchestrator.eval.source]]
name = "aime2024"
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer]
[trainer.model]
seq_len = 16384
attn = "flash_attention_2"
[inference.parallel]
dp = 4
[inference.model]
[inference.vllm]
max_model_len = 8192
data_parallel_size = 4
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+9 -3
View File
@@ -20,9 +20,15 @@ group_size = 16
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 128
+11 -7
View File
@@ -25,17 +25,21 @@ enforce = true
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "wiki-search-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
[trainer]
[inference.parallel]
dp = 4
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
data_parallel_size = 4
+11 -6
View File
@@ -20,17 +20,22 @@ group_size = 16
[[orchestrator.train.source]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.player.harness = { id = "null" }
env.player.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "wordle-v1"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer]
[inference.parallel]
dp = 6
[inference.vllm]
data_parallel_size = 6
[orchestrator.renderer]
name = "prime-qwen3"
@@ -22,9 +22,16 @@ max_completion_tokens = 64
[[orchestrator.train.source]]
name = "color-codeword"
env.taskset = { id = "color-codeword-v1", images_per_turn = 1 }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "color-codeword-v1"
images_per_turn = 1
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[trainer]
+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
+16 -3
View File
@@ -26,9 +26,20 @@ alpha = 0.1
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
@@ -47,4 +58,6 @@ name = "prime-qwen3"
lr = 1e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+20 -6
View File
@@ -23,9 +23,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -36,9 +42,15 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -46,4 +58,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+20 -6
View File
@@ -23,9 +23,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -36,9 +42,15 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -46,4 +58,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+32 -12
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
@@ -33,22 +33,34 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text-grpo"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text-opd"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.source.algo]
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
@@ -59,12 +71,20 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+23 -9
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/opd.toml
@@ -24,7 +24,7 @@ type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
@@ -35,9 +35,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -48,9 +54,15 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -58,4 +70,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+23 -9
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/opd_lora.toml
@@ -24,7 +24,7 @@ type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
@@ -35,9 +35,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -48,9 +54,15 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 1e-4
@@ -64,4 +76,6 @@ save_adapter_separately = true
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+32 -10
View File
@@ -23,11 +23,21 @@ max_completion_tokens = 512
[[orchestrator.train.source]]
name = "kuhn-poker"
env.taskset = { id = "kuhn-poker-v1" }
env.player0.harness = { id = "null" }
env.player0.runtime = { type = "subprocess" }
env.player1.harness = { id = "null" }
env.player1.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "kuhn-poker-v1"
[orchestrator.train.source.env.player0.harness]
id = "null"
[orchestrator.train.source.env.player0.runtime]
type = "subprocess"
[orchestrator.train.source.env.player1.harness]
id = "null"
[orchestrator.train.source.env.player1.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -38,11 +48,21 @@ max_completion_tokens = 512
[[orchestrator.eval.source]]
name = "kuhn-poker"
env.taskset = { id = "kuhn-poker-v1" }
env.player0.harness = { id = "null" }
env.player0.runtime = { type = "subprocess" }
env.player1.harness = { id = "null" }
env.player1.runtime = { type = "subprocess" }
[orchestrator.eval.source.env.taskset]
id = "kuhn-poker-v1"
[orchestrator.eval.source.env.player0.harness]
id = "null"
[orchestrator.eval.source.env.player0.runtime]
type = "subprocess"
[orchestrator.eval.source.env.player1.harness]
id = "null"
[orchestrator.eval.source.env.player1.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -50,4 +70,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+20 -6
View File
@@ -31,9 +31,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -44,12 +50,20 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+23 -9
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/sft_distill.toml
@@ -25,7 +25,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -40,9 +40,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -53,9 +59,15 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -63,4 +75,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+23 -9
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/sft_distill_lora.toml
@@ -25,7 +25,7 @@ type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
base_url = "http://localhost:8001/v1"
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -40,9 +40,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -53,9 +59,15 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 1e-4
@@ -69,4 +81,6 @@ save_adapter_separately = true
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+69
View File
@@ -0,0 +1,69 @@
# Minimal multi-env debug run: two reverse-text train sources + one eval source.
# The launcher spawns one env server per source at its derived address
# (tcp://127.0.0.1:5000-5002); the orchestrator connects to each.
max_steps = 10
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.renderer]
name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text-a"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text-b"
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 5
num_examples = 64
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+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:
+61 -23
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.
@@ -100,7 +100,9 @@ Echo also takes an optional user-supplied token filter that narrows the role sel
```toml
[orchestrator.algo.filter]
import_path = "my_module.drop_warnings"
kwargs = { patterns = ["WARNING"] }
[orchestrator.algo.filter.kwargs]
patterns = ["WARNING"]
```
```python
@@ -121,18 +123,32 @@ Both components resolve per environment. Each env inherits `[orchestrator.algo]`
type = "grpo"
[[orchestrator.train.source]]
name = "math"
env.taskset = { id = "math-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
# inherits the top-level grpo
name = "math" # inherits the top-level grpo
[orchestrator.train.source.env.taskset]
id = "math-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "terminal"
env.taskset = { id = "terminal-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "subprocess" }
algo = { type = "echo" } # this env runs its own algorithm
[orchestrator.train.source.env.taskset]
id = "terminal-v1"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
# this env runs its own algorithm
[orchestrator.train.source.algo]
type = "echo"
```
### The Algorithm Classes
@@ -253,7 +269,9 @@ Wire it up:
[trainer.loss]
type = "custom"
import_path = "my_module.ppo_clip_loss"
kwargs = { clip_eps = 0.2 }
[trainer.loss.kwargs]
clip_eps = 0.2
```
The dataclasses:
@@ -346,12 +364,22 @@ episode_agents = ["solver"]
[[orchestrator.train.source]]
name = "proposer-solver"
group_size = 4 # proposed problems per source task
env.taskset = { id = "proposer-solver-v1" }
env.n = 4 # solver attempts per proposed problem
env.proposer.harness = { id = "null" }
env.proposer.runtime = { type = "subprocess" }
env.solver.harness = { id = "null" }
env.solver.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "proposer-solver-v1"
[orchestrator.train.source.env.proposer.harness]
id = "null"
[orchestrator.train.source.env.proposer.runtime]
type = "subprocess"
[orchestrator.train.source.env.solver.harness]
id = "null"
[orchestrator.train.source.env.solver.runtime]
type = "subprocess"
```
`group_size` controls how many problems are proposed from each source task. `env.n` controls how many solvers attempt each proposed problem. If a comparison contains only one trace—for example, a solver when `env.n = 1`—its advantage is zero and the zero-advantage filter removes it.
@@ -371,11 +399,21 @@ decay = 0.95
[[orchestrator.train.source]]
name = "kuhn-poker"
env.taskset = { id = "kuhn-poker-v1" }
env.player0.harness = { id = "null" }
env.player0.runtime = { type = "subprocess" }
env.player1.harness = { id = "null" }
env.player1.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "kuhn-poker-v1"
[orchestrator.train.source.env.player0.harness]
id = "null"
[orchestrator.train.source.env.player0.runtime]
type = "subprocess"
[orchestrator.train.source.env.player1.harness]
id = "null"
[orchestrator.train.source.env.player1.runtime]
type = "subprocess"
```
Both of `kuhn-poker-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.
+37 -14
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`).
@@ -97,7 +97,7 @@ Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one i
### Dicts
CLI takes a JSON literal. TOML uses a table or inline-table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
CLI takes a JSON literal. TOML uses a table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
```bash
uv run rl @ rl.toml --orchestrator.train.source.0.args \
@@ -106,7 +106,10 @@ uv run rl @ rl.toml --orchestrator.train.source.0.args \
```toml
[[orchestrator.train.source]]
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
[orchestrator.train.source.args]
dataset_name = "openai/gsm8k"
dataset_subset = "main"
```
### Optional Sub-Configs
@@ -123,11 +126,11 @@ To **disable** a sub-config that's on by default, use `--no-<name>` on the CLI o
TOML has no `null`. Use the string `"None"`, which the loader coerces:
```toml
[inference.model]
[inference.vllm]
max_model_len = "None"
```
On the CLI: `--inference.model.max-model-len None`.
On the CLI: `--inference.vllm.max-model-len None`.
### Discriminated Unions
@@ -149,23 +152,43 @@ Training and evaluation sources are arrays of tables. Set one source per environ
```toml
[[orchestrator.train.source]]
name = "gsm8k"
env.taskset = { id = "gsm8k-v1", split = "train" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
ratio = 3 # 75% of batches
[orchestrator.train.source.env.taskset]
id = "gsm8k-v1"
split = "train"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
ratio = 1 # default — 25% of batches
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.eval.source]]
name = "gsm8k-eval"
env.taskset = { id = "gsm8k-v1", split = "test" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval.source.env.taskset]
id = "gsm8k-v1"
split = "test"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
```
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
+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:
+41 -34
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
@@ -174,11 +168,17 @@ Every deployment fronts its vLLM engines with a single global router — it list
```toml
[inference.router] # or [router] for the standalone inference entrypoint
type = "llm-d" # "vllm-router" (default) or "llm-d"
# llm-d-only knobs (all optional):
scorers = { "prefix-cache-scorer" = 3.0, "active-request-scorer" = 2.0 } # base, applied to every profile
prefill_scorer_overrides = { "queue-scorer" = 2.0, "kv-cache-utilization-scorer" = 2.0 } # merged onto the P/D prefill profile
decode_scorer_overrides = {} # merged onto the P/D decode profile
non_cached_tokens = 16 # below this many non-cached prompt tokens, skip remote prefill (P/D)
non_cached_tokens = 16 # llm-d only: below this many non-cached prompt tokens, skip remote prefill (P/D)
# llm-d only: base scorer weights, applied to every profile
[inference.router.scorers]
"prefix-cache-scorer" = 3.0
"active-request-scorer" = 2.0
# llm-d only: merged onto the P/D prefill profile (decode_scorer_overrides for decode)
[inference.router.prefill_scorer_overrides]
"queue-scorer" = 2.0
"kv-cache-utilization-scorer" = 2.0
```
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`. The only backend supported for single-node (local) deployments.
@@ -255,34 +255,41 @@ For configuring various knobs with environment variables, we enable you to confi
[inference.deployment]
type = "disaggregated"
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip"}
[inference.deployment.prefill_env_vars]
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
[inference.deployment.decode_env_vars]
"VLLM_DEEP_GEMM_WARMUP" = "skip"
```
These are role-specific and layer on top of [`env_vars`](configuration.md#environment-variables) shared by all inference processes regardless of role.
### Other vLLM features
We support various other vLLM features. Some of those, such as `enable_dbo`, `enable_eplb` are exposed as a top-level config fields. For those that are not, you can configure them by setting `inference.vllm_extra` to the desired value.
The `[inference.vllm]` section is a pass-through: every key is forwarded to the vLLM server under vLLM's own argument name, whether prime-rl types it or not. Anything `vllm serve` accepts can be set here.
```toml
[inference.vllm_extra]
[inference.vllm]
headless = true
max_num_seqs = 256
```
On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (or `--vllm.max-num-seqs 256` for the standalone inference entrypoint); dict-valued arguments take a JSON string, e.g. `--vllm.compilation-config '{"cudagraph_mode": "NONE"}'`.
### Router Replay
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.enable_return_routed_experts = true`.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`.
```toml
[trainer]
enable_router_replay = true # this will also auto-set the inference.enable_return_routed_experts = true
enable_router_replay = true # this will also auto-set inference.vllm.enable_return_routed_experts = true
[inference]
[inference.vllm]
enable_return_routed_experts = true
```
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env-server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
+2 -2
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.
@@ -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
+6 -7
View File
@@ -36,7 +36,8 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer + inference. |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at a derived loopback address); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
## RL Trainer
@@ -102,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.
@@ -217,7 +218,7 @@ Checkpointing is split across processes because the orchestrator and trainer can
| Process | What's saved | Where |
|---|---|---|
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<output_dir>/checkpoints/step_N/trainer/` |
| Orchestrator | Step counter, total tokens / samples / problems | `<output_dir>/checkpoints/step_N/orchestrator/` |
| Orchestrator | Progress, per-env data state | `<output_dir>/checkpoints/step_N/orchestrator/` |
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
| Trainer (HF weights) | HF-compatible weight snapshot for serving | `<output_dir>/weights/step_N/` |
@@ -271,12 +272,10 @@ The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The f
├── inference/
│ ├── node_*.log # per-node inference stdout (multi-node only)
│ └── router.log # the single global router (multi-node only)
└── envs/{train,eval}/<env_name>/
├── env_server.log
└── env_worker_<id>.log
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
```
Env worker logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
+45 -13
View File
@@ -95,8 +95,18 @@ num_turns_weight = 0.0
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
[[orchestrator.train.source]]
name = "openseeker"
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "openseeker-v1"
@@ -118,8 +128,18 @@ choices = ["A", "B"]
[[orchestrator.train.source]]
name = "redsearcher"
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
@@ -147,13 +167,27 @@ interval = 20
[[orchestrator.eval.source]]
name = "browsecomp"
num_examples = 500 # full set is 1266; cap eval at 500
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-search"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "browsecomp-v1"
task = { judge = { model = "Qwen/Qwen3-235B-A22B-Instruct-2507" } }
[orchestrator.eval.source.env.taskset.task.judge]
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.eval.source.env.taskset.task.judges]]
@@ -166,15 +200,13 @@ task = { judge = { model = "Qwen/Qwen3-235B-A22B-Instruct-2507" } }
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
[inference.vllm]
max_model_len = 131072
[inference.parallel]
tp = 8
tensor_parallel_size = 8
enable_return_routed_experts = true
+32 -12
View File
@@ -99,9 +99,19 @@ thinking_retention = "all"
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] }
[orchestrator.train.source.env.taskset]
id = "scaleswe-v1"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-swe"]
[orchestrator.prime_monitor]
@@ -112,23 +122,33 @@ interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-swe"]
[orchestrator.eval.source.env.agent.timeout]
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
+39 -13
View File
@@ -93,8 +93,16 @@ num_turns_weight = 0.1
[[orchestrator.train.source]]
name = "tmax"
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-terminal"]
[orchestrator.train.source.env.taskset]
id = "tmax-v1"
@@ -121,9 +129,19 @@ interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-terminal"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
@@ -145,9 +163,19 @@ id = "swebench-verified-v1"
[[orchestrator.eval.source]]
name = "terminal-bench-2"
group_size = 4 # avg@4
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["glm45air-terminal"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "terminal-bench-2-v1"
@@ -169,15 +197,13 @@ id = "terminal-bench-2-v1"
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
[inference.vllm]
max_model_len = 131072
[inference.parallel]
tp = 8
tensor_parallel_size = 8
enable_return_routed_experts = true
+32 -18
View File
@@ -6,22 +6,9 @@
output_dir = "/shared/outputs/glm5.2-16node-llmd"
enable_expert_parallel = true
gpu_memory_utilization = 0.75
enable_eplb = false
use_deep_gemm = true
enable_fp32_lm_head = true
[model]
name = "zai-org/GLM-5.2-FP8"
max_model_len = 91000
tool_call_parser = "glm47"
reasoning_parser = "glm45"
[vllm_extra]
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[kv_cache_offload]
type = "mooncake"
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
@@ -35,16 +22,43 @@ prefill_nodes_per_replica = 2
num_prefill_replicas = 4
decode_nodes_per_replica = 8
num_decode_replicas = 1
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
[deployment.prefill_env_vars]
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
[deployment.decode_env_vars]
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
[router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 }
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 }
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 }
non_cached_tokens = 128
[router.scorers]
"prefix-cache-scorer" = 3.0
[router.prefill_scorer_overrides]
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[router.decode_scorer_overrides]
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[slurm]
job_name = "glm5.2-16node-llmd"
partition = "all"
[vllm]
model = "zai-org/GLM-5.2-FP8"
max_model_len = 91000
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
+8 -8
View File
@@ -1,12 +1,4 @@
enable_expert_parallel = true
enable_eplb = false
use_deep_gemm = true
gpu_memory_utilization = 0.85
[model]
name = "zai-org/GLM-5-FP8"
tool_call_parser = "auto"
reasoning_parser = "glm45"
[deployment]
type = "disaggregated"
@@ -17,3 +9,11 @@ gpus_per_node = 8
[slurm]
job_name = "glm5"
partition = "cluster"
[vllm]
model = "zai-org/GLM-5-FP8"
tool_call_parser = "auto"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.85
enable_expert_parallel = true
enable_eplb = false
+49 -26
View File
@@ -28,23 +28,53 @@ prefill_nodes_per_replica = 2
num_prefill_replicas = 4
decode_nodes_per_replica = 8
num_decode_replicas = 1
# skip warmup for faster start in cost of some jit overhead early
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
[inference.deployment.prefill_env_vars]
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
[inference.deployment.decode_env_vars]
"VLLM_DEEP_GEMM_WARMUP" = "skip"
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
# gives the most KV cache while keeping decent throughput, KV cache increase comes in from lower deep-ep LL static buffers
prefill_vllm_overrides = {"enable_dbo"=true}
decode_vllm_overrides = {"max_num_batched_tokens"=96, "max_num_seqs"=96}
[inference.deployment.prefill_vllm_overrides]
"enable_dbo" = true
[inference.deployment.decode_vllm_overrides]
"max_num_batched_tokens" = 96
"max_num_seqs" = 96
[inference.router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 } # need some prefix-cache routing, however due to shared mooncake pool do low prio
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 } # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 } # decode doesn't really create queue, it fills in KV cache fast, give 4.0
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[inference.vllm]
model = "zai-org/GLM-5.1-FP8"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[slurm]
job_name = "glm5-llmd"
partition = "all" # FILL IN: set to your cluster's partition
@@ -93,35 +123,28 @@ clear_thinking = false
[orchestrator.train.sampling]
temperature = 1.0
extra_body = {chat_template_kwargs = {clear_thinking = false}}
[orchestrator.train.sampling.extra_body.chat_template_kwargs]
clear_thinking = false
[[orchestrator.train.source]]
name = "r2e"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "rlm" }
env.agent.runtime = { type = "prime", labels = ["glm5-llmd"] }
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
[orchestrator.train.source.env.agent.runtime]
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
+16 -11
View File
@@ -23,10 +23,15 @@ type = "disaggregated"
prefill_nodes_per_replica = 4
decode_nodes_per_replica = 4
[inference.vllm]
model = "zai-org/GLM-5-FP8"
tool_call_parser = "glm47"
gpu_memory_utilization = 0.80
enable_expert_parallel = true
enable_eplb = false
[slurm]
job_name = "glm5-pd-disag"
[ckpt]
interval = 100
@@ -58,7 +63,6 @@ type = "adamw"
lr = 1e-6
weight_decay = 0.1
[orchestrator]
batch_size = 4096
group_size = 16
@@ -73,21 +77,22 @@ interval = 20
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] }
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
labels = ["glm5-pd-disag", "swe-bench-verified"]
[[orchestrator.post_batch_filters]]
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"
+72 -24
View File
@@ -50,37 +50,74 @@ oversampling_factor = 2
[[orchestrator.train.source]]
name = "swe"
ratio = 0.3
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "swe"] }
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["intellect-3.1", "swe"]
[[orchestrator.train.source]]
name = "deepdive"
ratio = 0.2
env.taskset = { id = "deepdive-v1" }
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"] }
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] }
[orchestrator.train.source.env.taskset]
id = "deepdive-v1"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["intellect-3.1", "deepdive"]
[[orchestrator.train.source]]
name = "math"
ratio = 0.3
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "i3_math_v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "logic"
ratio = 0.2
env.taskset = { id = "i3_logic_v1", filter = { max = 0.874 } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "i3_logic_v1"
[orchestrator.train.source.env.taskset.filter]
max = 0.874
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.train.source]]
name = "code"
ratio = 0.2
env.taskset = { id = "i3_code_v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "i3_code_v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
@@ -91,19 +128,30 @@ interval = 25
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] }
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
labels = ["intellect-3.1", "swe-bench-verified"]
[[orchestrator.eval.source]]
name = "aime2025"
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference.parallel]
tp = 8
[orchestrator.eval.source.env.taskset]
id = "aime25-v1"
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[inference.vllm]
tensor_parallel_size = 8
[orchestrator.renderer]
name = "default"
+21 -10
View File
@@ -48,25 +48,36 @@ batch_size = 2048
oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.train.source]]
name = "swe"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["minimax-swe", "swe"] }
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["minimax-swe", "swe"]
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] }
[inference.parallel]
tp = 8
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
# PrimeIntellect/MiniMax-M2.5-bf16 — template-identical to MiniMaxAI/MiniMax-M2.5 (mapped).
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
labels = ["minimax-swe", "swe-bench-verified"]
[inference.vllm]
tensor_parallel_size = 8
[orchestrator.renderer]
name = "minimax-m2"
+35 -15
View File
@@ -83,9 +83,19 @@ truncate_history_thinking = false
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset = { id = "scaleswe-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] }
[orchestrator.train.source.env.taskset]
id = "scaleswe-v1"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["nemotron-3-super-swe"]
[orchestrator.prime_monitor]
@@ -94,19 +104,29 @@ interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
vm = true
idle_timeout = "None"
labels = ["nemotron-3-super-swe"]
[orchestrator.eval.source.env.agent.timeout]
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
+20 -8
View File
@@ -50,18 +50,30 @@ max_completion_tokens = 32768
[[orchestrator.train.source]]
name = "math"
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "i3_math_v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
name = "aime2025"
env.taskset = { id = "aime25-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[inference.parallel]
tp = 8
[orchestrator.eval.source.env.taskset]
id = "aime25-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[inference.vllm]
tensor_parallel_size = 8
+22 -8
View File
@@ -48,18 +48,32 @@ max_off_policy_steps = 16
[[orchestrator.train.source]]
name = "swe"
env.taskset = { id = "r2e-gym-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] }
[orchestrator.train.source.env.taskset]
id = "r2e-gym-v1"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "prime"
labels = ["qwen30b-swe", "swe"]
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset = { id = "swebench-verified-v1" }
env.agent.harness = { id = "bash" }
env.agent.runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] }
[inference.parallel]
tp = 8
[orchestrator.eval.source.env.taskset]
id = "swebench-verified-v1"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
type = "prime"
labels = ["qwen30b-swe", "swe-bench-verified"]
[inference.vllm]
tensor_parallel_size = 8
+17 -9
View File
@@ -36,16 +36,24 @@ group_size = 16
max_off_policy_steps = 32
[[orchestrator.train.source]]
env.taskset = { id = "general-agent-v1", task = { tools = { colocated = true } }, min_tier = 1 }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "modal" }
[orchestrator.train.source.env.taskset]
id = "general-agent-v1"
min_tier = 1
[orchestrator.train.source.env.taskset.task.tools]
colocated = true
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "modal"
[inference]
gpu_memory_utilization = 0.85
[inference.model]
[inference.vllm]
max_model_len = 32768
[inference.parallel]
dp = 2
tp = 4
data_parallel_size = 2
tensor_parallel_size = 4
gpu_memory_utilization = 0.85
+2 -2
View File
@@ -32,7 +32,7 @@ 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:
@@ -110,7 +110,7 @@ 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
+14 -3
View File
@@ -33,8 +33,19 @@ max_completion_tokens = 768
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "alphabet-sort-v1"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[inference] # Default inference config
+21 -9
View File
@@ -18,27 +18,39 @@ seq_len = 8192
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "math-env-v1"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.eval]
interval = 50
[[orchestrator.eval.source]]
name = "aime2024"
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24-v1"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[trainer.model]
seq_len = 16384
[inference.model]
[inference.vllm]
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+3 -3
View File
@@ -22,7 +22,7 @@ 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
@@ -95,7 +95,7 @@ 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
@@ -210,7 +210,7 @@ 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 \
+9 -3
View File
@@ -17,9 +17,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[trainer.optim]
lr = 3e-6
+2 -2
View File
@@ -70,7 +70,7 @@ 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:
@@ -114,7 +114,7 @@ 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
+13 -7
View File
@@ -40,17 +40,23 @@ name = "qwen3-4b-wiki-search"
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.source]]
name = "wiki-search"
[orchestrator.train.source.env.taskset]
id = "wiki-search-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[ckpt] # Checkpoint at the end of training
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
+2 -2
View File
@@ -22,7 +22,7 @@ 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.
@@ -98,7 +98,7 @@ 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
+11 -7
View File
@@ -20,18 +20,22 @@ group_size = 16
[[orchestrator.train.source]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.player.harness = { id = "null" }
env.player.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "wordle-v1"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer] # Default trainer config
[inference.parallel]
dp = 6
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
[inference.vllm]
data_parallel_size = 6
[orchestrator.renderer]
name = "prime-qwen3"
+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"
+9 -3
View File
@@ -15,9 +15,15 @@ max_completion_tokens = 128
[[train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[train.source.env.taskset]
id = "reverse-text-v1"
[train.source.env.agent.harness]
id = "null"
[train.source.env.agent.runtime]
type = "subprocess"
[renderer]
name = "prime-qwen3"
+6 -8
View File
@@ -59,9 +59,6 @@ spec:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.orchestrator.replicas }}"
- name: HEADLESS_SERVICE
value: "{{ .Release.Name }}-orchestrator-headless.{{ .Values.namespace }}.svc.cluster.local"
- name: INFERENCE_URL
{{- $releaseName := .Release.Name }}
{{- $namespace := .Values.namespace }}
{{- $port := int .Values.inference.service.port }}
@@ -71,6 +68,9 @@ spec:
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
{{- $urls = append $urls $url }}
{{- end }}
- name: INFERENCE_URL
value: {{ first $urls | quote }}
- name: ADMIN_INFERENCE_URLS
value: {{ $urls | join "," | quote }}
{{- with .Values.orchestrator.env }}
{{- toYaml . | nindent 8 }}
@@ -163,8 +163,6 @@ spec:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.inference.replicas }}"
- name: HEADLESS_SERVICE
value: "{{ .Release.Name }}-inference-headless.{{ .Values.namespace }}.svc.cluster.local"
{{- with .Values.inference.env }}
{{- toYaml . | nindent 8 }}
{{- end }}
@@ -294,13 +292,10 @@ spec:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.trainer.replicas }}"
- name: HEADLESS_SERVICE
value: "{{ .Release.Name }}-trainer-headless.{{ .Values.namespace }}.svc.cluster.local"
{{- if .Values.trainer.pytorchCudaAllocConf }}
- name: PYTORCH_CUDA_ALLOC_CONF
value: {{ .Values.trainer.pytorchCudaAllocConf | quote }}
{{- end }}
- name: INFERENCE_URL
{{- $releaseName := .Release.Name }}
{{- $namespace := .Values.namespace }}
{{- $port := int .Values.inference.service.port }}
@@ -310,6 +305,9 @@ spec:
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
{{- $urls = append $urls $url }}
{{- end }}
- name: INFERENCE_URL
value: {{ first $urls | quote }}
- name: ADMIN_INFERENCE_URLS
value: {{ $urls | join "," | quote }}
{{- with .Values.trainer.env }}
{{- toYaml . | nindent 8 }}
+6 -3
View File
@@ -28,9 +28,12 @@ orchestrator:
# Auto-start configuration (set to false to use sleep infinity for debugging)
autoStart: false
# Example command - use $INFERENCE_URL directly (comma-separated list of all inference server URLs)
command: "" # e.g., 'uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs/run_default --client.base-url $INFERENCE_URL'
# $INFERENCE_URL is auto-set to: 'http://<release>-inference-0...:8000/v1,http://<release>-inference-1...:8000/v1,...'
# Example command - use $INFERENCE_URL directly (the first inference server URL)
command: "" # e.g., 'uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL'
# $INFERENCE_URL is auto-set to 'http://<release>-inference-0...:8000/v1'. With more than one
# inference replica, put a router in front and point --client.base-url at it; admin operations
# (weight updates, health checks) fan out to every replica via
# --client.admin-base-url $ADMIN_INFERENCE_URLS (comma-separated list of all replica URLs).
resources:
requests:
+2 -2
View File
@@ -7,10 +7,10 @@ requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.4.2",
"renderers>=0.1.8",
"renderers>=0.1.9",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.2.2.dev43",
"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."
@@ -1,14 +1,66 @@
from pathlib import Path
from prime_rl.configs.orchestrator import EnvConfig
import verifiers.v1 as vf
from pydantic import SerializeAsAny, model_validator
from prime_rl.configs.shared import LogConfig
from prime_rl.utils.config import BaseConfig
class EnvServerConfig(BaseConfig):
env: EnvConfig
"""``uv run env-server``: what to serve (``[env]``, 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."""
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
"""The environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
serve: vf.ServeConfig = vf.ServeConfig()
"""How it's served: the worker pool, the bind address, each worker's episode bound."""
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")
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
@model_validator(mode="before")
@classmethod
def _resolve_env(cls, data):
"""Narrow ``env`` to the selected env's config class."""
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
@property
def 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 ""
@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)'
)
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
@@ -25,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."""
@@ -122,17 +117,6 @@ class EvalSamplingConfig(BaseConfig):
return args
class ServingConfig(vf.ServingConfig):
"""Verifiers' serving block with ``address`` back to optional. Verifiers defaults it
to the address its own ``serve`` CLI binds; here the question is whether to spawn a
server or connect to one already running, and that answer has to survive the
resolved config being written to a file and read back — so it must be a *value*
(``None``), not field-set metadata, which a round-trip drops."""
address: str | None = None
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to that server instead of spawning one; when None, it spawns a subprocess env server on a free port. ``pool`` sizes the spawned server."""
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
@@ -141,8 +125,8 @@ class EnvConfig(BaseConfig):
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: ServingConfig = ServingConfig()
"""How the env server is run: ``serve.pool`` sizes the spawned server, ``serve.address`` points at an external one instead, and ``serve.max_concurrent`` bounds one worker's episodes in flight (unset = unbounded; the dispatcher's ``max_inflight_episodes`` is the run's bound)."""
serve: vf.ServeConfig = vf.ServeConfig()
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config with an unset ``address`` filled in as the derived ``tcp://127.0.0.1:<env_server_base_port + index>``. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
"""A classic (v0) environment to run through the bridge instead of ``env``."""
@@ -296,6 +280,11 @@ class EvalConfig(BaseConfig):
"""If True, skip the startup eval that otherwise runs before any
train rollouts."""
retrigger_on_resume: bool = False
"""If True, re-trigger evals at the checkpoint step on resume (e.g. after a
crash that left in-flight evals unfinished). By default, assumes a clean
exit where all evals already completed."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
@@ -344,7 +333,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."""
@@ -467,14 +456,6 @@ class OrchestratorConfig(BaseConfig):
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. RL/OPD roll out through the renderer
client; SFT uses it to backfill tokens for its chat-completions teacher."""
pool_size: int | None = Field(None, ge=1)
"""Number of renderer slots shared across concurrent rollouts. Bump
for long multi-turn prompts where client-side jinja tokenization
serializes."""
optim: OptimizerConfig = OptimizerConfig()
"""Per-run optimizer configuration for multi-run training."""
eval: EvalConfig | None = None
"""Evaluation configuration."""
@@ -523,12 +504,15 @@ 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."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the source at position ``i`` (train, then eval) is served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address`` keep it instead, without shifting the other sources' ports (indices stay positional). Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
batch_size: int | None = Field(None, ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
@@ -547,9 +531,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."""
@@ -619,22 +605,6 @@ class OrchestratorConfig(BaseConfig):
"""True when at least one train env samples rollouts from the live policy."""
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.source)
@model_validator(mode="after")
def validate_pool_size(self):
"""``pool_size`` sizes the renderer-client pool for policy-sourced
sampling. Reject it when that path never runs — no train env samples
from the policy — so callers don't silently pass it and wonder why
it's ignored."""
if self.pool_size is None:
return self
if not self.any_policy_sourced:
raise ValueError(
f"orchestrator.pool_size={self.pool_size!r} is set but no train env samples "
"from the policy — the renderer-client sampling pool never runs (the renderer "
"is still used for client-side tokenization). Remove pool_size."
)
return self
@model_validator(mode="after")
def validate_renderer_auto_resolves(self):
"""Reject the silent DefaultRenderer fallback at config time.
@@ -741,3 +711,26 @@ class OrchestratorConfig(BaseConfig):
# bridge applies legacy.extra_env_kwargs via env.set_kwargs).
env.legacy.extra_env_kwargs["max_seq_len"] = self.seq_len
return self
@property
def env_sources(self) -> list[tuple[str, EnvConfig]]:
"""Every ``(split, source)`` this run pulls from, train first then eval — the
order that fixes each source's deterministic env-server port."""
sources: list[tuple[str, EnvConfig]] = [("train", source) for source in self.train.source]
if self.eval is not None:
sources += [("eval", source) for source in self.eval.source]
return sources
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each source's env server lives, keyed by ``(split, resolved_name)``:
the source's own ``serve.address`` when set (an externally managed server), else
``tcp://127.0.0.1:<port>`` with ports from ``env_server_base_port`` in
``env_sources`` order. The launcher binds env servers at exactly these addresses
and the orchestrator connects to them, so both sides agree from the config
alone."""
return {
(split, source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, (split, source) in enumerate(self.env_sources)
}
@@ -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"):
@@ -2,12 +2,17 @@ import re
# (regex, parser_name) — first match wins.
TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
# Trinity-Large-Thinking uses the Qwen3-Coder tool format; the rest of the family is Hermes.
(re.compile(r"^arcee-ai/Trinity-Large-Thinking"), "qwen3_coder"),
(re.compile(r"^arcee-ai/Trinity-"), "hermes"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.2"), "deepseek_v32"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.1"), "deepseek_v31"),
(re.compile(r"^zai-org/GLM-4\.5"), "glm45"),
(re.compile(r"^zai-org/GLM-4\.7"), "glm47"),
(re.compile(r"^zai-org/GLM-5"), "glm47"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2"),
(re.compile(r"^openai/gpt-oss"), "openai"),
(re.compile(r"^poolside/Laguna"), "poolside_v1"),
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "qwen3_coder"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3"), "qwen3_coder"),
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
@@ -18,9 +23,13 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
]
REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
# Trinity-Large-Preview doesn't reason; the Thinking/Mini/Nano variants do.
(re.compile(r"^arcee-ai/Trinity-(Large-Thinking|Mini|Nano)"), "deepseek_r1"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.[12]"), "deepseek_r1"),
(re.compile(r"^zai-org/GLM-"), "glm45"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
# openai/gpt-oss has no entry here — vLLM's harmony serving path splits reasoning natively.
(re.compile(r"^poolside/Laguna"), "poolside_v1"),
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
@@ -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."
)
+32 -11
View File
@@ -1,6 +1,6 @@
[project]
name = "prime-rl"
version = "0.7.0"
version = "0.8.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
@@ -18,7 +18,7 @@ dependencies = [
"torchaudio",
"torchdata>=0.11.0",
"transformers==5.6.2",
"vllm>=0.24.0",
"vllm>=0.26.0",
"mooncake-transfer-engine>=0.3.10.post2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.2.2.dev43",
"verifiers[harbor]>=0.3.0",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -53,14 +53,19 @@ sft = "prime_rl.entrypoints.sft:main"
inference = "prime_rl.entrypoints.inference:main"
trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
env-server = "prime_rl.orchestrator.env_server.env_server:main"
env-server = "prime_rl.entrypoints.env_server:main"
[project.entry-points."vllm.general_plugins"]
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
[project.optional-dependencies]
# Both wheels are the same flash-attn 2.8.3 / cu128 / torch 2.11 / cp312 build and carry
# sm_80 / sm_90 / sm_100 / sm_120 cubins. `attn="auto"` picks FA4 on sm_100 and FA3 on
# sm_90, so FA2 is the resolved backend on sm_120 (see `_resolve_attn_impl` in
# trainer/model.py).
flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.22/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
]
flash-attn-3 = ["flash_attn_3"]
@@ -123,13 +128,22 @@ 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`.
# research-environments 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/verifiers/environments/alphabet_sort_v1",
"deps/verifiers/environments/color_codeword_v1",
"deps/verifiers/environments/gsm8k_v1",
"deps/verifiers/environments/kuhn_poker_v1",
"deps/verifiers/environments/proposer_solver_v1",
"deps/verifiers/environments/reverse_text_v1",
"deps/verifiers/environments/wiki_search_v1",
"deps/verifiers/environments/wordle_v1",
]
# 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.
@@ -200,8 +214,8 @@ vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
@@ -235,7 +249,14 @@ explicit = true
[tool.ruff.lint]
select = ["F", "I"]
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
# jaxtyping writes shapes as string annotations (`Int[Tensor, "batch seq"]`), which ruff reads as
# forward references and reports as syntax errors / undefined names.
[tool.ruff.lint.per-file-ignores]
"src/prime_rl/trainer/model.py" = ["F722", "F821"]
"src/prime_rl/trainer/rl/data.py" = ["F722", "F821"]
"src/prime_rl/trainer/rl/loss.py" = ["F722", "F821"]
"src/prime_rl/trainer/sft/data.py" = ["F722", "F821"]
[tool.ruff.lint.isort]
# `prime_rl` is split across two editable wheels (prime-rl + prime-rl-configs).
-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!"
}
+27 -10
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
@@ -34,29 +34,46 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
## Special syntax
**No inline tables** — checked-in configs use `[section]` headers, never `key = { ... }`. Expand `env.taskset = { id = "..." }` to a full-path header (`[orchestrator.train.source.env.taskset]` — subtable headers after a `[[...]]` entry attach to that entry).
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--model.max-model-len None`.
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--vllm.max-model-len None`.
**Lists** — TOML uses array of tables; later config files replace lists wholesale, so overlays must include the full desired list:
```toml
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.train.source.env.taskset]
id = "reverse-text-v1"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.eval.source]]
name = "reverse-text-eval"
env.taskset = { id = "reverse-text-v1", split = "test" }
env.agent.harness = { id = "null" }
env.agent.runtime = { type = "subprocess" }
[orchestrator.eval.source.env.taskset]
id = "reverse-text-v1"
split = "test"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
```
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text-v1` or `--orchestrator.eval.source.0.env.taskset.id reverse-text-v1`.
**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.
@@ -73,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
+1 -1
View File
@@ -29,7 +29,7 @@ uv sync --all-extras --all-packages # + all env packages (needed to train
uv sync --package prime-rl --package gsm8k-v1 # 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/research-environments/environments/*/*` are auto-discovered — adding a new env there needs no `pyproject.toml` change. verifiers' example envs are enumerated explicitly in `[tool.uv.workspace].members` (only the ones prime-rl trains or tests on) — to use another, add its path to the list. Members are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
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`.
+20 -12
View File
@@ -89,17 +89,25 @@ grep -E "WARNING|ERROR" {output_dir}/logs/envs/{train,eval}/*.log
All metrics print to the console log (and W&B when configured).
**Progress** — orchestrator log. Rollout metrics are keyed `{scope}/{subset}/<metric>/<stat>`: `scope` is `train/agg` (all train envs) or `train/<env>` (`eval/<env>` for eval); `subset` is `all` (every rollout) or `effective` (post-filter).
**Progress** — orchestrator log. Rollout metrics mirror the episode/trace hierarchy, at two levels:
- `{scope}/{subset}/<metric>/<stat>` — episode-level facts only: the token/turn/branch counts, summed over an episode's traces.
- `{scope}/{subset}/<agent>/<metric>/<stat>` — every trace-level metric (reward, truncation, errors, timing, env metrics, filter verdicts, eval scores), keyed by agent name so seats never mix. Flat over that agent's traces: one sample is one trace, so an in-episode fan-out like n solvers contributes n samples.
`scope` is `train/agg` (all train envs) or `train/<env>` (`eval/<env>` for eval); `subset` is `all` (every rollout) or `effective` (post-filter). Single-agent envs have one agent — usually `agent` — and one trace per episode, so both levels agree; multi-agent envs name each seat (`proposer`, `solver`, `judge`, …).
| Metric | Description |
|--------|-------------|
| `train/agg/effective/reward/mean` | mean training reward (per env: `train/<env>/effective/reward/mean`) |
| `train/agg/effective/num_total_tokens/mean` | avg tokens per rollout (also `num_input_tokens`, `num_output_tokens`) |
| `train/agg/effective/num_turns/mean` | avg turns per rollout (multi-turn only) |
| `train/agg/effective/is_truncated/mean` | fraction truncated |
| `train/agg/all/has_error/mean` | fraction errored (per-type under `train/agg/all/error/<type>`; also `dispatcher/errored/{train,eval}`) |
| `train/<env>/effective/metrics/<name>/mean` | env-specific metrics (e.g. pass rate) |
| `eval/<env>/effective/{avg@k,pass@k}` | eval scores when configured |
| `train/agg/effective/<agent>/reward/mean` | mean training reward for that agent (per env: `train/<env>/effective/<agent>/reward/mean`) |
| `train/agg/effective/num_total_tokens/mean` | avg tokens per episode, summed over its agents (also `num_input_tokens`, `num_output_tokens`) |
| `train/agg/effective/num_turns/mean` | avg turns per episode, summed over its agents |
| `train/<env>/effective/<agent>/num_turns/mean` | avg turns for that agent alone (also token counts, `num_branches`) |
| `train/agg/effective/<agent>/is_truncated/mean` | fraction of that agent's rollouts truncated |
| `train/agg/all/<agent>/has_error/mean` | fraction of that agent's rollouts errored (per-type under `train/agg/all/<agent>/error/<type>`; also `dispatcher/errored/{train,eval}`) |
| `train/agg/all/<agent>/is_trainable/mean` | fraction carrying a training signal — 0.0 for a frozen seat like a judge (also `is_filtered`, `filters/<name>`) |
| `train/<env>/effective/<agent>/metrics/<name>/mean` | env-specific metrics for that agent (e.g. pass rate) |
| `train/<env>/effective/<agent>/timing/agent/model/mean` | model vs harness share of that agent's phase |
| `eval/<env>/effective/<agent>/{avg@k,pass@k}` | eval scores for that agent, when configured |
**Stability** — trainer log:
@@ -154,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
@@ -172,9 +180,9 @@ All processes use `setproctitle` so they're visible in `ps`/`htop`/`pstree`:
```
PRIME-RL::Launcher
├── PRIME-RL::Inference (vLLM server, GPU 0)
├── PRIME-RL::Orchestrator (CPU-only)
│ └── Verifiers::EnvServer (ZMQ env server per environment)
│ └── Verifiers::EnvWorker0..N
├── PRIME-RL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
│ └── Verifiers::EnvWorker0..N
├── PRIME-RL::Orchestrator (CPU-only; connects to each env server)
├── torchrun
│ └── PRIME-RL::Trainer (GPU 1+)
└── tail trainer.log
+2 -2
View File
@@ -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:
@@ -12,28 +12,26 @@ from prime_rl.utils.utils import clean_exit
@clean_exit
def run_server(config: EnvServerConfig):
env = config.env
address = env.serve.address or "tcp://127.0.0.1:5000"
# The env's ``serve.pool`` (static or elastic) sizes the server; a v0/legacy env runs through
# ``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": env.env_id, "env_args": env.legacy.args, "extra_env_kwargs": env.legacy.extra_env_kwargs}
if env.is_legacy
else {"config_data": env_config_data(env.env), "max_concurrent": env.serve.max_concurrent}
{"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_env(
**pool_serve_kwargs(env.serve.pool),
legacy=env.is_legacy,
address=address,
**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,
)
def main():
"""Main entry-point for env-server. Run using `uv run env-server`"""
"""Main entry-point for the env server. Run using `uv run env-server`"""
set_proc_title("EnvServer")
run_server(cli(EnvServerConfig))
+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()
+104 -24
View File
@@ -8,12 +8,14 @@ import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from urllib.parse import urlparse
import pynvml
import tomli_w
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.inference import vllm_overrides_fragment
from prime_rl.utils.config import cli, to_toml_dict
@@ -43,6 +45,27 @@ TRAINER_TOML = "trainer.toml"
ORCHESTRATOR_TOML = "orchestrator.toml"
INFERENCE_TOML = "inference.toml"
ENVS_DIR = "envs"
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig, str]]:
"""``(split, source, address)`` for every launcher-managed train/eval source. The
launcher runs one env server per source at its deterministic address; the
orchestrator connects there. A source with ``serve.address`` set is externally
managed — its server runs elsewhere and only the orchestrator connects to it — so
the launcher neither writes its TOML nor spawns a server for it."""
addresses = config.orchestrator.env_addresses
return [
(split, source, addresses[(split, source.resolved_name)])
for split, source in config.orchestrator.env_sources
if source.serve.address is None
]
def env_server_names(config: RLConfig, split: str) -> list[str]:
"""Names of the launcher-managed env servers for one split."""
return [source.resolved_name for source_split, source, _ in env_servers(config) if source_split == split]
def get_physical_gpu_ids() -> list[int]:
"""Return physical GPU IDs visible to the launcher."""
@@ -80,6 +103,23 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
with open(output_dir / INFERENCE_TOML, "wb") as f:
tomli_w.dump(inference_dict, f)
# One EnvServerConfig TOML per launcher-managed source: `env-server @ <path>` binds
# at the source's deterministic address, where the orchestrator connects. The source's
# env/serve/legacy blocks carry over; its other knobs (sampling, algo, name, ...) are
# orchestrator-side.
for split, source, address in env_servers(config):
env_dir = output_dir / ENVS_DIR / split
env_dir.mkdir(parents=True, exist_ok=True)
source_dict = to_toml_dict(source)
env_server_dict = {
"env": source_dict["env"],
"serve": {**source_dict.get("serve", {}), "address": address},
"legacy": source_dict.get("legacy", {}),
"log": {"level": config.orchestrator.log.vf_level, "json_logging": config.orchestrator.log.json_logging},
}
with open(env_dir / f"{source.resolved_name}.toml", "wb") as f:
tomli_w.dump(env_server_dict, f)
def rl_local(config: RLConfig):
assert config.deployment.type == "single_node"
@@ -130,11 +170,8 @@ def rl_local(config: RLConfig):
}
# Validate client port matches inference server port
if config.inference is not None and not config.orchestrator.model.client.is_elastic:
from urllib.parse import urlparse
base_url = config.orchestrator.model.client.base_url[0]
parsed = urlparse(base_url)
if config.inference is not None:
parsed = urlparse(config.orchestrator.model.client.base_url)
client_port = parsed.port
expected_port = config.inference.server.port
if client_port != expected_port:
@@ -200,7 +237,7 @@ def rl_local(config: RLConfig):
"No [inference] block configured - the policy inference server will not be started here. "
"Every algorithm requires a policy inference pool for evals + weight sync; "
"make sure one is running at orchestrator.model.client.base_url "
f"({', '.join(config.orchestrator.model.client.base_url)}), otherwise the orchestrator "
f"({config.orchestrator.model.client.base_url}), otherwise the orchestrator "
"will hang waiting for it."
)
@@ -210,7 +247,7 @@ def rl_local(config: RLConfig):
assert algo is not None, "TrainSourceConfig.algo must be resolved before launch (inherit_env_algorithms)"
for ref in (algo.sampling.source, getattr(algo, "teacher", None)):
if isinstance(ref, FrozenModelConfig):
frozen_endpoints.append(f"{ref.name} ({', '.join(ref.base_url)})")
frozen_endpoints.append(f"{ref.name} ({ref.base_url})")
if frozen_endpoints:
endpoints = ", ".join(dict.fromkeys(frozen_endpoints))
logger.info(
@@ -219,6 +256,41 @@ def rl_local(config: RLConfig):
"otherwise rollouts will hang."
)
# Start one env server per source. The orchestrator connects to each source's
# deterministic address, polling until the server is up, so the servers and the
# orchestrator start in parallel.
for split, source, address in env_servers(config):
name = source.resolved_name
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.toml").as_posix()]
logger.info(f"Starting {split} env server {name} at {address}")
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
env_server_log.parent.mkdir(parents=True, exist_ok=True)
with open(env_server_log, "w") as log_file:
env_server_process = Popen(
env_server_cmd,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**config.env_vars,
**config.orchestrator.env_vars,
},
stdout=log_file,
stderr=log_file,
)
processes.append(env_server_process)
# Start monitoring thread
stop_event = Event()
stop_events[f"env/{split}/{name}"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(env_server_process, stop_event, error_queue, f"{split} env server {name}"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_TOML).as_posix()]
logger.info("Starting orchestrator process")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
@@ -391,6 +463,10 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
else {}
)
# Env servers launch next to the orchestrator, one per launcher-managed train/eval source.
train_env_names = env_server_names(config, "train")
eval_env_names = env_server_names(config, "eval")
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
@@ -406,7 +482,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
is_disaggregated=True,
config_dir=config_dir,
output_dir=config.output_dir,
orchestrator_output_dir=config.orchestrator.output_dir,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
nodes_per_infer_replica=infer_deploy.num_nodes,
@@ -422,8 +497,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
router_port=config.inference.server.port,
prefill_port=infer_deploy.prefill_port,
decode_port=infer_deploy.decode_port,
inference_tp=config.inference.parallel.tp,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port,
inference_tp=config.inference.vllm.tensor_parallel_size,
inference_data_parallel_rpc_port=config.inference.vllm.data_parallel_rpc_port,
use_deep_gemm=config.inference.use_deep_gemm,
prefill_env_vars=infer_deploy.prefill_env_vars,
decode_env_vars=infer_deploy.decode_env_vars,
@@ -432,12 +507,14 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
inference_env_vars=inference_env_vars,
prefill_vllm_extra_json=vllm_overrides_fragment(infer_deploy.prefill_vllm_overrides),
decode_vllm_extra_json=vllm_overrides_fragment(infer_deploy.decode_vllm_overrides),
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
**mooncake_vars,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
)
else:
script = template.render(
@@ -445,7 +522,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
is_disaggregated=False,
config_dir=config_dir, # TODO: should prob have each subconfig path separately
output_dir=config.output_dir,
orchestrator_output_dir=config.orchestrator.output_dir,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.total_infer_nodes,
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
@@ -455,10 +531,16 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
router_port=config.inference.server.port if config.inference else 8000,
infer_nodes_per_replica=config.deployment.infer_nodes_per_replica,
backend_port=config.inference.backend_port if config.inference else 8100,
inference_tp=config.inference.parallel.tp if config.inference else 1,
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
dp_per_node=(config.deployment.gpus_per_node // config.inference.parallel.tp) if config.inference else 1,
inference_tp=config.inference.vllm.tensor_parallel_size if config.inference else 1,
inference_enable_expert_parallel=config.inference.vllm.enable_expert_parallel
if config.inference
else False,
inference_data_parallel_rpc_port=config.inference.vllm.data_parallel_rpc_port
if config.inference
else 29600,
dp_per_node=(config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size)
if config.inference
else 1,
**mooncake_vars,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
@@ -467,6 +549,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
trainer_env_vars=trainer_env_vars,
orchestrator_env_vars=orchestrator_env_vars,
inference_env_vars=inference_env_vars,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
@@ -487,10 +571,8 @@ def rl_slurm(config: RLConfig):
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean_output_dir"})
logger.info(f"Wrote config to {config_dir / RL_TOML}")
train_env_names = [env.resolved_name for env in config.orchestrator.train.source]
eval_env_names = (
[source.resolved_name for source in config.orchestrator.eval.source] if config.orchestrator.eval else []
)
train_env_names = env_server_names(config, "train")
eval_env_names = env_server_names(config, "eval")
log_message = format_log_message(
log_dir=log_dir,
@@ -504,10 +586,8 @@ def rl_slurm(config: RLConfig):
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
train_env_names = [env.resolved_name for env in config.orchestrator.train.source]
eval_env_names = (
[source.resolved_name for source in config.orchestrator.eval.source] if config.orchestrator.eval else []
)
train_env_names = env_server_names(config, "train")
eval_env_names = env_server_names(config, "eval")
has_infer = config.deployment.infer_nodes_per_replica > 0
log_message = format_log_message(
-3
View File
@@ -1,7 +1,5 @@
import torch
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
def apply_shared_vllm_patches():
"""vLLM general plugin: prime-rl patches that must run in every vLLM process.
@@ -16,7 +14,6 @@ def apply_shared_vllm_patches():
monkey_patch_nano_v3_reasoning_parser()
monkey_patch_qwen3_coder_param_newline_trim()
monkey_patch_minimax_m2_think_end_passthrough()
monkey_patch_vllm_padded_input_scrub()
monkey_patch_return_routed_experts_with_nixl_connector()
monkey_patch_kv_xfer_finished_tolerate_freed()
monkey_patch_online_fp8_parameter_cast()
+5 -9
View File
@@ -10,14 +10,10 @@ def setup_vllm_env(config: InferenceConfig):
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
# Force the V1 GPU model runner. vLLM 0.24.0 routes Llama/Mistral/Qwen3 plus MoE archs
# (DeepseekV2, Qwen2Moe, GraniteMoe; the 0.23 MoE/quantized guard was removed) to the
# V2 runner, which has no `_preprocess` hook for our padded-input scrub (see
# inference/vllm/padded_input_scrub.py) and doesn't zero the padded decode tail
# itself; that stale tail poisons CUDA-graph replay as NaN logits (reproduced on
# Nemotron-Nano SWE, PR #2506; upstream fix vllm#42779 is still unmerged). V1 keeps
# the scrub effective for every model and is also required for routed-experts capture
# (the NIXL PD path rejects V2). setdefault so it stays overridable.
# Force the V1 GPU model runner. vLLM routes Llama/Mistral/Qwen3 plus MoE archs
# (DeepseekV2, Qwen2Moe, GraniteMoe) to the V2 runner by default, but V2 doesn't
# support routed-experts capture (the NIXL PD path rejects it). setdefault so it
# stays overridable.
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
@@ -30,7 +26,7 @@ def setup_vllm_env(config: InferenceConfig):
os.environ["VLLM_USE_DEEP_GEMM"] = deep_gemm_enabled
os.environ["VLLM_MOE_USE_DEEP_GEMM"] = deep_gemm_enabled
if config.enable_lora:
if config.vllm.enable_lora:
os.environ["VLLM_ALLOW_RUNTIME_LORA_UPDATING"] = "True"
if config.log.json_logging:
@@ -1,88 +0,0 @@
from __future__ import annotations
import logging
import threading
from collections.abc import Sequence
from typing import Any
logger = logging.getLogger(__name__)
_INSTALL_LOCK = threading.Lock()
_INSTALLED = False
def monkey_patch_vllm_padded_input_scrub() -> None:
"""Zero vLLM's padded model inputs before graph replay.
vLLM pads decode batches up to CUDA graph capture sizes. Some kernels read
model-input tensors past the scheduled-token prefix, so stale values in the
padded tail can affect replayed decode graphs. Keep this shim until the
vLLM-side fix is available in the pinned runtime.
Remove this patch once https://github.com/vllm-project/vllm/pull/42779 is
included in the vLLM release we pin/use.
"""
global _INSTALLED
with _INSTALL_LOCK:
if _INSTALLED:
return
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
if getattr(GPUModelRunner, "_prime_rl_padded_input_scrub", False):
_INSTALLED = True
return
original_preprocess = GPUModelRunner._preprocess
def _patched_preprocess(
self: Any,
scheduler_output: Any,
num_input_tokens: int,
intermediate_tensors: Any | None = None,
) -> tuple[Any, ...]:
result = original_preprocess(
self,
scheduler_output,
num_input_tokens,
intermediate_tensors,
)
num_scheduled_tokens = int(scheduler_output.total_num_scheduled_tokens)
_zero_padded_model_inputs(
result,
num_scheduled_tokens,
int(num_input_tokens),
)
return result
GPUModelRunner._preprocess = _patched_preprocess
GPUModelRunner._prime_rl_padded_input_scrub = True
_INSTALLED = True
logger.warning("Enabled vLLM padded model-input scrub.")
def _zero_padded_model_inputs(
preprocess_result: Sequence[Any],
num_scheduled_tokens: int,
num_input_tokens: int,
) -> None:
"""Zero the model-input tail beyond scheduled tokens in-place."""
if num_input_tokens <= num_scheduled_tokens:
return
input_ids = preprocess_result[0]
inputs_embeds = preprocess_result[1]
positions = preprocess_result[2]
pad_slice = slice(num_scheduled_tokens, num_input_tokens)
if input_ids is not None:
input_ids[pad_slice].zero_()
if inputs_embeds is not None:
inputs_embeds[pad_slice].zero_()
if positions is not None:
if positions.ndim == 1:
positions[pad_slice].zero_()
else:
positions[..., pad_slice].zero_()
+4 -11
View File
@@ -1,6 +1,5 @@
import asyncio
from argparse import Namespace
from typing import Any
import uvloop
from fastapi import APIRouter, Request
@@ -25,7 +24,6 @@ from prime_rl.inference.patches import (
monkey_patch_nano_v3_reasoning_parser,
monkey_patch_strip_routed_experts_from_chat,
monkey_patch_tokenize_params_validation,
monkey_patch_vllm_padded_input_scrub,
)
# NOTE: Fix harmony stop token propagation for GPT-OSS models
@@ -37,9 +35,6 @@ monkey_patch_tokenize_params_validation()
# NOTE: Register Nano V3 reasoning parser so configs can use
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
monkey_patch_nano_v3_reasoning_parser()
# NOTE: Optional mitigation for vLLM padded decode inputs until the native fix
# is available in our pinned runtime.
monkey_patch_vllm_padded_input_scrub()
# NOTE: routed_experts are consumed only via the serialized /generate path (router
# replay). The chat-completions path encodes them as a base64 np.save string the PD
# router cannot merge, which fails eval rollouts (they use chat completions). Strip
@@ -215,20 +210,18 @@ vllm.v1.utils.run_api_server_worker_proc = custom_run_api_server_worker_proc
# Adapted from vllm/entrypoints/cli/serve.py
# Only difference we do some config translation (i.e. pass populated namespace
# to `parse_args`) and additional arg validation
def server(config: InferenceConfig, vllm_extra: dict[str, Any] | None = None):
def server(config: InferenceConfig):
import os
from vllm.entrypoints.cli.serve import run_headless, run_multi_api_server
from vllm.entrypoints.openai.api_server import run_server
# Signal worker processes to disable LoRA on MoE layers when LoRA targets don't include experts
if config.lora_target_modules and not any("expert" in m for m in config.lora_target_modules):
lora_target_modules = config.vllm.lora_target_modules
if lora_target_modules and not any("expert" in m for m in lora_target_modules):
os.environ["PRIME_NO_MOE_LORA"] = "1"
namespace = config.to_vllm()
if vllm_extra:
for key, value in vllm_extra.items():
setattr(namespace, key, value)
namespace = config.to_namespace()
parser = FlexibleArgumentParser(description="vLLM OpenAI-Compatible RESTful API server.")
parser = make_arg_parser(parser)

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