Compare commits

...
Author SHA1 Message Date
faresobeidandGitHub 41a8ed0190 feat(configs): one weight wait timeout, default 3600 s (#3980)
## What
- `weight_broadcast.timeout` default goes from 1200 s to 3600 s
(`configs/shared.py`).
- It now also bounds the orchestrator's wait for the trainer's startup
broadcast. `orchestrator.ckpt.wait_for_weights_timeout` and the
hardcoded `STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200` fallback are removed.
Configs that set the old field fail validation (`extra="forbid"`); no
in-repo config sets it.
- The `[weight_broadcast]` blocks in five recipes only repeated `type =
"nccl"` (already the `rl` default when inference is managed and LoRA is
off) and `timeout = 3600`. They are removed: glm-4.5-air
swe/swe-budget/search/terminal and nemotron-3-super swe. glm-5.3 keeps
its `timeout = 12000`.
- Orchestrator `ckpt` and `resume` docstrings: `resume` had two
docstrings and `ckpt` had none. The stray one now documents `ckpt`.

## Why
- Every large multi-node recipe raises the timeout: 3600 s in five
recipes, 12000 s in glm-5.3.
- Measured startups come close to 1200 s or pass it. GLM-4.5-Air TP8
cold start takes 465-623 s. GLM-5.3 and DeepSeek-V4 inference startup
with cudagraph capture took about 16 min.
- vLLM's own engine-ready timeout is already 4200 s
(`VLLM_ENGINE_READY_TIMEOUT_S`).
- The startup wait and the per-step waits had two knobs with the same
1200 s default. The startup one was under `ckpt`, but it applies without
`ckpt` too.
- Trade-off: a consumer that dies is detected after 60 min instead of
20.

## Overlap
- #3652 (mikasenghaas, draft) reformats the `wait_timeout = ...` line
that this PR removes. Whichever lands second has a one-line conflict.
- Rebased over #3983, which removed the neighbouring orchestrator
`ckpt.keep_last`/`keep_interval` fields. The orchestrator
`CheckpointConfig` now has only `interval`.

## Test plan
- Rebased onto origin/main 32c48f5d9. `pytest tests/unit/orchestrator
tests/unit/test_configs.py -m "not gpu"`: 335 passed. `test_configs`
validates every TOML under `configs/` and `examples/`.
- `ruff check` and `ruff format --check` on the changed files: clean.
- Resolved `RLConfig` of the 5 edited recipes, main vs this branch:
identical (apart from the checkout path in `template_path`).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes orchestrator startup behavior and timeout defaults for
trainer–inference weight sync; mis-tuned timeouts could delay failure
detection (up to 60 min) or still timeout on very slow large-model
startups.
> 
> **Overview**
> **Unifies weight-broadcast timing** so one knob
(`weight_broadcast.timeout`) covers both the trainer handshake and the
orchestrator’s wait for the trainer’s **startup** broadcast. The default
rises from **1200 s to 3600 s**, and docs note raising it for large
models on slow filesystems.
> 
> **Removes** `orchestrator.ckpt.wait_for_weights_timeout` and the
orchestrator’s `STARTUP_WEIGHT_WAIT_TIMEOUT_S` fallback; startup sync
now uses `config.weight_broadcast.timeout` in `sync_startup`.
**Orchestrator config** docstrings are fixed so `ckpt` is documented on
the right field.
> 
> **Five example/advanced recipes** drop redundant `[weight_broadcast]`
blocks that only repeated NCCL type and `timeout = 3600` (now defaults).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e318f1cb0b10a8a5507520f2c6b1176f9fbd0813. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:34:47 +01:00
faresobeidandGitHub 9cde4d74f5 fix(slurm): stop crashed multi-node RL jobs idling for an hour (#3979)
Multi-node RL jobs that crash currently sit idle for an hour.

On any non-zero exit (crash, OOM, SIGTERM, wall-time),
`multi_node_rl.sbatch.j2` ran an unconditional `sleep {{
cleanup_grace_period }}` (default 3600 s, #2670) before tearing down.
The sleep keeps the task alive so `--kill-on-bad-exit` does not reap
trainers that are mid-checkpoint. But it waits the full hour even when
no checkpoint is being written, so a crashed N-node job idles for 1 h.

Now the node waits only while the newest `checkpoints/step_*/trainer`
has no DCP `.metadata` yet, i.e. a trainer save is still in flight. It
polls every 10 s, with `cleanup_grace_period` as the cap, and tears down
as soon as that save finishes or there is none. Runs without `[ckpt]`
tear down immediately. The checkpoint dir follows `ckpt.output_dir` when
it is set. The default stays 3600 s; it is now only an upper bound.

Limitation: if the crash happens right before a save starts (step dir
not created yet), we no longer wait for that save. Only that save is
lost; the previous checkpoint is intact.

**Interaction with #3875 (requeue + step watchdog):** before this
change, every requeue of a crashed multi-node RL job first waited the
full grace period. Now it waits only for an in-flight checkpoint.
`.metadata` is the same completeness marker that #3906 uses for "latest
complete checkpoint". The SFT and inference templates do not use
`cleanup_grace_period` and are unchanged.

Test plan (all run):
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed.
- `rl @ examples/advanced/glm-4.5-air/swe.toml --dry-run`: the rendered
sbatch has the wait loop with the run's `checkpoints/` path and passes
`bash -n`. With `--no-ckpt` the loop is not rendered.
- Ran the rendered teardown snippet in bash against a temp checkpoint
dir:
  - empty dir: no wait;
  - newest step complete: no wait;
  - newest step in flight: waits until the cap;
  - older incomplete step but newest complete: no wait;
  - in-flight save that completes after 1 s: waits ~1 s.
- `ruff check` and `ruff format --check` on the changed Python files.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes multi-node job teardown timing and checkpoint detection logic;
incorrect polling could tear down early or delay allocation release, but
scope is limited to SLURM RL launcher scripts.
> 
> **Overview**
> Multi-node SLURM RL jobs no longer **sleep the full
`cleanup_grace_period` (default 1h) on every failure**. Teardown after a
non-zero exit now waits only while an **in-flight trainer checkpoint**
is detected.
> 
> The `multi_node_rl.sbatch.j2` teardown block is gated on both
`cleanup_grace_period` and a rendered **`ckpt_dir`** (from
`get_ckpt_dir` when `[ckpt]` is enabled). Instead of a fixed `sleep`, it
polls every 10s: if the newest `step_*/trainer` directory lacks DCP
**`.metadata`**, it keeps the task alive (preserving
`--kill-on-bad-exit` behavior for peer trainers); otherwise it tears
down immediately. **`cleanup_grace_period` is documented as an upper
bound**; runs without checkpoints skip the wait entirely.
> 
> `write_slurm_script` in `rl.py` passes `ckpt_dir` into the multi-node
template renders.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8168264718f38f6e2e9636ea7bc7098e91743ba3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:31:54 +01:00
faresobeidandGitHub 32c48f5d9a chore(configs)!: rename tasks_per_minute to dispatch_per_minute (#3991)
## What

Renames `tasks_per_minute` to `dispatch_per_minute` on `orchestrator`,
the `eval` entrypoint and the SFT online `[eval]` block. This uses the
same name and wording as #3652.

The old name was wrong. The dispatcher takes one rate-limiter token per
**episode** it starts (`Dispatcher.acquire`, called once per scheduled
episode), not one per task. With `group_size = 8`, `tasks_per_minute =
80` started only 10 tasks per minute. The docstrings now say what is
counted: at most N episodes start per minute, and a group counts
`group_size` times.

Breaking: configs that set `tasks_per_minute` now fail validation
(`extra="forbid"`). No shipped config, doc, test or skill sets it or
mentions it.

## Overlap
#3652 (draft, orchestrator as hook-wired components) makes the same
rename. This PR lands it on its own and does not depend on that
refactor.

## Test plan
- `pytest tests/unit/orchestrator tests/unit/eval
tests/unit/test_configs.py -m "not gpu"`: 357 passed.
- `ruff check` and `ruff format --check` on the changed files.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Breaking config field rename only; runtime rate limiting behavior is
unchanged aside from clearer documentation.
> 
> **Overview**
> **Breaking rename:** `tasks_per_minute` → `dispatch_per_minute` on
orchestrator config, eval/SFT online eval config (`ServedEvalConfig`),
and everywhere it is passed into `Dispatcher` (orchestrator + eval
runner).
> 
> The limit semantics are unchanged in code (still `AsyncLimiter` with
one token per scheduled episode in `Dispatcher.acquire`), but the name
and docstrings now match behavior: the cap is **episodes started per
minute**, and a rollout group with `group_size` N consumes N tokens.
Configs that still use `tasks_per_minute` will fail validation under
`extra="forbid"`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0436304d5e40baed76abfadaa5b989048e818b6a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:29:40 +01:00
faresobeidandGitHub 8b2eb329e1 chore(trainer)!: remove the model.index_cache override (#3984)
Removes `model.index_cache` (`IndexCacheConfig.topk_freq` and
`.topk_pattern`). The trainer still turns on IndexShare from the model's
own `indexer_types` schedule (`src/prime_rl/trainer/model.py`), as
before.

Why: the override changes the trainer only. No inference-side config
matches it, so setting it makes the trainer pick different top-k indices
than vLLM unless the user also passes the same vLLM `hf_overrides` by
hand. The setting appears in no config, example or test. The HF-level
`use_index_cache` / `index_topk_freq` / `index_topk_pattern` attributes
on `GlmMoeDsaConfig` stay, so a checkpoint's own `config.json` still
drives them.

Breaking: `[trainer.model.index_cache]` / `[model.index_cache]` now
fails validation.

Overlap with open PRs:
- #3833 rewrites the same `index_cache` lines in `model.py`
(`set_model_options(model_config, "index_cache", ...)`). Whichever lands
second drops or rebases that block; the conflict is small.
- #3879 is based on that code too.
- #3616 already leaves `trainer.model.index_cache` unset for the reason
above: a trainer frequency override replaces the checkpoint schedule and
requests weights the checkpoint does not have.

Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed.
- `pytest tests/unit/utils/test_weights.py` (includes
`GlmMoeDsaForCausalLM`): 7 passed.
- `ruff check` and `ruff format --check` on the changed Python files:
clean.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking config validation for anyone using `index_cache`, and it
changes sparse-attention index scheduling to follow the checkpoint
only—important for trainer/inference logprob alignment on DSA models.
> 
> **Overview**
> **Removes the trainer-only `[trainer.model.index_cache]` override**
(`topk_freq` / `topk_pattern`). Configs that still set it will fail
validation.
> 
> IndexShare for GLM-5.2-style DSA models is unchanged in behavior: when
the checkpoint’s `indexer_types` includes `"shared"` layers, the trainer
still sets `use_index_cache` on the HF config and logs the full/shared
layer counts. It no longer applies manual `index_topk_freq` /
`index_topk_pattern` or clears `indexer_types`, which could diverge from
vLLM rollouts.
> 
> Docs no longer mention manually overriding the schedule via
`[trainer.model.index_cache]`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bf75c92edd9982a776bff29601c1e8c4519aebeb. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:22:14 +01:00
faresobeidandGitHub be89bbdaa1 fix(inference): keep the routed-experts dtype vLLM picks from the model config (#3965)
vLLM 0.31's routed-experts capturer already returns uint8 or uint16,
chosen from the model's expert count (`uint8 if num_experts <= 256 else
uint16`). `serialize_routed_experts` cast every request back to uint8
whenever its ids happened to be below 256. On a >256-expert model
(NemotronH Super/Ultra: 512 experts), a request whose ids all fall below
256 therefore came out uint8 while the others were uint16. Packing two
such samples into one micro batch trips `assert routed_experts.dtype ==
sample.routed_experts.dtype` in `orchestrator/batch.py`. Multi-turn
traces hit the same mix: verifiers concatenates the per-turn arrays, and
NumPy widens the result.

`serialize_routed_experts` now keeps the capturer's dtype and asserts
that it is uint8 or uint16. Every request of a model then has the same
dtype. Models with 256 or fewer experts are unchanged (uint8).

Tests: the existing serialize test now passes a uint16 array with ids
below 256 and checks that it stays uint16. `tests/unit/orchestrator`,
`tests/unit/inference`, `tests/unit/utils`, `tests/unit/test_configs.py`
pass with `-m "not gpu"`; `ruff check` and `ruff format --check` are
clean.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Narrow inference serialization fix; ≤256-expert models stay uint8, and
behavior only changes where mixed dtypes previously caused orchestrator
batch asserts.
> 
> **Overview**
> **Fixes inconsistent routed-experts dtypes** that broke micro-batch
packing on models with more than 256 experts (e.g. NemotronH 512).
> 
> `serialize_routed_experts` no longer re-encodes expert indices to the
smallest integer width based on per-request max values. It keeps the
array dtype from vLLM’s capturer (`uint8` or `uint16` from model expert
count), with assertions that the input is 3-D and one of those two
types. The serialized payload’s `"dtype"` field reflects that array
unchanged.
> 
> Unit tests now decode using `encoded["dtype"]` and assert a `uint16`
capture with all ids &lt; 256 stays `uint16` through serialize/decode.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e4a8e9ea05cb4e960192cdb7929e2c2566ca9734. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:18:00 +01:00
faresobeidandGitHub a1e0edbb4f fix(rl): inherit inference.deployment.gpus_per_node from deployment (#3978)
Under `rl`, `inference.deployment.gpus_per_node` was never set from
`deployment.gpus_per_node`. `InferenceConfig.auto_setup_disaggregated`
sizes `data_parallel_size_local`, `data_parallel_size` and
`api_server_count` from the nested copy, which defaults to 8. The
launcher, sbatch `dp_per_node` and weight-broadcast world size use the
top-level copy. So a P/D run on nodes that do not have 8 GPUs got
mismatched engine counts.

Example: `examples/advanced/glm-5.3/swe.toml` with
`deployment.gpus_per_node = 4` resolved to `data_parallel_size_local =
8` and `api_server_count = 8`, while the template launched 4 engines per
node.

Changes:
- `propagate_shared_fields` now fills
`inference.deployment.gpus_per_node` from `deployment.gpus_per_node`. As
with the other shared fields, setting both to different values raises.
- `RLConfig.validate_shared_configs` requires the two to be equal. This
catches a nested-only override that leaves the top-level value at its
default.

## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 335 passed (includes the new
`test_disaggregated_inference_inherits_deployment_gpus_per_node`)
- Parsed all 78 tomls under `configs/` and `examples/` with every config
class on main and on this branch: same results, none fail
- glm-5.3 `swe.toml` with `deployment.gpus_per_node = 4` now resolves
`inference.deployment.gpus_per_node = 4`, `dp_local = 4`,
`api_server_count = 4`
- `ruff check` / `ruff format --check` on the changed files

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Mis-sized inference parallelism and launcher/engine counts on
multi-node disaggregated runs; the change is narrow config propagation
plus validation with low blast radius beyond P/D sizing.
> 
> **Overview**
> Fixes a config bug where **`deployment.gpus_per_node`** at the RL top
level did not flow into **`inference.deployment.gpus_per_node`**, so
disaggregated P/D runs could size **`data_parallel_size_local`**,
**`api_server_count`**, and related fields from the nested default (8)
while SLURM/launchers used the top-level value (e.g. 4).
> 
> **`propagate_shared_fields`** now copies top-level
**`deployment.gpus_per_node`** into
**`inference.deployment.gpus_per_node`** (with the same
shared-vs-sub-config conflict rules as other shared fields).
**`RLConfig.validate_shared_configs`** additionally requires the two
values to match when inference is enabled, catching nested-only
overrides that disagree with the top-level deployment.
> 
> A unit test asserts inheritance and that mismatched nested/top-level
**`gpus_per_node`** fails validation.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
863bbf67298b456c48418c7326c820cc930ca203. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-10 19:14:07 +01:00
faresobeidandGitHub 8493109b7d chore(inference): drop typed vLLM fields that only repeat vLLM defaults (#3986)
Drops seven typed `[inference.vllm]` fields: `seed`, `enforce_eager`,
`dtype`, `trust_remote_code`, `enable_dbo`, `max_loras`,
`all2all_backend`, and the `All2AllBackend` alias. Each one only
repeated vLLM 0.31's own default, and nothing in prime-rl reads it.
`VllmConfig` is `extra="allow"`, so all seven keys still pass through to
vLLM unchanged. The `VllmConfig` docstring says to type only fields that
prime-rl types, defaults or reads back; these were none of those.

`all2all_backend` also suggested control it doesn't have for P/D: the
sbatch templates set the per-role backend in `ROLE_EXTRA`
(`inference.sbatch.j2:261,276`, `multi_node_rl.sbatch.j2:405,419`). That
stays as is.

Behavior: I resolved the vLLM serve args (`to_namespace` →
`make_arg_parser().parse_args`) on main and on this branch for the
default config and for `--vllm.enforce-eager`, `--vllm.enforce-eager
true`, `--vllm.max-loras 2`, `--vllm.dtype bfloat16`, `--vllm.seed 7`,
`--vllm.all2all-backend deepep_low_latency`, `--vllm.enable-dbo true`,
`--vllm.trust-remote-code true`, `@
examples/advanced/glm-5.3/infer/pd.toml`. All seven values are
identical. The nested rl form `--inference.vllm.enforce-eager
--inference.vllm.max-loras 2` also resolves to `True, 2`. `"enable_dbo"
= true` in `examples/advanced/glm-5.3/swe.toml` sits under
`prefill_vllm_overrides` and is unaffected.

Differences:
- `--no-vllm.enforce-eager` (the negated bool flag) only exists for
typed fields. Use `--vllm.enforce-eager false`. All four removed bools
default to False, so this only matters when undoing a toml that set one
to true.
- `dtype` now accepts every value vLLM accepts (for example `half`)
instead of prime-rl's narrower Literal.

`skills/configs/SKILL.md` used `enforce_eager = true` as its TOML
boolean example. It now uses `enable_prefix_caching = true`, which is
still typed, so `--no-flag` applies to it.

## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py
tests/unit/test_parsers.py -m "not gpu"`: 489 passed
- Parsed all 78 tomls under `configs/` and `examples/` with every config
class on main and on this branch: same results
- The resolved-args comparison above
- `ruff check` / `ruff format --check` on the changed file
2026-10-10 19:07:27 +01:00
23 changed files with 89 additions and 133 deletions
@@ -22,10 +22,6 @@ num_infer_replicas = 4
project = "nemotron-3-super"
name = "nemotron-3-super-swe"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
+1 -1
View File
@@ -100,7 +100,7 @@ Backend shape checks and token alignment apply only to the selected compute path
In RL runs, configure the same precision selection for rollouts. Inference module names can differ from the trainer's names, and inference precision is configured explicitly, not inferred from `apply_to`. Check the selected modules on both sides before comparing trainer and rollout logprobs.
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`).
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.
### Expert Parallelism Backends
@@ -21,10 +21,6 @@ num_infer_replicas = 4
project = "search-ablations"
name = "glm45air-search"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
@@ -34,10 +34,6 @@ num_infer_nodes = 1
[monitors.wandb]
project = "swe-ablations"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
-4
View File
@@ -35,10 +35,6 @@ num_infer_replicas = 4
project = "swe-ablations"
name = "glm45air-scaleswe"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
@@ -22,10 +22,6 @@ num_infer_replicas = 4
project = "terminal-ablations"
name = "glm45air-terminal"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
@@ -28,10 +28,11 @@ class ServedEvalConfig(EvalSourcesConfig):
"""Adaptive in-flight episode concurrency, sized by the same controller as
``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on episode dispatch, in tasks per minute. Use it for
sandbox-backed environments to pace provisioning during autoscaling. None disables
rate limiting."""
dispatch_per_minute: int | None = Field(None, ge=1)
"""Rate limit on episode dispatch: at most this many episodes start per minute. Each
episode counts once, so a group of ``group_size`` episodes counts ``group_size``
times. Use it for sandbox-backed environments to pace provisioning during
autoscaling. None disables it."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat for the run: pinged by landed episodes — the first
@@ -29,15 +29,6 @@ class ServerConfig(BaseConfig):
# not depend on vLLM, and importing it costs seconds in every config-parsing process.
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
# vLLM all2all backend options for expert-parallel deployments.
All2AllBackend = Literal[
"allgather_reducescatter",
"deepep_high_throughput",
"deepep_low_latency",
"flashinfer_nvlink_one_sided",
"flashinfer_nvlink_two_sided",
]
QuantizationType = Literal["fp8_per_block"]
@@ -59,18 +50,9 @@ class VllmConfig(BaseConfig):
model: str = "Qwen/Qwen3-0.6B"
"""HF model name or local path."""
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models."""
max_model_len: int | None = None
"""Maximum model context length. If None, uses the model config's value."""
enforce_eager: bool = False
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance."""
trust_remote_code: bool = False
"""Trust remote code when loading the model."""
chat_template: str | None = None
"""Chat template — a Jinja2 template string or path to a template file. If None, uses the model's default."""
@@ -98,9 +80,6 @@ class VllmConfig(BaseConfig):
api_server_count: int = Field(1, ge=0)
"""API servers to run. Set to 0 for headless mode."""
seed: int = 0
"""Seed the inference components."""
gpu_memory_utilization: float = 0.9
"""GPU memory utilization."""
@@ -113,10 +92,6 @@ class VllmConfig(BaseConfig):
enable_lora: bool = False
"""Enable LoRA."""
max_loras: int = 1
"""Maximum number of concurrently served LoRAs. prime-rl serves one adapter and reloads
it in place every policy version (same name, same lora_int_id), so one slot suffices."""
max_lora_rank: int | None = None
"""Maximum LoRA rank. Rounded up to the nearest value vLLM accepts."""
@@ -126,9 +101,6 @@ class VllmConfig(BaseConfig):
enable_expert_parallel: bool = False
"""Enable expert parallelism for MoE models."""
all2all_backend: All2AllBackend = "allgather_reducescatter"
"""All-to-all backend for expert-parallel communication."""
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB)."""
@@ -138,9 +110,6 @@ class VllmConfig(BaseConfig):
expert parallelism is disabled, or under EPLB (redundant expert slots need all
logical expert weights)."""
enable_dbo: bool = False
"""Enable dual batch overlap (DBO)."""
enable_return_routed_experts: bool = False
"""Return routed experts in responses."""
@@ -426,9 +426,6 @@ class CheckpointConfig(BaseConfig):
interval: int | None = Field(None, ge=1)
"""Step interval at which to save the orchestrator checkpoint."""
wait_for_weights_timeout: int | None = Field(None, ge=1)
"""Wait up to this many seconds for the startup weight directory to appear (the trainer broadcasts the incoming policy — v0 from scratch, the resumed step's version on resume — before the first step). If None, fall back to a default timeout. Raise this for large models on slow shared filesystems."""
class ConcurrencyConfig(BaseConfig):
"""Adaptive in-flight concurrency control. The orchestrator sizes the
@@ -498,10 +495,10 @@ class OrchestratorConfig(BaseConfig):
"""Role for each policy admin client when collecting P/D inference metrics."""
ckpt: CheckpointConfig | None = None
"""Checkpoint configuration."""
resume: ResumeConfig | None = None
"""Resume the orchestrator from a checkpoint. None starts from scratch; an empty block resumes from the latest checkpoint, ``resume.step`` from that step, ``resume.dir`` from an external checkpoint step directory. Without ``ckpt`` the run loads but saves no new checkpoints."""
"""Checkpoint configuration."""
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
"""Transport used to receive updated weights from the trainer."""
@@ -512,8 +509,8 @@ class OrchestratorConfig(BaseConfig):
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
dispatch_per_minute: int | None = Field(None, ge=1)
"""Rate limit on episode dispatch, shared by train and eval: at most this many episodes start per minute. Each episode counts once, so a group of ``group_size`` episodes counts ``group_size`` times. Recommended for sandbox-backed environments to pace provisioning during autoscaling. None disables it."""
batch_size: int = Field(128, ge=1)
"""Samples to train on per step."""
@@ -360,6 +360,13 @@ class RLConfig(BaseConfig):
# The orchestrator queries the inference server it is paired with; without one, it
# must match the trainer whose weights the external server receives.
if inference is not None:
require_equal(
"deployment.gpus_per_node",
{
"deployment.gpus_per_node": self.deployment.gpus_per_node,
"inference.deployment.gpus_per_node": inference.deployment.gpus_per_node,
},
)
require_equal(
"model.name",
{"inference.vllm.model": inference.vllm.model, "orchestrator.model.name": orchestrator.model.name},
@@ -39,9 +39,10 @@ EnvVars: TypeAlias = Annotated[dict[str, str], AfterValidator(reject_protected_e
class BaseWeightBroadcastConfig(BaseConfig):
timeout: int = 1200
"""Timeout in seconds for the broadcast handshake and transfer. The trainer
fails the run when no consumer acknowledges an offered version in time."""
timeout: int = 3600
"""Timeout in seconds for the broadcast handshake and transfer, including the orchestrator's wait
for the trainer's startup broadcast. The trainer fails the run when no consumer acknowledges an
offered version in time. Raise it for large models on slow shared filesystems."""
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
@@ -153,7 +154,7 @@ class SlurmConfig(BaseConfig):
"""Start a job-scoped ModelExpress service for NIXL weight transfer."""
cleanup_grace_period: int = Field(3600, ge=0)
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
"""Maximum seconds a multi-node RL job that hit a non-zero exit waits for an in-flight trainer checkpoint to finish before tearing down. Without an in-flight checkpoint (or without ``[ckpt]``) it tears down immediately. Set to 0 to never wait."""
shared_fs: bool = True
"""Whether the project filesystem (including the venv) is shared across nodes (e.g. NFS). When True, a single ``uv sync`` on the batch node suffices. Set to False when the venv is node-local (e.g. ``UV_PROJECT_ENVIRONMENT`` on ``/tmp``) so ``uv sync`` runs on every node via srun."""
@@ -95,14 +95,6 @@ class FusionsConfig(BaseConfig):
"""Experimental. Shard fused 2-D weights along dim 1 under FSDP so that weight loading and checkpointing are zero-copy: the checkpoint reads and writes the fused weights and their optimizer state in place, instead of assembling a full copy of every fused weight on each rank first. Requires the hidden size to be divisible by the FSDP shard mesh size."""
class IndexCacheConfig(BaseConfig):
topk_freq: int = Field(1, ge=1)
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
topk_pattern: str | None = None
"""Optional per-layer schedule that overrides ``topk_freq``. ``'F'`` computes fresh indices for that layer; ``'S'`` reuses the previously cached indices. Length should match the number of decoder layers."""
class LoRAConfig(BaseConfig):
rank: int = Field(16, ge=1)
"""Rank of the low-rank decomposition matrices."""
@@ -329,9 +321,6 @@ class ModelConfig(BaseModelConfig):
dsa_backend: DSABackend = "tilelang"
"""Kernels for the DSA sparse MLA attention (``glm_moe_dsa``, e.g. GLM-5). ``tilelang`` runs the TileLang forward and backward. ``cudnn_flashmla`` runs the FlashMLA sparse prefill forward with the cuDNN frontend CuTe-DSL backward; it needs the ``flash-mla`` extra and an SM90 GPU (SM100/SM103 are wired up but untested)."""
index_cache: IndexCacheConfig | None = None
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
freeze_moe_router: bool | Literal["auto"] = "auto"
"""Freeze MoE router gate parameters. ``auto`` (default): ``True`` for RL, ``False`` for SFT; a no-op on non-MoE models. Frozen routers get no optimizer state, so resuming a checkpoint saved with a frozen router with ``freeze_moe_router=false`` fails on missing DCP keys."""
@@ -133,6 +133,10 @@ def propagate_shared_fields(data: Any) -> Any:
propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps")
propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len")
# [deployment] gpus_per_node → inference: the nested inference deployment sizes its
# engines per node from its own copy.
propagate("deployment.gpus_per_node", "inference.deployment.gpus_per_node")
# [slurm] → inference: a multi-node RL run drives its inference deployment under
# the same SLURM allocation, so the nested inference inherits [slurm]. This is
# what lets the nested InferenceConfig's multi-node / disaggregated SLURM check
+1 -1
View File
@@ -42,7 +42,7 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
**Sources are one block** — inside a `[[...source]]` entry, write nested sub-configs as dotted keys in the same block (`env.taskset.id = "..."`, `env.agent.harness.id = "..."`), not one subsection header per nested config. Nested arrays of tables (e.g. `[[orchestrator.train.source.env.taskset.task.judges]]`) keep full-path headers — they attach to the preceding `[[...source]]` entry.
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enable_prefix_caching = true`).
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--vllm.max-model-len None`.
+4
View File
@@ -320,6 +320,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
"modelexpress_redis_port": 6380 if nixl_broadcast is not None and nixl_broadcast.port == 6379 else 6379,
}
ckpt_dir = get_ckpt_dir(config.trainer.ckpt.output_dir or config.run_dir) if config.trainer.ckpt else None
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
@@ -342,6 +344,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
config_dir=config_dir,
log_dir=log_dir,
output_dir=config.run_dir,
ckpt_dir=ckpt_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
num_train_nodes=config.deployment.num_train_nodes,
@@ -387,6 +390,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
config_dir=config_dir, # TODO: should prob have each subconfig path separately
log_dir=log_dir,
output_dir=config.run_dir,
ckpt_dir=ckpt_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
num_train_nodes=config.deployment.num_train_nodes,
+1 -1
View File
@@ -118,7 +118,7 @@ class EvalRunner:
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
tasks_per_minute=config.tasks_per_minute,
dispatch_per_minute=config.dispatch_per_minute,
max_off_policy_steps=0,
run_id=self.run_id,
run_name=self.run_name,
+6 -14
View File
@@ -12,24 +12,16 @@ def serialize_routed_experts(routed_experts: Any, start: int = 0) -> dict[str, A
if routed_experts is None:
return None
array = np.asarray(routed_experts)
assert array.ndim == 3
assert np.issubdtype(array.dtype, np.integer)
dtype = np.uint8
if array.size:
assert array.min() >= 0
if array.max() > np.iinfo(np.uint8).max:
# Models with >256 experts (e.g. NemotronH Super/Ultra: 512) need wider
# indices. The payload self-describes via "dtype" so consumers pick it up.
assert array.max() <= np.iinfo(np.uint16).max
dtype = np.uint16
compact = np.ascontiguousarray(array.astype(dtype, copy=False))
# vLLM's capturer picks uint8 or uint16 from the model's expert count, so every request of a
# model has the same dtype and the orchestrator can pack them into one micro batch.
compact = np.ascontiguousarray(routed_experts)
assert compact.ndim == 3
assert compact.dtype in (np.uint8, np.uint16), compact.dtype
return {
"data": pybase64.b64encode(memoryview(compact)).decode("ascii"),
"shape": list(compact.shape),
"start": start,
"dtype": np.dtype(dtype).name,
"dtype": compact.dtype.name,
}
+3 -3
View File
@@ -5,7 +5,7 @@
the concurrency controller moves it via ``set_limit``; refills are
burst-capped so a raised (or drained) cap never lands all its prefills at
once.
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
- Optional rate limiting via ``AsyncLimiter(dispatch_per_minute, 60)``, one token per episode.
- Every dispatched attempt reaches ``out_q`` exactly once: as the native
episode returned by the environment, as a ``DispatchFailure`` when no
episode was produced, or under the group's ``GroupCancellation`` when the
@@ -139,7 +139,7 @@ class Dispatcher:
progress: Progress | None,
initial_max_inflight: int,
max_inflight_ceiling: int | None,
tasks_per_minute: float | None,
dispatch_per_minute: float | None,
max_off_policy_steps: int,
run_id: str,
run_name: str | None,
@@ -168,7 +168,7 @@ class Dispatcher:
self.max_inflight = initial_max_inflight
self.current_inflight = 0
self.rate_limiter: AsyncLimiter | None = (
AsyncLimiter(tasks_per_minute, time_period=60) if tasks_per_minute else None
AsyncLimiter(dispatch_per_minute, time_period=60) if dispatch_per_minute else None
)
# Admission smoothing: the pool may only GROW by ``burst_cap`` per
# window. Replacing a completed episode is always free (each natural
+2 -10
View File
@@ -86,11 +86,6 @@ SHUTDOWN_TIMEOUT_S = 300
# resumed when the watcher advances ``policy.version``.
TARGET_LAG = 1
# Default wait for the trainer's startup weight broadcast when no ckpt block
# configures ``wait_for_weights_timeout`` (e.g. a from-scratch run). The
# broadcast is always coming, so wait rather than fail immediately.
STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200
class Orchestrator:
# Set in ``__init__``
@@ -302,9 +297,6 @@ class Orchestrator:
# scratch). The startup broadcast is always coming, so wait for it rather
# than failing immediately when it is not there yet.
sync_version = self.resume_step if self.resume_step is not None else 0
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
STARTUP_WEIGHT_WAIT_TIMEOUT_S
)
self.eval_source: EvalSource | None = (
EvalSource(
@@ -330,7 +322,7 @@ class Orchestrator:
progress=self.progress,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
tasks_per_minute=config.tasks_per_minute,
dispatch_per_minute=config.dispatch_per_minute,
max_off_policy_steps=config.max_off_policy_steps,
run_id=self.run_id,
run_name=self.run_name,
@@ -383,7 +375,7 @@ class Orchestrator:
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
t0 = time.perf_counter()
await self.watcher.sync_startup(sync_version, timeout=wait_timeout)
await self.watcher.sync_startup(sync_version, timeout=config.weight_broadcast.timeout)
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
async def start(self) -> None:
+16 -8
View File
@@ -599,17 +599,25 @@ while true; do
done
REMAINING_PIDS=$(jobs -p)
{%- if cleanup_grace_period %}
{%- if cleanup_grace_period and ckpt_dir %}
# Cross-node teardown is driven by `srun --kill-on-bad-exit=1`, which reaps peer
# tasks only once a task *exits* non-zero. So on a non-zero exit (crash, SIGTERM,
# wall-time) we stay alive for the grace period and signal nothing: this lets an
# in-flight trainer checkpoint on this node finish, and — because the task has
# not exited yet — keeps --kill-on-bad-exit from reaping checkpointing trainers
# on peer nodes. We then propagate the exit code so the allocation tears down. A
# clean (zero) exit cannot trip --kill-on-bad-exit, so we tear down immediately.
# wall-time) we stay alive and signal nothing while the newest trainer checkpoint
# is still being written (no DCP `.metadata` yet), up to the grace period: this lets
# it finish on this node, and — because the task has not exited yet — keeps
# --kill-on-bad-exit from reaping checkpointing trainers on peer nodes. We then
# propagate the exit code so the allocation tears down. A clean (zero) exit cannot
# trip --kill-on-bad-exit, so we tear down immediately.
if [ "$EXIT_CODE" -ne 0 ]; then
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for in-flight checkpoints to flush before teardown"
sleep {{ cleanup_grace_period }}
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for an in-flight trainer checkpoint to finish before teardown"
GRACE_DEADLINE=$((SECONDS + {{ cleanup_grace_period }}))
while [ "$SECONDS" -lt "$GRACE_DEADLINE" ]; do
LATEST_CKPT=$(ls -d {{ ckpt_dir }}/step_*/trainer 2>/dev/null | sort -V | tail -n 1)
if [ -z "$LATEST_CKPT" ] || [ -f "$LATEST_CKPT/.metadata" ]; then
break
fi
sleep 10
done
fi
{%- endif %}
echo "[$(hostname)] tearing down (exit code $EXIT_CODE) - terminating remaining processes"
+8 -15
View File
@@ -353,22 +353,15 @@ def get_model(
if subconfig is not None and hasattr(subconfig, "use_cache"):
subconfig.use_cache = False
model_config.dsa_backend = config.dsa_backend
if config.index_cache is not None:
# 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
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)"
)
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.
+5 -4
View File
@@ -31,7 +31,7 @@ from prime_rl.inference.vllm.serving_tokens import (
def _decode_routed_experts(encoded: dict) -> np.ndarray:
return np.frombuffer(
pybase64.b64decode_as_bytearray(encoded["data"]),
dtype=np.uint8,
dtype=encoded["dtype"],
).reshape(encoded["shape"])
@@ -45,20 +45,21 @@ def test_subclass_overrides_serve_tokens_full_generator():
assert PrimeRlServingTokens.serve_tokens_full_generator is not upstream.serve_tokens_full_generator
def test_serialize_routed_experts_uses_compact_raw_payload():
def test_serialize_routed_experts_keeps_the_capture_dtype():
# A >256-expert model captures uint16 even when every id of a request is below 256.
routed_experts = np.array(
[
[[1, 2], [3, 4]],
[[5, 6], [7, 8]],
],
dtype=np.int64,
dtype=np.uint16,
)
encoded = serialize_routed_experts(routed_experts)
assert encoded is not None
decoded = _decode_routed_experts(encoded)
assert decoded.dtype == np.uint8
assert decoded.dtype == np.uint16
np.testing.assert_array_equal(decoded, routed_experts)
+18
View File
@@ -714,6 +714,24 @@ def test_multi_node_auto_inference_parallelism():
assert config.inference.vllm.data_parallel_size == 2
def test_disaggregated_inference_inherits_deployment_gpus_per_node():
config = {
"trainer": {},
"orchestrator": {},
"inference": {"vllm": {"tensor_parallel_size": 2}, "deployment": {"type": "disaggregated"}},
"deployment": {"type": "multi_node", "gpus_per_node": 4, "num_train_nodes": 1},
"slurm": {},
}
resolved = RLConfig.model_validate(config)
assert resolved.inference.deployment.gpus_per_node == 4
assert resolved.inference.vllm.data_parallel_size_local == 2
config["deployment"].pop("gpus_per_node")
config["inference"]["deployment"]["gpus_per_node"] = 4
with pytest.raises(ValidationError, match="gpus_per_node must match"):
RLConfig.model_validate(config)
def test_orchestrator_vlm_requires_renderer():
with pytest.raises(ValidationError, match="renderer"):
OrchestratorConfig.model_validate(