Compare commits

...
Author SHA1 Message Date
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
75 changed files with 2137 additions and 2639 deletions
+1 -1
View File
@@ -157,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*)
+1 -3
View File
@@ -36,10 +36,8 @@ type = "subprocess"
[trainer.model]
seq_len = 16384
[inference.model]
[inference.vllm]
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+1 -1
View File
@@ -54,5 +54,5 @@ type = "subprocess"
[ckpt] # Checkpoint at the end of training
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
@@ -39,10 +39,12 @@ id = "null"
type = "subprocess"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[inference.vllm]
enable_lora = true
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "prime-qwen3"
@@ -38,10 +38,12 @@ id = "null"
type = "subprocess"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[inference.vllm]
enable_lora = true
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "prime-qwen3"
@@ -38,11 +38,9 @@ id = "null"
type = "subprocess"
[inference]
gpu_memory_utilization = 0.7
[inference.model]
[inference.vllm]
max_model_len = 2048
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "default"
@@ -1,13 +1,11 @@
# Inference config for multi-run RL integration test
[vllm]
model = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
max_model_len = 2048
enable_lora = true
max_lora_rank = 8
max_loras = 4
gpu_memory_utilization = 0.7
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
max_model_len = 2048
[weight_broadcast]
type = "filesystem"
@@ -72,4 +72,6 @@ type = "subprocess"
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.4
@@ -78,4 +78,6 @@ type = "subprocess"
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.4
+2 -2
View File
@@ -40,5 +40,5 @@ max_completion_tokens = 768
[trainer]
[inference.parallel]
dp = 4
[inference.vllm]
data_parallel_size = 4
+2 -5
View File
@@ -54,12 +54,9 @@ type = "subprocess"
seq_len = 16384
attn = "flash_attention_2"
[inference.parallel]
dp = 4
[inference.model]
[inference.vllm]
max_model_len = 8192
data_parallel_size = 4
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+2 -4
View File
@@ -40,8 +40,6 @@ max_completion_tokens = 512
[trainer]
[inference.parallel]
dp = 4
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
data_parallel_size = 4
+2 -3
View File
@@ -35,8 +35,7 @@ max_completion_tokens = 1024
[trainer]
[inference.parallel]
dp = 6
[inference.vllm]
data_parallel_size = 6
[orchestrator.renderer]
name = "prime-qwen3"
+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
+2
View File
@@ -58,4 +58,6 @@ name = "prime-qwen3"
lr = 1e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+2
View File
@@ -58,4 +58,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+2
View File
@@ -58,4 +58,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+4 -2
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
@@ -85,4 +85,6 @@ type = "subprocess"
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+4 -2
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
@@ -70,4 +70,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+4 -2
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
@@ -76,4 +76,6 @@ save_adapter_separately = true
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+2
View File
@@ -70,4 +70,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+2
View File
@@ -64,4 +64,6 @@ type = "subprocess"
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+4 -2
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
@@ -75,4 +75,6 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+4 -2
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
@@ -81,4 +81,6 @@ save_adapter_separately = true
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+2
View File
@@ -64,4 +64,6 @@ type = "subprocess"
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+1 -1
+1 -1
+3 -3
View File
@@ -50,7 +50,7 @@ CLI flags mirror the TOML tree using dots:
--max-steps 50 # top-level
--model.name Qwen/Qwen3-4B # nested
--trainer.optim.lr 1e-5 # double-nested
--inference.parallel.tp 4
--inference.vllm.tensor-parallel-size 4
```
> Field names are snake_case in TOML (`max_model_len`) and kebab-case on the CLI (`--max-model-len`).
@@ -126,11 +126,11 @@ To **disable** a sub-config that's on by default, use `--no-<name>` on the CLI o
TOML has no `null`. Use the string `"None"`, which the loader coerces:
```toml
[inference.model]
[inference.vllm]
max_model_len = "None"
```
On the CLI: `--inference.model.max-model-len None`.
On the CLI: `--inference.vllm.max-model-len None`.
### Discriminated Unions
+2 -2
View File
@@ -118,8 +118,8 @@ Then run the full RL stack on reverse-text:
uv run rl @ configs/ci/integration/reverse-text-moe/start.toml \
--model.name samsja/mini-glm-moe \
--trainer.model.impl custom \
--inference.gpu-memory-utilization 0.7 \
--inference.model.max-model-len 2048
--inference.vllm.gpu-memory-utilization 0.7 \
--inference.vllm.max-model-len 2048
```
What to look for:
+23 -26
View File
@@ -42,7 +42,7 @@ type = "single_node" # or "multi_node" or "disaggregated"
To configure the inference server, you can use the `InferenceConfig` field. This is a config-field that allows you to set the inference server-specific knobs. Most of these are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
```toml
[inference]
[inference.vllm]
model = "PrimeIntellect/INTELLECT-3"
...
```
@@ -63,12 +63,10 @@ The launcher starts a `vllm-router` on `inference.server.port` (default `8000`)
This deployment shape runs the inference server on a single node, if configured with NVLink enabled, it allows you more freedom in terms of parallelism configurations.
```toml
[inference]
[inference.vllm]
enable_expert_parallel = true # defaults to False
[inference.parallel]
tp = 2
dp = 4
tensor_parallel_size = 2
data_parallel_size = 4
[inference.deployment]
type = "single_node"
@@ -76,7 +74,7 @@ type = "single_node"
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required `orchestrator.max_inflight_requests`. Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.enable_expert_parallel` or `inference.parallel.tp` to maximize the available GPU memory.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.vllm.enable_expert_parallel` or `inference.vllm.tensor_parallel_size` to maximize the available GPU memory.
You can also increase the available KV cache memory by enabling `inference.kv_cache_offload`. More details in the [Advanced Configuration](#advanced-configuration) section.
@@ -86,7 +84,7 @@ You can also increase the available KV cache memory by enabling `inference.kv_ca
This deployment shape branches into 2 sub-shapes:
- [Multi-replica](#multi-replica) - Runs the inference server on multiple nodes, but each node runs an independent vLLM replica. You can think of this as a for-loop over single-node deployments.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.vllm.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
### Multi-replica
@@ -98,35 +96,31 @@ Parallelism configuration is the same as the single-node deployment. The shape i
type = "multi_node"
num_nodes = 2
[inference]
[inference.vllm]
model = "PrimeIntellect/INTELLECT-3"
[inference.parallel]
tp = 2
dp = 4
tensor_parallel_size = 2
data_parallel_size = 4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a single global router running on the first inference node, fronting the per-rank endpoints of all replicas — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[inference.router]` block. You can read more about the supported routing options in the [router](#router) section.
This configuration will run 2 independent vLLM replicas, each with `tensor_parallel_size=2` and `data_parallel_size=4`. Routing is handled by a single global router running on the first inference node, fronting the per-rank endpoints of all replicas — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[inference.router]` block. You can read more about the supported routing options in the [router](#router) section.
### Wide-EP
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.enable_expert_parallel = true`.
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.vllm.enable_expert_parallel = true`.
```toml
[inference.deployment]
type = "multi_node"
num_nodes = 2
[inference]
[inference.vllm]
model = "PrimeIntellect/INTELLECT-3"
enable_expert_parallel = true
[inference.parallel]
tp = 2
dp = 8
tensor_parallel_size = 2
data_parallel_size = 8
```
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tp = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tensor_parallel_size = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
## P/D Disaggregation
@@ -272,24 +266,27 @@ type = "disaggregated"
These are role-specific and layer on top of [`env_vars`](configuration.md#environment-variables) shared by all inference processes regardless of role.
### Other vLLM features
We support various other vLLM features. Some of those, such as `enable_dbo`, `enable_eplb` are exposed as a top-level config fields. For those that are not, you can configure them by setting `inference.vllm_extra` to the desired value.
The `[inference.vllm]` section is a pass-through: every key is forwarded to the vLLM server under vLLM's own argument name, whether prime-rl types it or not. Anything `vllm serve` accepts can be set here.
```toml
[inference.vllm_extra]
[inference.vllm]
headless = true
max_num_seqs = 256
```
On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (or `--vllm.max-num-seqs 256` for the standalone inference entrypoint); dict-valued arguments take a JSON string, e.g. `--vllm.compilation-config '{"cudagraph_mode": "NONE"}'`.
### Router Replay
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.enable_return_routed_experts = true`.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`.
```toml
[trainer]
enable_router_replay = true # this will also auto-set the inference.enable_return_routed_experts = true
enable_router_replay = true # this will also auto-set inference.vllm.enable_return_routed_experts = true
[inference]
[inference.vllm]
enable_return_routed_experts = true
```
+1 -1
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.
+2 -2
View File
@@ -37,7 +37,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at the source's derived `serve.address`); only needed when running the orchestrator standalone. |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at a derived loopback address); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
## RL Trainer
@@ -103,7 +103,7 @@ Frozen models are declared inline on the algorithm, named where the model is use
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name <frozen-model> --server.port 8001
--vllm.model <frozen-model> --server.port 8001
```
The standalone `uv run sft` entrypoint is the more traditional SFT path — pure dataset-based, no orchestrator. Use the `sft` algorithm only when you want a frozen model to generate the supervision on the fly.
+3 -5
View File
@@ -200,15 +200,13 @@ 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
+3 -5
View File
@@ -142,15 +142,13 @@ rollout = 3600
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
[inference.vllm]
max_model_len = 131072
[inference.parallel]
tp = 8
tensor_parallel_size = 8
enable_return_routed_experts = true
+3 -5
View File
@@ -197,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
+11 -13
View File
@@ -6,22 +6,9 @@
output_dir = "/shared/outputs/glm5.2-16node-llmd"
enable_expert_parallel = true
gpu_memory_utilization = 0.75
enable_eplb = false
use_deep_gemm = true
enable_fp32_lm_head = true
[model]
name = "zai-org/GLM-5.2-FP8"
max_model_len = 91000
tool_call_parser = "glm47"
reasoning_parser = "glm45"
[vllm_extra]
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[kv_cache_offload]
type = "mooncake"
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
@@ -64,3 +51,14 @@ non_cached_tokens = 128
[slurm]
job_name = "glm5.2-16node-llmd"
partition = "all"
[vllm]
model = "zai-org/GLM-5.2-FP8"
max_model_len = 91000
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
+8 -8
View File
@@ -1,12 +1,4 @@
enable_expert_parallel = true
enable_eplb = false
use_deep_gemm = true
gpu_memory_utilization = 0.85
[model]
name = "zai-org/GLM-5-FP8"
tool_call_parser = "auto"
reasoning_parser = "glm45"
[deployment]
type = "disaggregated"
@@ -17,3 +9,11 @@ gpus_per_node = 8
[slurm]
job_name = "glm5"
partition = "cluster"
[vllm]
model = "zai-org/GLM-5-FP8"
tool_call_parser = "auto"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.85
enable_expert_parallel = true
enable_eplb = false
+10 -17
View File
@@ -48,7 +48,6 @@ num_decode_replicas = 1
"max_num_batched_tokens" = 96
"max_num_seqs" = 96
[inference.router]
type = "llm-d"
@@ -66,6 +65,16 @@ non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[inference.vllm]
model = "zai-org/GLM-5.1-FP8"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[slurm]
job_name = "glm5-llmd"
partition = "all" # FILL IN: set to your cluster's partition
@@ -118,7 +127,6 @@ temperature = 1.0
[orchestrator.train.sampling.extra_body.chat_template_kwargs]
clear_thinking = false
[[orchestrator.train.source]]
name = "r2e"
@@ -133,25 +141,10 @@ type = "prime"
labels = ["glm5-llmd"]
[inference]
enable_expert_parallel = true
# <0.80 because glm5 layers are too large for 0.85
gpu_memory_utilization = 0.75
enable_eplb = false
use_deep_gemm = true
enable_fp32_lm_head = true
[inference.model]
name = "zai-org/GLM-5.1-FP8"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
# Speed up GLM-5.1 weight load: EP weight filtering + safetensors prefetch.
[inference.vllm_extra]
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
# Mooncake distributed CPU KV store: 1TB/node shared pool across all inference nodes.
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
+6 -8
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
@@ -89,12 +93,6 @@ type = "gibberish"
enforce = true
[inference]
enable_expert_parallel = true
# we need <0.85 bc glm5 layers are too large for 0.85
gpu_memory_utilization = 0.80
enable_eplb = false
use_deep_gemm = true
[inference.model]
name = "zai-org/GLM-5-FP8"
tool_call_parser = "glm47"
+2 -4
View File
@@ -151,9 +151,7 @@ id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[inference.parallel]
tp = 8
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[inference.vllm]
tensor_parallel_size = 8
[orchestrator.renderer]
name = "default"
+2 -5
View File
@@ -48,7 +48,6 @@ batch_size = 2048
oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.train.source]]
name = "swe"
@@ -78,9 +77,7 @@ id = "bash"
type = "prime"
labels = ["minimax-swe", "swe-bench-verified"]
[inference.parallel]
tp = 8
# PrimeIntellect/MiniMax-M2.5-bf16 — template-identical to MiniMaxAI/MiniMax-M2.5 (mapped).
[inference.vllm]
tensor_parallel_size = 8
[orchestrator.renderer]
name = "minimax-m2"
+6 -8
View File
@@ -122,13 +122,11 @@ labels = ["nemotron-3-super-swe"]
rollout = 3600
[inference]
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
enable_prefix_caching = true
enable_expert_parallel = true
enable_return_routed_experts = true
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
enable_prefix_caching = true
[inference.model]
max_model_len = 131072
[inference.parallel]
tp = 8
+2 -2
View File
@@ -75,5 +75,5 @@ id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
[inference.parallel]
tp = 8
[inference.vllm]
tensor_parallel_size = 8
+2 -2
View File
@@ -75,5 +75,5 @@ id = "bash"
type = "prime"
labels = ["qwen30b-swe", "swe-bench-verified"]
[inference.parallel]
tp = 8
[inference.vllm]
tensor_parallel_size = 8
+4 -6
View File
@@ -51,11 +51,9 @@ id = "null"
type = "modal"
[inference]
gpu_memory_utilization = 0.85
[inference.model]
[inference.vllm]
max_model_len = 32768
[inference.parallel]
dp = 2
tp = 4
data_parallel_size = 2
tensor_parallel_size = 4
gpu_memory_utilization = 0.85
+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
+1 -3
View File
@@ -49,10 +49,8 @@ type = "subprocess"
[trainer.model]
seq_len = 16384
[inference.model]
[inference.vllm]
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+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 \
+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
+5 -5
View File
@@ -40,10 +40,6 @@ name = "qwen3-4b-wiki-search"
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[[orchestrator.train.source]]
name = "wiki-search"
@@ -56,7 +52,11 @@ id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[ckpt] # Checkpoint at the end of training
[inference.model]
[inference.vllm]
tool_call_parser = "hermes"
+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
+2 -4
View File
@@ -35,9 +35,7 @@ max_completion_tokens = 1024
[trainer] # Default trainer config
[inference.parallel]
dp = 6
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
[inference.vllm]
data_parallel_size = 6
[orchestrator.renderer]
name = "prime-qwen3"
+2 -2
View File
@@ -7,10 +7,10 @@ requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.4.2",
"renderers>=0.1.9.dev10",
"renderers>=0.1.9",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.2.2.dev76",
"verifiers>=0.3.0",
]
[build-system]
@@ -1,12 +1,13 @@
import json
from argparse import Namespace
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import Field, model_validator
from pydantic import ConfigDict, Field, model_validator
from pydantic_config import BaseConfig
from prime_rl.configs.shared import BaseModelConfig, EnvVars, LogConfig, SlurmConfig
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
from prime_rl.configs.shared import EnvVars, LogConfig, SlurmConfig
from prime_rl.utils.config import find_package_resource
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
# TODO: Set thinking/ solution budget
@@ -23,61 +24,192 @@ class ServerConfig(BaseConfig):
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. With Kubernetes liveness probes, keep the probe ``timeoutSeconds`` at least this high."""
class ParallelConfig(BaseConfig):
tp: int = 1
"""Tensor parallel size. Forwarded to vLLM as ``--tensor-parallel-size``."""
# Valid vLLM max_lora_rank values (`vllm.config.lora.MaxLoRARanks`), excluding 1 so
# tiny adapters round up to 8. Hardcoded rather than imported: prime-rl-configs does
# not depend on vLLM, and importing it costs seconds in every config-parsing process.
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
dp: int = Field(1, ge=1)
"""Data parallel size. Forwarded to vLLM as ``--data-parallel-size``."""
def __str__(self) -> str:
return f"tp={self.tp} dp={self.dp}"
# vLLM all2all backend options for expert-parallel deployments.
All2AllBackend = Literal[
"allgather_reducescatter",
"deepep_high_throughput",
"deepep_low_latency",
"flashinfer_nvlink_one_sided",
"flashinfer_nvlink_two_sided",
]
class ModelConfig(BaseModelConfig):
"""Configures the inference model. Most arguments are passed directly to the vLLM LLM class (https://docs.vllm.ai/en/latest/api/vllm.LLM.html).
class VllmConfig(BaseConfig):
"""Arguments forwarded to the vLLM server, under vLLM's own argument names
(https://docs.vllm.ai/en/latest/configuration/engine_args.html).
The fields below are the arguments prime-rl types, defaults, or reads back;
any other vLLM argument can be set as well (``[inference.vllm] max_num_seqs = 256``
or ``--vllm.max-num-seqs 256``) and passes through to the server verbatim.
Parser fields (``tool_call_parser``, ``reasoning_parser``) default to ``"auto"``,
which resolves to a concrete parser name at validation time from the model name.
Set to ``None`` to disable.
"""
model_config = ConfigDict(extra="allow")
model: str = "Qwen/Qwen3-0.6B"
"""HF model name or local path."""
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models. Forwarded as ``--dtype``."""
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models."""
max_model_len: int | None = None
"""Maximum model context length. If None, uses the model config's value. Forwarded as ``--max-model-len``."""
"""Maximum model context length. If None, uses the model config's value."""
enforce_eager: bool = False
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance. Forwarded as ``--enforce-eager``."""
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance."""
trust_remote_code: bool = False
"""Trust remote code. Forwarded to vLLM engine init."""
"""Trust remote code when loading the model."""
chat_template: str | None = None
"""Chat template — a Jinja2 template string or path to a template file. Forwarded as ``--chat-template``. If None, uses the model's default."""
"""Chat template — a Jinja2 template string or path to a template file. If None, uses the model's default."""
tool_call_parser: str | None = "auto"
"""Tool-call parser. Forwarded as ``--tool-call-parser``. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
"""Tool-call parser. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
reasoning_parser: str | None = "auto"
"""Parser for extracting reasoning content from model outputs. Forwarded as ``--reasoning-parser``. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
"""Parser for extracting reasoning content from model outputs. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
rope_scaling: dict[str, Any] | str | None = None
"""RoPE scaling configuration as a dict (e.g. ``{rope_type="yarn", factor=4.0, original_max_position_embeddings=32768}``). Forwarded as ``--rope-scaling``."""
"""RoPE scaling configuration as a dict (e.g. ``{rope_type="yarn", factor=4.0, original_max_position_embeddings=32768}``)."""
tensor_parallel_size: int = 1
"""Tensor parallel size."""
data_parallel_size: int = Field(1, ge=1)
"""Data parallel size."""
data_parallel_size_local: int | None = Field(None, ge=1)
"""Data parallel replicas to run on this node."""
data_parallel_rpc_port: int = Field(13345, ge=1, le=65535)
"""RPC port for data parallel communication."""
api_server_count: int = Field(1, ge=0)
"""API servers to run. Set to 0 for headless mode."""
seed: int = 0
"""Seed the inference components."""
gpu_memory_utilization: float = 0.9
"""GPU memory utilization."""
enable_prefix_caching: bool | None = None
"""Enable prefix caching."""
quantization: str | None = None
"""Online inference quantization method. If None, vLLM infers it from the checkpoint."""
enable_lora: bool = False
"""Enable LoRA."""
max_loras: int = 8
"""Maximum number of LoRAs."""
# TODO: The default value is very high because our areal impl for lora isn't ideal
# We add a lora with the same name instead of changing weights inplace
# Because we dont cancel requests that are past max_async, these requests could be using a LoRA that gets unloaded which will crash the inference server
max_cpu_loras: int = 100
"""Maximum number of LoRAs on CPU."""
max_lora_rank: int | None = None
"""Maximum LoRA rank. Rounded up to the nearest value vLLM accepts."""
lora_target_modules: list[str] | None = None
"""LoRA target modules."""
enable_expert_parallel: bool = False
"""Enable expert parallelism for MoE models."""
all2all_backend: All2AllBackend = "allgather_reducescatter"
"""All-to-all backend for expert-parallel communication."""
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB)."""
enable_dbo: bool = False
"""Enable dual batch overlap (DBO)."""
enable_return_routed_experts: bool = False
"""Return routed experts in responses."""
@model_validator(mode="before")
@classmethod
def parse_extra_values(cls, data: dict) -> dict:
"""Normalize pass-through (untyped) entries: kebab-case keys become snake_case,
and string values — which is how CLI overrides arrive — are JSON-parsed so
``--vllm.max-num-seqs 256`` lands as an int and ``--vllm.compilation-config
'{"cudagraph_mode": "NONE"}'`` as a dict. Non-JSON strings stay strings."""
if not isinstance(data, dict):
return data
for key in [k for k in data if k not in cls.model_fields]:
value = data.pop(key)
if isinstance(value, str):
try:
value = json.loads(value)
except json.JSONDecodeError:
pass
data[key.replace("-", "_")] = value
return data
@model_validator(mode="after")
def auto_resolve_parsers(self):
"""Resolve ``"auto"`` parser values to concrete parser names from the model name.
Runs after ``RLConfig.auto_setup_shared_configs`` (mode=before) has
propagated the shared ``[model] name`` into ``inference.model``, so the
propagated the shared ``[model] name`` into ``inference.vllm``, so the
name is set even when only the shared block specifies it.
"""
if self.tool_call_parser == "auto":
self.tool_call_parser = resolve_tool_call_parser(self.name)
self.tool_call_parser = resolve_tool_call_parser(self.model)
if self.reasoning_parser == "auto":
self.reasoning_parser = resolve_reasoning_parser(self.name)
self.reasoning_parser = resolve_reasoning_parser(self.model)
return self
@model_validator(mode="after")
def auto_setup_max_lora_rank(self):
"""Auto-setup max_lora_rank by rounding up to the nearest valid vLLM value.
vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512).
This validator ensures that any configured rank is rounded up to the minimum valid value
that can serve adapters of the requested rank.
"""
if self.max_lora_rank is not None:
original_rank = self.max_lora_rank
for valid_rank in VALID_VLLM_LORA_RANKS:
if valid_rank >= self.max_lora_rank:
self.max_lora_rank = valid_rank
break
else:
raise ValueError(f"max_lora_rank={original_rank} exceeds vLLM maximum of {VALID_VLLM_LORA_RANKS[-1]}")
return self
@model_validator(mode="after")
def auto_setup_api_server_count(self):
"""
Ensures that we have at least as many API servers as data parallel
size. Unless LoRA is enabled, in which case only one API server is
supported (vLLM limitation).
"""
if self.model_extra and self.model_extra.get("headless", False):
self.api_server_count = 0
return self
if "api_server_count" not in self.model_fields_set:
min_api_server_count = self.data_parallel_size_local or self.data_parallel_size
if self.api_server_count < min_api_server_count:
self.api_server_count = min_api_server_count
if self.enable_lora:
self.api_server_count = 1 # LoRA requires only one API server
return self
@@ -153,20 +285,6 @@ KVCacheOffloadConfig: TypeAlias = Annotated[
]
# Valid vLLM max_lora_rank values (from vllm/config/lora.py)
# TODO: on newer vLLM, can import via `get_args(vllm.config.lora.MaxLoRARanks)`
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
# vLLM all2all backend options for expert-parallel deployments.
All2AllBackend = Literal[
"allgather_reducescatter",
"deepep_high_throughput",
"deepep_low_latency",
"flashinfer_nvlink_one_sided",
"flashinfer_nvlink_two_sided",
]
# Known llm-d EPP scorer plugins (used to guard the ``scorers`` map against typos).
KNOWN_SCORERS = frozenset(
{
@@ -325,10 +443,8 @@ class InferenceConfig(BaseConfig):
backend_port: int = 8100
"""Port for the vLLM engine(s) behind the router. Defaults to ``server.port + 100``. Multi-node deployments start one engine per local DP rank at ``backend_port + rank``."""
model: ModelConfig = Field(default_factory=ModelConfig)
parallel: ParallelConfig = ParallelConfig()
"""Multi-node and multi-GPU parallelism (TP, DP, PP)."""
vllm: VllmConfig = Field(default_factory=VllmConfig)
"""vLLM server arguments, under vLLM's own argument names. Unknown fields pass through verbatim."""
log: LogConfig = LogConfig()
"""Logging configuration."""
@@ -336,57 +452,6 @@ class InferenceConfig(BaseConfig):
env_vars: EnvVars = {}
"""Extra environment variables for the inference server process(es). Merged on top of the launcher defaults."""
enable_lora: bool = False
"""Enable LoRA. Forwarded as ``--enable-lora``."""
max_loras: int = 8
"""Maximum number of LoRAs. Forwarded as ``--max-loras``."""
# TODO: The default value is very high because our areal impl for lora isn't ideal
# We add a lora with the same name instead of changing weights inplace
# Because we dont cancel requests that are past max_async, these requests could be using a LoRA that gets unloaded which will crash the inference server
max_cpu_loras: int = 100
"""Maximum number of LoRAs on CPU. Forwarded as ``--max-cpu-loras``."""
max_lora_rank: int | None = None
"""Maximum LoRA rank. Forwarded as ``--max-lora-rank``."""
lora_target_modules: list[str] | None = None
"""LoRA target modules. Forwarded as ``--lora-target-modules``."""
enable_prefix_caching: bool | None = None
"""Enable prefix caching. Forwarded as ``--enable-prefix-caching``."""
gpu_memory_utilization: float = 0.9
"""GPU memory utilization. Forwarded as ``--gpu-memory-utilization``."""
quantization: str | None = None
"""Online inference quantization method. Forwarded as ``--quantization``."""
api_server_count: int = Field(1, ge=0)
"""API servers to run. Forwarded as ``--api-server-count``. Set to 0 for headless mode."""
data_parallel_size_local: int | None = Field(None, ge=1)
"""Data parallel replicas to run on this node. Forwarded as ``--data-parallel-size-local``."""
data_parallel_rpc_port: int = Field(13345, ge=1, le=65535)
"""RPC port for data parallel communication. Forwarded as ``--data-parallel-rpc-port``."""
seed: int = 0
"""Seed the inference components. Forwarded as ``--seed``."""
enable_expert_parallel: bool = False
"""Enable expert parallelism for MoE models. Forwarded as ``--enable-expert-parallel``."""
all2all_backend: All2AllBackend = "allgather_reducescatter"
"""All-to-all backend for expert-parallel communication. Forwarded as ``--all2all-backend``."""
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB). Forwarded as ``--enable-eplb``."""
enable_dbo: bool = False
"""Enable dual batch overlap (DBO). Forwarded as ``--enable-dbo``."""
use_deep_gemm: bool = False
"""Enable vLLM DeepGEMM FP8 kernels ``VLLM_USE_DEEP_GEMM=1``. Only works with block-wise FP8 quantization (e.g. GLM-5-FP8)."""
@@ -398,18 +463,12 @@ class InferenceConfig(BaseConfig):
use_pd_kv_transfer: bool = False
"""Auto-set for disaggregated P/D: emit the NIXL transfer connector. Persisted into the per-node config (which drops ``deployment``) so the connector is still built per worker. Not meant to be set by hand."""
enable_return_routed_experts: bool = False
"""Return routed experts in responses. Forwarded as ``--enable-return-routed-experts``."""
enable_fp32_lm_head: bool = True
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
enable_fp32_router_logits: bool = True
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
vllm_extra: dict[str, Any] = {}
"""Extra arguments forwarded to vLLM. Applied as attributes on the vLLM namespace after config translation."""
# Launcher-only fields
deployment: InferenceDeploymentConfig = SingleNodeInferenceDeploymentConfig()
@@ -432,7 +491,7 @@ class InferenceConfig(BaseConfig):
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
if self.router is not None and self.router.type == "llm-d" and self.enable_return_routed_experts:
if self.router is not None and self.router.type == "llm-d" and self.vllm.enable_return_routed_experts:
raise ValueError(
"The llm-d router backend does not support routed-expert return "
"(enable_return_routed_experts): it breaks P/D and is unverified for multi-node. "
@@ -458,10 +517,10 @@ class InferenceConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_kv_cache_offload(self):
if self.kv_cache_offload is not None:
if self.enable_prefix_caching is False:
raise ValueError("KV cache offloading requires inference.enable_prefix_caching to be true.")
if "enable_prefix_caching" not in self.model_fields_set:
self.enable_prefix_caching = True
if self.vllm.enable_prefix_caching is False:
raise ValueError("KV cache offloading requires inference.vllm.enable_prefix_caching to be true.")
if "enable_prefix_caching" not in self.vllm.model_fields_set:
self.vllm.enable_prefix_caching = True
return self
@@ -470,19 +529,19 @@ class InferenceConfig(BaseConfig):
"""Auto-configure inference for disaggregated P/D: enable EP and compute DP."""
if self.deployment.type == "disaggregated":
self.use_pd_kv_transfer = True
if "enable_expert_parallel" not in self.model_fields_set:
self.enable_expert_parallel = True
if "enable_eplb" not in self.model_fields_set:
self.enable_eplb = False
if "enable_expert_parallel" not in self.vllm.model_fields_set:
self.vllm.enable_expert_parallel = True
if "enable_eplb" not in self.vllm.model_fields_set:
self.vllm.enable_eplb = False
gpus_per_node = self.deployment.gpus_per_node
tp = self.parallel.tp
tp = self.vllm.tensor_parallel_size
dp_per_node = gpus_per_node // tp
if self.data_parallel_size_local is None:
self.data_parallel_size_local = dp_per_node
if self.parallel.dp == 1:
self.parallel.dp = dp_per_node
if self.api_server_count == 1:
self.api_server_count = dp_per_node
if self.vllm.data_parallel_size_local is None:
self.vllm.data_parallel_size_local = dp_per_node
if self.vllm.data_parallel_size == 1:
self.vllm.data_parallel_size = dp_per_node
if self.vllm.api_server_count == 1:
self.vllm.api_server_count = dp_per_node
return self
@model_validator(mode="after")
@@ -493,44 +552,6 @@ class InferenceConfig(BaseConfig):
self.slurm.template_path = templates_dir / "inference.sbatch.j2"
return self
@model_validator(mode="after")
def auto_setup_max_lora_rank(self):
"""Auto-setup max_lora_rank by rounding up to the nearest valid vLLM value.
vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512).
This validator ensures that any configured rank is rounded up to the minimum valid value
that can serve adapters of the requested rank.
"""
if self.max_lora_rank is not None:
original_rank = self.max_lora_rank
for valid_rank in VALID_VLLM_LORA_RANKS:
if valid_rank >= self.max_lora_rank:
self.max_lora_rank = valid_rank
break
else:
raise ValueError(f"max_lora_rank={original_rank} exceeds vLLM maximum of {VALID_VLLM_LORA_RANKS[-1]}")
return self
@model_validator(mode="after")
def auto_setup_api_server_count(self):
"""
Ensures that we have at least as many API servers as data parallel
size. Unless LoRA is enabled, in which case only one API server is
supported (vLLM limitation).
"""
if self.vllm_extra.get("headless", False):
self.api_server_count = 0
return self
if "api_server_count" not in self.model_fields_set:
min_api_server_count = self.data_parallel_size_local or self.parallel.dp
if self.api_server_count < min_api_server_count:
self.api_server_count = min_api_server_count
if self.enable_lora:
self.api_server_count = 1 # LoRA requires only one API server
return self
def build_kv_transfer_config(self) -> dict[str, Any] | None:
"""Build the single vLLM ``kv_transfer_config`` from the transfer + offload connectors.
@@ -560,90 +581,49 @@ class InferenceConfig(BaseConfig):
"kv_connector_extra_config": {"connectors": connectors},
}
def to_vllm(self) -> Namespace:
"""Convert InferenceConfig to vLLM-compatible Namespace."""
namespace = Namespace()
to_vllm = {
"server.host": "host",
"server.port": "port",
"server.liveness_timeout_seconds": "liveness_timeout_seconds",
"model.name": "model",
"model.dtype": "dtype",
"model.max_model_len": "max_model_len",
"model.enforce_eager": "enforce_eager",
"model.trust_remote_code": "trust_remote_code",
"model.chat_template": "chat_template",
"model.tool_call_parser": "tool_call_parser",
"model.reasoning_parser": "reasoning_parser",
"model.rope_scaling": "rope_scaling",
"parallel.tp": "tensor_parallel_size",
"parallel.dp": "data_parallel_size",
"data_parallel_size_local": "data_parallel_size_local",
"data_parallel_rpc_port": "data_parallel_rpc_port",
"enable_lora": "enable_lora",
"enable_prefix_caching": "enable_prefix_caching",
"max_loras": "max_loras",
"max_cpu_loras": "max_cpu_loras",
"max_lora_rank": "max_lora_rank",
"lora_target_modules": "lora_target_modules",
"gpu_memory_utilization": "gpu_memory_utilization",
"quantization": "quantization",
"api_server_count": "api_server_count",
"enable_return_routed_experts": "enable_return_routed_experts",
"enable_expert_parallel": "enable_expert_parallel",
"all2all_backend": "all2all_backend",
"enable_eplb": "enable_eplb",
"enable_dbo": "enable_dbo",
"seed": "seed",
}
# Fields vLLM rejects as None — omitted from the namespace so vLLM applies its
# own default (e.g. quantization is inferred from the checkpoint).
_OMIT_IF_NONE = frozenset(
{"chat_template", "tool_call_parser", "reasoning_parser", "lora_target_modules", "quantization", "rope_scaling"}
)
for config_key, vllm_key in to_vllm.items():
value = rgetattr(self, config_key.replace("-", "_"))
rsetattr(namespace, vllm_key, value)
def to_namespace(self) -> Namespace:
"""Dump the server + vllm sections into a vLLM-compatible Namespace."""
namespace = Namespace(
host=self.server.host,
port=self.server.port,
liveness_timeout_seconds=self.server.liveness_timeout_seconds,
)
# Set `logprobs_mode` to `processed_logprobs` by default
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
extra_fields = self.vllm.model_extra or {}
for key in (*type(self.vllm).model_fields, *extra_fields):
value = getattr(self.vllm, key)
# None extras are dropped too: `--vllm.foo None` means "use vLLM's default".
if value is None and (key in self._OMIT_IF_NONE or key in extra_fields):
continue
setattr(namespace, key, value)
# Auto tool choice is gated on a tool-call parser being resolved, unless
# explicitly overridden.
if "enable_auto_tool_choice" not in extra_fields:
namespace.enable_auto_tool_choice = hasattr(namespace, "tool_call_parser")
# Default `logprobs_mode` to `processed_logprobs`
if not hasattr(namespace, "logprobs_mode"):
namespace.logprobs_mode = "processed_logprobs"
kv_transfer_config = self.build_kv_transfer_config()
if kv_transfer_config is not None:
rsetattr(namespace, "kv_transfer_config", kv_transfer_config)
namespace.kv_transfer_config = kv_transfer_config
# Pass prime-rl-specific flags through vLLM's additional_config dict;
# workers read these via get_current_vllm_config().additional_config.
additional_config = getattr(namespace, "additional_config", None) or {}
if self.enable_fp32_lm_head:
existing = getattr(namespace, "additional_config", None) or {}
existing["fp32_lm_head"] = True
rsetattr(namespace, "additional_config", existing)
additional_config["fp32_lm_head"] = True
if self.enable_fp32_router_logits:
existing = getattr(namespace, "additional_config", None) or {}
existing["fp32_router_logits"] = True
rsetattr(namespace, "additional_config", existing)
# Remove chat_template if not set (vLLM doesn't accept None)
if namespace.chat_template is None:
delattr(namespace, "chat_template")
# Remove tool_call_parser if not set (vLLM doesn't accept None) and gate
# `enable_auto_tool_choice` on its presence.
if namespace.tool_call_parser is None:
delattr(namespace, "tool_call_parser")
namespace.enable_auto_tool_choice = hasattr(namespace, "tool_call_parser")
# Remove reasoning_parser if not set (vLLM doesn't accept None)
if namespace.reasoning_parser is None:
delattr(namespace, "reasoning_parser")
# Remove lora_target_modules if not set (vLLM doesn't accept None)
if hasattr(namespace, "lora_target_modules") and namespace.lora_target_modules is None:
delattr(namespace, "lora_target_modules")
# Remove quantization if not set so vLLM can infer it from the checkpoint.
if namespace.quantization is None:
delattr(namespace, "quantization")
# Remove rope_scaling if not set (vLLM doesn't accept None)
if hasattr(namespace, "rope_scaling"):
if namespace.rope_scaling is None:
delattr(namespace, "rope_scaling")
additional_config["fp32_router_logits"] = True
if additional_config:
namespace.additional_config = additional_config
return namespace
@@ -4,7 +4,6 @@ from typing import Annotated, Any, Literal, TypeAlias
import verifiers.v1 as vf
from pydantic import Field, SerializeAsAny, model_validator
from renderers import AutoRendererConfig, RendererConfig
from verifiers.v1.configs.serve import PoolConfig
from prime_rl.configs.algorithm import (
AlgoConfig,
@@ -123,21 +122,6 @@ class EvalSamplingConfig(BaseConfig):
return args
class ServeConfig(BaseConfig):
"""The subset of verifiers' ``ServeConfig`` a source configures — the worker pool
and the per-worker bound. The launcher materializes it into the env server's full
``[serve]`` block, filling in the source's derived address
(``OrchestratorConfig.env_addresses``)."""
pool: PoolConfig = Field(default_factory=vf.ElasticPoolConfig)
"""Worker-pool sizing. ``elastic`` (default) starts at one worker and scales up on
demand; ``static`` pre-spawns a fixed ``num_workers``."""
max_concurrent: int | None = Field(None, ge=1)
"""Episodes in flight per worker (None = unbounded; the dispatcher's
``max_inflight_episodes`` is the run's bound)."""
class EnvConfig(BaseConfig):
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
runs, ``serve`` — how it's hosted, ``legacy`` — a classic v0 env instead) plus this
@@ -146,8 +130,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: ServeConfig = ServeConfig()
"""How this source's env server is sized. Consumed by the launcher (which writes each source's env-server config), not by the orchestrator — the orchestrator only connects."""
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``."""
@@ -535,7 +519,7 @@ class OrchestratorConfig(BaseConfig):
"""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>``. Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
"""First port of the env-server port range: the source at position ``i`` (train, then eval) is served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address`` keep it instead, without shifting the other sources' ports (indices stay positional). Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
batch_size: int | None = Field(None, ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
@@ -746,11 +730,13 @@ class OrchestratorConfig(BaseConfig):
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each source's env server lives, keyed by ``(split, resolved_name)``:
the source's own ``serve.address`` when set (an externally managed server), else
``tcp://127.0.0.1:<port>`` with ports from ``env_server_base_port`` in
``env_sources`` order. The launcher binds env servers at exactly these addresses
and the orchestrator connects to them, so both sides agree from the config
alone."""
return {
(split, source.resolved_name): f"tcp://127.0.0.1:{self.env_server_base_port + index}"
(split, source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, (split, source) in enumerate(self.env_sources)
}
@@ -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."
)
@@ -608,17 +612,17 @@ 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
@@ -635,35 +639,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 +678,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 +728,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
)
@@ -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).
@@ -155,7 +154,7 @@ def propagate_shared_fields(data: Any) -> Any:
conflicts.append(("output_dir", sub))
fill(sub, expected_value)
# Cascade trainer.tokenizer.chat_template → inference.model.chat_template
# Cascade trainer.tokenizer.chat_template → inference.vllm.chat_template
# (vLLM ``--chat-template``). Read trainer's value *after* the shared
# propagation above so we cover both:
# - shared ``[tokenizer] chat_template`` (already filled all three above,
@@ -165,7 +164,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 +224,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
@@ -310,9 +309,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."
)
+15 -6
View File
@@ -1,6 +1,6 @@
[project]
name = "prime-rl"
version = "0.7.0"
version = "0.8.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.2.2.dev76",
"verifiers[harbor]>=0.3.0",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -128,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.
+5 -3
View File
@@ -19,7 +19,7 @@ uv run rl @ base.toml --trainer @ trainer.toml --trainer.lr 1e-3 # mix
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base.
Naming: CLI uses kebab-case (`--model.max-model-len`); TOML uses snake_case (`max_model_len`).
Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max_model_len`).
## Inspect & validate
@@ -38,7 +38,7 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--model.max-model-len None`.
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--vllm.max-model-len None`.
**Lists** — TOML uses array of tables; later config files replace lists wholesale, so overlays must include the full desired list:
@@ -71,7 +71,9 @@ 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.
+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`.
+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:
+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()
+37 -25
View File
@@ -49,14 +49,24 @@ ENVS_DIR = "envs"
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig, str]]:
"""``(split, source, address)`` for every train/eval source. The launcher runs one
env server per source at its deterministic address; the orchestrator connects there."""
"""``(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
(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."""
raw_visible = os.environ.get("CUDA_VISIBLE_DEVICES")
@@ -93,9 +103,10 @@ 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 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.
# 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)
@@ -453,10 +464,9 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
else {}
)
# Env servers launch next to the orchestrator, one per train/eval source.
sources = config.orchestrator.env_sources
train_env_names = [source.resolved_name for split, source in sources if split == "train"]
eval_env_names = [source.resolved_name for split, source in sources if split == "eval"]
# 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(
@@ -489,8 +499,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,
@@ -499,7 +509,7 @@ 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",
@@ -524,10 +534,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",
@@ -558,10 +574,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,
@@ -575,10 +589,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(
+1 -1
View File
@@ -26,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:
+4 -7
View File
@@ -1,6 +1,5 @@
import asyncio
from argparse import Namespace
from typing import Any
import uvloop
from fastapi import APIRouter, Request
@@ -211,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)
+8 -3
View File
@@ -23,9 +23,14 @@ launch_inference_rank() {
mkdir -p "$rpcbase"
local -a cmd=(uv run inference @ "$CONFIG_PATH"
--server.host 0.0.0.0 --server.port "$port"
--parallel.dp "$dp" --data-parallel-size-local 1 --api-server-count 1)
[ -n "$rpc" ] && cmd+=(--data-parallel-rpc-port "$rpc")
[ -n "$extra" ] && cmd+=(--vllm-extra "$extra")
--vllm.data-parallel-size "$dp" --vllm.data-parallel-size-local 1 --vllm.api-server-count 1)
[ -n "$rpc" ] && cmd+=(--vllm.data-parallel-rpc-port "$rpc")
# Per-rank vLLM overrides go through a JSON file merged into [inference.vllm]
# (dict-valued keys like compilation_config can't be inlined as CLI flags).
if [ -n "$extra" ]; then
printf '%s' "$extra" > "$rpcbase/vllm-overrides.json"
cmd+=(--vllm @ "$rpcbase/vllm-overrides.json")
fi
if [ -n "$nixl" ]; then
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
else
+14 -6
View File
@@ -67,7 +67,9 @@ source .venv/bin/activate
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
SYNC_SH
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
uv sync --all-extras --all-packages
@@ -155,7 +157,13 @@ CLEANUP_SH
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a crashed router/engine terminates the SLURM job instead of leaving
# the surviving ranks holding nodes.
srun --kill-on-bad-exit=1 bash -c '
#
# The body goes to bash on stdin through a quoted heredoc instead of a
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
# (including in the shared _launch_*.sh.j2 includes) need no escaping. Nothing in
# the body reads stdin, which would otherwise eat the rest of the script.
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
# pipefail ensures `cmd | tee log` propagates `cmd` failures, and the
# wait/cleanup block at the end of this script surfaces background
# process crashes (router) as task failures.
@@ -220,9 +228,9 @@ srun --kill-on-bad-exit=1 bash -c '
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
# The kv_transfer_config (NIXL transfer + any KV offload connector) is built in
# InferenceConfig.to_vllm() from the per-node config, so it is no longer assembled here.
# InferenceConfig.to_namespace() from the per-node config, so it is no longer assembled here.
DECODE_COMPILE_CFG='"'"'{"cudagraph_mode":"FULL_DECODE_ONLY"}'"'"'
DECODE_COMPILE_CFG='{"cudagraph_mode":"FULL_DECODE_ONLY"}'
DP_PER_NODE={{ dp_per_node }}
TP=$((GPUS_PER_NODE / DP_PER_NODE))
@@ -293,7 +301,7 @@ srun --kill-on-bad-exit=1 bash -c '
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
# group rooted on the role-replica head (HEAD_HOST); the router balances across the per-rank
# endpoints. The kv_transfer_config is built in InferenceConfig.to_vllm() from the config.
# endpoints. The kv_transfer_config is built in InferenceConfig.to_namespace() from the config.
if [ "$ROLE_RANK" -eq 0 ]; then DP_ADDR=$LOCAL_IP; else DP_ADDR=$HEAD_HOST; fi
for k in $(seq 0 $((DP_PER_NODE - 1))); do
GLOBAL_RANK=$((ROLE_RANK * DP_PER_NODE + k))
@@ -350,4 +358,4 @@ for pid in $(jobs -p); do
kill -TERM $pid 2>/dev/null || true
done
exit $EXIT_CODE
'
LAUNCH_SH
+14 -6
View File
@@ -135,7 +135,9 @@ source .venv/bin/activate
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
SYNC_SH
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
uv sync --all-extras --all-packages
@@ -183,7 +185,13 @@ CLEANUP_SH
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a crashed component terminates the SLURM job instead of leaving the
# surviving ranks holding nodes.
srun --kill-on-bad-exit=1 bash -c '
#
# The body goes to bash on stdin through a quoted heredoc instead of a
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
# (including in the shared _launch_*.sh.j2 includes) need no escaping. Nothing in
# the body reads stdin, which would otherwise eat the rest of the script.
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
# pipefail ensures `cmd | tee log` propagates `cmd` failures, and the
# wait/cleanup block at the end of this script surfaces background
# process crashes (router, orchestrator) as task failures.
@@ -258,9 +266,9 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
# The kv_transfer_config (NIXL transfer + any KV offload connector) is built in
# InferenceConfig.to_vllm() from the per-node config, so it is no longer assembled here.
# InferenceConfig.to_namespace() from the per-node config, so it is no longer assembled here.
DECODE_COMPILE_CFG='"'"'{"cudagraph_mode":"FULL_DECODE_ONLY"}'"'"'
DECODE_COMPILE_CFG='{"cudagraph_mode":"FULL_DECODE_ONLY"}'
REPLICA_BASE=$((REPLICA_IDX * NODES_PER_INFER_REPLICA))
@@ -323,7 +331,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
# group rooted on the role-replica head (HEAD_HOST); the router balances across the per-rank
# endpoints. The kv_transfer_config is built in InferenceConfig.to_vllm() from the config.
# endpoints. The kv_transfer_config is built in InferenceConfig.to_namespace() from the config.
if [ "$ROLE_RANK" -eq 0 ]; then DP_ADDR=$LOCAL_IP; else DP_ADDR=$HEAD_HOST; fi
for k in $(seq 0 $((INFERENCE_DP_LOCAL - 1))); do
GLOBAL_RANK=$((START_RANK + k))
@@ -461,4 +469,4 @@ for pid in $REMAINING_PIDS; do
kill -TERM $pid 2>/dev/null || true
done
exit $EXIT_CODE
'
LAUNCH_SH
@@ -54,7 +54,9 @@ source $PROJECT_DIR/.venv/bin/activate
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
SYNC_SH
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
cd $PROJECT_DIR && uv sync --all-extras --all-packages
@@ -94,7 +96,13 @@ CLEANUP_SH
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a single trainer crash terminates the entire SLURM job instead of
# leaving the surviving ranks (and their nodes) idle.
srun --kill-on-bad-exit=1 bash -c '
#
# The body goes to bash on stdin through a quoted heredoc instead of a
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
# need no escaping. Nothing in the body reads stdin, which would otherwise eat
# the rest of the script.
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
set -o pipefail
# Setup environment
@@ -130,4 +138,4 @@ srun --kill-on-bad-exit=1 bash -c '
-m prime_rl.trainer.sft.train \
@ $CONFIG_PATH \
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log
'
LAUNCH_SH
@@ -49,11 +49,11 @@ def ref_inference(output_dir: Path) -> Generator[subprocess.Popen, None, None]:
"uv",
"run",
"inference",
"--model.name",
"--vllm.model",
"PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL",
"--server.port",
str(REF_PORT),
"--gpu-memory-utilization",
"--vllm.gpu-memory-utilization",
"0.4",
]
env = {**os.environ, "CUDA_VISIBLE_DEVICES": "0"}
@@ -48,11 +48,11 @@ def ref_inference(output_dir: Path) -> Generator[subprocess.Popen, None, None]:
"uv",
"run",
"inference",
"--model.name",
"--vllm.model",
"PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL",
"--server.port",
str(REF_PORT),
"--gpu-memory-utilization",
"--vllm.gpu-memory-utilization",
"0.4",
]
env = {**os.environ, "CUDA_VISIBLE_DEVICES": "0"}
+14 -14
View File
@@ -222,7 +222,7 @@ def test_single_node_auto_inference_ports_follow_server_port():
{
"trainer": {},
"orchestrator": {},
"inference": {"server": {"port": 8001}, "parallel": {"tp": 1}},
"inference": {"server": {"port": 8001}, "vllm": {"tensor_parallel_size": 1}},
"deployment": {
"type": "single_node",
"gpus_per_node": 4,
@@ -233,7 +233,7 @@ def test_single_node_auto_inference_ports_follow_server_port():
)
assert config.inference is not None
assert config.inference.parallel.dp == 2
assert config.inference.vllm.data_parallel_size == 2
assert config.inference.backend_port == 8101
assert config.orchestrator.model.client.admin_base_url == ["http://localhost:8101/v1"]
@@ -243,7 +243,7 @@ def test_multi_node_auto_inference_parallelism():
{
"trainer": {},
"orchestrator": {},
"inference": {"parallel": {"tp": 4}},
"inference": {"vllm": {"tensor_parallel_size": 4}},
"deployment": {
"type": "multi_node",
"gpus_per_node": 8,
@@ -255,8 +255,8 @@ def test_multi_node_auto_inference_parallelism():
)
assert config.inference is not None
assert config.inference.data_parallel_size_local == 2
assert config.inference.parallel.dp == 2
assert config.inference.vllm.data_parallel_size_local == 2
assert config.inference.vllm.data_parallel_size == 2
def test_orchestrator_vlm_requires_renderer():
@@ -324,7 +324,7 @@ def test_shared_model_name_propagates_to_subconfigs():
)
assert config.trainer.model.name == model_name
assert config.orchestrator.model.name == model_name
assert config.inference is not None and config.inference.model.name == model_name
assert config.inference is not None and config.inference.vllm.model == model_name
assert config.trainer.tokenizer.name == model_name
assert config.orchestrator.tokenizer.name == model_name
@@ -468,7 +468,7 @@ def test_shared_and_sub_max_steps_conflict_raises():
def test_trainer_chat_template_cascades_to_inference():
"""``[trainer.tokenizer] chat_template`` set directly (no shared
``[tokenizer] chat_template``) must still reach
``inference.model.chat_template`` so vLLM's ``--chat-template`` is wired
``inference.vllm.chat_template`` so vLLM's ``--chat-template`` is wired
up. Regression: the original ``auto_setup_tokenizer`` cascaded this; the
refactored propagator must keep doing it."""
config = RLConfig.model_validate(
@@ -482,7 +482,7 @@ def test_trainer_chat_template_cascades_to_inference():
assert config.trainer.tokenizer.chat_template == "TPL"
assert config.orchestrator.tokenizer.chat_template == "TPL"
assert config.inference is not None
assert config.inference.model.chat_template == "TPL"
assert config.inference.vllm.chat_template == "TPL"
def test_shared_wandb_fields_propagate_to_subconfigs():
@@ -632,7 +632,7 @@ def test_orchestrator_explicit_default_renderer_with_unmapped_model():
def test_shared_model_name_resolves_inference_parsers():
"""Shared [model] name must reach inference.model BEFORE ModelConfig's after-validator
"""Shared [model] name must reach inference.vllm BEFORE VllmConfig's after-validator
runs auto_resolve_parsers — i.e. the parsers resolve from the propagated name, not
from an empty default.
"""
@@ -645,20 +645,20 @@ def test_shared_model_name_resolves_inference_parsers():
}
)
assert config.inference is not None
assert config.inference.model.name == "Qwen/Qwen3-Coder-30B-A3B-Instruct"
assert config.inference.model.tool_call_parser == "qwen3_coder"
assert config.inference.vllm.model == "Qwen/Qwen3-Coder-30B-A3B-Instruct"
assert config.inference.vllm.tool_call_parser == "qwen3_coder"
def test_explicit_inference_parser_wins_over_auto():
"""Explicit inference.model.tool_call_parser is preserved even when the shared model
"""Explicit inference.vllm.tool_call_parser is preserved even when the shared model
name would otherwise auto-resolve to something else."""
config = RLConfig.model_validate(
{
"model": {"name": "Qwen/Qwen3-Coder-30B-A3B-Instruct"},
"trainer": {},
"orchestrator": {"renderer": {"name": "default"}},
"inference": {"model": {"tool_call_parser": "hermes"}},
"inference": {"vllm": {"tool_call_parser": "hermes"}},
}
)
assert config.inference is not None
assert config.inference.model.tool_call_parser == "hermes"
assert config.inference.vllm.tool_call_parser == "hermes"
+29 -18
View File
@@ -104,46 +104,57 @@ def test_resolve_reasoning_parser(model_name: str, expected_tool_call: str | Non
def test_inference_config_resolves_parsers_from_model_name():
"""InferenceConfig.ModelConfig.auto_resolve_parsers fires when parsers default to 'auto'."""
config = InferenceConfig(model={"name": "deepseek-ai/DeepSeek-V3.2"})
assert config.model.tool_call_parser == "deepseek_v32"
assert config.model.reasoning_parser == "deepseek_r1"
"""VllmConfig.auto_resolve_parsers fires when parsers default to 'auto'."""
config = InferenceConfig(vllm={"model": "deepseek-ai/DeepSeek-V3.2"})
assert config.vllm.tool_call_parser == "deepseek_v32"
assert config.vllm.reasoning_parser == "deepseek_r1"
def test_inference_config_explicit_parser_not_overridden():
config = InferenceConfig(model={"name": "Qwen/Qwen3-4B", "tool_call_parser": "my_parser"})
assert config.model.tool_call_parser == "my_parser"
config = InferenceConfig(vllm={"model": "Qwen/Qwen3-4B", "tool_call_parser": "my_parser"})
assert config.vllm.tool_call_parser == "my_parser"
def test_inference_config_none_disables_parser():
config = InferenceConfig(
model={"name": "Qwen/Qwen3-4B", "tool_call_parser": None, "reasoning_parser": None},
vllm={"model": "Qwen/Qwen3-4B", "tool_call_parser": None, "reasoning_parser": None},
)
assert config.model.tool_call_parser is None
assert config.model.reasoning_parser is None
assert config.vllm.tool_call_parser is None
assert config.vllm.reasoning_parser is None
def test_to_vllm_resolves_parsers():
config = InferenceConfig(model={"name": "deepseek-ai/DeepSeek-V3.2"})
ns = config.to_vllm()
def test_to_namespace_resolves_parsers():
config = InferenceConfig(vllm={"model": "deepseek-ai/DeepSeek-V3.2"})
ns = config.to_namespace()
assert ns.tool_call_parser == "deepseek_v32"
assert ns.reasoning_parser == "deepseek_r1"
assert ns.enable_auto_tool_choice is True
def test_to_vllm_none_strips_parser_attrs_from_namespace():
def test_to_namespace_none_strips_parser_attrs_from_namespace():
"""vLLM doesn't accept None for these — they must be removed, not passed through."""
config = InferenceConfig(
model={"name": "Qwen/Qwen3-4B", "tool_call_parser": None, "reasoning_parser": None},
vllm={"model": "Qwen/Qwen3-4B", "tool_call_parser": None, "reasoning_parser": None},
)
ns = config.to_vllm()
ns = config.to_namespace()
assert not hasattr(ns, "tool_call_parser")
assert not hasattr(ns, "reasoning_parser")
assert ns.enable_auto_tool_choice is False
def test_to_vllm_unknown_model_disables_auto_tool_choice():
config = InferenceConfig(model={"name": "some/unknown-model"})
ns = config.to_vllm()
def test_to_namespace_unknown_model_disables_auto_tool_choice():
config = InferenceConfig(vllm={"model": "some/unknown-model"})
ns = config.to_namespace()
assert not hasattr(ns, "tool_call_parser")
assert ns.enable_auto_tool_choice is False
def test_to_namespace_passes_through_unknown_args():
"""Untyped [inference.vllm] keys land on the namespace verbatim, with CLI-style
string values JSON-coerced."""
config = InferenceConfig(
vllm={"model": "Qwen/Qwen3-4B", "max_num_seqs": "256", "kv-cache-dtype": "fp8"},
)
ns = config.to_namespace()
assert ns.max_num_seqs == 256
assert ns.kv_cache_dtype == "fp8"
Generated
+1526 -2045
View File
File diff suppressed because it is too large Load Diff