Compare commits

...
Author SHA1 Message Date
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
faresobeidandGitHub c9ce5f3d30 chore(configs): drop dead orchestrator fields (#3983) 2026-10-10 19:04:40 +01:00
faresobeidandGitHub 9570bccc28 chore(configs): drop recipe lines that repeat defaults (#3982)
## What
Drop recipe lines that only repeat what the config already resolves to.
The resolved configs do not change, except for `skip_optimizer` (see
below).
- `[weight_broadcast] type = "nccl"`: `rl` already picks NCCL when
inference is managed and LoRA is off. Removed from minimax-m2.5 swe,
intellect-3.1 rl, and qwen3-30b-a3b swe/math. The block stays in
examples/extra/dynamo/rl.toml (no managed inference, so the default
there is filesystem) and in glm-5.3 (it also sets port and timeout).
- `ac.freq = 1` (the default) is removed from 8 recipes. The
`[*.model.ac]` table header stays, matching the GLM-4.5-Air recipes.
- `trainer.dist_timeout_seconds = 3600` / `dist_timeout_seconds = 3600`
(the default) is removed from 5 RL recipes and vlm/sft-moe.
- `inference.vllm.enable_return_routed_experts = true` is removed where
`trainer.enable_router_replay = true` already sets it (glm-4.5-air ×4,
nemotron-3-super).
- `[trainer.ckpt] skip_optimizer = true` is removed from glm-4.5-air
swe-budget/search/terminal and nemotron-3-super swe.
  - It only affects loading: on resume, it drops the AdamW/Muon state.
- It came from the #2862/#2915 ablation configs. None of these recipes
warm-starts from another run's checkpoint. They train from the HF model
and resume their own checkpoints, which include optimizer state.
- configs/ci/integration/reverse-text-sft/full-offload-resume.toml keeps
it on purpose: it tests that path.
- docs/scaling.md: the `fused_lm_head_token_chunk_size` default is 8192
(since #3302), not 1024.

## Not touched
- `fused_lm_head_token_chunk_size = 1024` pins (7 recipes) and `attn =
"flash_attention_3"` pins (10). Should they stay as memory/hardware
choices?
- `[ac_offloading] max_inflight_activations` lines (a separate PR
removes the field).
- The `[weight_broadcast]` blocks of the GLM-4.5-Air and nemotron
recipes (handled in the weight_broadcast.timeout PR, to avoid a
conflict).

## Test plan
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 334 passed (validates every TOML under configs/ and examples/).
- Resolved configs of all 14 edited recipes, main vs this branch
(RLConfig/SFTConfig `model_dump`):
- identical, except `trainer.ckpt.skip_optimizer` True → False in the 4
recipes above;
- the checkout path in `template_path` also differs (main checkout vs
this worktree), which is not a recipe change.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Mostly documentation and deduplication; the only resolved-config
change is `skip_optimizer` false on four recipes that resume with full
optimizer state, which matches their intended training flow.
> 
> **Overview**
> Trims RL/SFT example and advanced recipe TOMLs by deleting settings
that already match framework defaults, so recipes only spell out
non-default choices.
> 
> Removed redundant **`[weight_broadcast] type = "nccl"`**,
**`trainer.model.ac` `freq = 1`**, **`dist_timeout_seconds = 3600`**,
and **`inference.vllm.enable_return_routed_experts`** where NCCL
broadcast, AC frequency, dist timeout, and routed-expert return are
implied (e.g. managed inference + **`enable_router_replay`**). Dropped
**`[trainer.ckpt] skip_optimizer = true`** from four GLM-4.5-Air and
Nemotron SWE/search/terminal recipes so resume loads optimizer state
from their own checkpoints instead of discarding it.
> 
> **`docs/scaling.md`** now documents
**`fused_lm_head_token_chunk_size`** default **8192** (was incorrectly
**1024**). Explicit pins like **`fused_lm_head_token_chunk_size =
1024`** in memory-tight recipes are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c87c43defc655e83c39559736ca874740327d266. 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 18:38:11 +01:00
faresobeidandGitHub c5406f8d09 perf(examples): use cudnn_flashmla DSA backend in GLM-5.3 RL example (#3968)
Sets `dsa_backend = "cudnn_flashmla"` for the trainer in the GLM-5.3 RL
example (`examples/advanced/glm-5.3/swe.toml`). The SFT example already
uses it (#3829); the RL example still ran the TileLang forward and
backward.

Measured on 1x8 H200 with the trainer settings of `swe.toml` (131k seq,
cp 4, ep 8, fp8 + `deepgemm_fp8`, full AC + offload, compile). Random
init, 8 layers (3 dense + 5 MoE), fake data, 2 micro-batches per dp
rank, balanced routing:

| `dsa_backend` | step 2 / 3 | sparse attn fwd per call | sparse attn
bwd per call |
|---|---|---|---|
| `tilelang` | 16.6 s / 15.5 s | 35 ms | 190 ms |
| `cudnn_flashmla` | 12.8 s / 12.1 s | 12 ms | 53 ms |

- Entropy and mismatch KL are identical to 4 decimals.
- With a 4-layer run (5.7 s), one MoE layer costs 1.6 s instead of 2.07
s. Extrapolated to 78 layers at this shape: ~124 s vs ~160 s per step
(-22%).
- Kernel check at the CP shape (8k local queries vs 32k keys, cp rank 0
and 3, top-k 2048, sentinel slots): out / dq / dkv relative error vs
TileLang 5e-4 to 9e-4, LSE 7e-8.
- Needs the `flash-mla` extra, which the README's `uv sync --all-extras`
installs.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single example TOML knob with no production code changes; requires the
optional flash-mla dependency for the new backend.
> 
> **Overview**
> Aligns the GLM-5.3 RL example trainer config with the SFT example by
setting **`dsa_backend = "cudnn_flashmla"`** in
`examples/advanced/glm-5.3/swe.toml`, so sparse DSA attention uses the
cuDNN/FlashMLA path instead of the default TileLang forward/backward.
> 
> This is a **performance-only** example change for long-context RL
training (131k seq, CP/EP, fp8 MoE); behavior should match TileLang
within measured numerical tolerance when the `flash-mla` extra is
installed.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e2135c38262af40b51d866026cdfa3a83fb7c7b4. 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 18:29:07 +01:00
Florian BrandandGitHub 9b39a10949 refactor(sampling): share parameter resolution across eval and training (#3782)
Use Verifiers' shared sampling config and resolution path for evaluation
and rollout dispatch. Parameter names, provider options, source
defaults, and agent overrides follow the same rules in native Verifiers
and Prime-RL. Training retains its strict config for the distribution
the trainer replays.

## Sampling flow

```mermaid
flowchart TD
    T["Train source and agent config<br/>TrainSamplingConfig and replay bounds"] --> V["Validate live-policy sampling<br/>Source owns the distribution"]
    V --> S["Shared Verifiers SamplingConfig<br/>Normalize aliases and extra_body"]
    V --> A["AgentConfig.sampling<br/>Sparse overrides across config transport"]
    E["Eval source and agent config"] --> S
    E --> A
    S --> R["RunRequest to env server"]
    A --> M["Verifiers resolve_agent<br/>Shared merge_defaults"]
    R --> M
    M --> P["Provider request<br/>Non-null resolved parameters"]
    M --> C["Trace<br/>Complete resolved sampling"]
```

## Shared parameters

Verifiers normalizes `max_tokens` / `max_completion_tokens` and flattens
`extra_body` before merging each override layer. Source values replace
group defaults; agent values replace inherited sampling. An explicit
null clears an inherited parameter.

Within one sampling block, top-level values take precedence over
`extra_body`. A typed training `top_k=20`, or the automatic replay bound
of `512`, therefore takes precedence over `extra_body.top_k=-1`. With no
typed `top_k`, the disabled sentinel remains effective.

Prime-RL carries `vf.SamplingConfig` through dispatch and converts
`TrainSamplingConfig` once. Source defaults and agent overrides use
Verifiers' `merge_defaults`; duplicate eval schemas and
sampling-dictionary converters are removed. Request-specific cache salts
are copied onto the shared config.

Unresolved agent overrides remain sparse across env-server config
boundaries. `resolve_agent` materializes the sampling used for
generation, and traces record the complete resolved config. Provider
dialects and the renderer client omit nulls when constructing requests.

## Training ownership

Live-policy sources validate their sampling when the config loads.
Unsupported source parameters, including `frequency_penalty`, are
rejected before generation.

The source owns the distribution replayed by the trainer. Every agent in
a live-policy source, including non-trainable roles, may override only
`max_tokens`, `reasoning_effort`, and `chat_template_kwargs`.
Distribution parameters belong on the source, even when an agent would
repeat the same value. Policy logprobs remain enabled. Evaluation and
frozen-model sources retain general agent overrides.

This removes the post-rollout sampling comparison from `TrainSink`.

## Dependency

Pins Verifiers `2cb0a6d`, the merged commit for [Verifiers
#2762](https://github.com/PrimeIntellect-ai/verifiers/pull/2762), for
shared sampling normalization and resolution. This includes merging
per-call judge sampling overrides before constructing SDK requests,
preserving unrelated configured provider parameters. The lockfile
updates `prime-tunnel` to `0.1.14` to meet the merged dependency's
minimum.

Before publishing packages outside this source checkout, release that
Verifiers change and raise the `verifiers` minimum in both `prime-rl`
and `prime-rl-configs`. The current `>=0.3.2.dev158` package constraints
do not guarantee these semantics.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how sampling is resolved and validated for all rollouts;
mis-merged configs or rejected agent overrides could break existing
TOMLs, though unit tests cover the main inheritance and policy rules.
> 
> **Overview**
> **Unifies rollout sampling** on Verifiers' shared `SamplingConfig` and
merge rules instead of Prime-RL–specific eval schemas and
`to_sampling_args()` dict builders.
> 
> Eval sources and group defaults now use `vf.SamplingConfig`;
train/eval env wrappers carry a typed `SamplingConfig` through to the
env server (including per-request `cache_salt` via `model_copy`). Policy
train sources get **load-time validation**: the source owns distribution
parameters (`temperature`, `top_p`, etc.), while agents may only
override `max_tokens`, `reasoning_effort`, and
`chat_template_kwargs`—frozen-model and eval paths stay permissive.
`TrainSink` reads temperature from `env.config.sampling` instead of a
resolved args dict.
> 
> **Docs** describe alias normalization (`max_tokens` /
`max_completion_tokens`), `extra_body` merging, and live-policy override
limits. **Tests** cover inherited sampling merges and policy sampling
rejection cases. Lockfile bumps `prime-tunnel` to `0.1.14`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
671a5aa9857a39a4d44fa7902f1c89021b8fd380. 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 00:30:12 -07:00
Florian BrandandGitHub f7e8ab6456 fix(eval): resume rollouts by task content and selected occurrence (#3808) 2026-10-09 15:47:46 -07:00
84e94bf05c perf(orchestrator): poll for new weight versions every 0.1s instead of 1s (#3952)
## Summary
- `WeightWatcher.poll_interval` default: 1.0s → 0.1s
- `WeightReceiver.wait_published` sleep: 0.2s → 0.1s

## Why
The trainer blocks in `WeightSender._wait_for_receiver_ready` until the
orchestrator notices `.sender_ready`. With a 1s poll, that adds 0–1s
(~0.5s avg) of idle trainer time on every step. NVIDIA flagged this
while benchmarking the ModelExpress broadcast (#3890).

A poll is one `glob("step_*")` on the broadcast dir (≤2 entries thanks
to `_clean`) plus a few `exists()` calls, so 10Hz is negligible.
Correctness relies on the marker handshake + `update_lock`, not on the
poll timing.

Caveat: these are sync FS calls on the orchestrator event loop. On a
very slow shared FS, that might show up in `EventLoopLagMonitor`. If it
does, we can move them to `asyncio.to_thread`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Timing-only tuning on poll loops; no change to weight handshake logic,
though more frequent sync FS calls could add event-loop lag on very slow
filesystems.
> 
> **Overview**
> **Faster weight-version discovery** so the trainer spends less time
blocked waiting for the orchestrator to see `.sender_ready`.
> 
> The orchestrator `WeightWatcher` default `poll_interval` drops from
**1.0s to 0.1s**, cutting typical idle wait on each broadcast handshake
from ~0.5s toward ~0.05s. `WeightReceiver.wait_published` uses the same
**0.1s** sleep (was 0.2s) while waiting for the sender marker.
> 
> Handshake correctness is unchanged (markers + `update_lock`); cost is
slightly more frequent lightweight FS checks on the orchestrator event
loop.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5c825d0f126e16885eae77f4f6ebc2ddf306de59. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:25:55 -07:00
IanandGitHub 37b48a996e security(ci): pin BuildKit builder to v0.33.1 and rotate registry buildcache (CVE-2026-93318) (#3889)
## security(ci): pin BuildKit builder to v0.33.1 and rotate the GHCR
registry buildcache (CVE-2026-93318)

### What changed (rebased onto current main)
`.github/workflows/build_image.yaml`:
1. **Builder pin** — `docker/setup-buildx-action@v4` now sets
`driver-opts: image=moby/buildkit:v0.33.1`. Without it the job starts
the rolling `moby/buildkit:buildx-stable-1` tag, and because these are
persistent self-hosted runners (`image-builder`,
`image-builder-arm-2204`), the builder version is not even guaranteed to
follow the tag — a stale local image can keep a pre-patch builder alive
indefinitely. The pin makes the builder version deterministic.
2. **Registry cache rotation** — both shared cache refs rotated:
- `:dependency-buildcache-<suffix>` ->
`:dependency-buildcache-v2-<suffix>`
- `:application-buildcache-<suffix>` ->
`:application-buildcache-v2-<suffix>`

### Why rotation (evidence)
- The registry-backed cache was introduced in d8f3d0101 (2026-08-16,
#3279) and has been written on nearly every run since — including all
runs before the patch was published.
- BuildKit v0.33.1 (the CVE fix) was released **2026-09-30T17:08Z**; the
rolling `moby/buildkit:buildx-stable-1` tag only moved to that digest at
**2026-09-30T17:32Z**. Every cache write before that timestamp came from
a builder older than v0.33.1, on runners that may also hold stale local
images.
- Per the CVE-2026-93318 playbook: stop importing a shared cache that
pre-fix builders wrote, rebuild from trusted inputs, and pin the patched
builder so every future write is attributable to a fixed version.

### Expected cost
The first run per platform suffix after merge does a cold build of the
dependency layer + application layer (no cache import). The old
`*-buildcache-*` tags can be deleted from the `prime-rl` GHCR package as
cleanup — they are cache-only refs, never deployed.

### Out of scope / notes
- `docker-push.yaml` (old Docker Hub publisher) no longer exists on main
— nothing to pin there.
- No GHA-scope (`type=gha`) caches exist in this repo's workflows
(verified by grep), so no Actions-cache cleanup applies.
- Build image runs are frequent and mostly manual dispatch; this PR
should merge before the next `main` image build.

### Security review requested
- Cache invalidation: confirm the `*-v2-*` refs fully replace the old
buildcache lineage.
- Published-image provenance: GHCR `prime-rl` images built before
2026-09-30T17:32Z were produced by a pre-patch builder; assess whether a
clean rebuild of the current release tags is warranted.
- No applicable CODEOWNERS entry exists in this repo; CI/build owner
please review.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> CI-only security remediation with intentional cache busting (slower
first builds); no application runtime code changes, but GHCR images
built before the fix may need a separate provenance/rebuild decision.
> 
> **Overview**
> Remediates **CVE-2026-93318** in the GHCR image build workflow by
making the BuildKit builder version fixed and breaking reuse of
artifacts produced before the patch.
> 
> **BuildKit pin:** `docker/setup-buildx-action` now sets `driver-opts`
to `moby/buildkit:v0.33.1` (digest-pinned) so self-hosted
`image-builder` runners do not keep serving a stale local
`buildx-stable-1` builder.
> 
> **Cache and deps lineage:** Shared registry cache refs move to
`dependency-buildcache-v2-*` and `application-buildcache-v2-*` so layers
written by pre-v0.33.1 builders are not imported. Dependency base tags
gain a `-v2-` epoch (`deps-${key}-v2-${suffix}`) so existing
`deps-${key}` images are not reused as the runtime base when only
Dockerfile/lock inputs are unchanged.
> 
> The first build per platform after merge is expected to be cold (no
old cache import); published runtime tags are unchanged—only CI
remediation naming and builder configuration.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0310e6d89608d9d34fd0c1a4c0e9a5c6ba5261bf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-09 08:22:03 -07:00
49 changed files with 355 additions and 403 deletions
+20 -5
View File
@@ -192,6 +192,12 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
with:
# CVE-2026-93318: pin the BuildKit builder to the patched release so
# the version is deterministic on the self-hosted runners (otherwise
# the rolling moby/buildkit:buildx-stable-1 tag is used, and a
# persistent runner may keep a stale local copy of it).
driver-opts: image=moby/buildkit:v0.33.1@sha256:cec9f139f45e93c5c69c60f8b07cfad9f43f4ef6b6a6cd917527fea5ff2e3dea
- name: Set up uv
uses: astral-sh/setup-uv@v7
@@ -207,7 +213,12 @@ jobs:
run: |
set -euo pipefail
key=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py fingerprint .)
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-${SUFFIX}"
# deps-v2: remediation epoch for CVE-2026-93318 — the fingerprint
# hashes only Dockerfile/lock inputs, not the workflow or BuildKit
# version, so pre-fix deps-${key} images would otherwise be reused
# as the runtime base instead of being rebuilt by the pinned v0.33.1
# builder.
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-v2-${SUFFIX}"
digest=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py resolve "$image")
echo "image=${image}" >> "$GITHUB_OUTPUT"
echo "digest=${digest}" >> "$GITHUB_OUTPUT"
@@ -222,8 +233,10 @@ jobs:
file: ./Dockerfile.cuda
target: dependencies
outputs: type=image,push=true,compression=zstd,compression-level=3
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
# builders (cache writers since 2026-08-16) must not be re-imported.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: ${{ steps.dependency.outputs.image }}
@@ -240,8 +253,10 @@ jobs:
RENDERERS_PRETEND_VERSION=${{ steps.dependency.outputs.renderers }}
PYDANTIC_CONFIG_PRETEND_VERSION=${{ steps.dependency.outputs.pydantic_config }}
outputs: type=image,push=true,compression=zstd,compression-level=3
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
# builders (cache writers since 2026-08-16) must not be re-imported.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
-4
View File
@@ -6,9 +6,6 @@ level = "debug"
[model]
name = "PrimeIntellect/MiniMax-M2.5-bf16"
[weight_broadcast]
type = "nccl"
[deployment]
type = "multi_node"
num_train_nodes = 4
@@ -35,7 +32,6 @@ fused_lm_head_token_chunk_size = 1024
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[trainer.optim]
type = "adamw"
@@ -36,7 +36,6 @@ keep_last = 1
name = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
@@ -54,9 +53,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "adamw"
@@ -110,4 +106,3 @@ max_model_len = 131072
tensor_parallel_size = 8
enable_prefix_caching = true
enable_expert_parallel = true
enable_return_routed_experts = true
@@ -24,8 +24,6 @@ group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.model.lora]
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -21,8 +21,6 @@ group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.model.lora]
[orchestrator.train.sampling]
max_completion_tokens = 128
+1 -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
+4
View File
@@ -173,6 +173,10 @@ env.agent.runtime.type = "subprocess"
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — holds defaults for its sources. Every field that a group and its sources both have is a default: `env`, `sampling`, `select` and `group_size`, plus `algo` on the train group and `interval` on the eval groups of a training run. Each source inherits the fields that its group sets. One rule applies to all of them: nested blocks merge key by key, a source's own values win, and a block whose `type` (e.g. of `algo`) differs from the group's is the source's alone.
Sampling parameters use Verifiers' shared normalization: `max_tokens` and `max_completion_tokens` name the same limit, and `extra_body` parameters merge like top-level parameters. Agent overrides apply after source defaults; an explicit null clears an inherited parameter. Resolved sampling is recorded on each trace.
For live-policy training, set distribution parameters (`temperature`, `top_p`, `top_k`) on the source's `sampling` block. Every agent in that source, including non-trainable roles, may override only `max_tokens`, `reasoning_effort`, and `chat_template_kwargs`. These rules are checked when loading the config; evaluation and frozen-model sources allow general agent sampling overrides.
```toml
[orchestrator.train]
group_size = 16
+2 -2
View File
@@ -82,7 +82,7 @@ Every source's env server is spawned by the eval process unless the source sets
## Resume
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: the episodes that landed rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch) and only the rollouts still owed run. Errored episodes and the ones the interruption cut off run again.
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: saved episodes with `episode.ok` rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch), and only the rollouts still owed run. Failed episodes and the ones the interruption cut off run again. Saved records that fail schema validation stop the resume before the current stream is archived.
```bash
uv run eval @ eval.toml --run.name my-eval
@@ -92,7 +92,7 @@ uv run eval @ eval.toml --run.name my-eval --resume
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
A landed episode counts toward the task with its `task.key`, so `select` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
A landed episode counts toward a selected task in the same source when their content hashes (`task.hash`) match. A task whose content changes runs again even if its public `task.key` stays the same. `select` and `group_size` may change between launches: each selected occurrence keeps up to `group_size` matching episodes, and only its missing rollouts run. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Each selected occurrence owns a separate group containing its restored and new rollouts, even when the same task is selected more than once, so pass@k and the dashboard see one group per selected occurrence. Use `--clean` to start over instead.
## Monitors
+3 -3
View File
@@ -147,11 +147,11 @@ State-only optimizer offload remains enabled by default with `model.optim_cpu_of
### LM Head Chunking
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization. It defaults to `1024` for RL training:
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization. It defaults to `8192` for RL training:
```toml
[trainer.model]
fused_lm_head_token_chunk_size = 1024 # default
fused_lm_head_token_chunk_size = 8192 # default
# fused_lm_head_token_chunk_size = "disabled" # vanilla LM head
```
@@ -173,7 +173,7 @@ freq = 1
max_inflight_activations = 1
```
The defaults already cover: fused LM head chunking (`1024`), `torch.compile` (fullgraph=False), AC (full mode), AC offloading (`max_inflight_activations=5`), and optimizer CPU offload. Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
The defaults already cover: fused LM head chunking (`8192`), `torch.compile` (fullgraph=False), AC (full mode), AC offloading (`max_inflight_activations=5`), and optimizer CPU offload. Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
## SLURM
@@ -37,7 +37,6 @@ name = "zai-org/GLM-4.5-Air"
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
@@ -53,9 +52,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "muon"
@@ -175,4 +171,3 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
enable_return_routed_experts = true
@@ -47,7 +47,6 @@ keep_last = 1
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
@@ -68,9 +67,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "sign_sgd"
@@ -107,4 +103,3 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
enable_return_routed_experts = true
-2
View File
@@ -48,7 +48,6 @@ keep_last = 1
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
@@ -123,4 +122,3 @@ gpu_memory_utilization = 0.85
max_model_len = 131072
tensor_parallel_size = 8
enable_expert_parallel = true
enable_return_routed_experts = true
@@ -38,7 +38,6 @@ name = "zai-org/GLM-4.5-Air"
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
@@ -54,9 +53,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "muon"
@@ -170,4 +166,3 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
enable_return_routed_experts = true
+1 -1
View File
@@ -89,6 +89,7 @@ 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
dsa_backend = "cudnn_flashmla"
[trainer.model.quantization]
type = "fp8"
@@ -97,7 +98,6 @@ type = "fp8"
type = "deepgemm_fp8"
[trainer.model.ac]
freq = 1
[trainer.model.compile]
-4
View File
@@ -6,9 +6,6 @@ level = "debug"
[model]
name = "PrimeIntellect/INTELLECT-3-Base"
[weight_broadcast]
type = "nccl"
[deployment]
type = "multi_node"
num_train_nodes = 4
@@ -35,7 +32,6 @@ fused_lm_head_token_chunk_size = 1024
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[trainer.optim]
type = "muon"
@@ -6,9 +6,6 @@ level = "debug"
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
[weight_broadcast]
type = "nccl"
[deployment]
type = "multi_node"
num_train_nodes = 2
@@ -33,7 +30,6 @@ ep = 8
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[trainer.optim]
type = "adamw"
-4
View File
@@ -6,9 +6,6 @@ level = "debug"
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
[weight_broadcast]
type = "nccl"
[deployment]
type = "multi_node"
num_train_nodes = 2
@@ -34,7 +31,6 @@ cp = 2
max_inflight_activations = 5
[trainer.model.ac]
freq = 1
[trainer.optim]
type = "adamw"
@@ -26,7 +26,6 @@ name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
cp = 2
[trainer.model.ac]
freq = 1
[trainer.model.compile]
-1
View File
@@ -12,7 +12,6 @@ project = "alphabet-sort"
name = "alphabet-sort"
[trainer.model.ac]
freq = 1
[trainer.model.lora]
rank = 32
-2
View File
@@ -38,8 +38,6 @@ group_size = 16
[orchestrator.concurrency]
initial_inflight = 1024
[orchestrator.model.lora]
[orchestrator.train.sampling]
max_completion_tokens = 512
-1
View File
@@ -1,6 +1,5 @@
# Multimodal (VLM) SFT on a Mixture-of-Experts model — single 8xH200 node.
max_steps = 1000
dist_timeout_seconds = 3600
[model]
name = "Qwen/Qwen3.6-35B-A3B"
-1
View File
@@ -19,7 +19,6 @@ freeze_vision_encoder = true
rank = 16
[model.ac]
freq = 1
[data]
type = "sft"
@@ -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."""
@@ -6,6 +6,7 @@ import verifiers.v1 as vf
from pydantic import AliasChoices, BaseModel, Field, SerializeAsAny, TypeAdapter, ValidationError, model_validator
from pydantic.fields import FieldInfo
from renderers import AutoRendererConfig, RendererConfig
from verifiers.v1.configs.agent import agent_config_fields
from prime_rl.configs.algorithm import (
AlgoConfig,
@@ -18,9 +19,9 @@ from prime_rl.configs.shared import (
FileSystemWeightBroadcastConfig,
HeartbeatConfig,
LogConfig,
PolicyClientConfig,
ResumeConfig,
TransportConfig,
VLLMClientConfig,
WeightBroadcastConfig,
ZMQTransportConfig,
)
@@ -28,19 +29,8 @@ from prime_rl.configs.trainer import TokenizerConfig
from prime_rl.utils.config import BaseConfig, default_output_dir
class LoRAConfig(BaseConfig):
rank: int | None = Field(None, ge=1)
"""LoRA rank for this run. Must be ≤ trainer's max rank. If None, uses the trainer's rank."""
alpha: float | None = Field(None, ge=0)
"""LoRA alpha for this run. If None, uses the trainer's alpha."""
class ModelConfig(BaseModelConfig):
lora: LoRAConfig | None = None
"""Per-run LoRA configuration. If None, LoRA is disabled."""
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
client: PolicyClientConfig = Field(default_factory=PolicyClientConfig)
"""Client of the live deployment (``[orchestrator.model.client]``)."""
@@ -90,70 +80,6 @@ class TrainSamplingConfig(BaseConfig):
)
return self
def to_sampling_args(self) -> dict[str, Any]:
"""Convert to OAI-compatible sampling args dict, omitting None values."""
args: dict[str, Any] = {
"temperature": self.temperature,
"top_p": self.top_p,
"logprobs": True,
}
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens
# top_k rides extra_body (like EvalSamplingConfig), overriding the sentinel.
extra_body = dict(self.extra_body)
if self.top_k is not None:
extra_body["top_k"] = self.top_k
if extra_body:
args["extra_body"] = extra_body
return args
class EvalSamplingConfig(BaseConfig):
temperature: float | None = Field(None, ge=0, le=2.0)
"""Sampling temperature. None defers to the inference server default."""
top_p: float | None = None
"""Nucleus sampling threshold. None defers to the inference server default."""
top_k: int | None = None
"""Top-k sampling. None defers to the inference server default."""
min_p: float | None = Field(None, ge=0)
"""Min-p sampling threshold. None defers to the inference server default."""
max_completion_tokens: int | None = None
"""Maximum output tokens per turn. None defers to the inference server default."""
reasoning_effort: Literal["minimal", "low", "medium", "high"] | None = None
"""Reasoning effort constraint for reasoning models."""
extra_body: dict[str, Any] = {}
"""Extra body parameters forwarded to the inference server."""
def to_sampling_args(self) -> dict[str, Any]:
"""Convert to OAI-compatible sampling args dict. Only includes non-None fields."""
args: dict[str, Any] = {}
if self.temperature is not None:
args["temperature"] = self.temperature
if self.top_p is not None:
args["top_p"] = self.top_p
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens
if self.reasoning_effort is not None:
args["reasoning_effort"] = self.reasoning_effort
extra_body = dict(self.extra_body)
if self.top_k is not None:
extra_body["top_k"] = self.top_k
if self.min_p is not None:
extra_body["min_p"] = self.min_p
if extra_body:
args["extra_body"] = extra_body
return args
class EnvConfig(BaseConfig):
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
@@ -316,9 +242,37 @@ class TrainSourceConfig(EnvConfig):
"""User-authored task sampler and admission gates. The default cycles
through the taskset and admits every finalized group."""
@model_validator(mode="after")
def validate_policy_sampling(self):
if self.algo.sampling.source != "policy":
return self
# The source owns the distribution replayed by the trainer; agents may
# change generation limits and rendering without changing that distribution.
agent_options = {"max_tokens", "reasoning_effort", "chat_template_kwargs"}
supported = (
agent_options
| TrainSamplingConfig.model_fields.keys()
| {"min_p", "logprobs", "return_token_ids", "cache_salt"}
)
sampling = vf.SamplingConfig(**self.sampling.model_dump(exclude_none=True))
if unsupported := sampling.model_dump(exclude_none=True).keys() - supported:
raise ValueError(
f"Policy source '{self.resolved_name}' has unsupported sampling parameters: {sorted(unsupported)}"
)
for name, agent in agent_config_fields(self.env).items():
if agent.sampling is None:
continue
if unsupported := agent.sampling.model_dump(exclude_unset=True).keys() - agent_options:
raise ValueError(
f"Agent '{name}' in policy source '{self.resolved_name}' sets sampling {sorted(unsupported)}. "
"Set distribution parameters on the source's sampling config; agent sampling only supports "
f"{sorted(agent_options)}."
)
return self
class EvalSourceConfig(EnvConfig):
sampling: EvalSamplingConfig = EvalSamplingConfig()
sampling: vf.SamplingConfig = vf.SamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
group_size: int = Field(1, ge=1)
@@ -409,7 +363,7 @@ class EvalSourcesConfig(SourceGroupConfig):
source: list[EvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources."""
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
sampling: vf.SamplingConfig = Field(default_factory=vf.SamplingConfig)
"""Sampling that every eval source inherits; can differ from training sampling."""
select: vf.SelectConfig = vf.SelectConfig()
@@ -475,12 +429,6 @@ class CheckpointConfig(BaseConfig):
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."""
keep_last: int | None = Field(None, ge=1)
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
keep_interval: int | None = Field(None, ge=1)
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
class ConcurrencyConfig(BaseConfig):
"""Adaptive in-flight concurrency control. The orchestrator sizes the
@@ -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},
@@ -470,37 +477,6 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_lora(self):
if self.trainer.model.lora is not None:
if self.orchestrator.model.lora is None:
from prime_rl.configs.orchestrator import LoRAConfig
self.orchestrator.model.lora = LoRAConfig()
if (
self.orchestrator.model.lora.rank is not None
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
):
raise ValueError(
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
)
if (
self.orchestrator.model.lora.alpha is not None
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
):
raise ValueError(
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
)
if self.orchestrator.model.lora.rank is None:
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.model.lora.alpha is None:
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
if self.inference is not None:
self.inference.vllm.enable_lora = True
self.inference.vllm.max_lora_rank = self.trainer.model.lora.rank
@@ -223,9 +223,6 @@ class ClientConfig(BaseClientConfig):
admin_base_url: list[str] | None = None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in multi-replica or disaggregated P/D deployments where the router must not handle admin traffic."""
dynamo: DynamoConfig | None = None
"""Dynamo RL worker-discovery configuration."""
class VLLMClientConfig(ClientConfig):
"""Client defaults for the live inference deployment managed by training."""
@@ -234,6 +231,13 @@ class VLLMClientConfig(ClientConfig):
api_key_var: str = "VLLM_API_KEY"
class PolicyClientConfig(VLLMClientConfig):
"""Client of the policy deployment the orchestrator drives (weight updates, admin plane)."""
dynamo: DynamoConfig | None = None
"""Dynamo RL worker-discovery configuration."""
class LogConfig(BaseConfig):
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
"""Log level for the process. Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``."""
@@ -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."""
@@ -86,8 +86,8 @@ def propagate_shared_fields(data: Any) -> Any:
# ``orchestrator.ckpt`` has no ``output_dir`` field — trainer-only.
propagate("ckpt.output_dir", "trainer.ckpt.output_dir")
propagate("ckpt.interval", "trainer.ckpt.interval", "orchestrator.ckpt.interval")
propagate("ckpt.keep_last", "trainer.ckpt.keep_last", "orchestrator.ckpt.keep_last")
propagate("ckpt.keep_interval", "trainer.ckpt.keep_interval", "orchestrator.ckpt.keep_interval")
propagate("ckpt.keep_last", "trainer.ckpt.keep_last")
propagate("ckpt.keep_interval", "trainer.ckpt.keep_interval")
# [monitors.wandb] leaves. (Bare empty ``[monitors.wandb]`` block enablement is at the end.)
# ``monitors.wandb.name`` flows verbatim to both sub-configs — shared W&B mode is
@@ -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`.
+5 -6
View File
@@ -8,6 +8,8 @@ rollouts still owed run (``prime_rl.eval.resume``)."""
from __future__ import annotations
import verifiers.v1 as vf
from prime_rl import monitors
from prime_rl.configs.eval import EvalConfig
from prime_rl.eval import resume
@@ -24,7 +26,7 @@ class Eval:
async def run(self) -> None:
config = self.config
landed: list[dict] = []
landed: list[vf.WireEpisode] = []
if config.resume:
# read and set aside before the monitors start: the resumed attempt writes a fresh stream
landed = resume.take_landed(config.run_dir)
@@ -41,17 +43,14 @@ class Eval:
)
resume.stamp_config(config.run_dir, dump_resolved_config(config))
await self.runner.setup()
restored: list = []
fired, restored = self.runner.eval_source.trigger(0, completed=landed)
if config.resume:
restored, owed, groups = resume.plan(landed, self.runner.eval_envs)
self.runner.eval_source.restore(owed, groups)
get_logger().info(
f"Resuming from the trace stream: {len(restored)} episodes restored, "
f"{sum(sum(counts.values()) for counts in owed.values())} rollouts owed"
f"{sum(request.rollouts or 0 for request in self.runner.eval_source.queue)} rollouts owed"
)
await self.runner.start()
fired = self.runner.eval_source.trigger(0)
await self.runner.run_epoch(fired, 0, restored=restored)
await self.runner.drain()
+1 -1
View File
@@ -178,7 +178,7 @@ class OnlineEval:
# Trigger before the reload: the dispatcher only schedules eval in PREFER_EVAL,
# so nothing dispatches until ``run_epoch`` switches modes below.
fired = runner.eval_source.trigger(step, force=force)
fired, _ = runner.eval_source.trigger(step, force=force)
self.last_step = max(self.last_step, step)
if reload_weights:
+14 -50
View File
@@ -1,20 +1,18 @@
"""Resume an interrupted eval from its trace stream.
The stream records what landed, so it is what a resume continues from. The run's ok
episodes are read back and rejoin the epoch as if they had just arrived - through the
monitors, so the rebuilt stream, the epoch's metrics and the platform upload cover the
whole epoch - and only the rollouts still owed run. Errored episodes and the in-flight
The stream records what landed, so it is what a resume continues from. Successful
episodes rejoin the epoch through the monitors as if they had just arrived,
so the rebuilt stream, the epoch's metrics and the platform upload cover the
whole epoch - and only the rollouts still owed run. Failed episodes and the in-flight
ones the interruption cut off are owed again.
A landed episode counts toward the task with its ``task.key``, so a resumed run may
select more or fewer examples or rollouts per example than the interrupted one: the
kept episodes are matched to the new selection and the rest is owed. The resumed
config is not checked against the interrupted one: any of it may be overridden.
The shared Verifiers rollout planner matches these episodes to the current tasks
by content hash. The resumed config is not checked against the interrupted one:
any of it may be overridden.
"""
from __future__ import annotations
from collections import Counter, defaultdict
from collections.abc import Iterator
from pathlib import Path
@@ -23,7 +21,6 @@ import verifiers.v1 as vf
from prime_rl.monitors.file.traces import get_trace_stream
from prime_rl.monitors.file.traces.chunks import chunk_numbers, open_chunk
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.utils.pathing import get_file_monitor_dir
CONFIG_NAME = "eval.json"
@@ -57,52 +54,19 @@ def archives(run_dir: Path) -> list[Path]:
return sorted(monitors.glob("file.attempt_*"), key=lambda path: int(path.name.rsplit("_", 1)[1]))
def take_landed(run_dir: Path) -> list[dict]:
"""The ok eval episodes the run has landed, each once, from every attempt's stream.
def take_landed(run_dir: Path) -> list[vf.WireEpisode]:
"""Successful episodes from every attempt; the planner deduplicates them.
The current file monitor directory joins the archives so the resumed attempt writes a
fresh stream, plan and metrics; nothing is deleted."""
current = get_file_monitor_dir(run_dir)
stream = get_trace_stream(run_dir).relative_to(current)
landed: dict[str, dict] = {}
landed: list[vf.WireEpisode] = []
for directory in [*archives(run_dir), current]:
if (directory / stream).is_dir():
for record in read_records(directory / stream):
if record.get("ok"):
landed.setdefault(record["id"], record)
episode = vf.WireEpisode.model_validate(record)
if episode.ok and "traces" in record:
landed.append(episode)
if current.is_dir():
current.rename(current.with_name(f"file.attempt_{len(archives(run_dir)) + 1}"))
return list(landed.values())
def plan(
landed: list[dict], eval_envs: EvalEnvs
) -> tuple[list[vf.WireEpisode], dict[str, dict[str, int]], dict[str, dict[str, str]]]:
"""Match the landed episodes to the run's tasks: the episodes to keep, in stream
order, the rollouts still owed per env and task key, and the group id a task's kept
episodes carry, so the owed ones complete that group rather than open another."""
targets: dict[str, Counter[str]] = {}
for env in eval_envs:
targets[env.name] = Counter(task.key for task in env.examples)
for key in targets[env.name]:
targets[env.name][key] *= env.config.group_size
kept: list[vf.WireEpisode] = []
counts: dict[str, Counter[str]] = defaultdict(Counter)
groups: dict[str, dict[str, str]] = defaultdict(dict)
for record in landed:
env_name = record["env"].get("name") or record["env"]["id"]
key = record["task"]["key"]
if counts[env_name][key] >= targets.get(env_name, Counter())[key]:
continue
kept.append(vf.WireEpisode.model_validate(record))
counts[env_name][key] += 1
if (group := record.get("group") or {}).get("id"):
groups[env_name].setdefault(key, group["id"])
owed = {
env_name: {
key: target - counts[env_name][key]
for key, target in target_counts.items()
if target > counts[env_name][key]
}
for env_name, target_counts in targets.items()
}
return kept, owed, dict(groups)
return landed
+1 -1
View File
@@ -105,7 +105,7 @@ class EvalRunner:
# Pessimistic per-episode token cost for the controller's starting cap,
# only used when the engine doesn't report its max context length.
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.source) or 8192
fallback_cost = max((source.sampling.max_tokens or 0) for source in config.source) or 8192
self.concurrency = ConcurrencyController(config.concurrency, fallback_cost=fallback_cost)
self.dispatcher = Dispatcher(
train_envs=None,
+3 -3
View File
@@ -10,7 +10,7 @@ from typing import Literal
import httpx
from pydantic import BaseModel, Field
from prime_rl.configs.shared import ClientConfig
from prime_rl.configs.shared import ClientConfig, PolicyClientConfig
from prime_rl.orchestrator.clients import (
ADMIN_TIMEOUT_S,
UPDATE_WEIGHTS_TIMEOUT_S,
@@ -100,7 +100,7 @@ def _discovery_headers(client_config: ClientConfig) -> dict[str, str]:
return headers
def resolve_dynamo_discovery_url(client_config: ClientConfig) -> str:
def resolve_dynamo_discovery_url(client_config: PolicyClientConfig) -> str:
dynamo = client_config.dynamo
if dynamo is None or not dynamo.enabled:
raise ValueError("Dynamo discovery is not enabled")
@@ -156,7 +156,7 @@ class DynamoAdminPlane(AdminPlane):
def __init__(
self,
client_config: ClientConfig,
client_config: PolicyClientConfig,
model_name: str,
*,
poll_interval: float = 1.0,
+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,
}
+2 -2
View File
@@ -21,7 +21,7 @@ from verifiers.v1.configs.client import (
)
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.configs.shared import ClientConfig, PolicyClientConfig
from prime_rl.utils.logger import get_logger
@@ -209,7 +209,7 @@ class AdminPlane:
await client.aclose()
def setup_admin_plane(client_config: ClientConfig, model_name: str) -> AdminPlane:
def setup_admin_plane(client_config: PolicyClientConfig, model_name: str) -> AdminPlane:
dynamo = client_config.dynamo
if dynamo is not None and dynamo.enabled:
from prime_rl.inference.dynamo import DynamoAdminPlane
+10 -9
View File
@@ -67,7 +67,7 @@ class Env:
self.address_file = address_file
"""Where a launcher-managed server publishes its address; read when ``address``
is None."""
self.sampling_args: dict = {}
self.sampling = vf.SamplingConfig()
self.num_tasks: int | None = 0
"""Task count; ``None`` means the selected tasks never end."""
self.tasks: Iterator[vf.Task] | None = None
@@ -110,10 +110,10 @@ class Env:
get_logger().info(f"Env {self.name} ready in {format_time(time.perf_counter() - t0)} (num_tasks={num_tasks})")
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
sampling = {**self.sampling_args}
sampling = self.sampling
if cache_salt is not None:
sampling["extra_body"] = {**sampling.get("extra_body", {}), "cache_salt": cache_salt}
return vf.SamplingConfig(**sampling)
sampling = sampling.model_copy(update={"cache_salt": cache_salt})
return sampling
async def run(
self,
@@ -155,10 +155,11 @@ class TrainEnv(Env):
self.connected: InferenceClient | None = None
self.algorithm = algorithm
self.uses_live_policy = config.algo.sampling.source == "policy"
self.sampling_args = config.sampling.to_sampling_args()
if not self.uses_live_policy:
# Logprobs only feed importance ratios on policy-sampled tokens; frozen endpoints may reject the knob.
self.sampling_args.pop("logprobs", None)
self.sampling = vf.SamplingConfig(
**config.sampling.model_dump(exclude_none=True),
# Only policy rollouts need sampling logprobs for importance ratios.
logprobs=True if self.uses_live_policy else None,
)
# Truncated policy sampling must ship the sampling masks the trainer replays.
self.requires_sampling_masks = config.sampling.truncates_distribution() and self.uses_live_policy
@@ -182,7 +183,7 @@ class EvalEnv(Env):
def __init__(self, config: EvalSourceConfig, address: str | None, address_file: Path):
super().__init__(config, address, address_file)
self.sampling_args = config.sampling.to_sampling_args()
self.sampling = config.sampling
self.examples: list[vf.Task] = []
async def start(self) -> None:
+26 -27
View File
@@ -6,15 +6,18 @@ including startup. The dispatcher pulls via ``next_task()`` until
from __future__ import annotations
from collections import deque
import uuid
from collections import defaultdict, deque
from collections.abc import Iterable
from itertools import zip_longest
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from verifiers.v1.utils.eval import plan_rollouts
from prime_rl.orchestrator.types import TaskRequest
if TYPE_CHECKING:
import verifiers.v1 as vf
from prime_rl.orchestrator.envs import EvalEnvs
@@ -42,54 +45,50 @@ class EvalSource:
self.intervals[env.name] = intervals[env.name] if intervals is not None else 1
self.queue: deque[TaskRequest] = deque()
self.owed: dict[str, dict[str, int]] | None = None
self.groups: dict[str, dict[str, str]] = {}
# A fresh run evaluates the base policy. Resumed runs apply interval
# rules to the loaded checkpoint and later policies.
self.first_trigger = not is_resumed
def restore(self, owed: dict[str, dict[str, int]], groups: dict[str, dict[str, str]]) -> None:
"""Rollouts the next trigger still owes per env and task key, the rest having
landed before a resume; a task without an entry is complete. ``groups`` is the
group id the landed rollouts of a task carry, which the owed ones join."""
self.owed = owed
self.groups = groups
def trigger(self, step: int, *, force: bool = False) -> list[str]:
"""Fire eligible envs for ``step`` and return their names. On resume
def trigger(
self, step: int, *, force: bool = False, completed: Iterable[vf.WireEpisode] = ()
) -> tuple[list[str], list[vf.WireEpisode]]:
"""Fire eligible envs and return their names and matched saved episodes. On resume
``first_trigger`` is False, so the startup/base eval doesn't re-run.
``force`` fires every env regardless of interval (e.g. the evals process's
final-checkpoint eval)."""
is_first, self.first_trigger = self.first_trigger, False
if is_first and self.skip_first_step:
return []
return [], []
fired = [
name
for name, interval in self.intervals.items()
if (is_first or force or step % interval == 0) and self.tasks_by_env[name]
]
owed, self.owed = self.owed, None
saved: dict[str, list[vf.WireEpisode]] = defaultdict(list)
for episode in completed:
saved[episode.env.name or episode.env.id].append(episode)
restored: list[vf.WireEpisode] = []
# Round-robin across fired envs (A₁, B₁, A₂, B₂, …) so the
# dispatcher rotates at example granularity. ``try_schedule``'s
# continue-group branch still keeps each example's group_size
# rollouts back-to-back, so per-example prefix-cache locality holds
iters = [iter(self.tasks_by_env[name]) for name in fired]
iters = [iter(plan_rollouts(self.tasks_by_env[name], self.group_sizes[name], saved[name])) for name in fired]
for round_tasks in zip_longest(*iters):
for env_name, task in zip(fired, round_tasks, strict=True):
if task is None:
for env_name, planned in zip(fired, round_tasks, strict=True):
if planned is None:
continue
rollouts = self.group_sizes[env_name]
if owed is not None:
# duplicate tasks share a key: each takes up to a group of what the key owes
rollouts = min(rollouts, owed[env_name].get(task.key, 0))
owed[env_name][task.key] = owed[env_name].get(task.key, 0) - rollouts
task, kept, rollouts = planned
# Each selected occurrence owns one group, including its restored episodes.
group = vf.GroupInfo(id=str(uuid.uuid4()))
for episode in kept:
episode.group = group
restored.extend(kept)
if rollouts > 0:
group_id = self.groups.get(env_name, {}).get(task.key)
self.queue.append(
TaskRequest(env_name=env_name, task=task, step=step, rollouts=rollouts, group_id=group_id)
TaskRequest(env_name=env_name, task=task, step=step, rollouts=rollouts, group_id=group.id)
)
return fired
return fired, restored
def next_task(self) -> TaskRequest | None:
"""Pop the next eval task, or ``None`` when the queue is empty."""
+1 -1
View File
@@ -766,7 +766,7 @@ class Orchestrator:
if self.resume_step == step and self.config.eval is not None and not self.config.eval.retrigger_on_resume:
return
is_final = self.config.max_steps is not None and step >= self.config.max_steps
fired = self.eval_source.trigger(step, force=is_final)
fired, _ = self.eval_source.trigger(step, force=is_final)
if not fired:
return
self.eval_triggered_steps.add(step)
+1 -1
View File
@@ -255,7 +255,7 @@ class TrainSink:
return
samples_by_trace: dict[str, list[TrainingSample]] = {}
temperature = env.sampling_args["temperature"]
temperature = env.config.sampling.temperature
for trace in survivors:
samples = await asyncio.to_thread(trace_to_samples, trace, env_name=env_name)
for sample in samples:
+1 -1
View File
@@ -24,7 +24,7 @@ class WeightWatcher:
policy: Policy,
observers: list[VersionObserver],
ckpt_step: int = 0,
poll_interval: float = 1.0,
poll_interval: float = 0.1,
) -> None:
self.receiver = receiver
self.policy = policy
+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.
+1 -1
View File
@@ -153,7 +153,7 @@ class WeightReceiver(ABC):
while not sender_ready.exists():
if cancelled is not None and cancelled():
raise asyncio.CancelledError
await asyncio.sleep(0.2)
await asyncio.sleep(0.1)
def _ack(self, step: int) -> None:
"""Acknowledge the offered version — unblocks the waiting trainer."""
+87 -27
View File
@@ -1,6 +1,11 @@
import uuid
from types import SimpleNamespace
import orjson
import pytest
import verifiers.v1 as vf
from pydantic import ValidationError
from verifiers.v1.utils.eval import plan_rollouts
from prime_rl.eval import resume
from prime_rl.monitors.file.traces import get_trace_stream
@@ -21,6 +26,7 @@ def _env(name: str, task_keys: list[str], *, group_size: int = 1) -> SimpleNames
def _record(env: str, key: str, *, ok: bool = True, group: str | None = None) -> dict:
return {
"id": uuid.uuid4().hex,
"env": {"id": env, "name": env},
"task": {"type": "Task", "data": {"idx": 0}, "key": key, "hash": key},
"group": {"id": group or f"group-{key}"},
@@ -29,38 +35,64 @@ def _record(env: str, key: str, *, ok: bool = True, group: str | None = None) ->
}
def test_plan_keeps_landed_rollouts_up_to_the_target_and_owes_the_rest() -> None:
envs = [_env("math", ["m0", "m1", "m2"], group_size=2), _env("code", ["c0"])]
landed = [
_record("math", "m0"),
_record("math", "m0"),
_record("math", "m0"), # a third rollout of m0 exceeds group_size 2
_record("math", "m1"),
_record("math", "m9"), # no longer selected (select.limit shrank)
_record("code", "c0", ok=False), # errored: owed again
]
@pytest.mark.parametrize(
"hashes,rollouts,landed,expected_kept,expected_missing",
[
(["a", "b"], 2, [], [[], []], [2, 2]),
(["a"], 1, [("e1", "a")], [["e1"]], [0]),
(["changed"], 1, [("e1", "a")], [[]], [1]),
(["a"], 3, [("e1", "a"), ("e2", "a")], [["e1", "e2"]], [1]),
(["a"], 1, [("e1", "a"), ("e2", "a")], [["e1"]], [0]),
(["a", "a"], 2, [("e1", "a")], [["e1"], []], [1, 2]),
(["a", "changed"], 1, [("e1", "a"), ("e2", "a")], [["e1"], []], [0, 1]),
(["a"], 2, [("e1", "a"), ("e1", "a")], [["e1"]], [1]),
(["a"], 1, [("e1", "removed")], [[]], [1]),
([], 1, [("e1", "a")], [], []),
],
)
def test_plan_keeps_landed_rollouts_up_to_the_target_and_owes_the_rest(
hashes, rollouts, landed, expected_kept, expected_missing
) -> None:
tasks = [SimpleNamespace(key="stable-key", hash=content_hash) for content_hash in hashes]
episodes = []
for episode_id, content_hash in landed:
row = _record("math", "stable-key")
row["id"] = episode_id
row["task"]["hash"] = content_hash
episodes.append(vf.WireEpisode.model_validate(row))
kept, owed, groups = resume.plan([record for record in landed if record["ok"]], envs)
plan = plan_rollouts(tasks, rollouts, episodes)
assert [(episode.env.name, episode.task.key) for episode in kept] == [
("math", "m0"),
("math", "m0"),
("math", "m1"),
]
assert owed == {"math": {"m1": 1, "m2": 2}, "code": {"c0": 1}}
# the owed rollout of m1 completes the group its landed rollout opened
assert groups == {"math": {"m0": "group-m0", "m1": "group-m1"}}
assert [task for task, _, _ in plan] == tasks
assert [[episode.id for episode in kept] for _, kept, _ in plan] == expected_kept
assert [missing for _, _, missing in plan] == expected_missing
assert all(len(kept) + missing == rollouts for _, kept, missing in plan)
def test_trigger_queues_only_owed_rollouts() -> None:
source = EvalSource([_env("math", ["m0", "m1", "m2"], group_size=2), _env("code", ["c0"])])
source.restore({"math": {"m1": 1, "m2": 2}, "code": {}}, {"math": {"m1": "group-m1"}})
source = EvalSource([_env("math", ["m0", "m1", "m1"], group_size=2), _env("code", ["m1"])])
episodes = [vf.WireEpisode.model_validate(_record("math", key)) for key in ["m0", "m0", "m1"]]
assert source.trigger(0) == ["math", "code"]
assert [(request.env_name, request.task.key, request.rollouts, request.group_id) for request in source.queue] == [
("math", "m1", 1, "group-m1"),
("math", "m2", 2, None),
fired, restored = source.trigger(0, completed=episodes)
assert fired == ["math", "code"]
requests = list(source.queue)
assert [(request.env_name, request.task.key, request.rollouts) for request in requests] == [
("code", "m1", 1),
("math", "m1", 1),
("math", "m1", 2),
]
assert restored == episodes
assert len({request.group_id for request in requests}) == 3
assert restored[-1].group.id == requests[1].group_id
assert restored[0].group == restored[1].group
assert restored[0].group != restored[-1].group
assert all(str(uuid.UUID(request.group_id)) == request.group_id for request in requests)
# Saved episodes affect only this epoch; later triggers plan every rollout again.
source.queue.clear()
assert source.trigger(1) == (["math", "code"], [])
assert [request.rollouts for request in source.queue] == [2, 1, 2, 2]
def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
@@ -71,11 +103,39 @@ def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
stream.close()
land("m0", "m1")
assert [record["id"] for record in resume.take_landed(tmp_path)] == ["m0", "m1"]
assert [episode.id for episode in resume.take_landed(tmp_path)] == ["m0", "m1"]
assert not get_file_monitor_dir(tmp_path).exists()
assert [path.name for path in resume.archives(tmp_path)] == ["file.attempt_1"]
# the resumed attempt re-logged one episode and landed a new one before it died
land("m0", "m2")
assert [record["id"] for record in resume.take_landed(tmp_path)] == ["m0", "m1", "m2"]
landed = resume.take_landed(tmp_path)
source = EvalSource([_env("math", ["m0", "m1", "m2"], group_size=2)])
_, kept = source.trigger(0, completed=landed)
assert [episode.id for episode in kept] == ["m0", "m1", "m2"]
assert [request.rollouts for request in source.queue] == [1, 1, 1]
assert [path.name for path in resume.archives(tmp_path)] == ["file.attempt_1", "file.attempt_2"]
@pytest.mark.parametrize("ok", [True, False])
@pytest.mark.parametrize("traces,valid", [([], True), (None, False), ([{}], False)])
def test_resume_validates_saved_episodes(tmp_path, ok, traces, valid) -> None:
record = {**_record("math", "m0", ok=ok), "id": "saved", "traces": traces}
stream = ChunkedJsonl(get_trace_stream(tmp_path), max_bytes=1 << 20, compress=False)
for row in [{key: value for key, value in record.items() if key != "traces"}, record]:
stream.append(orjson.dumps(row, option=orjson.OPT_APPEND_NEWLINE))
stream.close()
if not valid:
with pytest.raises(ValidationError):
resume.take_landed(tmp_path)
assert get_file_monitor_dir(tmp_path).is_dir()
assert resume.archives(tmp_path) == []
return
landed = resume.take_landed(tmp_path)
source = EvalSource([_env("math", ["m0"], group_size=2)])
_, restored = source.trigger(0, completed=landed)
assert [episode.id for episode in restored] == (["saved"] if ok else [])
assert [request.rollouts for request in source.queue] == [1 if ok else 2]
+7 -7
View File
@@ -3,7 +3,7 @@ from unittest.mock import AsyncMock, patch
import pytest
from prime_rl.configs.shared import ClientConfig
from prime_rl.configs.shared import PolicyClientConfig
from prime_rl.inference.dynamo import (
DynamoAdminPlane,
DynamoDiscoveryPending,
@@ -42,7 +42,7 @@ def parsed(*workers: dict):
def admin_for(*workers: dict) -> DynamoAdminPlane:
config = ClientConfig(
config = PolicyClientConfig(
base_url="http://worker:8000/v1",
skip_model_check=True,
wait_for_ready_timeout=2,
@@ -96,7 +96,7 @@ def test_dynamo_admin_plane_factory_pins_two_identical_snapshots():
discovered_worker = parsed(worker(1))
discover = AsyncMock(side_effect=[discovered_worker, discovered_worker])
admin = setup_admin_plane(
ClientConfig(
PolicyClientConfig(
base_url="http://worker:8000/v1",
skip_model_check=True,
wait_for_ready_timeout=2,
@@ -124,7 +124,7 @@ def test_dynamo_admin_plane_factory_pins_two_identical_snapshots():
def test_dynamo_worker_client_propagates_admin_headers(monkeypatch, api_key, authorization):
monkeypatch.setenv("DYNAMO_HEADER", "from-env")
monkeypatch.setenv("DYNAMO_API_KEY", api_key)
config = ClientConfig(
config = PolicyClientConfig(
base_url="http://worker:8000/v1",
headers={"X-Static": "static"},
headers_from_env={"X-Environment": "DYNAMO_HEADER"},
@@ -144,7 +144,7 @@ def test_dynamo_worker_client_propagates_admin_headers(monkeypatch, api_key, aut
def test_dynamo_admin_plane_derives_discovery_url_from_client_port():
admin = setup_admin_plane(
ClientConfig(
PolicyClientConfig(
base_url="http://worker:8000/v1",
dynamo={"enabled": True},
),
@@ -158,7 +158,7 @@ def test_dynamo_admin_plane_derives_discovery_url_from_client_port():
def test_dynamo_admin_plane_can_be_disabled():
admin = setup_admin_plane(
ClientConfig(
PolicyClientConfig(
base_url="http://worker:8000/v1",
dynamo={"enabled": False},
),
@@ -172,7 +172,7 @@ def test_dynamo_admin_plane_can_be_disabled():
def test_dynamo_discovery_url_derivation_requires_an_explicit_port():
with pytest.raises(ValueError, match="Set dynamo.discovery_url"):
setup_admin_plane(
ClientConfig(
PolicyClientConfig(
base_url="http://worker/v1",
dynamo={"enabled": True},
),
+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)
+86 -4
View File
@@ -4,6 +4,7 @@ from typing import Annotated, Literal, get_args
import pytest
import tomli_w
import verifiers.v1 as vf
from pydantic import BaseModel, Field, ValidationError
from pydantic_config import ConfigFileError
from renderers import custom_renderer_config
@@ -17,6 +18,7 @@ from prime_rl.configs.orchestrator import (
RLOnlineEvalConfig,
ScheduledEvalConfig,
TrainConfig,
TrainSourceConfig,
)
from prime_rl.configs.orchestrator import (
ModelConfig as OrchestratorModelConfig,
@@ -462,11 +464,25 @@ def test_env_algo_inherits_the_group_algo():
assert [env.algo.type for env in reloaded.train.source] == ["grpo", "echo", "echo"]
def test_sources_inherit_the_group_fields_they_leave_unset():
@pytest.mark.parametrize("group_token_key", ["max_tokens", "max_completion_tokens"])
@pytest.mark.parametrize("source_token_key", ["max_tokens", "max_completion_tokens"])
@pytest.mark.parametrize("source_token_limit", [200, None])
@pytest.mark.parametrize("nested_sampling", [False, True])
def test_sources_inherit_the_group_fields_they_leave_unset(
group_token_key, source_token_key, source_token_limit, nested_sampling
):
overrides = {source_token_key: source_token_limit, "top_k": 20}
config = EvalConfig.model_validate(
{
"r": 4,
"sampling": {"temperature": 0.5, "extra_body": {"a": 1}},
"sampling": {
group_token_key: 100,
"temperature": 3.0,
"reasoning_effort": "xhigh",
"top_k": 40,
"frequency_penalty": 0.5,
"extra_body": {"a": 1},
},
"select": {"limit": 8, "include": {"idx": [":100"]}},
"env": {"retries": {"max_retries": 3}},
"source": [
@@ -475,7 +491,11 @@ def test_sources_inherit_the_group_fields_they_leave_unset():
"name": "b",
"env": {"taskset": {"id": "gsm8k"}},
"group_size": 2,
"sampling": {"extra_body": {"b": 2}},
"sampling": {
**({} if nested_sampling else overrides),
"reasoning_effort": "max",
"extra_body": {"b": 2, **(overrides if nested_sampling else {})},
},
"select": {"include": {"names": ["x"]}},
},
],
@@ -483,7 +503,18 @@ def test_sources_inherit_the_group_fields_they_leave_unset():
)
a, b = config.source
assert (a.group_size, b.group_size) == (4, 2)
assert b.sampling.temperature == 0.5 and b.sampling.extra_body == {"a": 1, "b": 2}
assert isinstance(a.sampling, vf.SamplingConfig) and isinstance(b.sampling, vf.SamplingConfig)
assert a.sampling.max_tokens == 100 and b.sampling.max_tokens == source_token_limit
assert a.sampling.reasoning_effort == "xhigh" and a.sampling.top_k == 40
assert b.sampling.model_dump(exclude_none=True) == {
**({"max_tokens": source_token_limit} if source_token_limit is not None else {}),
"temperature": 3.0,
"reasoning_effort": "max",
"top_k": 20,
"frequency_penalty": 0.5,
"a": 1,
"b": 2,
}
assert b.select.limit == 8 and b.select.include.idx == [":100"] and b.select.include.names == ["x"]
assert a.env.retries.max_retries == 3 and b.env.retries.max_retries == 3
reloaded = EvalConfig.model_validate(config.model_dump(mode="json"))
@@ -564,6 +595,39 @@ def test_policy_sources_accept_different_top_p_values():
assert [source.sampling.top_k for source in config.train.source] == [512, 512]
@pytest.mark.parametrize("frozen", [False, True])
@pytest.mark.parametrize(
"sampling,agent_sampling,rejected",
[
({}, {}, False),
({"top_p": 0.9}, {"max_completion_tokens": 200, "reasoning_effort": "high"}, False),
({}, {"extra_body": {"chat_template_kwargs": {"enable_thinking": True}}}, False),
({}, {"temperature": 1.0}, True),
({}, {"temperature": None}, True),
({}, {"extra_body": {"top_k": 20}}, True),
({}, {"frequency_penalty": 0.5}, True),
({}, {"extra_body": {"frequency_penalty": 0.5}}, True),
({"extra_body": {"frequency_penalty": 0.5}}, {}, True),
],
)
def test_policy_sampling_is_validated_before_rollouts(sampling, agent_sampling, rejected, frozen):
source = {
"env": {"taskset": {"id": "reverse-text"}, "agent": {"sampling": agent_sampling}},
"sampling": sampling,
}
if frozen:
source["algo"] = {
"type": "sft",
"sampling": {"source": {"name": "teacher", "base_url": "http://localhost:8000/v1"}},
}
if rejected and not frozen:
with pytest.raises(ValidationError, match="sampling"):
TrainSourceConfig.model_validate(source)
else:
config = TrainSourceConfig.model_validate(source)
assert TrainSourceConfig.model_validate_json(config.model_dump_json()) == config
def test_policy_sources_reject_mixed_top_k_capture():
with pytest.warns(UserWarning, match="defaulting top_k"):
with pytest.raises(ValidationError, match="cannot mix top_k > 0 and top_k = -1"):
@@ -650,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(
Generated
+4 -4
View File
@@ -5311,16 +5311,16 @@ wheels = [
[[package]]
name = "prime-tunnel"
version = "0.1.12"
version = "0.1.14"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx" },
{ name = "pydantic" },
{ name = "tenacity" },
]
sdist = { url = "https://files.pythonhosted.org/packages/9e/8b/b819661ea7dcfff21e4e000d7dfa799bc8107e2659cd5e0d961ecea08235/prime_tunnel-0.1.12.tar.gz", hash = "sha256:157c77cd15a16d091dba4b2df228a6b7e997ed1a3c5bc5f2c51ee989a31602e1", size = 16900, upload-time = "2026-10-04T20:33:47.617Z" }
sdist = { url = "https://files.pythonhosted.org/packages/db/7d/8d8cdd03aada223acc53d4de49cf7f195d7656705a0f3d2339051890a9f1/prime_tunnel-0.1.14.tar.gz", hash = "sha256:4968787d8702578b213204d2524c3525985cd0362f50841af5fa2465d0d4e2cb", size = 22378, upload-time = "2026-10-09T00:16:40.263Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/6a/b368c2cececc589bb8b13bf3c9cc819b4d29fc962d0ea9ffde005b873222/prime_tunnel-0.1.12-py3-none-any.whl", hash = "sha256:441d0a2f29c7e78a9337ee336c828fcc5ce1515c8cd12014b7d6c0b9728c355b", size = 16992, upload-time = "2026-10-04T20:33:46.17Z" },
{ url = "https://files.pythonhosted.org/packages/b8/d4/51e2b8fea13709edf3a6b94fb81d27a0eb3da11b339d870ace41de813dbb/prime_tunnel-0.1.14-py3-none-any.whl", hash = "sha256:a0e21f2b9ff61cf07c038486ddc541fe07326c65e703aaf4c795fae460ac6402", size = 19345, upload-time = "2026-10-09T00:16:38.845Z" },
]
[[package]]
@@ -7818,7 +7818,7 @@ requires-dist = [
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.3" },
{ name = "prime-runs", specifier = ">=0.1.4" },
{ name = "prime-sandboxes", specifier = ">=0.4.2" },
{ name = "prime-tunnel", specifier = ">=0.1.12" },
{ name = "prime-tunnel", specifier = ">=0.1.14" },
{ name = "pydantic", specifier = ">=2.12.3" },
{ name = "pyzmq", specifier = ">=27.1.0" },
{ name = "renderers", extras = ["multimodal"], specifier = ">=0.1.12.dev2" },