Compare commits

...
Author SHA1 Message Date
38494ccb41 fix: sync uv.lock to v0.6.0 (#2858)
Tag and Release / auto-tag-on-main (push) Canceled after 0s
Tag and Release / release-from-auto-tag (push) Canceled after 0s
Tag and Release / tag-and-release (push) Canceled after 0s
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The release bump (#2855) updated pyproject.toml but not uv.lock, so
`uv sync --locked` fails on main (CPU Tests, Docker Push).

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:52:13 -07:00
375d8596d8 chore: release v0.6.0 (#2855)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:00:59 -07:00
e035135126 feat: llm-d (EPP+Envoy) router backend (#2697)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* refactor: drop client-side DP-rank pinning for external-LB

With external-LB data parallelism each DP rank is its own API server on its
own port (the URL is the rank selector), so the client no longer needs the
hybrid-LB `X-data-parallel-rank` header to pin a rollout to an internal DP
shard. Remove the `dp_rank_count` client field + its auto-setup and the
per-rank client expansion: one client per base URL, no rank header. The
router (vllm-router or llm-d EPP) balances across the per-rank endpoints.

This also fixes llm-d routing: the EPP forwards the header to the dp=1
backend, which rejected it ("data_parallel_rank N is out of range").

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

* feat: llm-d (EPP+Envoy) router backend

Add llm-d as a second router backend alongside vllm-router, selected via
`[inference.deployment.router] type = "llm-d"`. Built on the external-LB
launch substrate — the per-rank vLLM engines launch identically; only the
router control plane differs.

- `LlmdRouterConfig`: discriminated-union member with `scorers` (base) +
  per-profile `prefill_scorer_overrides`/`decode_scorer_overrides`,
  `non_cached_tokens`, `decode_sidecar_port`, and a known-scorer validator.
- `launch_router` helper gains an llm-d branch: renders per-replica EPP +
  Envoy + file-discovery endpoints and launches `epp` + `envoy` instead of
  vllm-router. Call sites stay router-agnostic.
- pd-sidecar on each decode node (P/D) for remote-prefill orchestration + NIXL.
- Entrypoints pass the `router` config object to the templates.
- Reject `enable_return_routed_experts` with llm-d (breaks P/D, unverified
  for multi-node).
- SLURM cleanup also clears stale `epp`/`envoy`/`pd-sidecar` processes.
- Presets under `templates/llmd/` + `scripts/install_llmd.sh`; docs + install skill.

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

* fix(inference): mooncake-store + llm-d EPP coexistence on SLURM P/D

- per-rank VLLM_RPC_BASE_PATH: external-LB runs one engine per process (all
  data_parallel_rank_local 0), so the mooncake-store lookup ipc socket collided
  on a node-shared dir; key it by $port. Also avoids an absent submit-node TMPDIR.
- EPP --grpc-health-port 9003 -> 9013: 9003 collided with mooncake_master's
  metrics server on the shared replica-head node, which killed the EPP.
- mooncake_master -default_kv_lease_ttl=3600000: KV blocks were expiring (5s
  default) before the decode side reused them.
- envoy circuit_breakers raised to 100000 on backend + epp clusters: the default
  (~1024) overflowed at high inflight concurrency -> "reset reason: overflow" 500s.
- pd-sidecar launches on every decode node (not just the replica head), else
  decode nodes past the head advertise endpoints nothing serves.

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

* Feat: dockerless llmd install

* chore(configs): add GLM-5.1 llm-d disaggregated RL config

End-to-end RL config used for the GLM-5.1-FP8 llm-d (EPP+Envoy) P/D run:
12 train nodes + 16 inference nodes (8 prefill x2 / 8 decode x2), mooncake KV
store, r2e env. Lives alongside the existing glm5 disaggregated inference preset.

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

* chore(configs): move GLM-5.1 llm-d RL config to dedicated configs/glm5_llmd/

Relocate the end-to-end GLM-5.1-FP8 llm-d (EPP+Envoy) P/D RL config into its own
configs/glm5_llmd/rl.toml (out of glm5_disagg_inference) and refresh it to the
latest tuned version.

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

* feat(inference): per-role prefill/decode vLLM overrides for disaggregated P/D

Add `prefill_vllm_overrides` / `decode_vllm_overrides` to the disaggregated
inference deployment config (mirrors the existing `*_env_overrides`): extra
vLLM config options merged into the per-role `--vllm-extra` JSON for prefill
vs decode ranks on SLURM. Rendered via a small `vllm_overrides_fragment` helper
into the `ROLE_EXTRA` string in the inference / multi-node-RL sbatch templates.

Needed by configs/glm5_llmd/rl.toml (sets `decode_vllm_overrides`), which
otherwise fails `extra="forbid"` validation in test_load_configs.

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

* chore(configs): enable prefill dual-batch-overlap in glm5_llmd config

Set prefill_vllm_overrides = {enable_dbo = true} (the inference-side perf knob
tuned during the GLM-5.1 run). Batch size / num-concurrent / node-scale knobs
left as-is — those are run-specific, not portable config.

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

* chore(configs): tune glm5_llmd prefill/decode replicas (4 prefill / 1 decode)

num_prefill_replicas 2->4, num_decode_replicas 2->1 — the disaggregation split
found to perform best for GLM-5.1 (prefill is the bottleneck; one wide decode
replica maximizes decode KV/batching).

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

* docs: add GLM-5 llm-d example (16-node / 131K trainer) (#2854)

* docs: add GLM-5 llm-d example (16-node / 131K trainer)

Move the glm5_llmd config from configs/ into examples/glm5_llmd/ with a
README, mirroring the other GLM-5 example. Frame llm-d as the faster
router for GLM-5 and document the placeholders users must tweak
(output_dir, slurm partition, mooncake device_name).

Tune the example for a 16-node trainer: seq_len=131072, num_train_nodes=16,
cp=4, and adamw optimizer.

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

* docs: reword GLM-5 llm-d example entry as one-line SLURM deploy

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

* docs: highlight GLM-5 llm-d one-line SLURM deploy in Overview

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

---------

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

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-06-22 16:08:07 -07:00
533e992ad2 fix(inference): tolerate KV-transfer finish for already-freed (aborted) reqs (#2843)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(inference): tolerate KV-transfer finish for already-freed (aborted) reqs

In disaggregated P/D (NIXL, optionally + a KV store), a request can be finished
— most often FINISHED_ABORTED from an off-policy cancel, client disconnect, or
request timeout — while it still has in-flight KV transfers. When such a
request's finished_recving and finished_sending both arrive in the same
Scheduler.update_from_output step, the stock
Scheduler._update_from_kv_xfer_finished frees it in the recving branch
(_free_blocks -> del self.requests[req_id]) and then the sending branch hits
`assert req_id in self.requests`, killing the EngineCore. On a DP deployment
that one death cascades to every rank via the gloo finish-state all-reduce and
takes down the whole decode pool.

Observed on two llm-d P/D runs: the genuine crash is always one rank asserting
in _update_from_kv_xfer_finished, the rest are gloo "Connection closed by peer"
cascade victims. It is abort-triggered, not pause/resume-related: it reproduced
during normal stepping (~19k log lines after the last resume, engine actively
running model batches) and on a run with max_off_policy_steps=80000 / zero
off-policy cancellations — driven purely by incidental client-side aborts.

Monkey-patch _update_from_kv_xfer_finished to skip request ids no longer in
self.requests instead of asserting. Their blocks are already freed, so dropping
the stale notification is safe. Installed via the vllm.general_plugins entry
point so it applies in the EngineCore process where the Scheduler runs.

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

* docs: link upstream vLLM issue #46240 in the KV-xfer patch

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

---------

Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 16:05:22 -07:00
858207d340 add glm 5.2 training support (#2851)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* add glm 5.2 training support

* simplify

* chore: revert accidental research-environments submodule bump

The "add glm 5.2 training support" commit unintentionally moved the
deps/research-environments submodule pointer. Restore it to main's SHA.

---------

Co-authored-by: faresobeid <fares@primeintellect.ai>
2026-06-22 15:33:01 -07:00
minh hoangandGitHub 570463cca2 chore(renderers): bump to submodule to renderers-v0.1.8.dev49 (#2852)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-22 12:28:27 -07:00
JannikStandGitHub 31e81e5b18 feat: support PRIME_RL_REF for runtime source override (#2850)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: support PRIME_RL_REF for runtime source override

Mirrors the existing VERIFIERS_VERSION hook so researchers can dispatch
a run against an arbitrary prime-rl commit/branch/tag without rebuilding
the image. Clones into a per-ref dir under /tmp, seeds the venv from
/app/.venv so heavy wheels (flash-attn, mamba-ssm) survive, then
uv sync --inexact re-installs prime_rl from the override source.

* fix: address bugbot findings on PRIME_RL_REF entrypoint

- Slugify ref for cache dir name so branch names with slashes work.
- Always fetch + checkout on cache hit so mutable refs (branches/tags)
  pick up new commits between pod restarts.
- Move VERIFIERS_VERSION install after the PRIME_RL_REF swap so when
  both are set the install lands in the override venv.

* fix: init submodules and hash-key the override cache dir

- git clone --recurse-submodules so deps/* (verifiers, renderers,
  research-environments, pydantic-config) are populated on cold
  checkout, and refresh on every entrypoint via
  'git submodule update --init --recursive'.
- Rewrite git@github.com SSH URLs to https at runtime so the SSH
  submodule URLs work from pods that have no ssh keys.
- Append md5 hash of the ref to the cache dir name so distinct refs
  that slugify the same way ('feat/foo' vs 'feat-foo') get distinct
  cache dirs.

* fix: drop hardlink seed and key cache on repo+ref

- cp -al hardlinked /app/.venv into the override tree, so the
  subsequent uv sync wrote through to the baked venv on filesystems
  shared with /tmp. Plain cp -a always copies.
- Include PRIME_RL_REPO in the cache-dir hash so the same ref on
  different forks gets distinct cache dirs.

* fix: --all-extras on override sync

uv sync --inexact --no-dev only installed base deps, so env / gpt-oss /
modelexpress changes in the override branch were silently missed. With
--all-extras the override picks them up, and --inexact still keeps
flash-attn-3 / mamba-ssm from the seeded venv.

* fix: mirror image extras explicitly instead of --all-extras

--all-extras pulled in disagg/quack which the baked image does not
ship; their deps (deep-ep, deep-gemm, quack-kernels) would trigger
heavy source builds at pod startup. Mirror Dockerfile.cuda:82's set
exactly so the override venv lines up with the image.

* fix: submodule sync before update to pick up .gitmodules URL changes
2026-06-22 12:15:37 -07:00
samsjaandGitHub 137f8f49c8 [codex] trim orchestrator memory after train steps (#2837)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(orchestrator): trim process memory each train step

* fix(orchestrator): collect garbage before memory trim
2026-06-22 12:13:26 -07:00
Maxwill LinandGitHub f04c8d988c fix(vlm): dispatch Gemma 4 as a VLM and read softcapping from the text config (#2844)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-22 02:23:13 +02:00
4d361adacc fix(orchestrator): drain off-policy rollouts before pausing for weight update (#2841)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The off-policy drain (cancelling rollouts past max_off_policy_steps) ran via
on_new_version *after* the inference engines resumed from the weight-update
pause. In a NIXL P/D deployment this reliably crashed the decode engines.

Aborting a rollout cancels its /generate request; vLLM marks the request
FINISHED_ABORTED and frees it, recording it in the NIXL connector's
_reqs_not_processed set so the worker suppresses its in-flight KV-transfer
completion. That suppression only propagates to the workers while the engine is
stepping. Pausing with mode="keep" (PAUSED_ALL) skips step(), so KV transfers
that complete during the pause are flushed on the first step after resume — at
the same moment the drain fires its aborts. The abort frees the request before
its suppression reaches the worker, so the flushed completion hits
`assert req_id in self.requests` in the decode scheduler's
_update_from_kv_xfer_finished, killing the engine and cascading to every DP
rank via the gloo finish-state all-reduce.

With max_off_policy_steps=8 the first mass drop lands at the 9th weight update,
which is why the run always died at step 8/9.

Move the drain to a new on_version_pending observer hook that the watcher calls
*before* update_weights (before the pause), so the aborts are processed under
normal stepping and the connector's native cleanup completes before the engine
freezes. on_new_version still runs post-update for the orchestrator's dispatch
gate, which needs the live policy version.

Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 20:04:08 -07:00
faresobeidandGitHub 7f77713886 update length penalty and add back length weighted baseline (#2702)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-19 02:09:32 +02:00
samsjaandGitHub efeddae6bb add rlm uuid ctf env (#2832)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-18 16:00:38 -07:00
42 changed files with 1279 additions and 340 deletions
+1
View File
@@ -2,6 +2,7 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`orchestrator.advantage` length-penalty overhaul + length-weighted baseline**: `length_penalty` is now a single shape — a linear penalty that subtracts `coef * pass_rate * (model completion tokens / orchestrator.seq_len)` from each reward before the baseline subtraction (`pass_rate` = group mean reward, so solved-often problems get the strongest concision pressure and never-solved groups get none), with an optional `gate_by_correctness` flag (default `false`) that restricts the penalty to correct rollouts (`reward == 1`). The previous discriminated `type = "tokens" | "turns"` efficiency-shaping variants and the per-penalty `max_length` field have been removed — configure `[orchestrator.advantage.length_penalty]` with `coef` (and optionally `gate_by_correctness`) instead; the denominator is always `orchestrator.seq_len`. Also adds `orchestrator.advantage.length_weighted_baseline` (default `false`): when enabled, the GRPO baseline is the token-length-weighted mean reward (`sum(len_i * reward_i) / sum(len_i)`) instead of the plain mean. (2026-06-03)
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
+1
View File
@@ -97,6 +97,7 @@ RUN apt-get update && apt-get install -y \
tmux \
iperf \
openssh-server \
git \
git-lfs \
gpg \
sudo \
+2
View File
@@ -38,6 +38,7 @@ PRIME-RL is a framework for large-scale reinforcement learning. It is designed t
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
7. Hackable, modular, and extensible by design.
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/glm5_llmd/README.md).
## Models support
@@ -221,6 +222,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
3. [**Intellect-3.1**](examples/Intellect-3.1/README.md): Reproduce our `INTELLECT-3.1` training run.
4. [**MiniMax-M2.5 SWE**](examples/minimax_m2.5_swe/README.md): Train `MiniMax-M2.5` on agentic SWE tasks.
5. [**High-throughput GLM-5**](examples/glm5_pd_disag/README.md): Train `GLM-5` with PD disaggregation and FP8 inference on SWE.
6. [**High-throughput GLM-5 (llm-d)**](examples/glm5_llmd/README.md): One-line SLURM deployment for `GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload — the faster way to run `GLM-5`.
## Docs
+1 -1
+3 -1
View File
@@ -25,7 +25,7 @@ impl = "custom" # or "hf" to force the HF path
| Family | HF config types | EP | CP |
|---|---|---|---|
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | ✅ | ✅ |
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
@@ -38,6 +38,8 @@ impl = "custom" # or "hf" to force the HF path
The custom path enables you to set EP, CP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
### Expert Parallelism Backends
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
+13 -3
View File
@@ -136,10 +136,20 @@ The default advantage is per-group reward minus per-group baseline (DR-GRPO with
This is intentionally simple — it does the right thing for most envs. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
Two built-in **length penalties** can be layered on top of any advantage to discourage rambling:
A **length penalty** can be layered on top of the default advantage to discourage rambling. Configured under `[orchestrator.advantage.length_penalty]`, it subtracts a `coef * pass_rate * (completion tokens / orchestrator.seq_len)` term from every reward before the baseline subtraction, where `pass_rate` is the problem's mean reward across the group. The pass-rate factor means problems the model already solves reliably get the strongest push toward concise outputs, while rarely-solved problems are barely penalized (a never-solved group, mean reward 0, gets none). Set `gate_by_correctness = true` to apply the penalty only to correct rollouts (`reward == 1`), leaving incorrect ones untouched:
- `[orchestrator.length_penalty] type = "tokens"` — penalizes long completions in tokens, with configurable target and slope.
- `[orchestrator.length_penalty] type = "turns"` — penalizes long multi-turn rollouts by turn count.
```toml
[orchestrator.advantage.length_penalty]
coef = 0.25 # effective penalty is coef * pass_rate * (completion_tokens / seq_len)
gate_by_correctness = false # when true, only penalize rollouts with reward == 1
```
By default the baseline is the plain group mean reward. Set `length_weighted_baseline = true` to instead use the token-length-weighted mean — `sum(len_i * reward_i) / sum(len_i)` — which centers advantages by per-token expected reward when rollouts vary a lot in length:
```toml
[orchestrator.advantage]
length_weighted_baseline = true
```
### Custom Advantage
+17 -4
View File
@@ -30,7 +30,7 @@ We support 3 distinct deployment shapes:
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `router_port`, `backend_port`, etc.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `backend_port`, and a `[...deployment.router]` block, etc.
```toml
[inference.deployment]
@@ -102,7 +102,7 @@ tp = 2
dp = 4
```
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing will be handled by the `vllm-router` instance running on the same node as the 1st replica. We aim to support more advanced routing options, such as `llm-d` or `dynamo` in the future. You can read more about the supported routing options in the [router](#router) section.
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a router instance running on the same node as the 1st replica — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[...deployment.router]` block. You can read more about the supported routing options in the [router](#router) section.
### Wide-EP
@@ -167,9 +167,22 @@ This will run 3 inference replicas, each running on 6 nodes. Each replica will r
## Router
We use our own fork of [vllm-router](https://github.com/PrimeIntellect-ai/router) as the request handler. We plan to support more advanced proxy options in the future.
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
Right now, router handles 2 most important things:
```toml
[inference.deployment.router] # or [deployment.router] for the standalone inference entrypoint
type = "llm-d" # "vllm-router" (default) or "llm-d"
# llm-d-only knobs (all optional):
scorers = { "prefix-cache-scorer" = 3.0, "active-request-scorer" = 2.0 } # base, applied to every profile
prefill_scorer_overrides = { "queue-scorer" = 2.0, "kv-cache-utilization-scorer" = 2.0 } # merged onto the P/D prefill profile
decode_scorer_overrides = {} # merged onto the P/D decode profile
non_cached_tokens = 16 # below this many non-cached prompt tokens, skip remote prefill (P/D)
```
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy. Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
Both backends support the 2 most important things:
- Request routing - KV cache re-use and balanced routing
- P/D disaggregation - handling the prefill and decode stages separately
+87
View File
@@ -0,0 +1,87 @@
# High-throughput GLM-5 with llm-d
This example trains `GLM-5.1` with RL on agentic SWE tasks using P/D disaggregation, FP8 inference, and a Mooncake distributed CPU KV store — fronted by the upstream [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy).
**llm-d is the faster way to run GLM-5.** It is the recommended router backend for large GLM-5 runs: its `active-request-scorer` is an in-flight load balancer that spreads requests across ranks immediately, instead of relying on metrics that are scraped on a delay (as the default `vllm-router` does). Combined with prefix-cache affinity for grouped rollouts, this keeps prefill and decode ranks evenly loaded under the bursty request pattern of RL. If you want the simpler default router instead, see the [GLM-5 PD disaggregation example](../glm5_pd_disag/README.md).
## Requirements
You need access to a Slurm cluster with at least **32 nodes** (16 trainer + 16 inference, 8 GPUs each) and a shared filesystem. In this guide we assume the NFS is mounted at `/shared`; you can change it to your own path.
You also need prime-rl cloned on your cluster into the shared filesystem.
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
```
### Install llm-d
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
```bash
bash scripts/install_llmd.sh
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
```bash
touch .env
echo "WANDB_API_KEY=your_wandb_api_key" >> .env
echo "HUGGINGFACE_TOKEN=your_huggingface_token" >> .env
```
### sandbox
The SWE environment is configured to use Prime Intellect Sandboxes. You can find more information about the sandboxes [here](https://docs.primeintellect.ai/sandboxes/overview). You will need to create a sandbox account and add the credentials to the `.env` file. Alternatively, you can adapt the code of the environment to use your own sandbox implementation.
## Tweak before launching
This config is tuned for our cluster — a few values **must** be adapted to yours before you run. Search the config for these markers:
- **`output_dir`** (`# FILL IN`) — point it at your shared filesystem.
- **`[slurm] partition`** (`# FILL IN`) — set it to your cluster's Slurm partition.
- **`[inference.kv_cache_offload] device_name`** (`# do it yourself`) — the list of RDMA NICs for Mooncake. Auto-detection is unreliable, so set it by hand from `nvidia-smi topo -m` on your nodes.
A few more knobs you may want to tune for your hardware:
- **Trainer parallelism** — this config assumes **16 trainer nodes** at **131K** sequence length with `cp = 4` (context parallel) and the `adamw` optimizer. If you have fewer trainer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` accordingly.
- **Scorer weights** (`[inference.deployment.router]`) — the `scorers` / `prefill_scorer_overrides` / `decode_scorer_overrides` weights follow the upstream llm-d P/D guide and are a good starting point; tune them if your prefill/decode balance drifts.
- **Mooncake CPU pool** (`[inference.kv_cache_offload.cpu] num_bytes`) — defaults to 1TB/node; lower it if your nodes have less RAM.
## Tmux session
We recommend using the tmux helper to start the run and look at the logs.
From your Slurm head node:
```bash
bash scripts/tmux.sh glm5-llmd /shared/outputs/glm5-llmd
```
You can then attach to it by doing `tmux attach -t glm5-llmd`.
## Start the run
Run the following command to start the RL training:
PS: If using the tmux helper, you can run the command in the `Terminal` (window 0) pane and look at the logs in the `Logs` (window 1) pane.
```bash
uv run rl @ examples/glm5_llmd/rl.toml --output-dir /shared/outputs/glm5-llmd
```
Output of the command:
```
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/glm5-llmd/configs [rl.py::515]
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/glm5-llmd/rl.sbatch [rl.py::534]
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/glm5-llmd/rl.sbatch [rl.py::540]
XXX:XX:XX SUCCESS Submitted batch job YYYY
Logs:
Trainer: tail -F /shared/outputs/glm5-llmd/logs/trainer.log
Orchestrator: tail -F /shared/outputs/glm5-llmd/logs/orchestrator.log
Inference: tail -F /shared/outputs/glm5-llmd/logs/inference.log
Envs: tail -F /shared/outputs/glm5-llmd/logs/envs/*/*/*.log
```
+140
View File
@@ -0,0 +1,140 @@
max_steps = 10000000
seq_len = 131072
output_dir = "/shared/outputs/glm5-llmd" # FILL IN: point at your shared filesystem
clean_output_dir = true
[log]
level = "debug"
[wandb]
project = "glm5-llmd"
name = "base"
[weight_broadcast]
type = "nccl"
port = 29502
timeout = 12000
quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
num_train_nodes = 16
num_infer_nodes = 16
gpus_per_node = 8
num_infer_replicas = 1
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 8
num_prefill_replicas = 4
num_decode_nodes = 8
num_decode_replicas = 1
# skip warmup for faster start in cost of some jit overhead early
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_overrides = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
# gives the most KV cache while keeping decent throughput, KV cache increase comes in from lower deep-ep LL static buffers
prefill_vllm_overrides = {"enable_dbo"=true}
decode_vllm_overrides = {"max_num_batched_tokens"=96, "max_num_seqs"=96}
[inference.deployment.router]
type = "llm-d"
scorers = { "prefix-cache-scorer" = 3.0 } # need some prefix-cache routing, however due to shared mooncake pool do low prio
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 } # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 } # decode doesn't really create queue, it fills in KV cache fast, give 4.0
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[slurm]
job_name = "glm5-llmd"
partition = "all" # FILL IN: set to your cluster's partition
[trainer]
dist_timeout_seconds = 1800
enable_token_export = true
[trainer.model]
name = "zai-org/GLM-5.1"
impl = "custom"
attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
ep = 8
optim_cpu_offload = true
fp8 = true
[trainer.model.ac]
freq = 1
[trainer.model.compile]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.optim]
type = "adamw"
lr = 1e-6
weight_decay = 0.0
[orchestrator]
batch_size = 256
rollouts_per_example = 16
max_inflight_rollouts = 2048
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
[orchestrator.model]
name = "zai-org/GLM-5.1-FP8"
[orchestrator.renderer]
name = "glm-5.1"
preserve_all_thinking = true
[orchestrator.train.sampling]
temperature = 1.0
extra_body = {chat_template_kwargs = {clear_thinking = false}}
[[orchestrator.train.env]]
id = "rlm_swe"
name = "r2e"
num_workers = 16
[orchestrator.train.env.args]
max_turns = 300
timeout_seconds = 21600
summarize_at_tokens = [35000, 80000]
poll_interval = 5
rlm_ref = "907115a79b2a50d193863e7ea1f3550acb4386f0"
labels = ["glm5-llmd"]
[orchestrator.advantage]
type = "default"
[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
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
@@ -167,8 +167,26 @@ All2AllBackend = Literal[
]
# Known llm-d EPP scorer plugins (used to guard the ``scorers`` map against typos).
KNOWN_SCORERS = frozenset(
{
"prefix-cache-scorer",
"precise-prefix-cache-scorer",
"queue-scorer",
"kv-cache-utilization-scorer",
"active-request-scorer",
"load-aware-scorer",
"running-requests-size-scorer",
"token-load-scorer",
"latency-scorer",
"session-affinity-scorer",
"lora-affinity-scorer",
}
)
class VllmRouterConfig(BaseConfig):
"""PrimeIntellect vllm-router fronting the per-rank (external-LB) endpoints."""
"""PrimeIntellect vllm-router."""
type: Literal["vllm-router"] = "vllm-router"
@@ -179,9 +197,57 @@ class VllmRouterConfig(BaseConfig):
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
# Discriminated on ``type`` so additional router backends can be added to the
# union (a single member needs no discriminator yet).
RouterConfig: TypeAlias = VllmRouterConfig
class LlmdRouterConfig(BaseConfig):
"""llm-d router backend (EPP + Envoy)."""
type: Literal["llm-d"] = "llm-d"
port: int = 8000
"""Port the Envoy gateway listens on — becomes the client-facing router URL."""
scorers: dict[str, float] = {
"prefix-cache-scorer": 3.0,
"active-request-scorer": 2.0,
}
"""EPP scorer name → weight, applied to every routing profile (before the per-profile P/D overrides). Defaults to prefix-cache affinity plus in-flight (active-request) load balancing. Unknown scorer names are rejected."""
prefill_scorer_overrides: dict[str, float] = {
"queue-scorer": 2.0,
"kv-cache-utilization-scorer": 2.0,
}
"""P/D only: scorer → weight merged onto ``scorers`` for the prefill profile (a per-profile weight overrides the base)."""
decode_scorer_overrides: dict[str, float] = {}
"""P/D only: scorer → weight merged onto ``scorers`` for the decode profile (a per-profile weight overrides the base); empty by default."""
non_cached_tokens: int = 16
"""P/D only: requests with fewer than this many non-cached prompt tokens skip remote prefill and run decode-only."""
decode_sidecar_port: int = 8300
"""P/D only: port the decode-side llm-d sidecar listens on."""
@property
def prefill_scorers(self) -> dict[str, float]:
"""Effective prefill-profile scorers: ``scorers`` merged with ``prefill_scorer_overrides``."""
return {**self.scorers, **self.prefill_scorer_overrides}
@property
def decode_scorers(self) -> dict[str, float]:
"""Effective decode-profile scorers: ``scorers`` merged with ``decode_scorer_overrides``."""
return {**self.scorers, **self.decode_scorer_overrides}
@model_validator(mode="after")
def validate_scorers(self):
unknown = (
set(self.scorers) | set(self.prefill_scorer_overrides) | set(self.decode_scorer_overrides)
) - KNOWN_SCORERS
if unknown:
raise ValueError(f"Unknown llm-d scorer(s): {sorted(unknown)}. Known scorers: {sorted(KNOWN_SCORERS)}.")
return self
# Discriminated on ``type`` so the launch path can pick the router backend.
RouterConfig: TypeAlias = Annotated[VllmRouterConfig | LlmdRouterConfig, Field(discriminator="type")]
class BaseInferenceDeploymentConfig(BaseConfig):
@@ -240,6 +306,12 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
decode_env_overrides: dict[str, str] = {}
"""Extra environment variables exported only on decode nodes."""
prefill_vllm_overrides: dict[str, Any] = {}
"""Extra vLLM config options merged into --vllm-extra only for prefill ranks (SLURM only)."""
decode_vllm_overrides: dict[str, Any] = {}
"""Extra vLLM config options merged into --vllm-extra only for decode ranks (SLURM only)."""
@property
def num_nodes(self) -> int:
return self.num_prefill_nodes + self.num_decode_nodes
@@ -369,6 +441,18 @@ class InferenceConfig(BaseConfig):
raise ValueError("Must use SLURM for multi-node / disaggregated deployment.")
return self
@model_validator(mode="after")
def validate_llmd_no_routed_experts(self):
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
router = getattr(self.deployment, "router", None)
if router is not None and router.type == "llm-d" and self.enable_return_routed_experts:
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. "
"Use router type 'vllm-router' for routed-expert runs."
)
return self
@model_validator(mode="after")
def auto_setup_kv_cache_offload(self):
if self.kv_cache_offload is not None:
@@ -143,31 +143,22 @@ class EvalSamplingConfig(BaseConfig):
return data
class TokensLengthPenaltyConfig(BaseConfig):
type: Literal["tokens"] = "tokens"
class LinearLengthPenaltyConfig(BaseConfig):
coef: float = Field(0.25, ge=0, allow_inf_nan=False)
"""Scale on the linear length penalty. Each reward is reduced by ``coef * pass_rate * (model completion tokens / orchestrator.seq_len)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative."""
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on model completion tokens. Finite and non-negative."""
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
class TurnsLengthPenaltyConfig(BaseConfig):
type: Literal["turns"] = "turns"
LengthPenaltyConfig: TypeAlias = Annotated[
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
Field(discriminator="type"),
]
gate_by_correctness: bool = False
"""When True, scale each rollout's penalty by its reward (``penalty * reward``), so correct rollouts (``reward == 1``) are penalized and incorrect ones (``reward == 0``) are not. When False, every rollout is penalized equally."""
class DefaultAdvantageConfig(BaseConfig):
type: Literal["default"] = "default"
length_penalty: LengthPenaltyConfig | None = None
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
length_penalty: LinearLengthPenaltyConfig | None = None
"""Length penalty applied during advantage computation. Subtracts a ``coef * pass_rate * (completion tokens / orchestrator.seq_len)`` term from each reward (``pass_rate`` = group mean reward) before the baseline subtraction, so solved-often problems get the strongest concision pressure and never-solved groups get none. None disables the penalty."""
length_weighted_baseline: bool = False
"""When True, the GRPO baseline is the token-length-weighted mean reward (``sum(len_i * reward_i) / sum(len_i)``) instead of the plain group mean, centering advantages by per-token expected reward."""
class CustomAdvantageConfig(BaseConfig):
@@ -438,6 +438,25 @@ class RLConfig(BaseConfig):
)
return self
@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).
Runs after ``auto_setup_router_replay`` so it also catches the
``trainer.enable_router_replay`` path, which sets the inference flag here
(after InferenceConfig's own validators, which therefore miss it).
"""
if self.inference is not None and self.inference.enable_return_routed_experts:
router = getattr(self.inference.deployment, "router", None)
if 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 "
"breaks P/D and is unverified for multi-node. Use router type 'vllm-router' "
"for router-replay runs."
)
return self
@model_validator(mode="after")
def validate_router_replay_without_kv_offload(self):
if (
+3 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "prime-rl"
version = "0.5.0"
version = "0.6.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
@@ -88,6 +88,7 @@ envs = [
"reverse-text",
"rlm-swe",
"rlm-search",
"rlm-uuid-ctf",
"science-env",
"simpleqa-verified",
"tau2-bench",
@@ -228,6 +229,7 @@ opencode-swe = { path = "deps/research-environments/environments/opencode_swe",
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
rlm-uuid-ctf = { path = "deps/research-environments/environments/rlm_uuid_ctf", editable = true }
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
+67 -1
View File
@@ -4,8 +4,74 @@ set -e
# Set higher ulimit for file descriptors to prevent API timeout issues
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
# Allow runtime override of the prime-rl source itself.
# PRIME_RL_REF can be a git tag, branch, or commit hash. PRIME_RL_REPO
# optionally points at a fork; defaults to the upstream repo.
#
# We clone into a per-ref dir under /tmp, seed the venv from the baked
# /app/.venv so heavy wheels (flash-attn, mamba-ssm, …) survive, then
# `uv sync --inexact` re-installs prime_rl from the override source.
# Workdir + PATH swap so the chart's `uv run trainer/inference/orchestrator`
# resolves the entrypoints from the override venv.
if [ -n "$PRIME_RL_REF" ]; then
PRIME_RL_REPO="${PRIME_RL_REPO:-https://github.com/PrimeIntellect-ai/prime-rl.git}"
# Slug + content hash for the cache dir name. Slug keeps the path
# human-readable; the hash (over repo + ref) prevents collisions
# between distinct refs that slugify the same way (e.g. `feat/foo`
# vs `feat-foo`) and between the same ref on different forks.
REF_SLUG="${PRIME_RL_REF//\//-}"
REF_HASH=$(echo -n "${PRIME_RL_REPO}|${PRIME_RL_REF}" | md5sum | cut -c1-12)
DEST="/tmp/prime-rl-${REF_SLUG}-${REF_HASH}"
# Rewrite ssh://git@github.com URLs to https so submodules listed
# with SSH URLs (deps/verifiers, deps/renderers, deps/research-envs)
# can be cloned from the pod without ssh keys.
git config --global url."https://github.com/".insteadOf "git@github.com:"
if [ ! -d "$DEST/.git" ]; then
echo "[prime-rl] cloning ${PRIME_RL_REPO} for ${PRIME_RL_REF}"
rm -rf "$DEST"
git clone --recurse-submodules "$PRIME_RL_REPO" "$DEST"
fi
# Always fetch + checkout so mutable refs (branches/tags) pick up new
# commits between pod restarts. No-op for immutable SHAs.
echo "[prime-rl] refreshing ${PRIME_RL_REF}"
git -C "$DEST" fetch --quiet --tags --force origin
git -C "$DEST" checkout --quiet --force "$PRIME_RL_REF"
# Fast-forward to upstream tip when PRIME_RL_REF is a branch name.
# Silently no-ops for SHAs/tags (no `origin/<sha>` exists).
git -C "$DEST" reset --hard --quiet "origin/${PRIME_RL_REF}" 2>/dev/null || true
# Refresh submodules to whatever the parent commit pins. `sync`
# picks up URL changes in .gitmodules between checkouts on cache
# hit; `update --init --recursive` applies the pinned SHAs.
git -C "$DEST" submodule sync --recursive
git -C "$DEST" submodule update --init --recursive
if [ ! -d "$DEST/.venv" ]; then
# Seed from the baked venv so the heavy wheels (flash-attn,
# mamba-ssm, …) don't have to be rebuilt. Plain `cp -a` (no
# hardlinks): a subsequent `uv sync` writes into this tree, and
# hardlinks would leak those writes back into /app/.venv when
# /tmp and /app share a filesystem.
cp -a /app/.venv "$DEST/.venv"
fi
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
# Mirror the image's extras (Dockerfile.cuda:82) — explicit instead
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
# startup. --inexact keeps the seeded venv's pre-built wheels
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
# override's lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev \
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
--extra envs --extra gpt-oss --extra modelexpress \
--group mamba-ssm )
export VIRTUAL_ENV="$DEST/.venv"
export PATH="$DEST/.venv/bin:$PATH"
cd "$DEST"
fi
# Allow runtime override of the verifiers package version.
# VERIFIERS_VERSION can be a git tag, branch, or commit hash.
# VERIFIERS_VERSION can be a git tag, branch, or commit hash. Runs after the
# PRIME_RL_REF swap so when both are set the install lands in the override
# venv (uv pip install targets $VIRTUAL_ENV when exported).
if [ -n "$VERIFIERS_VERSION" ]; then
echo "Installing verifiers version: $VERIFIERS_VERSION"
uv pip install --reinstall-package verifiers \
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env bash
# Install the llm-d standalone (no-Kubernetes) routing binaries into
# third_party/llmd/bin:
# - epp : llm-d-router Endpoint Picker (the routing brain)
# - pd-sidecar : decode-side proxy for P/D disaggregation
# - envoy : the data-plane proxy that calls the EPP via ext_proc
#
# epp/pd-sidecar are built from a pinned llm-d-router commit. We currently build
# from a small fork that adds P/D disaggregation for vLLM's token-in
# /inference/v1/generate endpoint (prime-rl's renderer / TITO rollout path) —
# upstream's pd-sidecar only disaggregates the OpenAI endpoints, so token-in P/D
# silently runs decode-only. The fork is pending upstream PR
# llm-d/llm-d-router#1458; switch LLMD_ROUTER_REPO back to the upstream repo and
# bump LLMD_ROUTER_REF once it merges. The fork is branched off the upstream
# commit that added the EPP vllmhttp parser (PR #1248), which the renderer path
# also needs.
#
# System Go is not required: a Go toolchain is vendored under third_party/llmd/go
# and used to bootstrap; GOTOOLCHAIN=auto fetches the exact version the module
# pins. Envoy is extracted as a static binary from its release container image
# WITHOUT docker: we build `crane` (pure-Go, talks straight to the OCI registry)
# with the same vendored toolchain and use it to export the image filesystem.
# This is the only step that previously required a docker daemon, which cluster
# compute nodes don't have.
set -euo pipefail
LLMD_ROUTER_REPO="${LLMD_ROUTER_REPO:-https://github.com/S1ro1/llm-d-router.git}"
LLMD_ROUTER_REF="${LLMD_ROUTER_REF:-1ca4243ec84c657b4a5f507a1776d6c15a618d5b}"
GO_BOOTSTRAP_VERSION="${GO_BOOTSTRAP_VERSION:-1.23.4}"
ENVOY_VERSION="${ENVOY_VERSION:-1.36.0}"
ENVOY_IMAGE="${ENVOY_IMAGE:-envoyproxy/envoy:v${ENVOY_VERSION}}"
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
PROJECT_DIR=$(cd "$SCRIPT_DIR/.." && pwd)
LLMD_DIR="$PROJECT_DIR/third_party/llmd"
BIN_DIR="$LLMD_DIR/bin"
GO_ROOT="$LLMD_DIR/go"
SRC_DIR="$LLMD_DIR/src"
GO_TOOLS_BIN="$LLMD_DIR/gotools/bin"
mkdir -p "$BIN_DIR" "$GO_TOOLS_BIN"
# --- Go toolchain (vendored bootstrap; auto-upgrades to the module's version) ---
if [ ! -x "$GO_ROOT/bin/go" ]; then
echo "[install_llmd] downloading bootstrap Go $GO_BOOTSTRAP_VERSION"
rm -rf "$GO_ROOT"
curl -fsSL "https://go.dev/dl/go${GO_BOOTSTRAP_VERSION}.linux-amd64.tar.gz" | tar -xz -C "$LLMD_DIR"
fi
export GOROOT="$GO_ROOT"
export PATH="$GO_ROOT/bin:$PATH"
export GOTOOLCHAIN=auto
echo "[install_llmd] bootstrap $(go version)"
# --- Fetch llm-d-router source at the pinned ref ---
echo "[install_llmd] fetching ${LLMD_ROUTER_REPO}@${LLMD_ROUTER_REF}"
if [ ! -d "$SRC_DIR/.git" ]; then
rm -rf "$SRC_DIR"
git clone --quiet "$LLMD_ROUTER_REPO" "$SRC_DIR"
fi
git -C "$SRC_DIR" remote set-url origin "$LLMD_ROUTER_REPO"
git -C "$SRC_DIR" fetch --quiet origin
git -C "$SRC_DIR" checkout --quiet "$LLMD_ROUTER_REF"
# --- Build epp + pd-sidecar ---
echo "[install_llmd] building epp + pd-sidecar"
( cd "$SRC_DIR" && go build -o "$BIN_DIR/epp" ./cmd/epp && go build -o "$BIN_DIR/pd-sidecar" ./cmd/pd-sidecar )
# --- Envoy static binary (extract from the release image; keep if present) ---
# No docker: build crane with the vendored toolchain and export the image's
# filesystem straight from the registry, then pull out the static envoy binary.
if [ ! -x "$BIN_DIR/envoy" ]; then
if [ ! -x "$GO_TOOLS_BIN/crane" ]; then
echo "[install_llmd] building crane (OCI registry client, no docker needed)"
GOBIN="$GO_TOOLS_BIN" GOFLAGS=-mod=mod \
go install github.com/google/go-containerregistry/cmd/crane@latest
fi
echo "[install_llmd] extracting Envoy ${ENVOY_VERSION} from ${ENVOY_IMAGE}"
"$GO_TOOLS_BIN/crane" export "$ENVOY_IMAGE" - \
| tar -xf - -O usr/local/bin/envoy > "$BIN_DIR/envoy"
chmod +x "$BIN_DIR/envoy"
fi
echo "[install_llmd] installed binaries in $BIN_DIR:"
"$BIN_DIR/epp" --version 2>&1 | head -1 || true
"$BIN_DIR/envoy" --version 2>&1 | head -1 || true
"$BIN_DIR/pd-sidecar" --help >/dev/null 2>&1 && echo " pd-sidecar OK" || true
echo "[install_llmd] done"
+11 -1
View File
@@ -27,7 +27,7 @@ uv sync --group dev # + pytest, ruff, pre-commit
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
```
The `envs` extra installs every env workspace listed in `[tool.uv.workspace]`. Adding a new env means adding it to `members`, the `envs` extra, and `[tool.uv.sources]`.
The `envs` extra installs environments listed under `[project.optional-dependencies].envs`, resolved through `[tool.uv.sources]`. Adding a new env means adding its package name to `envs` and its editable source path to `[tool.uv.sources]`.
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`.
@@ -59,6 +59,16 @@ Flags: `--workspace DIR`, `--deepep-ref REF` (default `73b6ea4`), `--nvshmem-ver
Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
### llm-d router backend
Multi-node / disaggregated deployments can route through the upstream llm-d Endpoint Picker instead of `vllm-router` (set `[...deployment.router] type = "llm-d"`). It needs three native binaries — install once:
```bash
bash scripts/install_llmd.sh # builds epp + pd-sidecar from a pinned llm-d-router commit (vendored Go), fetches envoy
```
Binaries land in `third_party/llmd/bin/{epp,envoy,pd-sidecar}` (a shared path, so SLURM nodes see them). `epp` is pinned to the commit that includes the `vllmhttp-parser` (PR #1248) so prime-rl's renderer/TITO `/inference/v1/generate` path routes correctly. Override the pin with `LLMD_ROUTER_REF=<sha>`. The EPP + Envoy + endpoints configs are rendered from `templates/llmd/*.yaml.j2` (included into the SLURM script); only the per-node IPv4 addresses are filled in inline at launch time.
## Key files
- `pyproject.toml` — dependencies, extras, dependency groups
+19 -5
View File
@@ -1,6 +1,8 @@
import json
import subprocess
import sys
from pathlib import Path
from typing import Any
import tomli_w
@@ -14,6 +16,17 @@ INFERENCE_TOML = "inference.toml"
INFERENCE_SBATCH = "inference.sbatch"
def vllm_overrides_fragment(overrides: dict[str, Any]) -> str:
"""Render per-role vLLM overrides as a JSON fragment for the ROLE_EXTRA bash string.
Returns a leading-comma fragment with quotes escaped for the double-quoted assignment
(e.g. `, \\"max_num_seqs\\": 256`), or an empty string when there are no overrides.
"""
if not overrides:
return ""
return ", " + json.dumps(overrides)[1:-1].replace('"', '\\"')
def write_config(config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None) -> Path:
"""Write resolved config to disk."""
output_dir.mkdir(parents=True, exist_ok=True)
@@ -47,7 +60,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
dp_per_node=dp_per_node,
num_nodes=getattr(config.deployment, "num_nodes", 1),
port=config.server.port,
disaggregated=is_disaggregated,
is_disaggregated=is_disaggregated,
kv_offload=offload is not None,
kv_offload_mooncake=is_mooncake,
kv_offload_cpu_bytes=int(offload.cpu.num_bytes) if is_mooncake else 0,
@@ -65,20 +78,21 @@ 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,
router_port=config.deployment.router.port,
router_policy=config.deployment.router.policy,
router=config.deployment.router,
data_parallel_rpc_port=config.data_parallel_rpc_port,
use_deep_gemm=config.use_deep_gemm,
prefill_env_overrides=config.deployment.prefill_env_overrides,
decode_env_overrides=config.deployment.decode_env_overrides,
prefill_vllm_extra_json=vllm_overrides_fragment(config.deployment.prefill_vllm_overrides),
decode_vllm_extra_json=vllm_overrides_fragment(config.deployment.decode_vllm_overrides),
)
elif is_multi_node:
template_vars.update(
router_port=config.deployment.router.port,
router=config.deployment.router,
backend_port=config.deployment.backend_port,
router_policy=config.deployment.router.policy,
data_parallel_rpc_port=config.data_parallel_rpc_port,
enable_expert_parallel=config.enable_expert_parallel,
infer_nodes_per_replica=config.deployment.num_nodes,
)
script = template.render(**template_vars)
+7 -2
View File
@@ -12,7 +12,9 @@ from threading import Event, Thread
import pynvml
import tomli_w
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.inference import vllm_overrides_fragment
from prime_rl.utils.config import cli
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import (
@@ -371,7 +373,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
num_prefill_replicas=infer_deploy.num_prefill_replicas,
num_decode_replicas=infer_deploy.num_decode_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router_port=infer_deploy.router.port,
router=infer_deploy.router,
prefill_port=infer_deploy.prefill_port,
decode_port=infer_deploy.decode_port,
inference_tp=config.inference.parallel.tp,
@@ -379,6 +381,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
use_deep_gemm=config.inference.use_deep_gemm,
prefill_env_overrides=infer_deploy.prefill_env_overrides,
decode_env_overrides=infer_deploy.decode_env_overrides,
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,
**mooncake_vars,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
@@ -397,7 +401,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
nodes_per_infer_replica=config.deployment.num_infer_nodes,
num_infer_replicas=config.deployment.num_infer_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router_port=config.inference.deployment.router.port if config.inference else 8000,
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
infer_nodes_per_replica=config.deployment.num_infer_nodes,
backend_port=config.inference.deployment.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,
+62
View File
@@ -21,6 +21,68 @@ def transformers_v5_compat():
monkey_patch_deep_gemm_silu_mul_quant_int64()
monkey_patch_vllm_padded_input_scrub()
monkey_patch_return_routed_experts_with_nixl_connector()
monkey_patch_kv_xfer_finished_tolerate_freed()
def monkey_patch_kv_xfer_finished_tolerate_freed():
"""Tolerate KV-transfer finish notifications for already-freed requests.
In disaggregated P/D (NIXL, optionally + a KV store connector) a request can
be finished — most often ``FINISHED_ABORTED`` from an off-policy cancel, a
client disconnect, or a request timeout — while it still has in-flight KV
transfers. When such a request's ``finished_recving`` and ``finished_sending``
both land in the same ``Scheduler.update_from_output`` step, the stock
``_update_from_kv_xfer_finished`` frees it in the recving branch
(``_free_blocks`` -> ``del self.requests[req_id]``) and then the sending
branch hits ``assert req_id in self.requests`` and kills the EngineCore. On a
DP deployment that one death cascades to every rank via the gloo finish-state
all-reduce, taking down the whole inference pool.
The trigger is the abort itself, not weight-update pause/resume: it reproduces
during normal stepping whenever an aborted request's recv and send complete in
the same step (observed with zero off-policy cancellations, driven only by
incidental client-side aborts). Skip already-freed request ids instead of
asserting — their blocks are freed either way, so dropping the stale
notification is safe.
Upstream issue: https://github.com/vllm-project/vllm/issues/46240
"""
from vllm.logger import init_logger
from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.request import RequestStatus
logger = init_logger("vllm.v1.core.sched.scheduler")
if getattr(Scheduler._update_from_kv_xfer_finished, "_prime_rl_tolerates_freed", False):
return
def _update_from_kv_xfer_finished(self, kv_connector_output):
if self.connector is not None:
self.connector.update_connector_output(kv_connector_output)
for req_id in kv_connector_output.finished_recving or ():
logger.debug("Finished recving KV transfer for request %s", req_id)
# Stale notification for a request freed earlier this step (e.g. an
# aborted request whose send completion freed it). Nothing to do.
if req_id not in self.requests:
continue
req = self.requests[req_id]
if req.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
self.finished_recving_kv_req_ids.add(req_id)
else:
assert RequestStatus.is_finished(req.status)
self._free_blocks(self.requests[req_id])
for req_id in kv_connector_output.finished_sending or ():
logger.debug("Finished sending KV transfer for request %s", req_id)
# See above: the recving branch may have already freed an aborted
# request whose send also completed this step.
if req_id not in self.requests:
continue
self._free_blocks(self.requests[req_id])
_update_from_kv_xfer_finished._prime_rl_tolerates_freed = True
Scheduler._update_from_kv_xfer_finished = _update_from_kv_xfer_finished
logger.warning("Patched Scheduler._update_from_kv_xfer_finished to tolerate freed (aborted) KV-transfer reqs.")
def monkey_patch_nano_v3_reasoning_parser():
+29 -60
View File
@@ -5,8 +5,6 @@ from typing import TYPE_CHECKING, Callable
import torch
import verifiers as vf
from jaxtyping import Float
from torch import Tensor
if TYPE_CHECKING:
from prime_rl.orchestrator.types import TrainRollout
@@ -14,11 +12,9 @@ if TYPE_CHECKING:
from prime_rl.configs.orchestrator import (
AdvantageConfig,
CustomAdvantageConfig,
LengthPenaltyConfig,
TokensLengthPenaltyConfig,
TurnsLengthPenaltyConfig,
LinearLengthPenaltyConfig,
)
from prime_rl.orchestrator.utils import get_model_completion_len, get_tool_response_len
from prime_rl.orchestrator.utils import get_model_completion_len
from prime_rl.utils.utils import import_object
@@ -50,68 +46,36 @@ entry per rollout. `assign_advantages` calls it on one already-grouped cohort.
def default_advantage_fn(
inputs: AdvantageInputs,
length_penalty: LengthPenaltyConfig | None = None,
length_penalty: LinearLengthPenaltyConfig | None = None,
max_seq_len: int | None = None,
length_weighted_baseline: bool = False,
) -> AdvantageOutputs:
"""Default GRPO advantage for a single group: reward minus per-group baseline.
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
cost: tokens (weighted completion + tool-response) or trajectory turn count.
``length_penalty`` subtracts ``coef * pass_rate * (completion tokens / max_seq_len)``
from each reward (``pass_rate`` = group mean reward), optionally gated to correct
(``reward == 1``) rollouts. ``length_weighted_baseline`` uses the token-length-weighted
mean reward as the baseline instead of the plain mean.
"""
rewards = torch.tensor([r["reward"] for r in inputs.rollouts], dtype=torch.float32)
lengths = torch.tensor([get_model_completion_len(r) for r in inputs.rollouts], dtype=rewards.dtype)
if isinstance(length_penalty, TokensLengthPenaltyConfig):
w_c = length_penalty.completion_weight
w_t = length_penalty.tool_response_weight
costs = torch.tensor(
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in inputs.rollouts],
dtype=rewards.dtype,
)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
costs = torch.tensor([len(r["trajectory"]) for r in inputs.rollouts], dtype=rewards.dtype)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
if length_penalty is not None:
if max_seq_len is None:
raise ValueError("max_seq_len is required when length_penalty is enabled")
penalty = length_penalty.coef * rewards.mean() * (lengths / max_seq_len)
if length_penalty.gate_by_correctness:
penalty = penalty * rewards
rewards = rewards - penalty
return AdvantageOutputs(advantages=(rewards - rewards.mean()).tolist())
if length_weighted_baseline:
baseline = (lengths * rewards).sum() / lengths.sum()
else:
baseline = rewards.mean()
return AdvantageOutputs(advantages=(rewards - baseline).tolist())
def _efficiency_shaping(
rewards: Float[Tensor, "group_size"],
costs: Float[Tensor, "group_size"],
) -> Float[Tensor, "group_size"]:
"""Correctness-gated efficiency shaping with bounded advantages.
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
preserving zero-mean advantages within the group. `costs` is a per-rollout cost
(e.g., completion length in tokens or number of turns).
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
"""
max_reward = rewards.max()
correct_mask = rewards >= max_reward
num_correct = correct_mask.sum()
# No shaping when max reward is 0 — no correct rollouts to differentiate
if max_reward <= 0:
return rewards - rewards.mean()
# Mean cost of correct rollouts
mean_correct_cost = (costs * correct_mask).sum() / num_correct.clamp(min=1)
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
if mean_correct_cost <= 0:
return rewards - rewards.mean()
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
shaped_rewards = rewards * (1 + bonus * correct_mask)
return shaped_rewards - shaped_rewards.mean()
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
def setup_advantage_fn(config: AdvantageConfig, max_seq_len: int | None = None) -> AdvantageFn:
"""Setup advantage function from config."""
if isinstance(config, CustomAdvantageConfig):
custom_fn = import_object(config.import_path)
@@ -123,7 +87,12 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
return advantage_fn
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
return default_advantage_fn(inputs, length_penalty=config.length_penalty)
return default_advantage_fn(
inputs,
length_penalty=config.length_penalty,
max_seq_len=max_seq_len,
length_weighted_baseline=config.length_weighted_baseline,
)
return advantage_fn
+15 -6
View File
@@ -11,8 +11,9 @@
schedule next. Transitions are level-triggered (driven by the eval
source's emptiness), so in-flight rollouts of the opposite kind drain
naturally on either side of an eval boundary.
- ``on_new_version`` (called by the watcher) bumps ``off_policy_steps`` on
in-flight train rollouts and drops groups past ``max_off_policy_steps``.
- ``on_version_pending`` (called by the watcher before the engines pause for
the weight update) bumps ``off_policy_steps`` on in-flight train rollouts and
drops groups past ``max_off_policy_steps``.
Eval rollouts are measurements for the policy version they started with,
so they are allowed to finish even if training advances.
Cancellations surface as synthetic ``Cancelled`` markers so the sink's
@@ -116,7 +117,7 @@ class RolloutDispatcher:
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules
rollouts under shared capacity, and emits ``FinishedRollout``\\ s to
``out_q``. The watcher drives ``on_new_version`` for off-policy
``out_q``. The watcher drives ``on_version_pending`` for off-policy
cancellation; the orchestrator triggers eval epochs."""
def __init__(
@@ -263,11 +264,16 @@ class RolloutDispatcher:
await safe_cancel(self.task)
self.task = None
async def on_new_version(self, step: int) -> None:
async def on_version_pending(self, step: int) -> None:
"""Bump off-policy counters and drop groups past
``max_off_policy_steps`` (drop_group emits ``Cancelled`` markers so
the sink still finalizes the partial group). Eval rollouts are not
aged because they are tied to their start-time policy version."""
aged because they are tied to their start-time policy version.
Runs *before* the inference engines are paused for the weight update so
the resulting aborts are processed while the engine is still stepping —
otherwise the orphaned KV transfers crash the decode engine on resume
(see ``WeightWatcher.apply_policy_update``)."""
stale_groups: set[uuid.UUID] = set()
cancelled = 0
for meta in self.inflight.values():
@@ -287,6 +293,9 @@ class RolloutDispatcher:
"Consider increasing it to avoid this."
)
async def on_new_version(self, step: int) -> None:
"""No-op: the dispatcher drains in ``on_version_pending`` (pre-pause)."""
async def fill_inflight(self) -> None:
"""Schedule new rollouts up to ``max_inflight``, honoring
``self.mode``. Eval scheduling ignores the orchestrator's dispatch
@@ -602,7 +611,7 @@ class RolloutDispatcher:
# markers for those too so the sink hits ``target_rollouts``
#
# ``last_meta`` can be ``None`` if the only inflight task for this
# group completed naturally between ``on_new_version``'s snapshot
# group completed naturally between ``on_version_pending``'s snapshot
# and us reaching it — synthesize a stand-in from the group state
unscheduled_cancelled = 0
if group is not None and group.rollouts_to_schedule > 0:
+4 -4
View File
@@ -162,13 +162,13 @@ class Env:
class TrainEnv(Env):
config: TrainEnvConfig
def __init__(self, config: TrainEnvConfig):
def __init__(self, config: TrainEnvConfig, max_seq_len: int):
super().__init__(config)
self.sampling_args = config.sampling.to_sampling_args()
# Built once — custom advantage funcs do an ``import_object`` we don't
# want to pay per group. ``None`` = reward-only path.
self.advantage_fn: AdvantageFn | None = (
setup_advantage_fn(config.advantage) if config.advantage is not None else None
setup_advantage_fn(config.advantage, max_seq_len=max_seq_len) if config.advantage is not None else None
)
def get_dataset(self, seed: int | None = None):
@@ -246,10 +246,10 @@ class Envs(Generic[EnvT]):
class TrainEnvs(Envs[TrainEnv]):
"""Collection of training environments."""
def __init__(self, configs: Sequence[TrainEnvConfig]):
def __init__(self, configs: Sequence[TrainEnvConfig], max_seq_len: int):
self._envs: dict[str, TrainEnv] = {}
for config in configs:
env = TrainEnv(config)
env = TrainEnv(config, max_seq_len=max_seq_len)
self._envs[env.name] = env
+8 -6
View File
@@ -21,7 +21,6 @@ in ``setup()`` and drives them from ``main_loop()``.
from __future__ import annotations
import asyncio
import ctypes
import logging
import os
import time
@@ -72,6 +71,7 @@ from prime_rl.orchestrator.utils import (
save_rollouts,
set_default_executor,
setup_student_inference_pool,
trim_process_memory,
)
from prime_rl.orchestrator.watcher import WeightWatcher
from prime_rl.trainer.model import setup_tokenizer
@@ -268,7 +268,7 @@ class Orchestrator:
post_filters = setup_filters(config.post_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="post-batch")
get_logger().info("Loading training environments")
self.train_envs = TrainEnvs(config.train.env)
self.train_envs = TrainEnvs(config.train.env, max_seq_len=config.seq_len)
if config.training_mode == "sft":
for env in self.train_envs:
env.sampling_args.pop("logprobs", None)
@@ -482,10 +482,7 @@ class Orchestrator:
get_logger().success("Orchestrator finished.")
else:
get_logger().warning("Orchestrator cleanup complete (forced).")
try:
ctypes.CDLL("libc.so.6").malloc_trim(0)
except Exception as e:
get_logger().debug(f"malloc_trim(0) failed: {e}")
trim_process_memory()
async def main_loop(self) -> None:
"""Consume ``FinishedRollout``\\ s from the dispatcher and route them
@@ -614,6 +611,7 @@ class Orchestrator:
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
self.update_dispatch_gate()
trim_process_memory()
metrics = self.metrics.build(
step=step,
@@ -876,6 +874,10 @@ class Orchestrator:
get_logger().info("Resuming dispatcher")
gate.set()
async def on_version_pending(self, step: int) -> None:
"""No-op: the dispatch gate is re-evaluated in ``on_new_version`` once
the new policy version is live."""
async def on_new_version(self, step: int) -> None:
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
+7 -2
View File
@@ -202,7 +202,12 @@ class EvalBatch:
class VersionObserver(Protocol):
"""Notified after each policy update; walked by the watcher after it
mutates ``Policy``."""
"""Notified around each policy update; walked by the watcher.
``on_version_pending`` fires *before* the inference engines are paused for
the weight update; ``on_new_version`` fires *after* the new weights are live
and ``Policy`` has been mutated."""
async def on_version_pending(self, step: int) -> None: ...
async def on_new_version(self, step: int) -> None: ...
+11
View File
@@ -1,4 +1,6 @@
import asyncio
import ctypes
import gc
import logging
import time
from concurrent.futures import ThreadPoolExecutor
@@ -96,6 +98,15 @@ def set_default_executor(max_workers: int = 64) -> None:
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=max_workers))
def trim_process_memory() -> None:
"""Return freed heap pages to the OS on glibc systems."""
gc.collect()
try:
ctypes.CDLL("libc.so.6").malloc_trim(0)
except Exception as exc:
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
async def compute_teacher_logprobs(
clients: list[vf.ClientConfig],
model_name: str,
+18
View File
@@ -92,6 +92,24 @@ class WeightWatcher:
f"Orchestrator resumed: checkpoint {next_step} ready (after {format_time(self.last_wait_for_ckpt_time)})"
)
# Drain off-policy rollouts BEFORE pausing the inference engines.
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
# ``_reqs_not_processed``), which is only propagated to the workers
# while the engine is stepping. If we drain after resume instead,
# the aborts race with the flush of KV transfers that completed
# during the pause and trip ``assert req_id in self.requests`` in
# the decode scheduler's ``_update_from_kv_xfer_finished`` — killing
# the engine and cascading to every DP rank. Draining first lets the
# aborts settle under normal stepping. ``on_new_version`` (below)
# still runs post-update for observers that need the live version.
for observer in self.observers:
try:
await observer.on_version_pending(next_step)
except Exception as exc:
get_logger().warning(
f"Observer {type(observer).__name__}.on_version_pending({next_step}) raised: {exc!r}"
)
get_logger().debug(f"Updating weights to step {next_step}")
t1 = time.perf_counter()
await self.inference.update_weights(weights_path, lora_name=self.lora_name, step=next_step)
+8 -2
View File
@@ -15,14 +15,20 @@ rank_log() {
# launch_inference_rank <port> <cuda_visible_devices> <dp> <rpc_port> <vllm_extra_json|""> <nixl_side_channel_port|""> <log_file>
launch_inference_rank() {
local port="$1" gpus="$2" dp="$3" rpc="$4" extra="$5" nixl="$6" log="$7"
# Per-rank dir for the mooncake-store lookup ipc socket. It must be unique per process:
# external-LB runs one engine per process, all with data_parallel_rank_local 0, so the
# lookup socket name collides on bind if the dir is shared node-wide. $port is unique per
# rank on the node. Node-local /tmp also avoids inheriting an absent submit-node TMPDIR.
local rpcbase="/tmp/vllm-rpc-$USER-$SLURM_JOB_ID-$port"
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")
if [ -n "$nixl" ]; then
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" "${cmd[@]}" 2>&1 | tee -a "$log" &
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
else
CUDA_VISIBLE_DEVICES="$gpus" "${cmd[@]}" 2>&1 | tee -a "$log" &
CUDA_VISIBLE_DEVICES="$gpus" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
fi
}
+55 -4
View File
@@ -1,9 +1,59 @@
{# Shared router launch helper, included once per template and called by the
replica-head rank. vllm-router today; an llm-d (EPP+Envoy) branch can slot in
here so the call sites stay router-agnostic. #}
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log_file> [replica_idx]
replica-head rank. The router backend (vllm-router vs llm-d EPP+Envoy) is
chosen here via router.type, so the call sites stay router-agnostic.
node_base/node_count locate this replica's nodes in HOSTNAMES for llm-d
endpoint discovery (disagg uses NUM_PREFILL_NODES/NUM_DECODE_NODES). #}
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log> <replica_idx> <node_base> [node_count]
launch_router() {
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-}"
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-0}" node_base="${7:-0}" node_count="${8:-0}"
{%- if router.type == "llm-d" %}
echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port for replica $replica" | tee "$log"
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
local LLMD_DIR="$OUTPUT_DIR/logs/inference/llmd_${replica}"
mkdir -p "$LLMD_DIR"
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
{%- if is_disaggregated %}
{%- set ep_disaggregated = true %}
{%- set ep_num_prefill = num_prefill_nodes %}
{%- set ep_num_decode = num_decode_nodes %}
{%- set ep_dp = dp_per_node %}
{%- set ep_prefill_port = prefill_port %}
{%- set ep_sidecar_port = router.decode_sidecar_port %}
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
{% include 'llmd/epp_pd.yaml.j2' %}
LLMD_EOF
cat > "$LLMD_DIR/endpoints.yaml" <<LLMD_EOF
{% include 'llmd/endpoints.yaml.j2' %}
LLMD_EOF
local node=0 ip
for ((p=0; p<NUM_PREFILL_NODES; p++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + p))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
for ((d=0; d<NUM_DECODE_NODES; d++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + NUM_PREFILL_NODES + d))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
{%- else %}
{%- set ep_disaggregated = false %}
{%- set ep_num_nodes = infer_nodes_per_replica %}
{%- set ep_dp = dp_per_node %}
{%- set ep_backend_port = backend_port %}
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
{% include 'llmd/epp_estimate.yaml.j2' %}
LLMD_EOF
cat > "$LLMD_DIR/endpoints.yaml" <<LLMD_EOF
{% include 'llmd/endpoints.yaml.j2' %}
LLMD_EOF
local ip
for ((n=0; n<node_count; n++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + n))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${n}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; done
{%- endif %}
cat > "$LLMD_DIR/envoy.yaml" <<LLMD_EOF
{% include 'llmd/envoy.yaml.j2' %}
LLMD_EOF
# grpc-health-port avoids 9003: mooncake_master runs its metrics server on 9003 and
# shares the replica-head node with the EPP, so 9003 would fail to bind and kill the EPP.
epp --pool-name prime-rl --pool-namespace slurm \
--config-file "$LLMD_DIR/epp.yaml" \
--grpc-port 9002 --grpc-health-port 9013 --metrics-port 9090 \
--secure-serving=false --metrics-endpoint-auth=false --tracing=false \
>> "$log" 2>&1 &
envoy -c "$LLMD_DIR/envoy.yaml" >> "$log" 2>&1 &
{%- else %}
local tag="vllm-router"; [ "$mode" = pd ] && tag="vllm-router (PD)"
echo "Starting $tag on $LOCAL_IP:$port${replica:+ for replica $replica}" | tee "$log"
local -a cmd=(vllm-router --policy "$policy" --host 0.0.0.0 --port "$port"
@@ -14,4 +64,5 @@ launch_router() {
cmd+=(--worker-urls $worker_args)
fi
"${cmd[@]}" >> "$log" 2>&1 &
{%- endif %}
}
+6 -3
View File
@@ -5,7 +5,8 @@
SLURM templates inside the per-node `bash -c` body, so NO single quotes / apostrophes.
Requires shell vars: LOCAL_IP, INFER_NODE_RANK, OUTPUT_DIR (and SLURM env).
Requires jinja vars: kv_offload_cpu_bytes, kv_offload_disk_path, kv_offload_device_name.
Exports PYTHONHASHSEED + MOONCAKE_CONFIG_PATH for the vLLM process on this node. -#}
Exports PYTHONHASHSEED + MOONCAKE_CONFIG_PATH for the vLLM process. (VLLM_RPC_BASE_PATH,
used by the mooncake-store lookup ipc socket, is set per-rank in _launch_rank.sh.j2.) -#}
# ---- Mooncake distributed store (shared pool across inference nodes) ----
MC_DIR="$OUTPUT_DIR/mooncake/node_${INFER_NODE_RANK}"
mkdir -p "$MC_DIR"
@@ -23,9 +24,11 @@
{%- endif %}
if [ "$SLURMD_NODENAME" = "$MC_HEAD" ]; then
{%- if kv_offload_disk_path %}
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -enable_offload=true -root_fs_dir={{ kv_offload_disk_path }} > "$MC_DIR/master.log" 2>&1 &
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -default_kv_lease_ttl=3600000 -enable_offload=true -root_fs_dir={{ kv_offload_disk_path }} > "$MC_DIR/master.log" 2>&1 &
{%- else %}
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 > "$MC_DIR/master.log" 2>&1 &
# default_kv_lease_ttl raised from 5s: KV blocks were expiring before the decode side
# reused them ("invalid KV blocks ... may have expired"), the real non-NIC config issue.
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -default_kv_lease_ttl=3600000 > "$MC_DIR/master.log" 2>&1 &
{%- endif %}
fi
# Every node waits for the shared master + metadata, then contributes its segment.
+37 -10
View File
@@ -28,7 +28,7 @@ set -e
# Configs
export NUM_NODES={{ num_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
{% if disaggregated -%}
{% if is_disaggregated -%}
export NUM_PREFILL_NODES={{ num_prefill_nodes }}
export NUM_DECODE_NODES={{ num_decode_nodes }}
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
@@ -38,10 +38,13 @@ export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
export PREFILL_PORT={{ prefill_port }}
export DECODE_PORT={{ decode_port }}
export ROUTER_PORT={{ router_port }}
export ROUTER_PORT={{ router.port }}
export RPC_PORT={{ data_parallel_rpc_port }}
{%- if router.type == "llm-d" %}
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
{%- endif %}
{%- elif num_nodes > 1 %}
export ROUTER_PORT={{ router_port }}
export ROUTER_PORT={{ router.port }}
export BACKEND_PORT={{ backend_port }}
export RPC_PORT={{ data_parallel_rpc_port }}
{%- endif %}
@@ -70,7 +73,7 @@ uv sync --all-extras
# Print inference URLs
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
export HOSTNAMES_STR="${HOSTNAMES[*]}"
{% if disaggregated -%}
{% if is_disaggregated -%}
# Build per-replica router URLs
INFER_URLS=""
ALL_ROUTER_ARGS=""
@@ -132,6 +135,10 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[t]orchrun" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
# llm-d router procs (EPP + Envoy + decode pd-sidecar) left over from a prior run.
pkill -9 -f "[e]pp.*pool-name" 2>/dev/null
pkill -9 -f "[e]nvoy.*envoy.yaml" 2>/dev/null
pkill -9 -f "[p]d-sidecar" 2>/dev/null
pkill -9 -f "[v]llm" 2>/dev/null
pkill -9 -f "[p]rime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
@@ -144,7 +151,7 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -x mooncake_client 2>/dev/null
sleep 2
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
CLEANUP_SH
@@ -179,7 +186,7 @@ srun --kill-on-bad-exit=1 bash -c '
{% include "_mooncake_store.sh.j2" %}
{%- endif %}
{% if disaggregated -%}
{% if is_disaggregated -%}
# NVSHMEM libs for DeepEP — ensure the rpath target exists on all nodes
if [ ! -d /tmp/deepep_build/nvshmem/lib ] && [ -d "$OUTPUT_DIR/nvshmem/lib" ]; then
mkdir -p /tmp/deepep_build/nvshmem
@@ -247,7 +254,7 @@ srun --kill-on-bad-exit=1 bash -c '
{% for key, value in prefill_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
else
# ── Decode node ──
export UCX_NET_DEVICES=mlx5_0:1
@@ -262,7 +269,7 @@ srun --kill-on-bad-exit=1 bash -c '
{% for key, value in decode_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
fi
echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT LOCAL_IP=$LOCAL_IP" \
@@ -271,8 +278,28 @@ srun --kill-on-bad-exit=1 bash -c '
# Start the router on the first prefill node of each replica (external LB across per-rank endpoints)
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router_policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
fi
{%- if router.type == "llm-d" %}
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
# + rank) -> vLLM decode (DECODE_PORT + rank) after orchestrating remote prefill.
# Every decode node fronts its own local ranks, so launch on each (not just the
# replica head), or decode nodes beyond the head get advertised but unserved endpoints.
if [ "$ROLE" = "decode" ]; then
SIDECAR_LOG="$OUTPUT_DIR/logs/inference/sidecar_${INFER_NODE_RANK}.log"
echo "Starting pd-sidecar on $LOCAL_IP:$DECODE_SIDECAR_PORT(+rank) -> vLLM $DECODE_PORT(+rank)" | tee $SIDECAR_LOG
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
pd-sidecar \
--port $DECODE_SIDECAR_PORT \
--vllm-port $DECODE_PORT \
--kv-connector nixlv2 \
--secure-proxy=false \
--enable-ssrf-protection=false \
--inference-pool prime-rl \
--data-parallel-size {{ dp_per_node }} \
>> $SIDECAR_LOG 2>&1 &
fi
{%- endif %}
# 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
@@ -296,7 +323,7 @@ srun --kill-on-bad-exit=1 bash -c '
# Start the router on node 0 (balances across per-rank endpoints — no intra-node DP header)
if [ "$INFER_NODE_RANK" -eq 0 ]; then
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router_policy }}" "$OUTPUT_DIR/logs/inference/router.log"
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log" 0 0 "$NUM_NODES"
fi
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
@@ -0,0 +1,41 @@
{# llm-d file-discovery endpoints: one entry per DP rank. Rendered (via include)
into the sbatch; the per-node address is the __LLMD_ADDR_<node>__ placeholder,
filled with each SLURM host's IPv4 inline in the sbatch (file-discovery rejects
hostnames). Node ordering matches the sbatch's host loop: prefill then decode.
The including sbatch sets ep_* via {% set %}. #}
endpoints:
{%- if ep_disaggregated %}
{%- for node in range(ep_num_prefill) %}
{%- for rank in range(ep_dp) %}
- name: prefill-{{ node }}-rank-{{ rank }}
address: __LLMD_ADDR_{{ node }}__
port: "{{ ep_prefill_port + rank }}"
namespace: default
labels:
llm-d.ai/pool: prime-rl
llm-d.ai/role: prefill
{%- endfor %}
{%- endfor %}
{%- for node in range(ep_num_decode) %}
{%- for rank in range(ep_dp) %}
- name: decode-{{ node }}-rank-{{ rank }}
address: __LLMD_ADDR_{{ ep_num_prefill + node }}__
port: "{{ ep_sidecar_port + rank }}"
namespace: default
labels:
llm-d.ai/pool: prime-rl
llm-d.ai/role: decode
{%- endfor %}
{%- endfor %}
{%- else %}
{%- for node in range(ep_num_nodes) %}
{%- for rank in range(ep_dp) %}
- name: backend-{{ node }}-rank-{{ rank }}
address: __LLMD_ADDR_{{ node }}__
port: "{{ ep_backend_port + rank }}"
namespace: default
labels:
llm-d.ai/pool: prime-rl
{%- endfor %}
{%- endfor %}
{%- endif %}
+97
View File
@@ -0,0 +1,97 @@
{# Envoy data plane: EPP picks the backend (ext_proc) and sets
x-gateway-destination-endpoint; the ORIGINAL_DST cluster routes there. Both
/v1/ (MITO) and /inference/v1/ (TITO) go through the picker. EPP gRPC is on
loopback 9002; the gateway listens on the configured port. #}
admin:
address: { socket_address: { address: 127.0.0.1, port_value: 9901 } }
static_resources:
listeners:
- name: prime_rl
address: { socket_address: { address: 0.0.0.0, port_value: {{ router.port }} } }
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: prime_rl
codec_type: AUTO
stream_idle_timeout: 0s
request_timeout: 0s
route_config:
virtual_hosts:
- name: prime_rl
domains: ["*"]
routes:
- match: { prefix: "/v1/" }
route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s }
- match: { prefix: "/inference/v1/" }
route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s }
http_filters:
- name: envoy.filters.http.ext_proc
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.ext_proc.v3.ExternalProcessor
grpc_service:
envoy_grpc: { cluster_name: epp_cluster }
timeout: 10s
processing_mode:
request_header_mode: SEND
response_header_mode: SEND
request_body_mode: FULL_DUPLEX_STREAMED
response_body_mode: FULL_DUPLEX_STREAMED
request_trailer_mode: SEND
response_trailer_mode: SEND
message_timeout: 1000s
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
suppress_envoy_headers: true
clusters:
- name: backend_cluster
type: ORIGINAL_DST
lb_policy: CLUSTER_PROVIDED
original_dst_lb_config:
use_http_header: true
http_header_name: x-gateway-destination-endpoint
connect_timeout: 5s
# Default circuit breakers (~1024) overflow at high inflight concurrency (>=1536),
# causing "reset reason: overflow" 500s. Raise far above the max concurrent rollouts.
circuit_breakers:
thresholds:
- priority: DEFAULT
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
- priority: HIGH
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
- name: epp_cluster
type: STRICT_DNS
typed_extension_protocol_options:
envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
"@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
explicit_http_config:
http2_protocol_options: {}
load_assignment:
cluster_name: epp_cluster
endpoints:
- lb_endpoints:
- endpoint:
address: { socket_address: { address: 127.0.0.1, port_value: 9002 } }
connect_timeout: 5s
# ext_proc (EPP) connection pool overflows at high concurrency without this — the
# gRPC ext_proc calls are 1:1 with inflight requests, so cap well above max rollouts.
circuit_breakers:
thresholds:
- priority: DEFAULT
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
- priority: HIGH
max_connections: 100000
max_pending_requests: 100000
max_requests: 100000
max_retries: 1000
@@ -0,0 +1,34 @@
{# llm-d EPP config: single-pool (non-P/D) routing with approximate prefix-cache
scoring. The vllmhttp parser embeds the OpenAI parser and also handles
/inference/v1/generate (token_ids), so MITO + TITO both get prefix-cache
scoring. Included into the sbatch as a heredoc; $LLMD_DIR is the per-replica
config dir, expanded at launch time. #}
apiVersion: inference.networking.x-k8s.io/v1alpha1
kind: EndpointPickerConfig
plugins:
- name: file-disc
type: file-discovery
parameters:
path: $LLMD_DIR/endpoints.yaml
watchFile: true
- name: vllmhttp-parser
type: vllmhttp-parser
{%- for scorer in router.scorers %}
- type: {{ scorer }}
{%- endfor %}
- type: max-score-picker
- type: single-profile-handler
schedulingProfiles:
- name: default
plugins:
{%- for scorer, weight in router.scorers.items() %}
- pluginRef: {{ scorer }}
weight: {{ weight }}
{%- endfor %}
- pluginRef: max-score-picker
requestHandler:
parser:
pluginRef: vllmhttp-parser
dataLayer:
discovery:
pluginRef: file-disc
@@ -0,0 +1,56 @@
{# llm-d EPP config: prefill/decode disaggregation. disagg-profile-handler runs
the prefill profile when prefix-based-pd-decider sees >= nonCachedTokens
non-cached prompt tokens, else decode-only. Mirrors the upstream llm-d PD
guide: the prefill profile uses prefill_scorers (prefix + queue/kv) and the
decode profile uses scorers (prefix + active-request); prefill-filter /
decode-filter select endpoints by llm-d.ai/role label. Included into the
sbatch as a heredoc; $LLMD_DIR is the per-replica config dir, expanded at
launch time. #}
apiVersion: inference.networking.x-k8s.io/v1alpha1
kind: EndpointPickerConfig
plugins:
- name: file-disc
type: file-discovery
parameters:
path: $LLMD_DIR/endpoints.yaml
watchFile: true
- name: vllmhttp-parser
type: vllmhttp-parser
- name: pd-decider
type: prefix-based-pd-decider
parameters:
nonCachedTokens: {{ router.non_cached_tokens }}
- name: profile-handler
type: disagg-profile-handler
parameters:
deciders:
prefill: pd-decider
- type: prefill-filter
- type: decode-filter
{%- for scorer in ((router.prefill_scorers.keys() | list) + (router.decode_scorers.keys() | list)) | unique %}
- type: {{ scorer }}
{%- endfor %}
- type: max-score-picker
schedulingProfiles:
- name: prefill
plugins:
- pluginRef: prefill-filter
{%- for scorer, weight in router.prefill_scorers.items() %}
- pluginRef: {{ scorer }}
weight: {{ weight }}
{%- endfor %}
- pluginRef: max-score-picker
- name: decode
plugins:
- pluginRef: decode-filter
{%- for scorer, weight in router.decode_scorers.items() %}
- pluginRef: {{ scorer }}
weight: {{ weight }}
{%- endfor %}
- pluginRef: max-score-picker
requestHandler:
parser:
pluginRef: vllmhttp-parser
dataLayer:
discovery:
pluginRef: file-disc
+33 -6
View File
@@ -32,7 +32,7 @@ export NODES_PER_INFER_REPLICA={{ nodes_per_infer_replica }}
export NUM_INFER_REPLICAS={{ num_infer_replicas }}
export GPUS_PER_NODE={{ gpus_per_node }}
{% if num_infer_nodes > 0 -%}
export ROUTER_PORT={{ router_port }}
export ROUTER_PORT={{ router.port }}
export INFERENCE_TP={{ inference_tp }}
export INFERENCE_DP_LOCAL=$((GPUS_PER_NODE / INFERENCE_TP))
export INFERENCE_DATA_PARALLEL_RPC_PORT={{ inference_data_parallel_rpc_port }}
@@ -45,6 +45,9 @@ export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
export PREFILL_PORT={{ prefill_port }}
export DECODE_PORT={{ decode_port }}
{%- if router.type == "llm-d" %}
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
{%- endif %}
{%- else -%}
export BACKEND_PORT={{ backend_port }}
export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parallel else "0" }}
@@ -166,6 +169,10 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[t]orchrun" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
# llm-d router procs (EPP + Envoy + decode pd-sidecar) left over from a prior run.
pkill -9 -f "[e]pp.*pool-name" 2>/dev/null
pkill -9 -f "[e]nvoy.*envoy.yaml" 2>/dev/null
pkill -9 -f "[p]d-sidecar" 2>/dev/null
pkill -9 -f "[v]llm" 2>/dev/null
pkill -9 -f "[p]rime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
@@ -178,7 +185,7 @@ srun bash -s <<'CLEANUP_SH'
pkill -9 -x mooncake_client 2>/dev/null
sleep 2
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
CLEANUP_SH
@@ -284,7 +291,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
{% for key, value in prefill_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
else
export UCX_NET_DEVICES=mlx5_0:1
ROLE="decode"
@@ -298,7 +305,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
{% for key, value in decode_env_overrides.items() %}
export {{ key }}="{{ value }}"
{% endfor %}
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
fi
echo "ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT" \
@@ -307,8 +314,28 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
# Start the router on the first node of each replica (PD mode, external LB across per-rank endpoints)
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
fi
{%- if router.type == "llm-d" %}
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
# + rank) -> vLLM decode (DECODE_PORT + rank) after orchestrating remote prefill.
# Every decode node fronts its own local ranks, so launch on each (not just the
# replica head), or decode nodes beyond the head get advertised but unserved endpoints.
if [ "$ROLE" = "decode" ]; then
SIDECAR_LOG="$OUTPUT_DIR/logs/inference/sidecar_${INFER_NODE_RANK}.log"
echo "Starting pd-sidecar on $LOCAL_IP:$DECODE_SIDECAR_PORT(+rank) -> vLLM $DECODE_PORT(+rank)" | tee $SIDECAR_LOG
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
pd-sidecar \
--port $DECODE_SIDECAR_PORT \
--vllm-port $DECODE_PORT \
--kv-connector nixlv2 \
--secure-proxy=false \
--enable-ssrf-protection=false \
--inference-pool prime-rl \
--data-parallel-size $INFERENCE_DP_LOCAL \
>> $SIDECAR_LOG 2>&1 &
fi
{%- endif %}
# 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
@@ -325,7 +352,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
# Start the router on the first node of each replica
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
launch_router regular "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
launch_router regular "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$((REPLICA_IDX * NODES_PER_INFER_REPLICA))" "$NODES_PER_INFER_REPLICA"
fi
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + d),
+12
View File
@@ -510,6 +510,18 @@ def get_model(
model_config.use_index_cache = True
model_config.index_topk_freq = config.index_cache.topk_freq
model_config.index_topk_pattern = config.index_cache.topk_pattern
# Explicit override supersedes the model's native IndexShare schedule.
model_config.indexer_types = None
else:
# Auto-enable IndexShare from the model's own indexer schedule (e.g. GLM-5.2). The model
# reads `indexer_types` directly: shared layers reuse cached indices and carry no indexer weights.
indexer_types = getattr(model_config, "indexer_types", None)
if indexer_types and any(t == "shared" for t in indexer_types):
model_config.use_index_cache = True
logger.info(
f"Auto-enabled IndexShare from indexer_types schedule "
f"({sum(t == 'full' for t in indexer_types)}/{len(indexer_types)} full layers)"
)
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
@@ -11,6 +11,10 @@ def _index_cache_skip_topk(config, layer_idx: int) -> bool:
if index_topk_pattern is not None:
return layer_idx < len(index_topk_pattern) and index_topk_pattern[layer_idx] == "S"
indexer_types = getattr(config, "indexer_types", None)
if indexer_types is not None:
return layer_idx < len(indexer_types) and indexer_types[layer_idx] == "shared"
return layer_idx % getattr(config, "index_topk_freq", 1) != 0
@@ -162,6 +166,7 @@ class GlmMoeDsaConfig(PretrainedConfig):
use_index_cache=False,
index_topk_freq=1,
index_topk_pattern=None,
indexer_types=None,
scoring_func="sigmoid",
topk_method="noaux_tc",
use_grouped_mm=True,
@@ -218,6 +223,7 @@ class GlmMoeDsaConfig(PretrainedConfig):
self.use_index_cache = use_index_cache
self.index_topk_freq = index_topk_freq
self.index_topk_pattern = index_topk_pattern
self.indexer_types = indexer_types
self.scoring_func = scoring_func
self.topk_method = topk_method
self.use_grouped_mm = use_grouped_mm
@@ -226,6 +232,10 @@ class GlmMoeDsaConfig(PretrainedConfig):
if not self.use_grouped_mm:
warnings.warn("not using grouped mm for moe is very slow, should only be used for debugging")
# head_dim is derived from qk_rope_head_dim (the RoPE slice). Some checkpoints (e.g. GLM-5.2)
# set head_dim=qk_nope_head_dim in config.json; drop it so PretrainedConfig.__init__ can't
# overwrite self.head_dim and break the rotary embedding dimension.
kwargs.pop("head_dim", None)
super().__init__(
pad_token_id=pad_token_id,
tie_word_embeddings=tie_word_embeddings,
@@ -158,7 +158,8 @@ class GlmMoeDsaAttention(nn.Module):
)
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, args.hidden_size, bias=args.attention_bias)
self.indexer = Indexer(args)
# IndexShare (GLM-5.2): layers that reuse cached indices carry no indexer weights.
self.indexer = Indexer(args) if not args.skip_topk else None
self.use_index_cache = args.use_index_cache
self.skip_topk = args.skip_topk
self.scaling = self.qk_head_dim ** (-0.5)
@@ -8,6 +8,7 @@ import torch.nn as nn
from torch import Tensor
from prime_rl.utils.logger import get_logger
from prime_rl.utils.vlm import get_final_logit_softcapping
FUSED_CE_IGNORE_INDEX = -100
@@ -299,8 +300,8 @@ def inject_prime_lm_head(
logger = get_logger()
# Check for Gemma-style softcapping - dispatch to specialized implementation
final_logit_softcapping = getattr(model.config, "final_logit_softcapping", None)
# Check for Gemma-style softcapping - dispatch to specialized implementation.
final_logit_softcapping = get_final_logit_softcapping(model.config)
if final_logit_softcapping:
if fused_cross_entropy == "quack":
raise ValueError(
+11
View File
@@ -29,6 +29,7 @@ VLM_REGISTRY: dict[str, VLMModelInfo] = {
"qwen3_5": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"qwen3_5_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"qwen3_vl_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
"gemma4": VLMModelInfo(vision_encoder_attr="model.vision_tower", language_model_attr="model.language_model"),
}
# Text-only default
@@ -86,6 +87,16 @@ def is_vlm_architecture(model_config: PretrainedConfig) -> bool:
return _get_model_info_from_config(model_config) is not None
def get_final_logit_softcapping(model_config: PretrainedConfig) -> float | None:
"""Read ``final_logit_softcapping`` from the text config.
For composite VLM configs (e.g. Gemma) the value lives under ``text_config``;
``get_text_config()`` returns that for VLMs and the config itself for text-only
models, so a plain top-level ``getattr`` would miss it and silently drop softcapping.
"""
return getattr(model_config.get_text_config(), "final_logit_softcapping", None)
def get_layer_prefix(model_config: PretrainedConfig, override: str | None = None) -> str:
"""Return the weight key prefix for language model layers.
+124 -190
View File
@@ -1,4 +1,3 @@
import math
import uuid
import pytest
@@ -6,8 +5,8 @@ import pytest
from prime_rl.configs.orchestrator import (
CustomAdvantageConfig,
DefaultAdvantageConfig,
TokensLengthPenaltyConfig,
TurnsLengthPenaltyConfig,
LinearLengthPenaltyConfig,
OrchestratorConfig,
)
from prime_rl.orchestrator.advantage import (
AdvantageInputs,
@@ -16,48 +15,29 @@ from prime_rl.orchestrator.advantage import (
default_advantage_fn,
setup_advantage_fn,
)
from prime_rl.orchestrator.envs import Env, TrainEnv
from prime_rl.orchestrator.types import TrainRollout
def _make_rollout(
reward: float,
completion_len: int = 0,
num_turns: int = 1,
env_name: str = "test",
example_id: int = 0,
) -> dict:
"""Create a minimal rollout dict for advantage testing.
`completion_len` tokens are split across `num_turns` trajectory steps.
"""
per_turn, rem = divmod(completion_len, max(num_turns, 1))
trajectory = [
{"tokens": {"prompt_ids": [0], "completion_ids": list(range(per_turn + (rem if i == 0 else 0)))}}
for i in range(num_turns)
]
def _make_rollout(reward: float, completion_len: int = 0) -> dict:
"""Minimal single-turn rollout dict with ``completion_len`` completion tokens."""
return {
"reward": reward,
"trajectory": trajectory,
"env_name": env_name,
"example_id": example_id,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(completion_len))}}],
"env_name": "test",
"example_id": 0,
}
def _make_group(rewards, completion_lengths=None, num_turns=None) -> AdvantageInputs:
"""Build single-group AdvantageInputs from 1D arrays of rewards/lengths/turns."""
def _make_group(rewards, completion_lengths=None) -> AdvantageInputs:
"""Build single-group AdvantageInputs from 1D arrays of rewards/lengths."""
rollouts = []
for i, reward in enumerate(rewards):
cl = int(completion_lengths[i]) if completion_lengths is not None else 0
nt = int(num_turns[i]) if num_turns is not None else 1
rollouts.append(_make_rollout(float(reward), cl, nt))
rollouts.append(_make_rollout(float(reward), cl))
return AdvantageInputs(rollouts=rollouts)
# Helper aliases for readability — completion-only and tool-only token shaping.
_TOKENS_COMPLETION = TokensLengthPenaltyConfig(completion_weight=1.0, tool_response_weight=0.0)
_TOKENS_TOOL_ONLY = TokensLengthPenaltyConfig(completion_weight=0.0, tool_response_weight=1.0)
def test_default_advantage_fn_simple_mean():
inputs = _make_group(rewards=[1.0, 0.5, 0.8], completion_lengths=[10, 12, 8])
result = default_advantage_fn(inputs)
@@ -66,187 +46,141 @@ def test_default_advantage_fn_simple_mean():
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
def test_efficiency_mixed_group():
"""Mixed group: reward shaping preserves zero-mean, shorter correct gets higher advantage."""
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
def test_linear_length_penalty_scales_by_pass_rate():
"""Linear penalty subtracts coef * pass_rate * (completion tokens / max_seq_len), then mean-centers.
# mean_correct_len = (10+30+20)/3 = 20
# bonus = clamp(1 - [10,30,20,20]/20, 0, 1) = [0.5, 0, 0, 0]
# shaped_rewards = R * (1 + bonus * correct_mask) = [1.5, 1, 0, 1]
# baseline = mean(shaped_rewards) = 0.875
# A = shaped_rewards - baseline = [0.625, 0.125, -0.875, 0.125]
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
``pass_rate`` is the group's mean reward, so a half-solved group scales the penalty by 0.5.
"""
rewards = [1.0, 1.0, 0.0, 0.0]
inputs = _make_group(rewards=rewards, completion_lengths=[10, 20, 30, 40])
result = default_advantage_fn(inputs, length_penalty=LinearLengthPenaltyConfig(coef=2.0), max_seq_len=100)
# Zero-mean per group
pass_rate = sum(rewards) / len(rewards) # 0.5
penalized = [r - 2.0 * pass_rate * (length / 100) for r, length in zip(rewards, (10, 20, 30, 40))]
mean = sum(penalized) / len(penalized)
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
# Zero-mean per group, and within each reward tier shorter output → higher advantage
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
# All correct rollouts have positive advantage
for rollout, adv in zip(inputs.rollouts, result.advantages):
if rollout["reward"] >= 1.0:
assert adv > 0
assert result.advantages[0] > result.advantages[1]
assert result.advantages[2] > result.advantages[3]
def test_efficiency_all_correct_group():
"""All-correct group: zero-mean, shorter gets higher advantage."""
inputs = _make_group(rewards=[1.0, 1.0, 1.0], completion_lengths=[10, 20, 40])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
# mean_len = 70/3 ≈ 23.33
# bonus = clamp(1 - [10, 20, 40] / (70/3), 0, 1) = [4/7, 1/7, 0]
# shaped_rewards = [1+4/7, 1+1/7, 1] = [11/7, 8/7, 1]
shaped = [11.0 / 7, 8.0 / 7, 1.0]
mean_shaped = sum(shaped) / len(shaped)
expected = [s - mean_shaped for s in shaped]
assert result.advantages == pytest.approx(expected, abs=1e-6)
# Zero-mean
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
# Shortest has highest advantage
assert result.advantages[0] > result.advantages[1] > result.advantages[2]
def test_linear_length_penalty_zero_pass_rate_disables_penalty():
"""A never-solved group (mean reward 0) gets no length pressure — falls back to plain GRPO."""
inputs = _make_group(rewards=[0.0, 0.0, 0.0], completion_lengths=[10, 50, 200])
penalized = default_advantage_fn(inputs, length_penalty=LinearLengthPenaltyConfig(coef=5.0), max_seq_len=100)
plain = default_advantage_fn(inputs)
assert penalized.advantages == pytest.approx(plain.advantages, abs=1e-6)
def test_efficiency_all_zero_rewards():
"""When all rewards are 0, no length shaping — falls back to standard GRPO."""
inputs = _make_group(rewards=[0.0, 0.0, 0.0], completion_lengths=[10, 20, 15])
result_with = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
result_without = default_advantage_fn(inputs)
def test_linear_length_penalty_gate_by_correctness():
"""Gating scales each rollout's penalty by its reward, so reward-0 rollouts are untouched."""
rewards = [1.0, 1.0, 0.0, 0.0]
inputs = _make_group(rewards=rewards, completion_lengths=[10, 20, 30, 40])
cfg = LinearLengthPenaltyConfig(coef=2.0, gate_by_correctness=True)
result = default_advantage_fn(inputs, length_penalty=cfg, max_seq_len=100)
assert result_with.advantages == pytest.approx(result_without.advantages, abs=1e-6)
pass_rate = sum(rewards) / len(rewards) # 0.5
penalized = [r - r * 2.0 * pass_rate * (length / 100) for r, length in zip(rewards, (10, 20, 30, 40))]
mean = sum(penalized) / len(penalized)
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
def test_efficiency_single_correct():
"""Single correct rollout: bonus=0 (at its own mean), same as standard GRPO."""
inputs = _make_group(rewards=[1.0, 0.0, 0.0, 0.0], completion_lengths=[100, 50, 200, 150])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
def test_setup_advantage_fn_threads_max_seq_len():
"""``setup_advantage_fn`` threads ``max_seq_len`` into the linear penalty denominator."""
rewards = [1.0, 1.0]
inputs = _make_group(rewards=rewards, completion_lengths=[10, 30])
fn = setup_advantage_fn(DefaultAdvantageConfig(length_penalty=LinearLengthPenaltyConfig(coef=1.0)), max_seq_len=100)
result = fn(inputs)
assert result.advantages == pytest.approx([0.75, -0.25, -0.25, -0.25], abs=1e-6)
pass_rate = sum(rewards) / len(rewards) # 1.0
penalized = [1.0 - 1.0 * pass_rate * (length / 100) for length in (10, 30)]
mean = sum(penalized) / len(penalized)
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
def test_efficiency_shorter_correct_higher_advantage():
"""Among correct rollouts in a mixed group, shorter always gets higher advantage."""
inputs = _make_group(rewards=[1.0, 1.0, 1.0, 0.0, 0.0], completion_lengths=[50, 100, 200, 80, 120])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
def test_train_env_threads_max_seq_len_into_advantage_fn(monkeypatch):
"""TrainEnv-built advantage funcs use orchestrator seq_len for length penalties."""
advs = result.advantages
assert advs[0] > advs[1] > advs[2]
assert all(a > 0 for a in advs[:3])
assert all(a < 0 for a in advs[3:])
def fake_env_init(self, config):
self.config = config
self._env = None
self._env_client = None
self._env_server_process = None
def test_efficiency_zero_mean_per_group():
"""Reward shaping preserves zero-mean advantages within each group."""
mixed = default_advantage_fn(
_make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20]),
length_penalty=_TOKENS_COMPLETION,
)
all_correct = default_advantage_fn(
_make_group(rewards=[1.0, 1.0, 1.0, 1.0], completion_lengths=[10, 20, 40, 80]),
length_penalty=_TOKENS_COMPLETION,
monkeypatch.setattr(Env, "__init__", fake_env_init)
config = OrchestratorConfig(
seq_len=100,
advantage={"type": "default", "length_penalty": {"coef": 1.0}},
)
assert sum(mixed.advantages) == pytest.approx(0.0, abs=1e-6)
assert sum(all_correct.advantages) == pytest.approx(0.0, abs=1e-6)
env = TrainEnv(config.train.env[0], max_seq_len=config.seq_len)
assert env.advantage_fn is not None
result = env.advantage_fn(_make_group(rewards=[1.0, 1.0], completion_lengths=[10, 30]))
assert result.advantages == pytest.approx([0.1, -0.1], abs=1e-6)
def test_efficiency_amplification_bounded():
"""Even with extreme length outliers, reward amplification is capped at 2x."""
inputs = _make_group(rewards=[1.0, 1.0, 0.0], completion_lengths=[1, 10000, 5000])
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
# Shortest correct gets bonus ≈ 1, so shaped_reward ≈ 2
# Standard reward = 1, so amplification ≈ 2x
# shaped_rewards ≈ [2, 1, 0], baseline ≈ 1, max advantage ≈ 1
assert result.advantages[0] < 1.0 + 1e-3
def test_efficiency_tokens_with_tool_response_weight():
"""`tool_response_weight` shifts shaping onto tool-response tokens read from rollout metrics."""
rollouts = [
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 200},
def test_per_env_linear_advantage_uses_runtime_schema():
config = OrchestratorConfig(
seq_len=100,
train={
"env": [
{
"advantage": {
"type": "default",
"length_penalty": {"coef": 1.0},
},
}
],
},
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 0},
},
{
"reward": 1.0,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
"metrics": {"rlm_total_tool_response_tokens": 100},
},
]
inputs = AdvantageInputs(rollouts=rollouts)
# completion tokens identical (10 each) → completion-only shaping is a no-op
result_completion_only = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
assert result_completion_only.advantages == pytest.approx([0.0, 0.0, 0.0], abs=1e-6)
# tool-response only: costs are [200, 0, 100], mean=100, bonus is one-sided
# so only the below-mean rollout (idx 1) gets amplified; the at/above-mean tie.
result_tool_only = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
advs = result_tool_only.advantages
assert advs[1] > advs[0]
assert advs[1] > advs[2]
assert advs[0] == pytest.approx(advs[2], abs=1e-6)
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
def test_efficiency_fractional_weight_with_int_rewards():
"""Fractional weights must not truncate when rollout rewards are emitted as ints."""
rollouts_int = [
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(7))}}]},
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(11))}}]},
{"reward": 0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(13))}}]},
]
rollouts_float = [{**r, "reward": float(r["reward"])} for r in rollouts_int]
fractional = TokensLengthPenaltyConfig(completion_weight=0.3, tool_response_weight=0.0)
int_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_int), length_penalty=fractional)
float_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_float), length_penalty=fractional)
assert int_result.advantages == pytest.approx(float_result.advantages, abs=1e-6)
def test_efficiency_zero_costs_falls_back_to_plain_grpo():
"""When all effective costs are zero, shaping is a no-op (no NaNs from div-by-zero)."""
# tool-only weights but no harness metric → all costs == 0
rollouts = [
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
{"reward": 0.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
]
inputs = AdvantageInputs(rollouts=rollouts)
result = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
expected = default_advantage_fn(inputs) # plain GRPO
assert not any(math.isnan(a) for a in result.advantages)
assert result.advantages == pytest.approx(expected.advantages, abs=1e-6)
def test_efficiency_tokens_default_weights_match_completion_when_no_metric():
"""Default TokensLengthPenaltyConfig (1,1) reduces to completion-only when rollouts lack the metric."""
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
result_default = default_advantage_fn(inputs, length_penalty=TokensLengthPenaltyConfig())
result_completion = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
assert result_default.advantages == pytest.approx(result_completion.advantages, abs=1e-6)
def test_efficiency_turns_penalty():
"""`TurnsLengthPenaltyConfig` shapes by trajectory turn count rather than token count."""
inputs = _make_group(
rewards=[1.0, 1.0, 0.0, 1.0],
# token counts identical, but turns differ — turns penalty should still differentiate
completion_lengths=[100, 100, 100, 100],
num_turns=[1, 3, 2, 2],
)
result = default_advantage_fn(inputs, length_penalty=TurnsLengthPenaltyConfig())
# mean_correct_turns = (1+3+2)/3 = 2
# bonus = clamp(1 - [1,3,2,2]/2, 0, 1) = [0.5, 0, 0, 0]
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
advantage = config.train.env[0].advantage
assert isinstance(advantage, DefaultAdvantageConfig)
assert isinstance(advantage.length_penalty, LinearLengthPenaltyConfig)
fn = setup_advantage_fn(advantage, max_seq_len=config.seq_len)
result = fn(_make_group(rewards=[1.0, 1.0], completion_lengths=[10, 30]))
assert result.advantages == pytest.approx([0.1, -0.1], abs=1e-6)
def test_per_env_custom_advantage_uses_runtime_schema():
config = OrchestratorConfig(
train={
"env": [
{
"advantage": {
"type": "custom",
"import_path": "tests.unit.orchestrator.test_advantage._dummy_custom_advantage",
"kwargs": {"scale": 3.0},
},
}
],
},
)
advantage = config.train.env[0].advantage
assert isinstance(advantage, CustomAdvantageConfig)
fn = setup_advantage_fn(advantage)
result = fn(_make_group(rewards=[1.0, 0.5], completion_lengths=[10, 20]))
assert result.advantages == pytest.approx([3.0, 1.5], abs=1e-6)
def test_length_weighted_baseline():
"""Length-weighted baseline uses sum(len_i * reward_i) / sum(len_i) instead of the plain mean."""
rewards = [1.0, 0.0, 0.0]
inputs = _make_group(rewards=rewards, completion_lengths=[10, 30, 60])
result = default_advantage_fn(inputs, length_weighted_baseline=True)
baseline = (10 * 1.0 + 30 * 0.0 + 60 * 0.0) / (10 + 30 + 60) # 0.1
assert result.advantages == pytest.approx([r - baseline for r in rewards], abs=1e-6)
# Token-weighted mean of advantages is zero
assert sum(length * adv for length, adv in zip((10, 30, 60), result.advantages)) == pytest.approx(0.0, abs=1e-5)
def _train_rollouts(rewards: list[float]) -> list[TrainRollout]:
Generated
+21 -2
View File
@@ -11,7 +11,7 @@ supported-markers = [
]
[options]
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
exclude-newer = "2026-06-10T23:37:49.383138959Z"
exclude-newer-span = "P7D"
[options.exclude-newer-package]
@@ -3930,7 +3930,7 @@ dev = [
[[package]]
name = "prime-rl"
version = "0.5.0"
version = "0.6.0"
source = { editable = "." }
dependencies = [
{ name = "aiolimiter", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
@@ -4016,6 +4016,7 @@ envs = [
{ name = "reverse-text", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "rlm-search", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "rlm-swe", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "rlm-uuid-ctf", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "science-env", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "simpleqa-verified", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "tau2-bench", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
@@ -4118,6 +4119,7 @@ requires-dist = [
{ name = "ring-flash-attn", specifier = ">=0.1.8" },
{ name = "rlm-search", marker = "extra == 'envs'", editable = "deps/research-environments/environments/rlm_search" },
{ name = "rlm-swe", marker = "extra == 'envs'", editable = "deps/research-environments/environments/rlm_swe" },
{ name = "rlm-uuid-ctf", marker = "extra == 'envs'", editable = "deps/research-environments/environments/rlm_uuid_ctf" },
{ name = "science-env", marker = "extra == 'envs'", editable = "deps/research-environments/environments/science_env" },
{ name = "setproctitle", specifier = ">=1.3.0" },
{ name = "simpleqa-verified", marker = "extra == 'envs'", editable = "deps/research-environments/environments/simpleqa_verified" },
@@ -4964,6 +4966,23 @@ requires-dist = [
{ name = "verifiers", extras = ["packages"], specifier = ">=0.1.15.dev17,<0.1.15.dev156" },
]
[[package]]
name = "rlm-uuid-ctf"
version = "0.1.1"
source = { editable = "deps/research-environments/environments/rlm_uuid_ctf" }
dependencies = [
{ name = "datasets", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "prime-sandboxes", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "verifiers", extra = ["packages"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
[package.metadata]
requires-dist = [
{ name = "datasets", specifier = ">=4.0.0" },
{ name = "prime-sandboxes", specifier = ">=0.2.21" },
{ name = "verifiers", extras = ["packages"], specifier = ">=0.1.15.dev17" },
]
[[package]]
name = "rpds-py"
version = "0.30.0"