Compare commits

...
Author SHA1 Message Date
753cfb5a42 fix: mark dashboard episodes failed by ok, not by carried errors (#3649)
## Summary
- The dashboard marks an episode as failed only when `ok` is false.
Retry history no longer turns a successful episode red: the episode
table row, the rollout list item, the error-rate tile on the eval
overview, and the server's `errors_only` filter all read `ok` alone.
- Episode errors and trace errors render in different places, each
tagged with its scope. A failed episode's own errors sit above the agent
and branch selectors, since they belong to the whole episode. A failed
trace's errors sit at the top of that trace's transcript, only on its
tab, and the tab is red. A failure recorded on both the episode and its
trace shows once, as the trace's.
- Errors an ok episode or ok trace carries render as a collapsed
`recovered from N episode|trace errors in earlier attempts` list in the
same two places, each entry with its traceback. The table row and
rollout list item get a dotted left edge with the recovery count in
their tooltip.

## Why
Verifiers retries a whole episode when a retryable error such as
`SandboxError` ends an attempt, and on success it prepends the earlier
attempts' errors to the final record: `final.errors[:0] = history`, with
the comment "success is the `ok` stamp, never errors-emptiness". The
agent-level retry does the same on the trace. An episode that hit the
sandbox creation limiter once and then completed cleanly therefore lands
with `ok = true`, a full trace, and the limiter error in `errors`. The
dashboard treated `num_errors > 0` as failure, so such episodes showed a
red row, an error banner over a clean transcript, and inflated the error
rate, which is what a user saw after a run with `retries.include =
["SandboxError", ...]`. Episode errors also rendered inside the open
trace, so a multi-agent episode showed a red banner over a green agent's
transcript.

## Verification
A synthetic eval run was built from a real 4-episode gsm8k stream and
served by an isolated dashboard on this branch, driven headlessly with
Playwright:

| Line | Shape | Before | After |
|---|---|---|---|
| 1 | episode failed; trace `solver` failed with `SandboxError`, trace
`judge` ok | red row, `error` badge, both banners inside the solver
transcript, episode banner inside the judge transcript | red row; the
`episode error` banner above the tabs on both; the `trace error` banner
only in the solver transcript; `solver` tab red |
| 2 | episode ok after a retry; episode and trace carry `SandboxError`
as history | red row, `error` badge, red banner over the clean
transcript | plain `done` row with a dotted edge and a "recovered from 1
error" tooltip, no banner, collapsed "recovered from 1 trace error in
earlier attempts" list holding the SandboxError and its traceback |
| 3, 4 | plain ok | `done` | `done` |
| error-rate tile | 2 failures counted | 50% | 25% |
| `errors_only=true` | | lines 1 and 2 | line 1 |

No console errors in either state.

## Screenshots
Episode table: line 1 failed (red edge), line 2 recovered (dotted edge),
lines 3 and 4 plain.

![episode
table](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/table.png)

Line 2, recovered after a retry: no banner, the SandboxError in the
collapsed recovered list (expanded here), `ok = true`.

![recovered
episode](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/recovered.png)

Line 1, `solver` tab: the episode error above the selectors, the failed
trace's error at the top of its transcript, the tab red.

![failed episode, solver
tab](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/failed_solver.png)

Line 1, `judge` tab: the episode error stays above the selectors; the
judge's transcript carries no banner because that trace completed.

![failed episode, judge
tab](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/720f7ed72f1a3a5b09f7aaad34d94487b8688867/dashboard-retry-errors/failed_judge.png)

Screenshots live on the `assets/dashboard-retry-errors` branch.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dashboard display and filtering only; no changes to training, eval
recording, or auth paths.
> 
> **Overview**
> Aligns the eval dashboard with Verifiers’ retry semantics: **success
is `ok`, not empty errors**. Episodes that recovered after retryable
failures no longer look failed or inflate error metrics.
> 
> **Failure detection** now keys off `ok` only—the episode table,
rollout list, swarm **error-rate** tile, and server **`errors_only`**
filter no longer treat `num_errors` on successful episodes as failures.
Recovered episodes get a **dotted “retried”** row style and tooltips
instead of red error styling.
> 
> **Error UI** splits episode vs trace scope: episode-level failures
render in a new **`#tm-episode-errors`** strip above agent/branch tabs;
trace failures stay at the top of that trace’s transcript, with failed
agent tabs highlighted. **`scopedErrors`** dedupes episode/trace
duplicates (trace wins) and separates **failed** errors from
**recovered** history on ok records, shown as collapsible “recovered
from N … errors” sections. **`resetTranscript`** clears the episode
error strip whenever the transcript is replaced.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c4f6e242745c085c4bac60388dfb8c775e7b65f4. 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 Fable 5.1 <noreply@anthropic.com>
2026-09-23 14:29:47 -07:00
Biswa PandaandGitHub 33e02a7a18 fix(trainer): preserve Nemotron Mamba parameter dtype (#3557)
## Summary

- Initialize Nemotron Mamba `A_log` and `D` parameters with the active
default dtype so FSDP units do not mix float32 and bfloat16 storage.
- Keep the existing float32 state-space computation by casting at use
time.
- Add a focused bfloat16 parameter-dtype regression test.

## Validation

- `ruff check src/prime_rl/trainer/models/nemotron_h/mamba.py
tests/unit/train/models/test_nemotron_h.py`
- Focused in-cluster GPU probe: `A_log=torch.bfloat16`,
`D=torch.bfloat16`
- One-step Nemotron 3.5 Super VLM + MATH + Dynamo run: optimizer
completed and policy v1 was applied over NCCL.
- Three-step Kubernetes run: all optimizer steps completed; policies v0
through v3 applied to Dynamo; Job succeeded.
- Trainer mismatch KL by step: `0.0274`, `0.0344`, `0.0309`.

W&B: https://wandb.ai/test232/nemotron35-vlm-rl/runs/jq06zl0l
2026-09-23 13:35:34 -07:00
94f359e8d6 feat: scope verifiers limiters by run id and bump verifiers to main (#3641)
## Summary
- Bump the verifiers submodule to main (`9cf0df22b`), which includes
PrimeIntellect-ai/verifiers#2657: creation limiters wait on backlog
instead of raising past 300s, and their bucket is scoped by
`$VF_RUN_ID`. `uv.lock` is regenerated; verifiers dropped its `lean`
extra.
- The env-server entrypoint sets `VF_RUN_ID` from `PRL_RUN_ID`, minting
a uuid only when neither is set. Its pool workers inherit it.
- The multi-node SFT SLURM script exports `PRL_RUN_ID` and
`PRL_RUN_NAME` unconditionally, as the RL script does. Only the W&B
shared-mode variables stay behind the wandb condition, now named
`wandb_shared` in the template.

## Why
With the bump, a run whose sandbox creation outpaces `creates_per_min`
throttles instead of failing every rollout past the 300s backlog.
Scoping the bucket by run id keeps one run's backlog from delaying
another.

The env server is the one prime-rl process that creates sandboxes, and
every launcher hands it `PRL_RUN_ID`: the `rl`, `sft`, and `eval`
entrypoints export it before spawning, and the SLURM scripts export it
at the top of the sbatch script, which `srun` propagates to the `uv run
env-server` tasks. Deriving `VF_RUN_ID` there covers every launch path
with one line. The SFT script previously exported the run id only for a
shared W&B run, so its online-eval env servers would otherwise each have
minted their own scope.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes run-id propagation for SLURM-launched env servers and sandbox
creation throttling behavior; mis-set env vars could affect multi-run
cluster behavior but not auth or data integrity.
> 
> **Overview**
> Aligns prime-rl with verifiers’ run-scoped sandbox **creation
limiters** (keyed on `$VF_RUN_ID`) so throttling and backlog are per run
instead of shared across jobs.
> 
> The **env-server** entrypoint now sets `VF_RUN_ID` from `PRL_RUN_ID`,
or mints a UUID when launched standalone, so pool workers inherit the
same scope on every launch path.
> 
> **Multi-node SFT** previously exported `PRL_RUN_ID` only when shared
Weights & Biases logging was enabled, which left online-eval env servers
without a consistent run id. The SLURM template now always exports
`PRL_RUN_ID` and `PRL_RUN_NAME` (matching RL), while W&B shared-mode env
vars are gated on a new `wandb_shared` flag passed from `sft.py`.
> 
> **Lockfile** metadata drops the removed `lean` extra from the bumped
verifiers dependency.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
364f0b58699ad556746116a1bf6208e37b5afc6b. 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 Fable 5.1 <noreply@anthropic.com>
2026-09-23 13:34:19 -07:00
Matej SirovatkaandGitHub cf400e7db9 perf: reduce DSV4 indexer stalls and overlap CP gathers (#3643)
Packed sequence lengths were causing repeated FP8-indexer autotuning
during training. Other DP groups then arrived late at the layer-4 FSDP
prefetch, making a normal ~1–3 ms parameter gather appear to take 1.78
s. Together with narrower checkpoint state, avoiding a query-layout
copy, and overlapping CP communication, the matched BF16 benchmark
improves from **22.741 s / 40.23% MFU** after #3638 to **18.999 s /
47.79% MFU**.

- Bucket the indexer's autotune key by compressed-key length, also
keying on head count and dimension. Exact key lengths still control
addressing and masks. An all-rank trace showed the last rank arriving
1.718 s late and completing the gather in 1.34 ms; it had been
benchmarking the first CSA indexer.
- Register the FP8 indexer as an opaque operation and make its final
int32 selection a mandatory checkpoint save. This preserves the top-k
replay requirement while retaining compact IDs and skipping indexer
scoring on replay.
- Apply query RoPE directly in the sparse kernel's `(batch, tokens,
heads, dim)` layout, removing the transpose/contiguous round trip in
attention and the indexer.
- Launch the main KV CP gather with PyTorch's asynchronous functional
collective before query/compressor computation, and wait just before
consuming KV. Its registered backward performs the corresponding sum
reduce-scatter. Compilation stays enabled; communication uses NCCL's
existing stream.

### SAC configuration

Exact configuration for the measured run:

```toml
[model.ac]
mode = "selective"
freq = 1
targets = [
  "prime_rl::dsv4_sparse_attn",
  "prime_rl_collectives::all_to_all_single_equal",
  "aten::sort.stable",
]
```

`prime_rl::fp8_indexer` is saved automatically by the mandatory policy
in both full and selective checkpointing. The qualified stable-sort
overload matters: `aten::sort` does not match `aten::sort.stable`.

### Measurements

| Variant | Mean step time | Logged tokens/s | Logged MFU |
| --- | ---: | ---: | ---: |
| PR #3638 only (job 653) | 22.741 s | 86,890 | 40.23% |
| Indexer tuning buckets, full AC (665) | 20.718 s | 95,043 | 44.01% |
| Buckets + sparse-attention/EP-count SAC (675) | 20.042 s | 97,636 |
45.21% |
| All changes + SAC above (691) | **18.999 s** | **103,210** |
**47.79%** |

This is a **1.197× step-time speedup** over #3638 alone and **1.055×**
over the prior SAC run. Peak rank-0 reserved memory is **232.5 GiB /
267.7 GiB**. All five losses are finite. These are short benchmark
results, not a long-run convergence measurement. Measurements use the
pinned job-492 environment; this branch is rebased onto current main,
whose touched modeling files were identical to that baseline.

### Validation

- CPU checkpoint-policy tests: 4 passed on the PR branch, including
mandatory indexer retention under custom SAC targets. Ruff lint and
formatting checks passed for all changed files.
- Existing FP8-indexer GPU correctness cases: 2 passed. Changing key
lengths 1060 → 1064 → 1073 reused one autotune entry (2.015 s initial
tuning, then 0.919 ms and 0.634 ms).
- Existing sparse/eager attention parity cases: 9 passed, covering CSA,
HCA, sliding attention, packed documents, and empty compression.
- Existing CP packing checks: 6 passed across CP2/CP4 and all three
attention types; rerun successfully after inlining the gather and wait
calls directly in attention forward.
- Two-rank async-collective probe: outputs and input/weight gradients
passed with full/selective checkpointing, eager execution and
`torch.compile(fullgraph=True)`.
- Compiled two-rank BF16 attention checks: all three attention types
passed under full/selective checkpointing against the blocking
implementation; maximum relative L2 difference across outputs and
gradients was 0.026%. The sliding cases ran in a separate process after
the combined test harness reached its compiled-variant limit.
- Query-layout microcheck: bitwise-equal outputs and input gradients in
BF16/FP32, including the production query shape.



<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes touch CP collectives, compile/custom-op boundaries, and SAC
correctness for non-replayable top-k; numerics are covered by existing
kernel and CP tests but production timing depends on NCCL stream overlap
behavior.
> 
> **Overview**
> This PR targets **DeepSeek V4 training step time** by cutting FP8
indexer autotune churn, overlapping context-parallel communication, and
tightening activation-checkpoint behavior around sparse indexing.
> 
> The **FP8 Lightning indexer** is registered as `prime_rl::fp8_indexer`
and added to the **mandatory** selective-activation-checkpoint save list
so replay keeps the final int32 top-k without re-running scoring. Triton
autotune now keys on **`next_power_of_2(S_k)`** plus head count and
dimension so packed batches with slightly different compressed-key
lengths reuse one tuned config.
> 
> In **attention**, queries stay in **`(batch, tokens, heads, dim)`**
through RoPE and into `dsv4_sparse_attn`, dropping the
transpose/contiguous path. Under CP, **KV all-gather** starts
asynchronously via `_c10d_functional.all_gather_into_tensor` before
query and compressor work, with **`wait_tensor`** immediately before KV
is consumed.
> 
> Tests assert mandatory checkpoint retention for the new op and extend
CP parity mocks for the async gather path.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6449f9212c3430c812b9623a1b5bd274e350b780. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 16:07:21 -04:00
samsjaandGitHub 8da21f16b8 feat(eval): make task dispatch rate configurable (#3602)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Optional config with default unchanged; reuses existing orchestrator
dispatch rate limiting with no auth or data-path changes.
> 
> **Overview**
> Eval runs can now cap how fast episodes are dispatched via a new
**`tasks_per_minute`** setting on **`ServedEvalConfig`** (shared by
standalone eval and SFT online eval). **`None`** keeps the previous
behavior with no rate limit; a positive value throttles dispatch through
the existing **`Dispatcher`** **`AsyncLimiter`**, intended to pace
sandbox provisioning during autoscaling.
> 
> The eval **`runner`** passes **`config.tasks_per_minute`** into the
dispatcher instead of hard-coding **`None`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
31f8041b908234dc4c45f128540af8e4daa6435b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 09:30:15 -07:00
ae37b35a34 fix(trainer): match vLLM's per-token FP8 activation quantization bit for bit (#3623)
RL compares trainer and inference logprobs token by token, so any
disagreement between the two FP8
quantizers is model-independent noise. The trainer's per-token
activation cast is now bit-identical to
vLLM's production CUDA op, `torch.ops._C.per_token_group_fp8_quant`.

- Three kernels in `fp8_utils.py` floor `amax` at `1e-10` and use
`tl.math.div_rn` for scale and quotient.
Triton's `/` lowers to multiply-by-reciprocal, one fp32 ULP off the
correctly rounded value.
- The weight kernel is untouched: vLLM's weight path is itself a
reciprocal-multiply and already matched.
- A new GPU test pins the equality against the CUDA op; the trainer
still imports vLLM nowhere.

Share of 128-wide groups whose scale is bitwise equal to vLLM's, and
share of elements whose fp8 byte
is, on four 4096x4096 bf16 activation tensors on an H200:

| tensor | scales: before | after | bytes: before | after |
|---|---|---|---|---|
| randn x0.02 | 42.8329% | 100.0000% | 98.1890% | 100.0000% |
| randn x1.0 | 41.0797% | 100.0000% | 99.8822% | 100.0000% |
| randn x30.0 | 43.6028% | 100.0000% | 99.8869% | 100.0000% |
| randn heavytail 16ch x50 | 42.7979% | 100.0000% | 99.8999% | 100.0000%
|

Every pre-fix mismatch was exactly one e4m3 step, so weights stay at
100% and dequantization error is
unchanged. Agreement with vLLM's Triton fallback drops to about 42% on
scales, which is forced since
vLLM's two backends are not bit-identical to each other and only the
CUDA op runs in production. Costs
3.1% of quant-kernel time at 4096x4096 and 8.7% at [8192, 7168].
Verified on sm90 with
`use_ue8m0=False`; sm100 takes a different vLLM kernel.

## Effect on training gradients

The old floor applied to the scale, not to `amax`, so any 128-wide group
with `amax < 0.0448` was
quantized against an inflated scale: its values were squeezed into a
corner of the e4m3 range
instead of spanning it, and everything below `1e-7` rounded to zero.
Forward activations sit above
that threshold; gradients do not, and both the input-gradient (dgrad)
and weight-gradient (wgrad)
paths cast `grad_output` through these kernels. The error is one-sided
toward zero, so it shrinks
gradients rather than adding noise.

Measured end to end: a 131k-context SWE RL run with an FP8 trainer on
pre-fix code logged
`optim/grad_norm` averaging 0.0079 over 100 steps, against 0.0465 and
0.0528 for otherwise
identical runs with a bf16 trainer. A rerun of that config on the fixed
kernels is at 0.0421 over
its first 17 steps, where the pre-fix run read 0.0094 and the bf16
reference 0.0468 over the same
window. Mismatch KL is blind to all of this, since it depends on the
forward alone: lr = 0 probes
read 0.0089 before the fix and 0.0091 after.

### Why the floor's location matters

Per 128-element group:

```
# before
amax  = max(|x|)
scale = max(amax / 448, 1e-4)      # floor on the SCALE
y     = x / scale

# after
amax  = max(max(|x|), 1e-10)       # floor on the AMAX
scale = div_rn(amax, 448)
y     = clamp(div_rn(x, scale), -448, 448)
```

A floor exists only to keep an all-zero group from dividing by zero. The
correct scale, `amax / 448`,
maps the group's largest element to exactly 448 and spans the full e4m3
range. Pinning the scale at
`1e-4` makes it too large whenever `amax < 0.0448`, and a scale that is
too large makes `y = x / scale`
too small, so the group occupies a corner of the range.

Take a gradient group with `amax = 1e-5`:

- correct scale is `1e-5 / 448 = 2.2e-8`, giving `y_max = 448`, the full
range
- old scale is `1e-4`, giving `y_max = 0.1`, a sliver of it
- e4m3's smallest subnormal is `2^-9 = 0.00195`, so any `|y|` below
about `0.001` rounds to zero
- that is every `|x|` below `1e-7`, which is 1% of this group's maximum
- at `amax = 1e-6` the same `1e-7` cutoff erases everything below 10% of
the maximum

Two properties make this worse than rounding noise. It is one-sided,
always toward zero, so it biases
the gradient short rather than jittering it. And it is non-uniform:
groups above `0.0448` are exact
while groups far below it are gutted, so the surviving gradient also
points in a different direction.
AdamW's per-parameter normalization absorbs much of the magnitude loss,
which is why a run carrying
this bug trains through it while looking healthy.

## Launch-config retune

This PR also reconfigures the kernel launch specs for perf (for H200).

Measuring the cost of correct rounding exposed a separate problem: these
kernels were already launched
at block sizes that spill registers. The per-channel cast used a `[128,
128]` fp32 tile, and
`div.rn.f32` needs more live temporaries than `div.full.f32`, which is
why correct rounding looked
expensive there. Retuning `BLOCK_M`, `BLOCK_N` and `num_warps` in five
host wrappers, with no kernel
body change, recovers more than correct rounding costs.

Measured on an H200 at this model's dimensions (hidden 4096, MoE
intermediate 2048, 8 local experts
with ragged routing), 102 configs against a noise-control arm:

| kernel | wins | regressions | noise | best delta |
|---|---|---|---|---|
| `grouped_per_channel` k-major | 24 | 0 | 2 | -54.1% |
| `grouped_per_channel` row-major | 21 | 0 | 5 | -35.3% |
| `per_token` transposed | 6 | 0 | 6 | -44.8% |
| `grouped_per_token` | 7 | 0 | 19 | -12.0% |
| `per_token` | 3 | 0 | 9 | -12.4% |

Ragged expert groups gain more than equal ones: at K=4096 with 4096
tokens per rank, the k-major
per-channel cast is -28.5% on an equal split and -54.1% under realistic
routing. A launch config cannot
change the arithmetic, so bit identity against the CUDA op is
unaffected.

## Verification

```
uv run --no-sync python -m pytest tests/unit/train/models/test_fp8_utils.py -q
```

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 11:14:43 -04:00
Matej SirovatkaandGitHub 77788ba020 fix: retain two reduce-scatter input buffers for FP32 MoE routers (#3638)
FP32 MoE routing uses a separate FSDP unit. Its post-backward hook can
request a reduce-scatter input buffer while the expert reduction is
still in flight; FSDP's default limit of one inserts a compute-stream
wait before attention backward can run.

Set `set_reduce_scatter_max_input_buffers(2)` on that router unit
immediately after sharding. FSDP resolves the shared buffer limit to the
maximum across its units, allowing the router to pack gradients while
the expert reduction completes. This adds two lines on top of main, with
no new configuration or numerical dtype changes. The tradeoff is
additional memory for in-flight reduction inputs.

### Measured timings

Same saved packed tokens and checkpoint, GLM-5.3 EP8/CP8 on 32 B300
GPUs, FP32 routing, full activation checkpointing, and activation
offloading enabled in both runs. Two warmup passes followed by one
profiled forward/backward; no optimizer update.

| Metric | One buffer | Two buffers |
| --- | ---: | ---: |
| Warm forward + backward, median across 32 ranks | 14.699 s | 12.649 s
|
| Profiled forward + backward, median across 32 ranks | 14.808 s |
12.717 s |
| Expert reduce-scatter overlap with main-stream compute, rank 0 | 11.1%
| 93.7% |
| Maximum reserved GPU memory across ranks/passes | 204.49 GiB | 205.29
GiB |

Warm forward/backward is **13.9% shorter**, equivalent to **16.2% higher
throughput**, at **0.80 GiB** more peak reserved memory in this run.

### Timeline of the stall

Actual CUDA kernel intervals for layer 77, rank 0. Each panel is aligned
independently to that layer's expert reduce-scatter launch. Blue is
other main-stream compute, green is attention backward, and orange is
expert gradient reduce-scatter.

![Measured one-buffer versus two-buffer reduce-scatter
overlap](https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/1bebf826b530cb7c52d18d8cf92d562174a7efbe/reduce-scatter-overlap.png)

With one buffer, the router's post-backward hook queues a compute-stream
wait while the **4.5 GiB expert reduction** is in flight. This creates a
**40.7 ms main-stream compute gap**. The router's own reduction is only
**6 MiB / 0.66 ms**. Attention backward starts **48.87 ms** after the
expert reduction launch; with two buffers it starts at **8.15 ms**
instead. The layer's expert-reduction overlap rises from **7.3% to
96.3%**. These layer-specific percentages differ from the aggregate
values in the table.

These are single-run comparisons, not repeated statistical benchmarks.
The measured experiment set the cap at the root; this PR applies the
same effective shared cap through the router unit. Ruff and `git diff
--check` pass; this exact main-based patch has not had a new distributed
run.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Two-line FSDP scheduling tweak in MoE setup only; no numerical or API
changes, with modest extra peak memory for reduction buffers.
> 
> **Overview**
> When **FP32 MoE routers** are sharded as their own FSDP unit
(alongside expert-parallel expert shards), backward can stall: the
router’s post-backward reduce-scatter needs an input buffer while the
much larger expert gradient reduction is still using FSDP’s default
single buffer, forcing a **compute-stream wait** before attention
backward can proceed.
> 
> Right after `fully_shard` on `block_mlp.router`, the PR calls
**`set_reduce_scatter_max_input_buffers(2)`** so the router can queue
its small reduction without blocking on the in-flight expert
reduce-scatter. FSDP’s shared limit becomes the max across units—same
effective behavior as raising the cap at the root, but scoped to the
router shard path. **Tradeoff:** slightly more memory for in-flight
reduction inputs; no new config or dtype changes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
51a9e3daef8a53a254d7e7ff35d1ee3c8afce18c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-23 17:02:46 +02:00
Scott CabrinhaandGitHub ab85b3b369 fix(docker): install the Prime CLI into the image venv for hosted-run env bootstrap (#3635)
## Problem

Since #3585 removed the `prime` CLI as a prime-rl dependency ("Stop
installing the `prime` CLI with prime-rl. Run `uv tool install prime`
when the CLI is needed"), the published GHCR images ship no `prime`
executable. That breaks Hosted Training runs on these images at
bootstrap:

The platform's env-server and orchestrator pods prepend an
**authenticated** Hub env install to their pod command,

```
uv run --no-sync prime env install '<owner/name>' && ... && uv run --no-sync env-server @ config
```

because verifiers' own `ensure_installed` resolver fetches the Hub
**unauthenticated** and 404s on private environments — the pre-install
into the pod's venv is what makes v1 Hub tasksets resolvable at boot
(envs baked into the image never hit this path).

With the executable absent from `/app/.venv/bin`, every pod dies at
spawn and the run wedges at `CREATING`. Observed on
`ghcr.io/primeintellect-ai/prime-rl:v0.9.1.dev100` dispatching a run
with a Hub taskset:

```
error: Failed to spawn: `prime`
```

(the orchestrator's entire log is two lines: the no-checkpoints warning,
then that spawn failure).

## Fix

Install the CLI into the image venv at build time — **not** as a project
dependency, so #3585's "CLI as a separate tool" boundary stands for
library code; the image just ships the executable and its runtime deps
so the platform bootstrap can run.

- One `RUN` after the main `uv sync`, using the same uv cache mount as
the rest of the file.
- `prime>=0.7` — pure-Python CLI, few MB; most deps
(httpx/pydantic/etc.) are already in the venv.
- The runtime stage copies `/app` wholesale, and `PATH` already puts
`/app/.venv/bin` first, so `uv run --no-sync prime env install ...` and
direct `prime` calls both resolve.

## Alternatives considered

- Reverting #3585's dependency removal: rejected — keeps the boundary;
the image need, not the library, is what broke.
- Platform-side init container with a dedicated prime-cli image (cleaner
long-term: keeps the CLI out of the framework image entirely) — worth
tracking on the platform side; this PR is the minimal unblock for hosted
Hub-env runs today.

## Verification

- `VIRTUAL_ENV=<venv> uv pip install 'prime>=0.7'` smoke-tested locally
(CLI 0.7.0 boots).
- Placement reviewed against the builder stage: runs after the locked
sync chain, before the optional NIXL block; nothing downstream
overwrites the venv.
2026-09-22 19:06:08 -06:00
Mika SenghaasandGitHub de5cdb8bae fix: read serialized dashboard token counts (#3632)
## Summary

- pin Verifiers `main` at the merge of [Verifiers
#2652](https://github.com/PrimeIntellect-ai/verifiers/pull/2652),
including the computed fields from [Verifiers
#2651](https://github.com/PrimeIntellect-ai/verifiers/pull/2651)
- read serialized token counts directly from completed episode and live
trace records
- remove dashboard-specific token reconstruction and prompt-token
summation

The previous implementation summed every full prompt in a multi-turn
trace.
This counted the shared conversation once per request and inflated long
rollouts.

## Verification

Before this change, a two-turn trace with prompt usages of 100 and 150
tokens
reported 250 input tokens. After this change, the serialized record and
both
dashboard paths report 130 input tokens and 50 output tokens.

- tested the dashboard flow end to end
- `ruff check` and `py_compile` passed for both changed modules
2026-09-22 15:50:19 -07:00
samsjaandGitHub b636a8b7ec chore: bump prime-envs to latest main (#3630)
## Summary
- Bump the `deps/prime-envs` submodule from `1f1e050ab` to `1213b7336`
(latest `main`).
  - Pulls in:
-
[prime-envs#791](https://github.com/PrimeIntellect-ai/prime-envs/pull/791):
strip v0 remnants.
-
[prime-envs#795](https://github.com/PrimeIntellect-ai/prime-envs/pull/795):
restore solver network access for training environments.
-
[prime-envs#797](https://github.com/PrimeIntellect-ai/prime-envs/pull/797):
500-trace SWE cheating recall benchmark (new `trace-cheating-recall-500`
judge env).
-
[prime-envs#796](https://github.com/PrimeIntellect-ai/prime-envs/pull/796):
run MCP Atlas and Enterprise Ops Gym services in VMs.
-
[prime-envs#798](https://github.com/PrimeIntellect-ai/prime-envs/pull/798):
fair-use solver prompts for SWE and terminal training tasksets.
-
[prime-envs#805](https://github.com/PrimeIntellect-ai/prime-envs/pull/805):
keep env CI evals off the platform.
-
[prime-envs#770](https://github.com/PrimeIntellect-ai/prime-envs/pull/770):
OfficeQA Pro V2 (new `officeqa-pro-v2` env).
-
[prime-envs#808](https://github.com/PrimeIntellect-ai/prime-envs/pull/808):
complete TMax platform hosting and source references.
-
[prime-envs#814](https://github.com/PrimeIntellect-ai/prime-envs/pull/814):
ask before changing repository skills.
-
[prime-envs#815](https://github.com/PrimeIntellect-ai/prime-envs/pull/815):
support renamed Verifiers eval CLI in CI.
-
[prime-envs#822](https://github.com/PrimeIntellect-ai/prime-envs/pull/822):
remove obsolete Prime VM configuration.
- Relock `uv.lock`: new workspace members `officeqa-pro-v2` and
`trace-cheating-recall-500` (auto-discovered via
`deps/prime-envs/environments/*/*`); env package version bumps.

## Validation

- `uv sync --all-extras --all-packages --locked` passes.
- `uv run pytest tests/unit -m "not gpu"`: 616 passed, 1 skipped.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Training and evaluation behavior can shift (solver prompts, network
access, VM-hosted tool services, new benchmarks) because many SWE,
terminal, and tool-use env packages change together.
> 
> **Overview**
> Updates the **`deps/prime-envs`** submodule to the latest **`main`**
and refreshes **`uv.lock`** so the workspace picks up new and bumped
editable environment packages.
> 
> The lockfile adds two auto-discovered members—**`officeqa-pro-v2`**
(search) and **`trace-cheating-recall-500`** (judge)—and bumps patch
versions across many existing env packages (SWE stacks like
**`openswe`**, **`multiswe`**, **`swesmith-env`**; terminal **`tmax`** /
**`terminal-lego`**; tool-use **`mcp-atlas`** /
**`enterprise-ops-gym`**; plus assorted math, lean, long-context, and
reasoning envs).
> 
> Upstream **`prime-envs`** changes bundled with this bump include
stripping v0 remnants, restoring solver network access for training
envs, fair-use solver prompts for SWE/terminal tasksets, MCP Atlas and
Enterprise Ops Gym running services in VMs, TMax hosting completion,
CI/eval CLI fixes, and related housekeeping—not new logic in this repo
beyond the dependency pin and lock refresh.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
75422004f320992e134a1d188368f15637bf8193. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-22 13:19:08 -07:00
Mika SenghaasandGitHub 9aa8563eae fix(inference): extend startup readiness timeout (#3626)
## Summary
- increase the default inference readiness timeout from 30 minutes to 60
minutes
- keep the direct `check_health` default aligned with `ClientConfig`

Large models can exceed 30 minutes on a cold node while vLLM compiles
architecture-specific kernels and captures CUDA graphs. The previous
default can tear down an otherwise healthy launch just before readiness.

## Test plan
- `PYTHONPATH="$PWD/src:$PWD/packages/prime-rl-configs/src" pytest -q
tests/unit/orchestrator/test_clients.py` (10 passed)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Only increases startup wait defaults; no changes to auth, weight
updates, or runtime inference behavior once ready.
> 
> **Overview**
> Raises the default **inference pool startup wait** from 30 to **60
minutes** so cold starts (e.g. vLLM kernel compile and CUDA graph
capture on large models) are less likely to fail right before `/health`
succeeds.
> 
> The change updates `ClientConfig.wait_for_ready_timeout` in shared
config and the default `timeout` on `check_health`, keeping orchestrator
health polling aligned with the config default used by
`AdminPlane.wait_for_ready`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f9fdfe25be6d643d43e830121bf22b6a9bd036c1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-22 11:58:23 -07:00
Mika SenghaasandGitHub a44dc3572c feat(inference): configurable vLLM router request timeout (#3620)
## Summary

- Add `VllmRouterConfig.request_timeout_secs` (**default 1800 — the
router's own built-in default**, `ge=1`): the maximum lifetime of a
routed request, including streamed completions.
- Wire it through both router launch paths — the Python entrypoint
(`--request-timeout-secs`) and the `_launch_router.sh.j2` template. When
unset, the router behaves exactly as before.
- Long agentic rollouts set it explicitly, e.g. `request_timeout_secs =
3600` for one-hour SWE eval requests.

## Note on "no timeout"

The Rust router applies the value as its HTTP client's **total request
timeout unconditionally** (`server.rs`,
`.timeout(Duration::from_secs(...))`): plain `u64`, no disable sentinel,
and `0` would be an *immediate* timeout. So "no timeout" is not
expressible — a finite configurable value with the upstream default is
the right shape.

## Validation

- `VllmRouterConfig` default (`1800`) / set (`3600`) / `ge=1` rejection
all verified; both launch paths interpolate the same field (the template
already receives the `router` config object).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Operational tuning of router HTTP client timeouts only; no auth or
data-path changes, though misconfigured values could still cut off or
hang long requests.
> 
> **Overview**
> Adds **`request_timeout_secs`** on **`VllmRouterConfig`** (default
**1800s**, minimum 1) so the maximum lifetime of a routed
request—including streamed completions—can be set from inference config
instead of relying on implicit router defaults.
> 
> Both managed router launch paths now pass
**`--request-timeout-secs`**: the local **`start_router`** entrypoint
and the SLURM **`_launch_router.sh.j2`** template read
**`router.request_timeout_secs`**. Long agentic or eval rollouts can
raise the value (e.g. via config override) without patching launch
scripts.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
adf7321a3604f2fc784ab961688a281ab6002165. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 16:22:12 -07:00
Mika SenghaasandGitHub 32f4f40f9e feat(orchestrator): unified taskset shuffle for train and eval sources (#3622)
## Summary

- `EnvConfig.shuffle` (`bool`, default `False`): shuffle the source's
finite taskset **once at startup** with a fixed seed
(`TASKSET_SHUFFLE_SEED = 42`).
- Defined in one place — `EnvConfig`, the shared base — so both
`TrainSourceConfig` and `EvalSourceConfig` inherit it: one knob covers
RL train envs, RL/SFT online evals, and standalone evals. Train
curricula and eval example selection both consume the shuffled order.
- Infinite tasksets reject `shuffle` at startup with a clear error.
- The eval resume allowlist now overrides `source.*.shuffle` (fixed seed
⇒ deterministic across resume).

```toml
[[train.source]]           # or [[eval.source]]
shuffle = true
```

Mirrors the existing SFT-data convention (`shuffle: bool` + fixed seed).

## Validation

- `pytest tests/unit/orchestrator/ tests/unit/eval/
tests/unit/test_configs.py` — 288 passed, 1 skipped.
- Smoke: `TrainSourceConfig(..., shuffle=True)` and
`EvalSourceConfig(..., shuffle=True)` both parse; default is `False`;
resume allowlist updated.
- **Manual eval-selection run (real `Env.start()` path, gsm8k,
`num_examples = 50` of 1319 test tasks; only the env-server network
handshake stubbed — no GPU on the validating node):**
- `shuffle = false`, run 1 → `[0, 1, 2, ..., 49]` (natural source order)
- `shuffle = true`, run 1 → `[588, 1214, 57, 906, 1252, 618, 599, 289,
...]`
- `shuffle = true`, run 2 → identical to run 1 (same 50 tasks, same
order) ✔ reproduces
  - `shuffle = false`, run 2 → identical to run 1 ✔ off is stable
- off vs on selections differ (set overlap 2/50, as expected for a
random 50-of-1319 subset) ✔

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior is opt-in with a fixed seed and only affects task ordering at
startup; infinite tasksets are explicitly rejected.
> 
> **Overview**
> Adds a **`shuffle`** flag on shared **`EnvConfig`** (default
**`false`**) so train and eval sources can reorder a **finite** taskset
once at env startup instead of always taking tasks in source order.
> 
> When **`shuffle=true`**, the orchestrator materializes the taskset and
shuffles it with a fixed seed (**`TASKSET_SHUFFLE_SEED = 42`**), so the
same permutation holds for the whole run and eval example selection
stays reproducible. **Infinite** tasksets fail fast with a clear error.
> 
> Eval **resume** may override **`source.*.shuffle`** alongside other
rollout knobs. New unit tests cover default order, changed selection,
reproducibility, full-taskset selection, and the infinite-taskset
rejection.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8358483c1144ed331f575a5e857fabe390de50c8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 16:20:06 -07:00
Mika SenghaasandGitHub ef07764841 feat(sft): per-row reasoning_effort renderer override (#3621)
## Summary

- A `reasoning_effort` column in the dataset overrides the `[renderer]`
config's `reasoning_effort` field **per row**, so one SFT run can mix
reasoning efforts with the configured renderer serving as the default
for rows that do not set one (or set null).
- Requires a typed renderer config that has the field: `renderer.name =
"auto"` and field-less renderers raise a clear `ValueError`. Renderer
configs are frozen, so resolved configs are cached and rows resolving to
the same config share one renderer instance.
- Doc paragraph in `docs/training.md`; dataloader and sft-dataset tests
updated.

```toml
[renderer]
name = "glm-5.3"          # typed renderer; reasoning_effort = "max" is the row default
# dataset rows may carry reasoning_effort = "low" | "high" | "max" per row
```

## Validation

- `pytest tests/unit/train/sft/` — 47/47 pass.
- E2E with the real GLM-5.3 renderer: rendered prompts carry the per-row
effort preamble (`Reasoning Effort: Low` vs `Max`), invalid efforts
rejected by the config `Literal`, `None` rows fall back to the
configured renderer, and the resolver caches one renderer per distinct
config.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are confined to SFT tokenization/renderer selection with
explicit validation for auto or unsupported renderers; misconfiguration
fails at load time rather than silently wrong training.
> 
> **Overview**
> SFT can now **mix reasoning efforts in one run** via an optional
dataset **`reasoning_effort`** column that overrides the typed
`[renderer]` config per row; null/missing values keep the TOML default.
> 
> **`RendererResolver`** (in `data.py`) builds and **caches** renderers
from `renderer_config` + row overrides instead of a single shared
renderer. **`SFTDataset`** takes a per-example renderer callable;
**`setup_dataset`** / **`train.py`** pass **`renderer_config`** and the
VLM **processor** rather than constructing one renderer up front (train
and validation use the same path).
> 
> Docs in **`training.md`** describe the column, typed-renderer
requirement, and supported model families. Unit tests were updated to
pass `lambda _: renderer` into **`SFTDataset`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3408b9918dccf06d86ab732faa94a18f6233ca31. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 16:20:00 -07:00
7745c669d1 feat(monitors): attach eval runs to a platform-created evaluation (#3619)
## Summary

`PrimeEvalMonitor` attaches to an existing platform evaluation when
`$PRIME_RUNS_EVAL_ID` is set, instead of always registering a new one.
This mirrors how `PrimeTrainMonitor` already attaches to `$RUN_ID`.

Why: A hosted evaluation is created by the platform before its sandbox
starts: the platform owns billing, secrets, timeouts, cancellation and
the final "did every episode reach the platform" check, and it hands the
sandbox the evaluation's id, which the monitor reads from
`$PRIME_RUNS_EVAL_ID`. Today `uv run eval --monitors.prime` inside that
sandbox would call `pr.init(kind="eval", ...)` without an id, register a
second evaluation and leave the platform's one open forever.


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes platform eval registration lifecycle for hosted runs;
misconfiguration (multiple sources or multiple epochs) fails fast with
explicit errors.
> 
> **Overview**
> **Hosted eval sandboxes** can now stream to an evaluation the platform
already created instead of registering a duplicate that leaves the
platform run orphaned.
> 
> When **`PRIME_RUNS_EVAL_ID`** is set, `PrimeEvalMonitor` calls
`pr.init` with that **`id`** (same attach pattern as training’s
**`$RUN_ID`**). Init requires **exactly one** eval source, and
**`open`** rejects a second epoch so one injected id maps to one epoch.
Logs note attachment when **`run.attached`** is true.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b4af11c50eb8201cbaf1b9a903b245a1bb8ed76e. 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 Fable 5.1 <noreply@anthropic.com>
2026-09-21 15:23:56 -07:00
87c5456806 chore(deps): bump vLLM to 0.29.0 (#3617)
Bumps vLLM from 0.28.0 to 0.29.0 and reconciles prime-rl's runtime
monkeypatches with 0.29's reorganized entrypoint layout. Three patches
are now obsolete and removed, each backed by a merged upstream PR.

- Rebound the API server layer onto `vllm.entrypoints.launchers.*`: on
0.29 the old `openai.api_server` path is a deprecation shim, so without
this the custom routes and the `PrimeRlServingTokens` swap would
silently not install.
- Dropped `monkey_patch_fp32_lm_head`: vLLM does the fp32 lm_head
projection natively via `head_dtype`
([#48390](https://github.com/vllm-project/vllm/pull/48390), LoRA path
[#48525](https://github.com/vllm-project/vllm/pull/48525)), so
`enable_fp32_lm_head` now injects `hf_overrides = {"head_dtype":
"float32"}`.
- Dropped the `PrimeRlServingTokens.serve_tokens` `kv_transfer_params`
bridge: upstream threads the params into the engine itself as of
[#42644](https://github.com/vllm-project/vllm/pull/42644), which landed
after the 0.28.0 cut.
- Dropped `monkey_patch_qwen3_coder_param_newline_trim`: upstream
restored the single-newline trim in
[#48846](https://github.com/vllm-project/vllm/pull/48846), making the
patch a byte-for-byte no-op.
- #48390 and #48846 already shipped in 0.28.0, so 0.29's role is to make
`fp32_lm_head` *fatal* via the new positional `skip_gather`; only #42644
is genuinely unlocked by the bump.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 15:36:25 -04:00
12b4d4b050 chore: whitelist the Environments Hub index for uv installs (#3612)
## Summary

- Add an explicit `[[tool.uv.index]]` named `prime-hub` for
`https://hub.primeintellect.ai/primeintellect/simple/` with
`exclude-newer = false`. Hub wheels carry no upload time, so the repo's
7-day `exclude-newer` cooldown filtered all of them out.
- `uv pip install gsm8k --index prime-hub` and `uv add gsm8k --index
prime-hub` now resolve inside prime-rl. The index is `explicit`, so `uv
sync` never consults it and `uv lock --check` passes unchanged.

Only the named index inherits the setting: passing the same URL via
`--extra-index-url` still hits the cooldown (uv matches index config by
name). Other Hub owners need their own entry or `--no-config`.

Verified in a fresh checkout: `uv lock --check`, slim `uv sync`, then
install through `--extra-index-url` (rejected), `--index prime-hub`
(0.1.4 installed), and the per-environment install index (rejected).

Companion: PrimeIntellect-ai/prime#934 (`prime eval run` installs Hub
environments into a prime-rl sandbox; it uses `--no-config` so any owner
works).

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dependency-index configuration only; narrows the exclude-newer bypass
to an explicit, opt-in first-party index without changing default sync
behavior.
> 
> **Overview**
> Adds a named **`prime-hub`** uv index pointing at the Environments Hub
with **`exclude-newer = false`**, so Hub wheels (which lack upload
timestamps) are no longer blocked by the repo-wide **7-day**
`exclude-newer` policy.
> 
> The index is **`explicit`**, so default **`uv sync`** / lock checks
stay unchanged; Hub packages resolve only when you opt in (e.g. **`uv
add gsm8k --index prime-hub`**). Passing the same URL via
**`--extra-index-url`** still applies the global cooldown because uv
matches index settings by configured name, not raw URL.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1ac034977bbf2a54ef2977314fc87a9d2f6b1b5f. 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 Fable 5.1 <noreply@anthropic.com>
2026-09-21 10:51:06 -07:00
JannikStandGitHub 64a0decfaa improvement(docker): bake the dashboard extra into the cuda image (#3613)
### What & why

The prime-rl-fft chart runs a standalone read-only dashboard pod per
release (prime-rl-fft #75) that serves prime-rl's run dashboard (`uv run
dashboard`, port 7788) off the run's shared PVC. The chart image does
not include the `dashboard` extra (fastapi/uvicorn), so the pod
previously installed it at start with `uv sync --inexact` — which hangs
on some clusters, leaves the Deployment permanently unready, and times
out the whole release's helm `--wait` readiness gate after 90m, killing
every trainer/inference/orchestrator pod regardless of their own health.
The dashboard was disabled by default as a stopgap (prime-rl-fft #86).

This bakes the `dashboard` extra directly into the cuda image so the
dashboard pod serves straight from the image with no runtime install.

### Changes
- `Dockerfile.cuda`: add `--extra dashboard` to both `uv sync` calls
(third-party deps layer + first-party source layer).

### Notes
- `fastapi` + `uvicorn` are a few MB next to the ~20 GB GPU venv;
negligible size impact.
- Both syncs use `--locked` and `uv.lock` already resolves the
`dashboard` extra — no lockfile changes.
- Follow-ups (fft chart repo, separate PRs): drop the pod-start `uv sync
--inexact` command and re-enable the dashboard by default; expose it to
the platform backend over the tailnet.

### Testing
- No runtime code touched; image CI builds the image from this branch.
- `uv lock --check` equivalent verified: lock already contains the
dashboard extra deps with markers.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Build-only Dockerfile change that adds two small locked deps to the
venv; no application or runtime behavior changes in this repo.
> 
> **Overview**
> **Bakes the `dashboard` optional extra (FastAPI + Uvicorn) into the
CUDA Docker image** so Helm FFT chart dashboard pods can run `uv run
dashboard` from the image without a startup `uv sync`.
> 
> Both dependency install steps in `Dockerfile.cuda` now pass `--extra
dashboard` alongside the existing GPU/flash-attn extras, with a short
comment tying this to the chart dashboard pod. Lockfile is unchanged;
syncs stay `--locked`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
78fecdd68099796469bc2cecce1ad10142d9a76c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-21 09:27:47 -07:00
samsjaandGitHub a1822f7a0a feat: default enable_ep_weight_filter to true (#3608)
## What

- Adds a typed `inference.vllm.enable_ep_weight_filter` field defaulting
to `true`, so every vLLM server prime-rl launches now passes
`--enable-ep-weight-filter` (previously this flag only appeared as an
explicit pass-through in the GLM-5.3 advanced examples).
- Drops the now-redundant explicit `enable_ep_weight_filter = true` from
the GLM-5.3 examples (`examples/advanced/glm-5.3/swe.toml`,
`examples/advanced/glm-5.3/infer/pd-llmd.toml`).
- Asserts the default lands on the server namespace.

## Why

Under expert parallelism, vLLM's weight filter skips non-local
per-expert tensors **before** reading them from disk: each rank reads
only its own expert shard instead of the full checkpoint (experts are
~85-90% of MoE weight bytes). This cuts load I/O and startup time,
especially on shared storage.

The default is safe elsewhere — vLLM only activates the filter when the
model is MoE, `enable_expert_parallel` is on, and EPLB is off. It is a
silent no-op for dense models, fused-expert checkpoints (GPT-OSS style),
and EPLB runs. The repo pins `vllm>=0.28.0`, which has the flag.

Set `inference.vllm.enable_ep_weight_filter = false` to restore the old
behavior.

Note: #3604 relocates these GLM-5.3 examples to `configs/advanced/` and
its copies still carry the explicit line — drop it when rebasing on this
PR.

## Test plan

- `uv run pytest tests/unit/test_parsers.py tests/unit/test_configs.py`
- Verified `to_namespace()` emits `enable_ep_weight_filter=True` for a
real GLM-5.3 config, and that `--vllm.enable-ep-weight-filter false`
overrides it.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior change is gated in vLLM to MoE + expert parallelism without
EPLB; dense models and other modes are no-ops, with an explicit config
escape hatch.
> 
> **Overview**
> **Expert-parallel MoE loads now opt into vLLM’s EP weight filter by
default**, via a typed `inference.vllm.enable_ep_weight_filter` field
(default `true`) that flows through `to_namespace()` to
`--enable-ep-weight-filter`. That lets each rank read only its local
expert shard at checkpoint load instead of full expert tensors, reducing
I/O and startup time when EP is on and EPLB is off.
> 
> The GLM-5.3 advanced TOML recipes **drop redundant**
`enable_ep_weight_filter = true` lines and rely on the default. A unit
test **asserts** the resolved server namespace includes
`enable_ep_weight_filter=True`. Set
`inference.vllm.enable_ep_weight_filter = false` to disable.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f26215dee423de2a19ec763106fd979183556cef. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 22:57:30 -07:00
samsjaandGitHub 8c2847721a chore(examples): glm-5.3 swe.toml base + swe-llmd.toml append, serve BF16 with vllm-side FP8 (#3607)
## What

Reworks the GLM-5.3 RL examples as a **base + append** pair instead of
two standalone configs, and moves both variants onto the shared
`GLM-5.3-BF16` checkpoint with vLLM-side online FP8 quantization:

- **`swe.toml`** — the base config, carrying all the params that used to
live only in `swe-llmd.toml` (r2e-gym train source under the `rlm`
harness, `deepgemm_fp8` trainer, `cp = 4` / `ep = 8`, 16 train + 16
disaggregated-P/D infer nodes) behind the default **`vllm-router`**.
Inference serves the same **`zai-org/GLM-5.3-BF16`** checkpoint the
trainer broadcasts; vLLM quantizes it to per-block FP8 online
(`quantization = "fp8_per_block"`) — no separate FP8 release checkpoint.
- **`swe-llmd.toml`** — now a small **append overlay**: llm-d router
(EPP scorer tuning), Mooncake KV offload, and run-identity swaps (run
name / W&B project / SLURM job / sandbox runtime label). Launch:

  ```bash
uv run rl @ examples/advanced/glm-5.3/swe.toml # vllm-router
uv run rl @ examples/advanced/glm-5.3/swe.toml @
examples/advanced/glm-5.3/swe-llmd.toml # llm-d + Mooncake
  ```

- **`README.md`** — documents the base/append split, the composed launch
command, and which FILL INs live where.

## Why

- Two nearly-identical 100+ line configs drifted apart; a base + `@`
overlay keeps the llm-d variant a true delta (router + KV offload) and
makes the router the only difference between runs.
- Serving `GLM-5.3-BF16` with online per-block FP8 matches the trainer's
broadcast target and removes the dependency on the official block-FP8
serving release for both variants.

## Validation

Both launch paths resolve and validate end-to-end with `rl --dry-run`
(resolved per-process configs + sbatch generation): the base launches
`vllm-router --policy sticky_least_loaded`; the composed run swaps in
the llm-d router (EPP + Envoy) and enables Mooncake KV offload. Overlay
list-replacement semantics verified — the composed run keeps exactly one
train source, with the runtime label swapped to `glm5-llmd`.

Infer pre-flight configs (`infer/pd.toml`, `infer/pd-llmd.toml`) are
untouched.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are limited to example TOMLs and documentation; no runtime or
library code paths are modified.
> 
> **Overview**
> Reorganizes the GLM-5.3 RL examples so **`swe.toml` is the full base
stack** (r2e-gym / `rlm`, FP8 trainer, P/D inference behind
**`vllm-router`**, serving **`GLM-5.3-BF16`** with online block FP8) and
**`swe-llmd.toml` is a thin overlay** for llm-d router scorer tuning,
Mooncake KV offload, and sandbox runtime labels.
> 
> Most settings that previously lived only in `swe-llmd.toml` move into
`swe.toml`; the llm-d file drops trainer/orchestrator/deployment
duplication. The README is updated to describe **base vs append**
launches (`rl @ swe.toml` vs `rl @ swe.toml @ swe-llmd.toml`), moves
“FILL IN” and Mooncake tuning notes to the right file, and states that
**neither RL file ships `[ckpt]`** by default (overlay to add
checkpoints). The old **`swe.toml` train-source-less / SWE-bench-eval
plane is replaced** by this composable layout—not removed entirely.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c9d87a57a24248945b3035d1cb87dee2f8f66a1a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 19:48:22 -07:00
samsjaandGitHub 9dbe8b5fa0 fix: select GLM-5.3 renderer in examples (#3606)
## Summary
- configure both GLM-5.3 example runs to use the matching `glm-5.3`
renderer

Requires the GLM-5.3 renderer pinned by #3605.
2026-09-18 16:03:56 -07:00
samsjaandGitHub 819993faac chore: bump renderers for GLM-5.3 (#3605)
## Summary
- pin `deps/renderers` to the GLM-5.3 renderer implementation

Depends on PrimeIntellect-ai/renderers#156.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> <sup>[Cursor Bugbot](https://cursor.com/bugbot) is generating a
summary for commit 8c41fdb84cd8bbfa5f2b2fc97887da57fbf3ba40. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 15:40:49 -07:00
Mika SenghaasandGitHub d57c59f16a fix: do not abort on consecutive empty train batches (#3595)
## Summary

- Remove the run-level aborts on consecutive empty train batches:
- The orchestrator raised after 10 consecutive no-sample train batches.
`MAX_CONSECUTIVE_EMPTY_BATCHES` and its counter are gone; an empty batch
now logs a warning and is skipped.
- The train sink raised after 10 batch-equivalents of finalized groups
that shipped no payload. The tally now only throttles the warning
(`_warn_zero_output`); there is no abort.
- Keep both warnings, so a run with no training signal stays visible in
the logs. A dead curriculum, an all-equal reward sweep, or an
infrastructure outage now stalls the run instead of killing it.
- Update the one `docs/algorithms.md` sentence that described the abort.
## Verification

- `uv run pytest tests/unit/orchestrator -q`: 82 passed, 1 skipped. The
8 failures are pre-existing `torch`/`vllm` import errors in a no-extras
env and fail the same way on `main`.
- `ruff check` / `ruff format --check` pass on both changed files.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Behavior change is limited to error handling: runs no longer fail fast
on sustained empty training signal, which may hide config issues but
avoids killing jobs on benign stalls.
> 
> **Overview**
> **Removes run-killing guards** when training produces no shippable
data, so misconfigured curricula or transient all-zero-advantage groups
**stall with warnings** instead of crashing the orchestrator.
> 
> In **`orchestrator.py`**, the **10 consecutive empty-batch abort** is
gone: empty `TrainBatch` samples log *"skipping empty train batch"* and
return without advancing the step. **`train_sink.py`** keeps counting
zero-output finalized units but **`_warn_zero_output`** only emits
throttled warnings—no **`RuntimeError`** after 10 batch-equivalents.
> 
> **`docs/algorithms.md`** now says group-relative `group_size = 1`
empty batches are **skipped at runtime**, not aborted.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3160f47b861a2c9c6cb33fef4961336f9b6560e9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 11:22:15 -07:00
Matej SirovatkaandGitHub c4a78d1134 fix: specialize FP8 indexer quantization constants (#3594)
Compiled GLM-5.3 training fails on its first forward pass because `eps`,
`fp8_min`, and `fp8_max` reach the FP8 indexer quantization kernel as
runtime FP64 scalars. Their arithmetic promotes the quantization result
to FP64, and Triton rejects the resulting conversion with `Unsupported
conversion from f64 to f8E4M3FN with rounding mode rtne`.

Mark these three fixed scalar arguments as `tl.constexpr` so Triton
specializes them at compile time.

Validation: reproduced the failure on an 8-node H200 BF16 trainer with
`torch.compile`, activation checkpointing/offloading, full CPU offload,
and SignSGD. With this patch, the first forward/backward pass and
optimizer update completed, and the trainer began broadcasting policy
v1. The 20-step verification run is still in progress. `git diff
--check` passes.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single-line Triton signature change with no API or logic changes; only
affects compile-time specialization of fixed FP8 bounds.
> 
> **Overview**
> Fixes **compiled training crashes** on the first forward pass when the
FP8 indexer quantizes activations under `torch.compile`.
> 
> The Triton kernel `_per_token_group_quant_fp8` now treats **`eps`,
`fp8_min`, and `fp8_max` as `tl.constexpr`** instead of runtime
arguments. Previously those scalars promoted quant math to FP64, and
Triton failed converting the result to FP8 (`f64` → `f8E4M3FN`).
Specializing them at compile time keeps the quant path in types Triton
can lower correctly; callers still pass the same module-level `FP8_EPS`
/ `FP8_MIN` / `FP8_MAX` constants.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
02f155d8ffb8776346c320be42a6be1f1f5299e9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-18 13:12:13 +02:00
cacae615e6 chore(examples): rename GLM example folder to glm-5.3 (#3593)
The advanced GLM presets now train GLM-5.3, but the directory was still
named glm-5.2. Rename it and update every inbound link and the
"GLM-5/GLM-5.2" prose in the READMEs and docs.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation and example path updates only; no training, inference,
or runtime code changes.
> 
> **Overview**
> Renames the advanced GLM example from **`glm-5.2`** to **`glm-5.3`**
and updates every inbound link and launch snippet so docs match the
presets that target GLM-5.3.
> 
> **README**, **docs** (`advanced.md`, `configuration.md`,
`scaling.md`), and **examples/README** now point at
`examples/advanced/glm-5.3/` and describe **`GLM-5`/`GLM-5.3`** instead
of 5.2. The **glm-5.3** walkthrough updates `uv run rl` / `uv run
inference` paths; **`infer/pd-llmd.toml`** only fixes its launch comment
to the new path (config content such as `GLM-5.2-FP8` model IDs is
unchanged).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fb2d99039d8719ff2bcdf2ac1e2c7baaa6f49946. 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: Johannes Hagemann <johannes@Johanness-MacBook-Pro.local>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-18 00:22:35 -07:00
samsjaandGitHub a9005aba8e fix(examples): express GLM-5.2 SWE shared model as a [model] table (#3591)
## Summary
PR #3588 centralized the model id for
`examples/advanced/glm-5.2/swe.toml` as a top-level
string (`model = "zai-org/GLM-5.3-BF16"`), but `RLConfig.model` is a
`SharedModelConfig`
table, so no config class could parse the file and CPU tests on `main`
failed
(`test_load_configs[examples/advanced/glm-5.2/swe.toml]`).

- Express the shared model as a `[model]` table with `name =
"zai-org/GLM-5.3-BF16"`, which
propagates to `trainer.model.name`, `orchestrator.model.name`, and
`inference.vllm.model`
  (same intent as #3588).
- Update the `[inference.vllm]` comment: it now serves the shared BF16
checkpoint with online
  per-block FP8 quantization, not a separate block-FP8 release.

Fixes the CPU Tests failure on `main` introduced by #3588.
2026-09-17 23:55:47 -07:00
samsjaandGitHub 788b9fdd1a Update swe.toml (#3588)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Example config-only change with no application code; verify the stack
resolves the correct vLLM checkpoint now that `[inference.vllm]` no
longer sets a separate `zai-org/GLM-5.3` id.
> 
> **Overview**
> **Centralizes the Hugging Face model id** for the GLM-5.2 SWE advanced
example by adding a top-level `model = "zai-org/GLM-5.3-BF16"` and
dropping duplicate `name` / `model` entries under `[trainer.model]`,
`[inference.vllm]`, and `[orchestrator.model]`.
> 
> Inference still uses the same vLLM settings (BF16 dtype,
`fp8_per_block` quantization, GLM tool parser); only the redundant
per-section model strings are removed so one field drives training and
orchestration.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4520df470f2417d4333f48fb80f40a2ed820574e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
2026-09-17 22:38:22 -07:00
samsjaandGitHub abcf7c0acc docs(examples): update GLM SWE presets to 5.3 (#3587)
<!-- CURSOR_SUMMARY -->
> [!NOTE]
> **Low Risk**
> Documentation and example TOML checkpoint IDs only; no runtime or auth
logic changes.
> 
> **Overview**
> Updates the **GLM-5.2** advanced SWE example presets and README so
runs target **GLM-5.3**: trainers load **`zai-org/GLM-5.3-BF16`**, while
disaggregated vLLM inference serves the **`zai-org/GLM-5.3`** block-FP8
checkpoint (with short comments explaining the train/serve split).
> 
> **`swe.toml`** and **`swe-llmd.toml`** swap prior **`GLM-5` /
`GLM-5.1`** Hugging Face IDs on **`[inference.vllm]`**,
**`[trainer.model]`**, and **`[orchestrator.model]`**. The base
**`swe.toml`** plane also gains **`[orchestrator.renderer] name =
"glm-5.1"`** so it matches the llm-d stack’s rendering setup. Docs and
launch comments now describe **GLM-5.3** full-stack RL instead of 5.1;
inference-only table rows for **`infer/pd*.toml`** are unchanged in this
diff.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e02482573c596a0c7b575a710e8cf09e38ef4757. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 21:45:53 -07:00
samsjaandGitHub 26c967c6e3 Default IPO to eps 0.3 without KL (#3586)
## Summary

- make IPO use `eps = 0.3` by default
- disable the IPO KL regularizer by default with `kl_tau = 0.0`
- update the algorithm documentation to match

Explicit `[trainer.loss]` values continue to override these defaults.

## Test plan

- instantiated `IPOLossConfig` and the default `TrainerConfig.loss`,
confirming `eps == 0.3` and `kl_tau == 0.0`
- `ruff check packages/prime-rl-configs/src/prime_rl/configs/trainer.py`
2026-09-17 20:59:24 -07:00
Mika SenghaasandGitHub 7760531310 feat: update Prime sandbox SDK (#3585)
## Summary

- Replace the full Prime CLI dependency with `prime-sandboxes` 0.3.0.
- Preserve API key and team discovery from `prime login` through the
sandbox SDK config reader.
- Advance the verifiers submodule to merged
[PrimeIntellect-ai/verifiers#2626](https://github.com/PrimeIntellect-ai/verifiers/pull/2626).
- Document the Prime CLI as a separate tool for login and sandbox
cleanup commands.

## Breaking

- Remove the Prime runtime `vm` and `guaranteed` fields. Delete these
fields from configs. Prime now always creates a VM sandbox.
- Stop publishing ports from Prime service runtimes. Colocate the
service and consumer, or use Docker or Modal for the service runtime.
- Stop installing the `prime` CLI with prime-rl. Run `uv tool install
prime` when the CLI is needed.

## Verification

- `uv lock --check`
- `uv sync --all-packages`
- `uv run ruff check src/prime_rl/orchestrator/clients.py
src/prime_rl/monitors/prime.py`
- `uv run pytest tests/unit/orchestrator/test_clients.py
tests/unit/test_configs.py -q` (199 passed)
- Confirmed `prime_sandboxes.Config` detects the existing CLI login and
team with `PRIME_API_KEY` and `PRIME_TEAM_ID` unset and the `prime`
distribution absent.
- `env -u PRIME_API_KEY -u PRIME_TEAM_ID uv run eval gsm8k -n 1 -r 1 -c
1 --run.name cli-login-smoke --output-dir /tmp/prl-cli-login-smoke`
(reward 1.0, no errors)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how Prime credentials are loaded and sandbox SDK version;
misconfiguration could break Prime Inference headers or sandbox rollouts
until users install the CLI and log in separately.
> 
> **Overview**
> Swaps the **`prime`** PyPI dependency for **`prime-sandboxes>=0.3.0`**
and points API key / team resolution at `prime_sandboxes.Config` instead
of `prime_cli.core.config` in the orchestrator client helpers and Prime
monitors.
> 
> Advanced example READMEs now tell users to install the **`prime`** CLI
separately (`uv tool install prime` + `prime login`) rather than
assuming it ships with prime-rl. The lockfile drops the full **`prime`**
package and its transitive UI stack while bumping **`prime-sandboxes`**
to 0.3.0 (and related Prime packages where resolved).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9c37d34fc380e4c0a8d79159e8323c31fe605ff2. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 20:04:56 -07:00
Matej SirovatkaandGitHub ce65f38fc0 Replace trainer-side FP8 transfer with online inference quantization (#3581)
NCCL weight updates now always send HF checkpoint-format weights and use
vLLM's layerwise reload, letting inference apply its configured
quantization. Remove the trainer-side FP8 transfer switch from config
schemas, propagation, admin requests, and worker RPCs, along with its
unused kernel conversion and loading helpers and tests. No references to
the removed setting remain in tracked project files.

Update both GLM SWE configs to use their BF16 checkpoints, `dtype =
"bfloat16"`, and `quantization = "fp8_per_block"`; align the
orchestrator model names with those checkpoints. EPLB remains rejected
for RL weight updates because the remaining reload path has not been
validated with it.

Validation:
- 131 config and admin/Dynamo RPC unit tests passed, plus both changed
GLM config-loading tests (133 total).
- Full RL config smoke checks cover model-name alignment, NCCL settings
propagation, and EPLB rejection for both examples.
- Ruff lint/format, Python compilation, TOML parsing, and diff
whitespace checks passed.
- The broader config-file sweep was blocked by missing optional taskset
plugins. GPU weight reload was not exercised.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes the critical trainer→inference weight update path and removes
a large alternate loading implementation; misalignment between trainer
weights and vLLM quantization could cause silent drift until GPU reload
is exercised.
> 
> **Overview**
> **Removes trainer-side FP8 kernel-format NCCL weight transfer** in
favor of always broadcasting HuggingFace checkpoint-format tensors and
reloading them in vLLM with layerwise processing, so inference applies
its own quantization settings.
> 
> The `weight_broadcast.quantize_in_weight_transfer` flag is deleted
from shared/trainer/orchestrator schemas, RL propagation,
`/init_broadcaster` RPCs, Dynamo admin, and the NCCL broadcaster/worker
path. Related trainer conversion (`convert_layer_to_vllm_kernel`,
GLM-MoE-DSA kernel export, `quantize_to_vllm_kernel_format`) and
inference helpers (`load_weights_kernel`, EPLB expert remapping) are
removed along with their unit tests.
> 
> **Example GLM SWE configs** switch from `*-FP8` checkpoints to BF16
base weights with `dtype = "bfloat16"` and `quantization =
"fp8_per_block"` on the vLLM side; orchestrator model names match.
> 
> **EPLB** is no longer tied to quantized NCCL transfer—`enable_eplb`
now fails validation for any RL run with weight updates, since the
checkpoint reload path is not validated with EPLB.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
33bf980a95d5ee259f0f8d7b52a7e29b7d8e4a63. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 16:43:34 -07:00
78 changed files with 732 additions and 1203 deletions
+7 -2
View File
@@ -94,9 +94,10 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# Third-party deps only — source edits don't bust this layer. First-party
# editables install in the source-layer sync below. No build-context bind
# mount here: .git would bust the cache every commit.
# `--extra dashboard` (fastapi/uvicorn) is baked in so the fft chart's dashboard pod needs no runtime uv sync (see PR body).
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
@@ -132,10 +133,14 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
# Needed for private environments hub auth
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
VIRTUAL_ENV=/app/.venv uv pip install 'prime>=0.7'
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
# (#2883); rebuilding against our UCX is the documented fix. Only needed for
+2 -2
View File
@@ -38,7 +38,7 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
7. Hackable, modular, and extensible by design.
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.2/).
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.3/).
## Models support
@@ -204,7 +204,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
3. [**GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` training with P/D disaggregation, the `llm-d` router, and FP8.
3. [**GLM-5**](examples/advanced/glm-5.3/): Large-scale `GLM-5`/`GLM-5.3` training with P/D disaggregation, the `llm-d` router, and FP8.
## Docs
+1 -1
+1 -1
+1 -1
View File
@@ -188,7 +188,7 @@ For large MoE serving, splitting prefill and decode onto separate vLLM groups ca
| Agentic (SWE, Lean) | 3:1 | Long growing contexts → prefill-heavy |
| Non-agentic (math, chat) | 1:2 | Short prompts, long generations → decode-heavy |
Example config: [`examples/advanced/glm-5.2/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.2/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.2/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2/infer).
Example config: [`examples/advanced/glm-5.3/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.3/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.3/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3/infer).
Monitor live queue depths to detect imbalance:
+3 -3
View File
@@ -112,7 +112,7 @@ patterns = ["WARNING"]
def drop_warnings(rollout, *, patterns: list[str]) -> list[list[bool]]: ...
```
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and aborts after repeated zero-trainable batches), not at config time.
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and skips it), not at config time.
### Per-Env Algorithms
@@ -209,9 +209,9 @@ The knobs under `[trainer.loss]` are:
| Knob | Default | What it does |
|---|---|---|
| `eps` | 0.1 | Maximum absolute probability change before a token is masked. |
| `eps` | 0.3 | Maximum absolute probability change before a token is masked. |
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
| `kl_tau` | 0.0 | Temperature on the KL regularizer. Set to 0 to disable. |
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
+1 -1
View File
@@ -229,7 +229,7 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation and FP8.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale `GLM-5`/`GLM-5.3` inference with P/D disaggregation and FP8.
### Worked Example: Compose, Override, Dry-Run
+1 -1
View File
@@ -287,7 +287,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.28 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.29 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
```toml
[trainer]
+1 -1
View File
@@ -233,7 +233,7 @@ gpus_per_node = 8
Full multi-node configs ship under [`examples/advanced/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced):
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/configs/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
- [`glm-5.3/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale and P/D-disaggregated inference across the GLM-5 family.
- [`glm-4.5-air/swe-2-node.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-4.5-air/swe-2-node.toml) — train a 100B+ MoE on only two nodes: a single-node sign-SGD trainer (full optimizer offload) paired with one inference replica at batch size 64. An overlay on the shared `swe-budget.toml` base — launch with `uv run rl @ swe-budget.toml @ swe-2-node.toml`.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
+2
View File
@@ -162,6 +162,8 @@ name = "qwen3"
enable_thinking = false
```
A `reasoning_effort` column in the dataset sets the renderer's `reasoning_effort` field per row, on top of the `[renderer]` config. The column requires a typed renderer that has that field (for example `gpt-oss`, `qwen3.8`, `deepseek-v4`); rows with a null value use the configured renderer unchanged. This lets one run mix reasoning efforts, with the `[renderer]` value as the default for rows that do not set one.
If a model needs another template control, add it to that model's renderer config in `renderers` (for example a new field on the relevant `*RendererConfig`) and consume it in the renderer implementation.
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5.
+1 -1
View File
@@ -10,7 +10,7 @@ Larger runs on frontier models, one folder per model, each with a launch README
- [`qwen3-30b-a3b/`](advanced/qwen3-30b-a3b/README.md) — `Qwen3-30B-A3B` RL on math (`i3_math`), SWE (`r2e-gym`), and agentic tool use (general-agent on Modal). 2 train + 2 infer nodes; the SWE config runs at 131k context with `ep = 8` + `cp = 2`.
- [`glm-4.5-air/`](advanced/glm-4.5-air/README.md) — `GLM-4.5-Air` (100B MoE) RL across search, SWE, and terminal domains at 131k context, with agents in sandboxes. 2 train + 4 infer nodes (SWE: 1 + 3).
- [`glm-5.2/`](advanced/glm-5.2/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
- [`glm-5.3/`](advanced/glm-5.3/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
- `intellect-3.1/` — reproduce the `INTELLECT-3.1` run: 4 train + 12 infer nodes on SWE.
All advanced configs submit through SLURM (the `rl` entrypoint writes the sbatch job when the config has a `[slurm]` table) and are monitored with `uv run dashboard`. See the per-model README for the full walkthrough.
+3 -2
View File
@@ -15,10 +15,11 @@ Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_paral
## Requirements
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — if you use those, log the `prime` CLI in (it ships with prime-rl's dependencies), and each config's `slurm.pre_run_command` will clean up the run's orphaned sandboxes by label before launching:
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. Install the `prime` CLI separately and log in. Each config's `slurm.pre_run_command` then cleans up the run's orphaned sandboxes by label before launch:
```bash
uv run prime login # or: uv run prime config set-api-key <your-key>
uv tool install prime
prime login # or: prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend) and drop the `slurm.pre_run_command` cleanup line.
-87
View File
@@ -1,87 +0,0 @@
seq_len = 131072
[log]
level = "debug"
[monitors.wandb]
project = "glm5-pd-disag"
[weight_broadcast]
type = "nccl"
port = 29502
timeout = 12000
quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
num_train_nodes = 16
gpus_per_node = 8
num_infer_replicas = 2
[inference.deployment]
type = "disaggregated"
prefill_nodes_per_replica = 4
decode_nodes_per_replica = 4
[inference.vllm]
model = "zai-org/GLM-5-FP8"
tool_call_parser = "glm47"
gpu_memory_utilization = 0.80
enable_expert_parallel = true
enable_eplb = false
[slurm]
job_name = "glm5-pd-disag"
[ckpt]
interval = 100
[trainer]
dist_timeout_seconds = 7200
[trainer.model]
name = "zai-org/GLM-5"
impl = "custom"
attn = "flash_attention_2" # dsa is skipping flash attn anyway
fused_lm_head_token_chunk_size = 2048
ep = 8
[trainer.model.ac]
freq = 1
[trainer.model.compile]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "adamw"
lr = 1e-6
weight_decay = 0.1
[orchestrator]
batch_size = 4096
group_size = 16
max_off_policy_steps = 16
[orchestrator.concurrency]
initial_inflight = 4096
max_inflight = 8192
[orchestrator.model]
name = "zai-org/GLM-5-FP8"
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swe-bench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm5-pd-disag", "swe-bench-verified"]
[inference]
# we need <0.85 bc glm5 layers are too large for 0.85
use_deep_gemm = true
@@ -1,22 +1,23 @@
# GLM-5 family at scale
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5`, `GLM-5.1`, and `GLM-5.2-FP8` — at 131k context: 16 trainer nodes on the custom MoE implementation (expert parallelism; the llm-d variant adds context parallelism) and P/D-disaggregated FP8 inference. The `-llmd` variants front the inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. They also offload KV to a Mooncake distributed CPU pool (1TB per node by default).
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5.3-BF16` for training and serving alike, quantized to per-block FP8 online on the vLLM side — at 131k context: 16 trainer nodes on the custom MoE implementation (expert + context parallelism) and P/D-disaggregated FP8 inference. The [`swe-llmd.toml`](swe-llmd.toml) append fronts the same inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. It also offloads KV to a Mooncake distributed CPU pool (1TB per node by default).
| Config | What it runs | Topology |
|---|---|---|
| [`swe.toml`](swe.toml) | GLM-5 RL plane: 16 train nodes, eval on `swebench-verified` every 20 steps, default vLLM router over 2 P/D replicas (4 prefill + 4 decode nodes each). Declares **no train source** — compose yours on top with an `[[orchestrator.train.source]]` overlay. | 16 train + 16 infer nodes |
| [`swe-llmd.toml`](swe-llmd.toml) | Full-stack GLM-5.1 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), llm-d router + Mooncake KV offload. | 16 train + 16 infer nodes |
| [`swe.toml`](swe.toml) | Base GLM-5.3 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), serves `GLM-5.3-BF16` with online per-block FP8 quantization behind the default `vllm-router`. | 16 train + 16 infer nodes |
| [`swe-llmd.toml`](swe-llmd.toml) | Append for `swe.toml`: swaps in the llm-d router (EPP scorer tuning) + Mooncake KV offload — launch as `rl @ swe.toml @ swe-llmd.toml`. | same |
| [`infer/pd.toml`](infer/pd.toml) | Inference-only pre-flight: P/D-disaggregated `GLM-5-FP8`. | 6 infer nodes |
| [`infer/pd-llmd.toml`](infer/pd-llmd.toml) | Inference-only pre-flight: `GLM-5.2-FP8` with llm-d + Mooncake. | 16 infer nodes |
## Requirements
- A Slurm cluster with 8-GPU nodes, a shared filesystem, and at least **32 nodes** (16 trainer + 16 inference) for the RL configs. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path. If you have fewer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` (llm-d variant) accordingly.
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d variants).
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in — it ships with prime-rl's dependencies:
- A Slurm cluster with 8-GPU nodes, a shared filesystem, and at least **32 nodes** (16 trainer + 16 inference) for the RL configs. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path. If you have fewer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` accordingly.
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d append).
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, install the `prime` CLI separately and log in:
```bash
uv run prime login # or: uv run prime config set-api-key <your-key>
uv tool install prime
prime login # or: prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend).
@@ -24,9 +25,9 @@ uv run prime login # or: uv run prime config set-api-key <your-key>
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
- `HF_TOKEN` — the GLM-5 family checkpoints are gated models.
- `WANDB_API_KEY` — both RL configs log to W&B (`[monitors.wandb]`).
- `WANDB_API_KEY` — both RL variants log to W&B (`[monitors.wandb]`).
### Install llm-d (llmd variants only)
### Install llm-d (llm-d append only)
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
@@ -47,28 +48,27 @@ uv sync --all-extras --all-packages
## Tweak before launching
- `swe-llmd.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`. `swe.toml` needs `--slurm.partition <your-partition>` or `--output-dir` overrides on the command line.
- `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
- `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
- `swe-llmd.toml` ships without `[ckpt]` — add a checkpoint overlay if you want resume support.
- `swe.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`.
- `swe-llmd.toml` `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
- `swe-llmd.toml` `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
## Start the run
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
```bash
# GLM-5.1 RL with llm-d + Mooncake (recommended)
uv run rl @ examples/advanced/glm-5.2/swe-llmd.toml
# GLM-5.3 RL behind the default vllm-router
uv run rl @ examples/advanced/glm-5.3/swe.toml
# GLM-5 base plane — compose your train source onto it
uv run rl @ examples/advanced/glm-5.2/swe.toml @ my-train-source.toml
# with the llm-d router + Mooncake KV offload appended
uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
```
The inference configs are standalone pre-flights: they serve the FP8 checkpoint through the same entrypoint the trainer uses (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster` included — never call `vllm serve` directly), and are a fast way to check that this cluster can serve the model at all before committing it to a run:
```bash
uv run inference @ examples/advanced/glm-5.2/infer/pd.toml
uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
uv run inference @ examples/advanced/glm-5.3/infer/pd.toml
uv run inference @ examples/advanced/glm-5.3/infer/pd-llmd.toml
```
## Monitor with the dashboard
@@ -97,6 +97,6 @@ Pass several output directories to track parallel experiments side by side (`uv
## Checkpoint and resume
`swe.toml` checkpoints every 100 steps (`[ckpt] interval = 100`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
Both RL configs ship without `[ckpt]` — add a `[ckpt]` overlay (e.g. `interval = 100`) for periodic checkpoints. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
See [Scaling](../../../docs/scaling.md) for SLURM details and [Inference](../../../docs/inference.md) for the disaggregated-inference and router reference.
@@ -2,7 +2,7 @@
# Step 3 / goal target. Topology mirrors the proven original glm5.1_llmd_inference
# (job 348 succeeded): 8 prefill nodes (4 replicas x 2) + 8 decode nodes (1 replica).
#
# Launch: uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
# Launch: uv run inference @ examples/advanced/glm-5.3/infer/pd-llmd.toml
output_dir = "/shared/outputs/glm5.2-16node-llmd"
@@ -60,5 +60,4 @@ reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
+47
View File
@@ -0,0 +1,47 @@
# llm-d append for swe.toml: fronts the P/D-disaggregated inference plane with
# the llm-d router (Endpoint Picker + Envoy) and offloads KV to a Mooncake
# distributed CPU pool. Everything else is inherited from the base config:
#
# uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
[run]
name = "glm5-llmd"
[monitors.wandb]
project = "glm5-llmd"
[slurm]
job_name = "glm5-llmd"
# Overlays replace arrays of tables wholesale, so the train source is spelled
# out again just to swap the sandbox runtime label.
[[orchestrator.train.source]]
name = "r2e"
env.taskset.id = "r2e-gym"
env.agent.harness.id = "rlm"
env.agent.runtime.labels = ["glm5-llmd"]
[inference.router]
type = "llm-d"
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
@@ -1,23 +1,29 @@
# Base GLM-5.3 RL config: P/D-disaggregated FP8 inference behind the default
# vllm-router. Serves the same GLM-5.3-BF16 checkpoint the trainer broadcasts,
# quantized to per-block FP8 online on the vLLM side. Append swe-llmd.toml to
# front the same plane with the llm-d router + Mooncake KV offload:
#
# uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
max_steps = 10000000
seq_len = 131072
output_dir = "/shared/outputs" # FILL IN: point at your shared filesystem
clean = true
[run]
name = "glm5-llmd"
name = "glm5"
[log]
level = "debug"
[monitors.wandb]
project = "glm5-llmd"
project = "glm5"
name = "base"
[weight_broadcast]
type = "nccl"
port = 29502
timeout = 12000
quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
@@ -52,41 +58,30 @@ num_decode_replicas = 1
"max_num_seqs" = 96
[inference.router]
type = "llm-d"
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
"prefix-cache-scorer" = 3.0
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
"queue-scorer" = 4.0
"active-request-scorer" = 5.0
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
"active-request-scorer" = 5.0
"kv-cache-utilization-scorer" = 4.0
"queue-scorer" = 3.0
type = "vllm-router"
[inference.vllm]
model = "zai-org/GLM-5.1-FP8"
# Serve the same GLM-5.3-BF16 checkpoint the trainer broadcasts; vLLM quantizes
# it to per-block FP8 online.
model = "zai-org/GLM-5.3-BF16"
dtype = "bfloat16"
quantization = "fp8_per_block"
max_model_len = 131072
tool_call_parser = "glm47"
reasoning_parser = "glm45"
gpu_memory_utilization = 0.75
enable_expert_parallel = true
enable_eplb = false
enable_ep_weight_filter = true
safetensors_load_strategy = "prefetch"
[slurm]
job_name = "glm5-llmd"
job_name = "glm5"
partition = "all" # FILL IN: set to your cluster's partition
[trainer]
dist_timeout_seconds = 1800
[trainer.model]
name = "zai-org/GLM-5.1"
name = "zai-org/GLM-5.3-BF16"
impl = "custom"
attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
@@ -122,10 +117,10 @@ initial_inflight = 256
max_inflight = 512
[orchestrator.model]
name = "zai-org/GLM-5.1-FP8"
name = "zai-org/GLM-5.3-BF16"
[orchestrator.renderer]
name = "glm-5.1"
name = "glm-5.3"
clear_thinking = false
[orchestrator.train.sampling]
@@ -138,17 +133,9 @@ clear_thinking = false
name = "r2e"
env.taskset.id = "r2e-gym"
env.agent.harness.id = "rlm"
env.agent.runtime.labels = ["glm5-llmd"]
env.agent.runtime.labels = ["glm5"]
[inference]
# <0.80 because glm5 layers are too large for 0.85
use_deep_gemm = true
enable_fp32_lm_head = true
[inference.kv_cache_offload]
type = "mooncake"
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
[inference.kv_cache_offload.cpu]
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
+3 -2
View File
@@ -13,10 +13,11 @@ RL on the 30B-A3B MoE across three domains: math, SWE, and agentic tool use. The
## Requirements
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
- **Sandboxes** (`swe.toml` only) — the SWE agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in (it ships with prime-rl's dependencies):
- **Sandboxes** (`swe.toml` only) — the SWE agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, install the `prime` CLI separately and log in:
```bash
uv run prime login # or: uv run prime config set-api-key <your-key>
uv tool install prime
prime login # or: prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on the source for a runtime your environments support (e.g. a local Docker backend).
@@ -21,6 +21,11 @@ class ServedEvalConfig(EvalSourcesConfig):
"""Adaptive in-flight episode concurrency, sized by the same controller as
``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on episode dispatch, in tasks per minute. Use it for
sandbox-backed environments to pace provisioning during autoscaling. None disables
rate limiting."""
@property
def env_addresses(self) -> dict[tuple[str, str], str | None]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
@@ -132,6 +132,12 @@ class VllmConfig(BaseConfig):
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB)."""
enable_ep_weight_filter: bool = True
"""Skip non-local expert weights at load time under expert parallelism, so each
rank reads only its own expert shard from disk. No-op for non-MoE models, when
expert parallelism is disabled, or under EPLB (redundant expert slots need all
logical expert weights)."""
enable_dbo: bool = False
"""Enable dual batch overlap (DBO)."""
@@ -305,6 +311,9 @@ class VllmRouterConfig(BaseConfig):
type: Literal["vllm-router"] = "vllm-router"
request_timeout_secs: int = Field(1800, ge=1)
"""Maximum lifetime of a routed request, including streamed completions."""
policy: str = "sticky_least_loaded"
"""Routing policy. Defaults to session-affine least-loaded routing; alternatives include ``consistent_hash`` and ``round_robin``."""
@@ -464,7 +473,7 @@ class InferenceConfig(BaseConfig):
"""Return per-token sampling masks (``sampling_mask``) on ``/inference/v1/generate`` responses via vLLM's native ``--return-sampling-mask`` (>= 0.28). The ``rl`` entrypoint enables this field for truncated policy sampling. Standalone inference must set it explicitly because no orchestrator sampling config is available. The field persists into per-node configs and selects the V2 model runner before vLLM starts. Capture is engine-wide: vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0`` while it is on."""
enable_fp32_lm_head: bool = True
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented natively by vLLM's LogitsProcessor, which reads ``head_dtype`` off the HF config, so this flag injects ``hf_overrides = {"head_dtype": "float32"}``."""
enable_fp32_router_logits: bool = True
"""Emit fp32 MoE router logits: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented natively by vLLM, which reads ``moe_router_dtype`` off the HF config — this flag injects ``hf_overrides = {"moe_router_dtype": "float32"}`` (GLM-5.x gets fp32 routing regardless)."""
@@ -638,6 +647,13 @@ class InferenceConfig(BaseConfig):
hf_overrides.setdefault("moe_router_dtype", "float32")
namespace.hf_overrides = hf_overrides
# vLLM's LogitsProcessor reads `head_dtype` off the HF config to pick the
# lm_head projection dtype (fp32 runs as a native bf16xbf16 -> fp32 GEMM).
if self.enable_fp32_lm_head:
hf_overrides = getattr(namespace, "hf_overrides", None) or {}
hf_overrides.setdefault("head_dtype", "float32")
namespace.hf_overrides = hf_overrides
if self.enable_return_sampling_mask:
namespace.return_sampling_mask = True
@@ -645,12 +661,4 @@ class InferenceConfig(BaseConfig):
if kv_transfer_config is not None:
namespace.kv_transfer_config = kv_transfer_config
# Pass prime-rl-specific flags through vLLM's additional_config dict;
# workers read these via get_current_vllm_config().additional_config.
additional_config = getattr(namespace, "additional_config", None) or {}
if self.enable_fp32_lm_head:
additional_config["fp32_lm_head"] = True
if additional_config:
namespace.additional_config = additional_config
return namespace
@@ -166,6 +166,9 @@ class EnvConfig(BaseConfig):
name: str | None = None
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
shuffle: bool = False
"""Shuffle the source's finite taskset once with a fixed seed. The shuffled order is fixed for the whole run; infinite tasksets cannot be shuffled."""
@model_validator(mode="before")
@classmethod
def _resolve_env(cls, data):
@@ -459,9 +462,6 @@ class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
@@ -145,9 +145,6 @@ class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
port: int = 29501
"""Port for NCCL weight broadcast."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
@@ -368,22 +365,6 @@ class RLConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_quantize_in_weight_transfer(self):
if not isinstance(self.weight_broadcast, SharedNCCLWeightBroadcastConfig):
return self
if not self.weight_broadcast.quantize_in_weight_transfer:
return self
if self.inference is None:
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires an inference config.")
if self.trainer.model.impl != "custom":
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires trainer.model.impl = 'custom'.")
return self
### Auto-setup shared configs (before sub-config construction)
@model_validator(mode="before")
@@ -487,9 +468,7 @@ class RLConfig(BaseConfig):
inference_world_size=inference_world_size,
)
if self.weight_broadcast.type == "nccl":
transport_config = dict(
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
transport_config = {}
trainer_config_type = TrainerNCCLWeightBroadcastConfig
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
else:
@@ -538,18 +517,9 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_eplb_requires_quantized_weight_transfer(self):
if self.inference is None or not self.inference.vllm.enable_eplb:
return self
# TODO(matej): check if weight reloading works itself before supporting EPLB without quantized transfer.
trainer_weight_broadcast = self.trainer.weight_broadcast
if trainer_weight_broadcast.type != "nccl" or not trainer_weight_broadcast.quantize_in_weight_transfer:
raise ValueError(
"inference.vllm.enable_eplb requires weight_broadcast.type = 'nccl' and "
"weight_broadcast.quantize_in_weight_transfer = true."
)
def validate_eplb(self):
if self.inference is not None and self.inference.vllm.enable_eplb:
raise ValueError("inference.vllm.enable_eplb is not supported with RL weight updates.")
return self
@model_validator(mode="after")
@@ -171,7 +171,7 @@ class DynamoConfig(BaseConfig):
class ClientConfig(BaseConfig):
wait_for_ready_timeout: int = 1800
wait_for_ready_timeout: int = 3600
"""Seconds to wait at startup for the inference pool to become ready."""
base_url: str = "http://localhost:8000/v1"
@@ -568,13 +568,13 @@ class CheckpointConfig(BaseConfig):
class IPOLossConfig(BaseConfig):
type: Literal["ipo"] = "ipo"
eps: float = Field(0.1, ge=0)
eps: float = Field(0.3, ge=0)
"""Maximum absolute probability change before a token is masked."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
kl_tau: float = Field(1e-3, ge=0)
kl_tau: float = Field(0.0, ge=0)
"""Temperature for the KL term."""
@@ -645,9 +645,6 @@ class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
+13 -7
View File
@@ -16,7 +16,7 @@ dependencies = [
"transformers==5.6.2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
"prime>=0.6.19",
"prime-sandboxes>=0.3.0",
"prime-runs[train]>=0.1.3",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
@@ -56,7 +56,7 @@ gpu = [
"torchvision ; sys_platform == 'linux'",
"torchaudio ; sys_platform == 'linux'",
"torchdata>=0.11.0 ; sys_platform == 'linux'",
"vllm>=0.28.0 ; sys_platform == 'linux'",
"vllm>=0.29.0 ; sys_platform == 'linux'",
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
"torchtitan ; sys_platform == 'linux'",
@@ -146,7 +146,7 @@ override-dependencies = [
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
"apache-tvm-ffi==0.1.11",
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
# vLLM 0.28.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
# vLLM 0.29.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
"nvidia-cutlass-dsl==4.6.2",
"transformers==5.6.2",
@@ -224,8 +224,6 @@ requires-dist = [
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
harbor = "2026-08-11T00:00:00Z"
# we want latest vllm, remove next patch
vllm = false
tokenspeed-mla = false
fastokens = false
flash_attn_3 = false
@@ -273,8 +271,8 @@ vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
@@ -310,6 +308,14 @@ name = "pytorch-cu130-test"
url = "https://download.pytorch.org/whl/test/cu130"
explicit = true
# Environments Hub wheels carry no upload time, so the exclude-newer cooldown
# would reject every one of them. The Hub is first-party: skip the cutoff there.
[[tool.uv.index]]
name = "prime-hub"
url = "https://hub.primeintellect.ai/primeintellect/simple/"
explicit = true
exclude-newer = false
[tool.ruff.lint]
select = ["F", "I"]
+1 -1
View File
@@ -1536,7 +1536,7 @@ def row_filter(
return False
if episode is not None and row.get("id") != episode:
return False
if errors_only and not (row.get("num_errors") or not row.get("ok")):
if errors_only and row.get("ok"):
return False
arrival = row.get("arrival") or 0
return not ((start is not None and arrival < start) or (end is not None and arrival >= end))
+81 -41
View File
@@ -1176,7 +1176,7 @@ function summaryTilesHtml(idx, all, scoreEntries) {
}
// failure rates count every landed episode, the errors filter notwithstanding
if (all.length) {
const errored = all.filter((i) => series.ok?.[i] === false || (series.num_errors?.[i] ?? 0) > 0).length;
const errored = all.filter((i) => series.ok?.[i] === false).length;
const truncated = all.filter((i) => (series.truncated?.[i] ?? TRUNCATING_STOPS.has(series.stop_condition?.[i])) === true).length;
for (const [label, n, what] of [["error rate", errored, "errored"], ["truncation rate", truncated, "truncated"]]) {
const rate = n / all.length;
@@ -3022,10 +3022,12 @@ function fmtSpan(dispatched, arrived, elapsed) {
}
function episodeRowHtml(ep) {
const failed = !ep.ok || !!ep.num_errors;
// an ok episode keeps the errors of the attempts it recovered from; they mark the
// row as retried, not as failed
const failed = !ep.ok;
const phase = failed ? "error" : "done";
const dispatched = ep.dispatch ?? (ep.arrival != null && ep.duration != null ? ep.arrival - ep.duration : null);
return `<tr data-line="${ep.line}" class="${failed ? "err" : ""}"${failed ? ` title="${ep.num_errors || 1} error${ep.num_errors === 1 ? "" : "s"}"` : ""}>
return `<tr data-line="${ep.line}" class="${episodeRowClass(ep)}" title="${esc(episodeRowTitle(ep))}">
<td class="muted">${ep.line}</td>
<td><span class="badge stage stage-${phase}">${phase}</span></td>
<td class="muted nowrap">${fmtSpan(dispatched, ep.arrival, ep.duration)}</td>
@@ -3209,7 +3211,7 @@ async function openLiveTrace(traceId, { refresh = false } = {}) {
semanticExpandedRuns.clear();
clearSemanticTranscriptOrigin();
$("#sg-inspector").hidden = true;
$("#tm-messages").innerHTML = `<div class="chart-empty">loading live trace…</div>`;
resetTranscript(`<div class="chart-empty">loading live trace…</div>`);
$("#tm-timeline").innerHTML = "";
$("#tm-meta").innerHTML = "";
}
@@ -3325,7 +3327,7 @@ function tmItemHtml(item) {
}
const e = item;
return (
`<div class="tm-item ${rolloutActive(item) ? "active" : ""}${e.num_errors || !e.ok ? " err" : ""}" data-line="${e.line}">` +
`<div class="tm-item ${rolloutActive(item) ? "active" : ""} ${episodeRowClass(e)}" data-line="${e.line}" title="${esc(episodeRowTitle(e))}">` +
`<span class="tm-num">#${e.line}</span><span class="tm-env muted" title="${esc(e.env ?? "")}">${esc(e.env ?? "")}</span>` +
`<span class="tm-reward ${rewardClass(e.reward)}">${fmtReward(e.reward)}</span></div>`
);
@@ -3426,7 +3428,7 @@ async function modalStep(delta) {
currentLine = null;
currentEpisode = null;
renderRolloutList();
$("#tm-messages").innerHTML = emptyState("no episodes", "this step has no rollouts for the current filters");
resetTranscript(emptyState("no episodes", "this step has no rollouts for the current filters"));
$("#tm-meta").innerHTML = "";
}
}
@@ -3474,6 +3476,15 @@ async function ensureTokens() {
currentEpisode = episode;
}
/* Every path that replaces the transcript with a placeholder goes through here, so the
previous episode's error strip never outlives its episode. */
function resetTranscript(html) {
const episodeErrors = $("#tm-episode-errors");
episodeErrors.hidden = true;
episodeErrors.innerHTML = "";
$("#tm-messages").innerHTML = html;
}
async function openEpisode(line, target = {}) {
currentLive = null;
$("#tm-live-label").textContent = "";
@@ -3486,7 +3497,7 @@ async function openEpisode(line, target = {}) {
currentEpisode = null;
renderModalStep();
renderRolloutList();
$("#tm-messages").innerHTML = `<div class="chart-empty">loading episode…</div>`;
resetTranscript(`<div class="chart-empty">loading episode…</div>`);
const timelineTarget = $("#tm-timeline");
timelineTarget.classList.remove("semantic-canvas");
delete timelineTarget.dataset.semanticEpisode;
@@ -3940,7 +3951,7 @@ function judgeEvidenceHtml(trace) {
function renderedTokensHtml(trace, branches) {
const rendered = trace.rendered_tokens;
const errors = errorBannersHtml(episodeErrors(currentEpisode, trace));
const errors = scopedErrorsHtml("trace", scopedErrors(currentEpisode, trace).trace);
if (!rendered) return errors + emptyState("rendered text not loaded", "select this view again to load recorded token IDs");
const path = currentPath(trace, branches);
const tokenCount = path.reduce((count, index) => count + (trace.nodes[index]?.token_ids?.length || 0), 0);
@@ -3980,43 +3991,67 @@ function renderedBoxHtml(tokenCount, body, canCopyText) {
let entriesObserver = null;
function episodeErrors(ep, trace) {
// one failure is often recorded twice, on the episode and on its trace; show it
// once, keeping whichever copy carries the traceback
const byMessage = new Map();
for (const error of [...(ep.errors || []), ...(trace?.errors || [])]) {
const record = error && typeof error === "object" ? error : { message: String(error) };
const key = `${record.type ?? "Error"}|${record.message ?? ""}`;
const kept = byMessage.get(key);
if (!kept || (!kept.traceback && record.traceback)) byMessage.set(key, record);
/* Errors carried by the episode and by the open trace, each split by what they mean.
Verifiers keeps every attempt's errors on the final record and stamps success as `ok`,
so the errors of an ok episode or trace are history it recovered from, while a failed
one's errors describe its outcome. A failure recorded on both the episode and its
trace shows once, as the trace's, keeping whichever copy carries the traceback. */
function scopedErrors(ep, trace) {
const record = (error) => (error && typeof error === "object" ? error : { message: String(error) });
const key = (r) => `${r.type ?? "Error"}|${r.message ?? ""}`;
const keep = (map, r) => {
const kept = map.get(key(r));
if (!kept || (!kept.traceback && r.traceback)) map.set(key(r), r);
};
const onTrace = new Map();
for (const error of trace?.errors || []) keep(onTrace, record(error));
const onEpisode = new Map();
for (const error of ep.errors || []) {
const r = record(error);
if (onTrace.has(key(r))) keep(onTrace, r);
else keep(onEpisode, r);
}
return [...byMessage.values()];
const split = (records, ok) => ({ failed: ok ? [] : records, recovered: ok ? records : [] });
return { episode: split([...onEpisode.values()], ep.ok), trace: split([...onTrace.values()], trace?.ok) };
}
function errorBannersHtml(errors) {
if (!errors.length) return "";
function errorEntryHtml(scope, record) {
const type = record.type ?? "Error";
const message = record.message ?? "No error message";
const traceback = Array.isArray(record.traceback) ? record.traceback.join("") : record.traceback;
return (
`<div class="trace-errors">` +
errors
.map((error) => {
const record = error && typeof error === "object" ? error : { message: String(error) };
const type = record.type ?? "Error";
const message = record.message ?? "No error message";
const traceback = Array.isArray(record.traceback) ? record.traceback.join("") : record.traceback;
return (
`<section class="trace-error-banner">` +
`<div class="trace-error-message"><span class="trace-error-type">${esc(type)}</span> ${esc(message)}</div>` +
(traceback
? `<details class="trace-error-tb"><summary><span>traceback</span><span class="entry-chev">›</span></summary><pre>${esc(traceback)}</pre></details>`
: "") +
`</section>`
);
})
.join("") +
`</div>`
`<div class="trace-error-message"><span class="trace-error-scope">${scope} error</span><span class="trace-error-type">${esc(type)}</span> ${esc(message)}</div>` +
(traceback
? `<details class="trace-error-tb"><summary><span>traceback</span><span class="entry-chev">›</span></summary><pre>${esc(traceback)}</pre></details>`
: "")
);
}
function scopedErrorsHtml(scope, { failed, recovered }) {
const banners = failed.length
? `<div class="trace-errors">${failed.map((record) => `<section class="trace-error-banner">${errorEntryHtml(scope, record)}</section>`).join("")}</div>`
: "";
const history = recovered.length
? `<details class="trace-recovered"><summary><span>recovered from ${recovered.length} ${scope} error${recovered.length === 1 ? "" : "s"} in earlier attempts</span><span class="entry-chev">›</span></summary>` +
recovered.map((record) => `<section class="trace-recovered-item">${errorEntryHtml(scope, record)}</section>`).join("") +
`</details>`
: "";
return banners + history;
}
function episodeRowClass(ep) {
if (!ep.ok) return "err";
return ep.num_errors ? "retried" : "";
}
function episodeRowTitle(ep) {
const n = ep.num_errors || 0;
const errors = `${n || 1} error${n === 1 ? "" : "s"}`;
if (!ep.ok) return errors;
return n ? `recovered from ${errors} in earlier attempts` : "";
}
function normalizedCallUsage(usage = {}) {
let input = usage.prompt_tokens;
let cached = usage.cached_input_tokens;
@@ -4036,7 +4071,7 @@ function normalizedCallUsage(usage = {}) {
function renderMessages(ep, trace, branches) {
const container = $("#tm-messages");
entriesObserver?.disconnect();
const errorsHtml = errorBannersHtml(episodeErrors(ep, trace));
const errorsHtml = scopedErrorsHtml("trace", scopedErrors(ep, trace).trace);
if (!trace) {
container.innerHTML = errorsHtml + emptyState("no traces", "this episode carries no trace data");
return;
@@ -5487,12 +5522,17 @@ function renderEpisode() {
const trace = traces[currentTraceIdx];
const branches = trace ? traceBranches(trace) : [];
if (currentBranchIdx >= branches.length) currentBranchIdx = 0;
// the episode's own errors sit above the agent and branch selectors: they belong to
// the whole episode, not to whichever trace is open
const episodeErrors = $("#tm-episode-errors");
episodeErrors.innerHTML = scopedErrorsHtml("episode", scopedErrors(ep, trace).episode);
episodeErrors.hidden = !episodeErrors.innerHTML;
const traceTabs = $("#tm-trace-tabs");
traceTabs.hidden = traces.length <= 1;
traceTabs.innerHTML =
traces.length > 1
? traces
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}">${esc(trace.agent?.name || "agent")}</button>`)
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}${trace.ok ? "" : " err"}">${esc(trace.agent?.name || "agent")}</button>`)
.join("")
: "";
const branchTabs = $("#tm-branch-tabs");
@@ -6538,7 +6578,7 @@ async function reopenFirstEpisode() {
currentLine = null;
currentEpisode = null;
renderRolloutList();
$("#tm-messages").innerHTML = emptyState("no episodes", "nothing here for the current filters");
resetTranscript(emptyState("no episodes", "nothing here for the current filters"));
$("#tm-meta").innerHTML = "";
}
+1
View File
@@ -302,6 +302,7 @@
<button id="tm-expand" class="btn">expand</button>
<button id="drawer-close" class="btn">✕</button>
</div>
<div id="tm-episode-errors" hidden></div>
<div class="tm-head tm-tabs-row" id="tm-tabs-row" hidden>
<div id="tm-trace-tabs" class="seg" hidden></div>
<div id="tm-branch-tabs" class="seg" hidden></div>
+36 -1
View File
@@ -834,6 +834,7 @@ mark.hit {
.tm-item.active { background: var(--grey-2); border-color: var(--grey-3); color: var(--grey-6); }
.tm-item.err { background: rgba(255, 69, 57, 0.08); border-color: var(--negative); }
.tm-item.err:hover, .tm-item.err.active { background: rgba(255, 69, 57, 0.16); }
.tm-item.retried { border-left: 2px dotted var(--grey-4); }
.tm-item .tm-reward { margin-left: auto; }
.tm-nav { padding: 0 8px; height: 24px; }
.tm-stephead { justify-content: space-between; background: var(--grey-2); min-height: 40px; }
@@ -1169,7 +1170,7 @@ mark.hit {
#sg-open-transcript { margin: 0 12px 12px; min-height: 30px; }
/* the banners lead the transcript, so they stand off the first entry */
.trace-errors { margin-top: auto; padding-top: 12px; margin-bottom: 14px; }
.trace-errors { margin-top: auto; margin-bottom: 14px; }
.trace-error-banner {
border: 1px solid var(--negative);
background: rgba(255, 69, 57, 0.08);
@@ -1178,6 +1179,39 @@ mark.hit {
.trace-error-banner + .trace-error-banner { margin-top: 8px; }
.trace-error-message { padding: 10px 12px; font-size: 12px; white-space: pre-wrap; word-break: break-word; }
.trace-error-type { font-weight: 500; color: var(--negative); }
.trace-error-scope {
display: inline-block;
margin-right: 8px;
padding: 1px 6px;
border: 1px solid currentColor;
font-size: 9px;
line-height: 11px;
letter-spacing: var(--track-mono);
text-transform: uppercase;
color: var(--grey-4);
vertical-align: middle;
}
.trace-error-banner .trace-error-scope { color: var(--negative); }
#tm-episode-errors { padding: 12px 16px 0; border-bottom: 1px solid var(--hairline); }
#tm-episode-errors .trace-errors { margin-top: 0; margin-bottom: 12px; }
#tm-episode-errors .trace-recovered { margin-bottom: 12px; }
.trace-recovered { margin-bottom: 14px; border: 1px solid var(--grey-3); color: var(--grey-6); }
.trace-recovered > summary {
display: flex;
align-items: center;
gap: 10px;
padding: 6px 12px;
font-size: 11px;
color: var(--grey-4);
cursor: pointer;
list-style: none;
}
.trace-recovered > summary::-webkit-details-marker { display: none; }
.trace-recovered[open] > summary .entry-chev { transform: rotate(90deg); }
.trace-recovered-item { border-top: 1px solid var(--grey-3); }
.trace-recovered-item .trace-error-type { color: var(--grey-4); }
.trace-recovered-item .trace-error-tb > summary { border-top-color: var(--grey-3); }
.seg button.err, .seg button.err.active { color: var(--negative); }
.trace-error-tb > summary {
display: flex;
align-items: center;
@@ -1697,6 +1731,7 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
place of their number set them apart */
.live-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); animation: live-pulse 2s ease-out infinite; }
#episode-table tr.err td:first-child { border-left: 2px solid var(--negative); }
#episode-table tr.retried td:first-child { border-left: 2px dotted var(--grey-4); }
#episode-table tr.live.landing .live-dot { animation: none; opacity: 0.45; }
.badge.stage { font-size: 9px; padding: 2px 5px; line-height: 12px; border-radius: 3px; background: var(--hairline); border-color: transparent; color: var(--accent); }
#tm-live-label { margin-left: 8px; }
+5
View File
@@ -1,6 +1,7 @@
import os
import queue
import threading
import uuid
from functools import partial
from pathlib import Path
@@ -53,6 +54,10 @@ def run_server(config: EnvServerConfig):
def main():
"""Main entry-point for the env server. Run using `uv run env-server`"""
set_proc_title("EnvServer")
# verifiers keys run-scoped state (creation limiters) by $VF_RUN_ID. Every launcher,
# the Python entrypoints and the SLURM templates alike, hands env servers $PRL_RUN_ID;
# a standalone server is a run of its own.
os.environ.setdefault("VF_RUN_ID", os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex)
run_server(cli(EnvServerConfig))
+2
View File
@@ -181,6 +181,8 @@ def start_router(config: InferenceConfig) -> subprocess.Popen:
str(config.vllm.data_parallel_size_local or config.vllm.data_parallel_size),
"--request-id-headers",
"x-session-id",
"--request-timeout-secs",
str(config.router.request_timeout_secs),
"--worker-startup-timeout-secs",
"4200",
"--prometheus-port",
+4 -5
View File
@@ -137,7 +137,7 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
def write_slurm_script(
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str | None = None
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str, wandb_shared: bool
) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
@@ -210,6 +210,7 @@ def write_slurm_script(
gpus_per_node=config.deployment.gpus_per_node,
ranks_filter=",".join(map(str, config.log.ranks_filter)),
prl_run_id=prl_run_id,
wandb_shared=wandb_shared,
run_name=config.run.name,
online_eval=online_eval,
use_nccl_broadcast=(
@@ -249,16 +250,14 @@ def sft_slurm(config: SFTConfig):
write_config(config, config_path, exclude=exclude)
# Trainer and online-eval processes log to a single shared W&B run.
prl_run_id: str | None = None
if online_eval and config.monitors.wandb is not None:
prl_run_id = os.environ["PRL_RUN_ID"]
wandb_shared = online_eval and config.monitors.wandb is not None
launcher_dir = get_launcher_dir(config.run_dir)
if online_eval:
write_eval_subconfigs(config, config_dir, strip_router=True)
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
script_path = launcher_dir / SFT_SBATCH
write_slurm_script(config, config_path, log_dir, script_path, prl_run_id)
write_slurm_script(config, config_path, log_dir, script_path, os.environ["PRL_RUN_ID"], wandb_shared)
logger.info(f"Wrote SLURM script to {script_path}")
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
+1
View File
@@ -40,6 +40,7 @@ RESUMABLE = (
"log",
"monitors",
"source.*.num_examples",
"source.*.shuffle",
"source.*.group_size",
"source.*.serve",
)
+1 -1
View File
@@ -114,7 +114,7 @@ class EvalRunner:
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
tasks_per_minute=None,
tasks_per_minute=config.tasks_per_minute,
max_off_policy_steps=0,
run_id=self.run_id,
run_name=self.run_name,
-2
View File
@@ -391,7 +391,6 @@ class DynamoAdminPlane(AdminPlane):
port: int,
timeout: int,
inference_world_size: int,
quantize_in_weight_transfer: bool = False,
) -> None:
async with self._mutation_lock:
self._require_uninitialized_nccl()
@@ -411,7 +410,6 @@ class DynamoAdminPlane(AdminPlane):
0,
1,
timeout,
quantize_in_weight_transfer,
"default",
],
)
+2 -114
View File
@@ -15,7 +15,6 @@ def apply_shared_vllm_patches():
_patch_lora_key_prefix()
_patch_qwen35_moe_lora_format()
monkey_patch_nano_v3_reasoning_parser()
monkey_patch_qwen3_coder_param_newline_trim()
monkey_patch_minimax_m2_think_end_passthrough()
monkey_patch_return_routed_experts_with_nixl_connector()
monkey_patch_kv_xfer_finished_tolerate_freed()
@@ -248,57 +247,6 @@ def monkey_patch_nano_v3_reasoning_parser():
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
def monkey_patch_qwen3_coder_param_newline_trim():
"""Restore vLLM 0.23's single-newline trim for qwen3_coder tool parameters.
vLLM 0.24's parser engine applies a full ``.strip()`` to every parameter
value in ``_qwen3_arg_converter``; 0.23's ``Qwen3CoderToolParser`` trimmed
exactly one leading and one trailing newline. A full strip corrupts
whitespace-significant string parameters (str_replace-style
``old_str``/``new_str``, file content with an indented first line, values
with intentional trailing newlines), silently changing tool execution and
rewards for agentic runs. Copy of ``_qwen3_arg_converter`` with only the
trim changed. Also covers ``nemotron_v3``, which reuses ``qwen3_config``.
"""
import json
from vllm.parser import qwen3
def _trim_one_newline(value: str) -> str:
if value.startswith("\n"):
value = value[1:]
if value.endswith("\n"):
value = value[:-1]
return value
def _patched_arg_converter(raw_args: str, partial: bool) -> str:
params: dict[str, object] = {}
for match in qwen3._PARAM_RE.finditer(raw_args):
name = match.group(1)
value = match.group(2)
## START PATCHED CODE (upstream: value.strip())
params[name] = _trim_one_newline(value)
## END PATCHED CODE
if partial:
remaining = qwen3._PARAM_RE.sub("", raw_args)
m = qwen3._PARTIAL_PARAM_RE.search(remaining)
if m:
name = m.group(1)
value = m.group(2)
if name:
## START PATCHED CODE (upstream: value.strip())
params[name] = _trim_one_newline(value)
## END PATCHED CODE
return json.dumps(params, ensure_ascii=False)
qwen3._qwen3_arg_converter = _patched_arg_converter
# qwen3_config captures the converter when first built; drop any cached configs.
qwen3.qwen3_config.cache_clear()
def monkey_patch_minimax_m2_think_end_passthrough():
"""Keep the literal ``</think>`` in MiniMax-M2 content on tool-calling turns.
@@ -757,68 +705,6 @@ def monkey_patch_no_moe_lora():
FusedMoEConfig.__post_init__ = _patched__post_init__
def monkey_patch_fp32_lm_head():
"""Run the lm_head projection in fp32, via a native bf16xbf16 -> fp32 GEMM.
Uses ``torch.mm(..., out_dtype=torch.float32)`` (PyTorch >= 2.10) so the
matmul accumulates and emits fp32 directly without zero-padding the bf16
operands or maintaining a separate fp32 weight copy. This avoids the
epilogue truncation to bf16 that `F.linear(bf16, bf16)` does, which is
where lm_head precision actually leaks before the sampler's softmax.
Activated by setting ``additional_config["fp32_lm_head"] = True`` on the
vLLM namespace; the launcher does this when ``inference.enable_fp32_lm_head``
is set. The flag is captured once on ``LogitsProcessor.__init__`` (where
vLLM guarantees a ``set_current_vllm_config()`` context) and stored on the
instance — reading it from ``_get_logits`` during serving doesn't work
because vLLM doesn't keep the context set during forwards.
Tracks vllm-project/vllm#24567 (which uses the operand-upcast approach).
Per @Jackmin801 on PR #2438, native ``out_dtype=fp32`` mm is more efficient
and just as correct.
"""
import torch
from vllm.config import get_current_vllm_config
from vllm.logger import init_logger
from vllm.model_executor.layers.logits_processor import LogitsProcessor
logger = init_logger(__name__)
_original_init = LogitsProcessor.__init__
_original_get_logits = LogitsProcessor._get_logits
def _patched_init(self, *args, **kwargs):
_original_init(self, *args, **kwargs)
vllm_config = get_current_vllm_config()
additional_config = vllm_config.additional_config or {}
self._fp32_lm_head_enabled = additional_config.get("fp32_lm_head", False)
if self._fp32_lm_head_enabled:
logger.warning("fp32 lm_head ENABLED for this LogitsProcessor instance.")
def _patched_get_logits(self, hidden_states, lm_head, embedding_bias):
if not getattr(self, "_fp32_lm_head_enabled", False):
return _original_get_logits(self, hidden_states, lm_head, embedding_bias)
# Native bf16xbf16 -> fp32 GEMM. torch.mm requires 2D inputs; vLLM v1's
# generative path passes 2D [num_tokens, hidden_size] hidden_states, but
# flatten defensively in case some future caller passes 3D.
flat = hidden_states.reshape(-1, hidden_states.shape[-1])
logits = torch.mm(flat, lm_head.weight.t(), out_dtype=torch.float32)
if embedding_bias is not None:
logits = logits + embedding_bias.to(torch.float32)
if hidden_states.dim() > 2:
logits = logits.reshape(*hidden_states.shape[:-1], -1)
logits = self._gather_logits(logits)
if logits is not None:
logits = logits[..., : self.org_vocab_size]
return logits
LogitsProcessor.__init__ = _patched_init
LogitsProcessor._get_logits = _patched_get_logits
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
def monkey_patch_dp_coordinator_startup_timeout():
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
@@ -935,6 +821,8 @@ def monkey_patch_deepseek_v4_per_layer_rope():
Note that nothing in vLLM's DeepSeek V4 calls the module's `forward`; every consumer reads
`cos_sin_cache` and hands it to a fused kernel. The class choice is therefore about the
cache's dtype and row count, not about which channels the module would rotate.
Remove this patch once the pin includes vllm-project/vllm#54815, which ships in 0.29.1.
"""
from vllm.models.deepseek_v4.common import rope as dsv4_rope
+11 -12
View File
@@ -6,10 +6,10 @@ from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from starlette.datastructures import State
from vllm.engine.protocol import EngineClient
from vllm.entrypoints.openai.api_server import init_app_state
from vllm.entrypoints.openai.cli_args import make_arg_parser, validate_parsed_serve_args
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
from vllm.entrypoints.launchers.api_server.app_state import init_app_state
from vllm.entrypoints.launchers.cli_args import make_arg_parser, validate_parsed_serve_args
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
from vllm.entrypoints.serve.lora.protocol import LoadLoRAAdapterRequest
from vllm.logger import init_logger
from vllm.utils.argparse_utils import FlexibleArgumentParser
@@ -26,7 +26,7 @@ from prime_rl.inference.patches import (
)
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
# Still needed in vLLM 0.28 — upstream rejects prompt_len > max_model_len - max_tokens
# Still needed in vLLM 0.29 — upstream rejects prompt_len > max_model_len - max_tokens
monkey_patch_tokenize_params_validation()
# NOTE: Register Nano V3 reasoning parser so configs can use
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
@@ -42,7 +42,7 @@ monkey_patch_strip_routed_experts_from_chat()
# weights concurrently (multi-node disaggregated deployments).
monkey_patch_dp_coordinator_startup_timeout()
logger = init_logger("vllm.entrypoints.openai.api_server")
logger = init_logger("vllm.entrypoints.launchers.api_server.entry")
# Create our own router for custom endpoints
router = APIRouter()
@@ -138,11 +138,10 @@ async def init_broadcaster(request: Request):
timeout = data.get("timeout")
rank_offset = data.get("rank_offset")
inference_world_size = data.get("inference_world_size")
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
session_id = data.get("session_id", "default")
await engine_client(request).collective_rpc(
"init_broadcaster",
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer, session_id),
args=(host, port, rank_offset, inference_world_size, timeout, session_id),
)
return {"status": "ok"}
@@ -177,9 +176,9 @@ async def custom_init_app_state(
state.serving_tokens = prime_serving
import vllm.entrypoints.openai.api_server
import vllm.entrypoints.launchers.api_server.entry
import vllm.v1.utils
from vllm.entrypoints.openai.api_server import build_app as _original_build_app
from vllm.entrypoints.launchers.app import build_app as _original_build_app
from vllm.v1.utils import run_api_server_worker_proc as _original_run_api_server_worker_proc
@@ -202,8 +201,8 @@ def custom_run_api_server_worker_proc(listen_address, sock, args, client_config=
_original_run_api_server_worker_proc(listen_address, sock, args, client_config, **uvicorn_kwargs)
vllm.entrypoints.openai.api_server.init_app_state = custom_init_app_state
vllm.entrypoints.openai.api_server.build_app = custom_build_app
vllm.entrypoints.launchers.api_server.entry.init_app_state = custom_init_app_state
vllm.entrypoints.launchers.api_server.entry.build_app = custom_build_app
vllm.v1.utils.run_api_server_worker_proc = custom_run_api_server_worker_proc
@@ -214,7 +213,7 @@ def server(config: InferenceConfig):
import os
from vllm.entrypoints.cli.serve import run_headless, run_multi_api_server
from vllm.entrypoints.openai.api_server import run_server
from vllm.entrypoints.launchers.api_server.entry import run_server
# Signal worker processes to disable LoRA on MoE layers when LoRA targets don't include experts
lora_target_modules = config.vllm.lora_target_modules
+8 -37
View File
@@ -4,19 +4,11 @@ vLLM ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
priority, ``data_parallel_rank`` header routing, server-side ``max_tokens``
defaulting and ``usage`` reporting. We subclass it for the bits still missing
from the upstream handler:
1. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as ``{data, shape, start, dtype}`` base64 raw-byte
objects (the form the PD router can merge and the renderers parse) instead
of upstream's single ``.npy`` base64 string.
2. ``kv_transfer_params`` bridging — upstream ``ServingTokens.serve_tokens``
parses ``request.kv_transfer_params`` but never threads it into the engine,
so PD disagg never fires on ``/inference/v1/generate``. Fixed upstream by
https://github.com/vllm-project/vllm/pull/42644, which missed the 0.28.0
cut — drop the bridge once we pin a release that includes it.
defaulting and ``usage`` reporting. We subclass it for the one bit still
missing from the upstream handler: compact ``routed_experts`` export — when the
engine emits routing decisions, surface them as ``{data, shape, start, dtype}``
base64 raw-byte objects (the form the PD router can merge and the renderers
parse) instead of upstream's single ``.npy`` base64 string.
Everything else (request/response schema, sampling params, error handling)
delegates to upstream so we track future vLLM changes for free.
@@ -27,17 +19,14 @@ from __future__ import annotations
from collections.abc import AsyncGenerator
from typing import Any
from fastapi import Request
from vllm.entrypoints.openai.engine.protocol import (
ErrorResponse,
RequestResponseMetadata,
)
from vllm.entrypoints.generate.base.protocol import RequestResponseMetadata
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateRequest,
GenerateResponse,
GenerateResponseChoice,
)
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
from vllm.outputs import RequestOutput
from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
@@ -67,25 +56,7 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
class PrimeRlServingTokens(ServingTokens):
"""ServingTokens + compact routed experts + PD kv_transfer_params bridging."""
async def serve_tokens(
self,
request: GenerateRequest,
raw_request: Request | None = None,
) -> GenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
# Upstream parses ``request.kv_transfer_params`` but never threads it
# into the engine, so decode receives an empty NIXL handshake and
# re-prefills the prompt locally (~100x slower under concurrency).
# Bridge it through ``sampling_params.extra_args`` so the engine's KV
# connector picks the params up. Fixed upstream by vllm#42644 (merged
# after 0.28.0) — drop once we pin a release that includes it.
if request.kv_transfer_params is not None:
extra = request.sampling_params.extra_args or {}
extra["kv_transfer_params"] = request.kv_transfer_params
request.sampling_params.extra_args = extra
return await super().serve_tokens(request, raw_request)
"""ServingTokens + compact routed experts."""
async def serve_tokens_full_generator( # type: ignore[override]
self,
@@ -2,7 +2,6 @@ import logging
import os
from prime_rl.inference.patches import (
monkey_patch_fp32_lm_head,
monkey_patch_minimax_m2_for_lora,
monkey_patch_no_moe_lora,
)
@@ -17,6 +16,3 @@ if os.environ.get("PRIME_NO_MOE_LORA") == "1":
monkey_patch_no_moe_lora()
else:
logger.info("PRIME_NO_MOE_LORA=0: no patch applied")
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
monkey_patch_fp32_lm_head()
+1 -12
View File
@@ -7,11 +7,7 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
from vllm.distributed.utils import StatelessProcessGroup
from vllm.logger import init_logger
from prime_rl.inference.vllm.worker.weight_transfer import (
load_weights_checkpoint_layerwise,
load_weights_kernel,
update_mla_absorbed_weights,
)
from prime_rl.inference.vllm.worker.weight_transfer import load_weights_checkpoint_layerwise
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
# This is to get type hints for the Worker class but not actually extend it at runtime as this is required by vLLM worker extension
@@ -99,7 +95,6 @@ class NCCLWeightUpdateWorker(Worker):
rank_offset: int,
inference_world_size: int,
timeout: int,
quantize_in_weight_transfer: bool = False,
session_id: str = "default",
) -> None:
"""Initialize the NCCL broadcast receiver.
@@ -109,7 +104,6 @@ class NCCLWeightUpdateWorker(Worker):
inference_world_size: Total number of inference GPUs across all servers.
"""
del session_id
self.quantize_in_weight_transfer = quantize_in_weight_transfer
# Use the worker's device index directly as the local rank.
# The previous dp_group-based computation broke in vLLM v1 multiprocess
# DP mode where each worker is a separate process with a singleton
@@ -145,11 +139,6 @@ class NCCLWeightUpdateWorker(Worker):
assert isinstance(model, Module)
state_iter = self.nccl_broadcast_receiver.receive_state_dict()
if self.quantize_in_weight_transfer:
load_weights_kernel(model, state_iter)
update_mla_absorbed_weights(model)
return
load_weights_checkpoint_layerwise(
model,
state_iter,
+1 -2
View File
@@ -98,10 +98,9 @@ class NIXLWeightUpdateWorker(Worker):
rank_offset: int,
inference_world_size: int,
timeout: int,
quantize_in_weight_transfer: bool = False,
session_id: str = "default",
) -> None:
del inference_world_size, quantize_in_weight_transfer
del inference_world_size
global_rank = rank_offset + self.device.index
server_url = f"{host}:{port}"
set_ucx_env_defaults(self.device.index)
@@ -1,11 +1,10 @@
from typing import Generator, Iterable
from typing import Iterable
import torch
from torch.nn import Module
from vllm.config import set_current_vllm_config
from vllm.logger import init_logger
from vllm.model_executor.model_loader.reload import finalize_layerwise_reload, initialize_layerwise_reload
from vllm.model_executor.model_loader.weight_utils import remap_moe_expert_weights
logger = init_logger("vllm.inference.vllm.worker_weight_transfer")
@@ -24,116 +23,6 @@ def load_weights_checkpoint_layerwise(
finalize_layerwise_reload(model, model_config)
def _invert_logical_to_physical_map(logical_to_physical_map: torch.Tensor, num_physical_experts: int) -> torch.Tensor:
"""Build a physical expert -> logical expert map from vLLM EPLB state."""
physical_to_logical = torch.full(
(num_physical_experts,),
-1,
dtype=torch.long,
device=logical_to_physical_map.device,
)
logical_indices = torch.arange(
logical_to_physical_map.shape[0],
dtype=torch.long,
device=logical_to_physical_map.device,
)[:, None].expand_as(logical_to_physical_map)
physical_indices = logical_to_physical_map.to(torch.long)
invalid = (physical_indices < -1) | (physical_indices >= num_physical_experts)
if invalid.any():
invalid_indices = physical_indices[invalid].unique().tolist()
raise ValueError(f"EPLB maps to invalid physical experts: {invalid_indices}")
valid = physical_indices >= 0
physical_to_logical[physical_indices[valid]] = logical_indices[valid]
return physical_to_logical
def _build_expert_source_indices(routed_experts, router) -> torch.Tensor | None:
if routed_experts._expert_map is None:
return None
physical_indices = torch.where(routed_experts._expert_map >= 0)[0]
local_indices = routed_experts._expert_map[physical_indices]
physical_indices = physical_indices[local_indices.argsort()]
eplb_layer_state = getattr(router, "eplb_state", None)
logical_to_physical_map = getattr(eplb_layer_state, "logical_to_physical_map", None)
if logical_to_physical_map is None:
return physical_indices
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, routed_experts.global_num_experts)
logical_indices = physical_to_logical[physical_indices.to(physical_to_logical.device)]
if (logical_indices < 0).any():
missing = physical_indices[(logical_indices < 0).to(physical_indices.device)].tolist()
raise ValueError(f"EPLB has no logical mapping for local physical experts: {missing}")
return logical_indices.to(physical_indices.device)
def build_expert_map(model: Module) -> dict[str, torch.Tensor]:
"""Map MoE module names to source expert indices local to this worker.
vLLM 0.24 turned ``FusedMoE`` into a factory returning a ``MoERunner`` and
split the state that used to live on the ``FusedMoE`` module: the expert map
(``_expert_map`` / ``global_num_experts``) now lives on
``MoERunner.routed_experts`` (a ``RoutedExperts``), and the EPLB state on
``MoERunner.router``. Keying by the ``MoERunner`` name prefix-matches the
nested ``routed_experts.*`` weight params after ``load_weights_kernel``
remaps incoming flat names via ``remap_moe_expert_weights``.
"""
from vllm.model_executor.layers.fused_moe import MoERunner
source_indices_by_module: dict[str, torch.Tensor] = {}
for module_name, module in model.named_modules():
if not isinstance(module, MoERunner):
continue
source_indices = _build_expert_source_indices(module.routed_experts, module.router)
if source_indices is None:
continue
source_indices_by_module[module_name] = source_indices
return source_indices_by_module
@torch.no_grad()
def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Tensor], None, None]) -> None:
"""Load vLLM kernel-format tensors using in-place copy_ updates."""
params = dict(model.named_parameters())
expert_source_indices = build_expert_map(model)
loaded = 0
skipped: list[str] = []
shape_mismatches: list[str] = []
# The trainer emits pre-0.24 flat kernel names (``...experts.w13_weight``); since
# vLLM 0.24 the expert params are nested (``...experts.routed_experts.w13_weight``).
# ``remap_moe_expert_weights`` is upstream's compat shim for exactly this transition.
for name, tensor in remap_moe_expert_weights(state_iter, params):
if name not in params:
skipped.append(name)
continue
param = params[name]
if param.shape != tensor.shape:
for module_name, source_indices in expert_source_indices.items():
if not name.startswith(f"{module_name}."):
continue
tensor = tensor[source_indices.to(tensor.device)]
break
if param.shape != tensor.shape:
shape_mismatches.append(f"{name}: param={list(param.shape)} != received={list(tensor.shape)}")
continue
param.copy_(tensor)
loaded += 1
if shape_mismatches:
raise ValueError(f"Kernel weight transfer had {len(shape_mismatches)} shape mismatches: {shape_mismatches}")
if skipped:
raise ValueError(f"Kernel weight transfer skipped {len(skipped)} weights not found in model: {skipped}")
logger.debug(f"Kernel weight transfer copied {loaded} weights in-place")
@torch.no_grad()
def update_mla_absorbed_weights(model: Module) -> None:
"""Recompute MLA absorbed KV weights after in-place kv_b_proj updates."""
+3 -11
View File
@@ -50,7 +50,9 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
``line`` numbers the episode within the stream from 1, so the last of n reads as
n — it is what a reader sees and what addresses the episode."""
rewards, advantages = [], []
input_tokens = output_tokens = turns = branches = 0
input_tokens = rec.get("num_input_tokens")
output_tokens = rec.get("num_output_tokens")
turns = branches = 0
stop_condition = None
truncated = False
reward_parts: dict[str, list[float]] = {}
@@ -86,20 +88,10 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
if advantage is not None:
advantages.append(advantage)
for node in nodes:
n_tokens = len(node.get("token_ids") or [])
if node.get("sampled"):
output_tokens += n_tokens
else:
input_tokens += n_tokens
if (node.get("message") or {}).get("role") == "assistant":
turns += 1
stop_condition = trace.get("stop_condition", stop_condition)
truncated = truncated or trace_truncated(trace)
if input_tokens == 0 and output_tokens == 0: # some eval traces carry no token arrays
for call in trace.get("calls") or []:
usage = call.get("usage") or {}
input_tokens += usage.get("prompt_tokens") or 0
output_tokens += usage.get("completion_tokens") or 0
first_info = ((rec.get("traces") or [{}])[0].get("info")) or {}
return {
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
+12 -12
View File
@@ -176,31 +176,31 @@ def message_text(message: dict[str, Any]) -> str:
return ""
def trace_row(trace: dict[str, Any]) -> dict[str, Any]:
def trace_row(record: dict[str, Any]) -> dict[str, Any]:
"""The live table's view of one trace: phase, turns, tokens, cost, last message."""
calls = trace.get("calls") or []
calls = record.get("calls") or []
usage = [call.get("usage") or {} for call in calls]
# The newest node is usually a tool result; the assistant's latest words say more.
last = ""
for node in reversed(trace.get("nodes") or []):
for node in reversed(record.get("nodes") or []):
message = node.get("message") or {}
if message.get("role") == "assistant" and (last := " ".join(message_text(message).split())):
break
costs = [u["cost"] for u in usage if u.get("cost") is not None]
nodes = trace.get("nodes") or []
nodes = record.get("nodes") or []
parents = {node.get("parent") for node in nodes if node.get("parent") is not None}
return {
"trace": trace.get("id"),
"agent": (trace.get("agent") or {}).get("name", "agent"),
"stage": stage(trace),
"trace": record.get("id"),
"agent": (record.get("agent") or {}).get("name", "agent"),
"stage": stage(record),
"turns": len(calls),
"branches": sum(1 for index in range(len(nodes)) if index not in parents),
"input_tokens": sum(u.get("prompt_tokens") or 0 for u in usage),
"output_tokens": sum(u.get("completion_tokens") or 0 for u in usage),
"input_tokens": record.get("num_input_tokens"),
"output_tokens": record.get("num_output_tokens"),
"cost": sum(costs) if costs else None,
"stop_condition": trace.get("stop_condition"),
"errors": len(trace.get("errors") or []),
"pending": len(trace.get("pending") or []),
"stop_condition": record.get("stop_condition"),
"errors": len(record.get("errors") or []),
"pending": len(record.get("pending") or []),
"last": last[:SNIPPET_CHARS],
}
+23 -2
View File
@@ -7,7 +7,7 @@ from typing import TYPE_CHECKING, Any
import orjson
import prime_runs as pr
from prime_cli.core.config import Config as PrimeConfig
from prime_sandboxes import Config as PrimeConfig
from prime_rl.configs.monitors import PrimeEvalMonitorConfig, PrimeTrainMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
@@ -19,6 +19,7 @@ if TYPE_CHECKING:
import verifiers.v1 as vf
BASE_URL_VAR = "PRIME_API_BASE"
EVAL_ID_VAR = "PRIME_RUNS_EVAL_ID"
# How long finish() and the SDK's atexit crash hook let queued uploads drain. The SDK
# default (300 s) is sized for eval sample batches; a crashed training process should
# not linger that long, and a clean finish rarely has more than the last step queued.
@@ -160,6 +161,12 @@ class PrimeEvalMonitor(Monitor):
# episodes do not retry the platform on every arrival
self.runs: dict[tuple[str, int], pr.Run | None] = {}
self._lock = asyncio.Lock()
self.evaluation_id = os.getenv(EVAL_ID_VAR)
if self.evaluation_id and len(self.sources) != 1:
raise ValueError(
f"${EVAL_ID_VAR} names one platform evaluation, so the run needs "
f"exactly one eval source (got {len(self.sources)})"
)
if self.mode == "online":
self.logger.info("Streaming eval epochs to the Prime platform")
if output_dir is not None:
@@ -172,6 +179,19 @@ class PrimeEvalMonitor(Monitor):
def open(self, env_name: str, step: int, expected: int | None) -> pr.Run:
"""Open the platform evaluation of one epoch. Blocking: runs in a worker thread."""
if self.evaluation_id:
# A hosted launch pre-created the platform evaluation and injected its id -
# attach instead of registering a duplicate. The backend owns its failure
# marking then; a clean finish still completes it.
if self.runs:
raise RuntimeError(f"${EVAL_ID_VAR} holds one epoch, and it already took one")
return pr.init(
kind="eval",
mode=self.mode,
base_url=_base_url(),
id=self.evaluation_id,
finish_timeout=FINISH_TIMEOUT,
)
source = self.sources[env_name]
name = self.config.name if len(self.sources) == 1 else f"{self.config.name}--{env_name}"
return pr.init(
@@ -206,7 +226,8 @@ class PrimeEvalMonitor(Monitor):
return None
self.runs[key] = run
if run.url:
self.logger.info(f"Streaming {env_name} (Step {step}) evaluation - {run.url}")
attached = f" (attached via ${EVAL_ID_VAR})" if run.attached else ""
self.logger.info(f"Streaming {env_name} (Step {step}) evaluation - {run.url}{attached}")
if self.output_dir is not None:
record = read_platform_record(self.output_dir) or {
"kind": "eval",
+3 -6
View File
@@ -24,7 +24,7 @@ def resolve_api_key(api_key_var: str) -> str:
CLI config (``prime login``), like the verifiers client does. ``"EMPTY"`` when unset."""
api_key = os.environ.get(api_key_var)
if not api_key and api_key_var == "PRIME_API_KEY":
from prime_cli.core.config import Config as PrimeConfig
from prime_sandboxes import Config as PrimeConfig
api_key = PrimeConfig().api_key
return api_key or "EMPTY"
@@ -39,7 +39,7 @@ def resolve_headers(client_config: ClientConfig) -> dict[str, str]:
}
headers = {**client_config.headers, **env_headers}
if client_config.base_url.startswith(PRIME_INFERENCE_URL) and "X-Prime-Team-ID" not in headers:
from prime_cli.core.config import Config as PrimeConfig
from prime_sandboxes import Config as PrimeConfig
if team_id := os.environ.get("PRIME_TEAM_ID") or PrimeConfig().team_id:
headers["X-Prime-Team-ID"] = team_id
@@ -169,7 +169,6 @@ class AdminPlane:
port: int,
timeout: int,
inference_world_size: int,
quantize_in_weight_transfer: bool = False,
) -> None:
gpus_per_server = inference_world_size // len(self.clients)
get_logger().info(
@@ -187,7 +186,6 @@ class AdminPlane:
"rank_offset": rank_offset,
"inference_world_size": inference_world_size,
"timeout": timeout,
"quantize_in_weight_transfer": quantize_in_weight_transfer,
},
)
response.raise_for_status()
@@ -335,7 +333,7 @@ async def check_health(
admin_clients: list[AsyncClient],
interval: int = 1,
log_interval: int = 30,
timeout: int = 1800,
timeout: int = 3600,
quiet: bool = False,
) -> None:
"""Wait until every client's /health responds. With ``quiet``, the periodic
@@ -513,7 +511,6 @@ async def init_nixl_broadcast(
"rank_offset": rank_offset,
"inference_world_size": inference_world_size,
"timeout": timeout,
"quantize_in_weight_transfer": False,
"session_id": session_id,
},
)
+10
View File
@@ -20,6 +20,7 @@ keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
from __future__ import annotations
import asyncio
import random
import time
from collections.abc import Callable, Iterator, Sequence
from itertools import islice
@@ -40,6 +41,11 @@ from prime_rl.utils.pathing import env_address_file
# before serving.
ENV_SERVER_STARTUP_TIMEOUT = 600.0
# Fixed seed for shuffle=True sources: the finite taskset is shuffled once at
# startup and the shuffled order is fixed for the whole run (train curricula and
# eval selection both consume it).
TASKSET_SHUFFLE_SEED = 42
async def wait_for_address(path: Path, timeout: float) -> str:
"""The address a launcher-managed env server published, polling for the file the
@@ -98,11 +104,15 @@ class Env:
await self.env_client.wait_for_server_startup(timeout=ENV_SERVER_STARTUP_TIMEOUT)
taskset = vf.load_taskset(self.config.env.taskset)
if type(taskset).INFINITE:
if self.config.shuffle:
raise ValueError(f"Env {self.name} has an infinite taskset — cannot shuffle it")
self.tasks = iter(taskset)
self.num_tasks = None
else:
# Materialize off the event loop — iterating may pull a dataset.
materialized = await asyncio.to_thread(lambda: list(taskset))
if self.config.shuffle:
random.Random(TASKSET_SHUFFLE_SEED).shuffle(materialized)
self.tasks = iter(materialized)
self.num_tasks = len(materialized)
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
+1 -15
View File
@@ -89,9 +89,6 @@ monkey_patch_chat_completion_logprobs()
# shutdown wedges (env-server ZMQ recv, vLLM admin aclose, etc)
SHUTDOWN_TIMEOUT_S = 300
# Abort after this many consecutive train batches contain no samples.
MAX_CONSECUTIVE_EMPTY_BATCHES = 10
# Maximum batches the orchestrator may run ahead of the trainer. The
# dispatcher is paused via ``update_dispatch_gate`` once this is exceeded;
# resumed when the watcher advances ``policy.version``.
@@ -111,7 +108,6 @@ class Orchestrator:
stopped: asyncio.Event
draining: bool
last_batch_at: float | None
consecutive_empty_batches: int
eval_triggered_at: dict[tuple[str, int], float]
ckpt_manager: CheckpointManager
component_tasks: list[asyncio.Task]
@@ -161,7 +157,6 @@ class Orchestrator:
self.last_batch_at = None
# Trigger timestamps so eval success logs can report epoch duration
self.eval_triggered_at = {}
self.consecutive_empty_batches = 0
self.gate_closed_at = None
# Pulsed after inference applies a policy so held work can re-check it.
self.version_advanced = asyncio.Event()
@@ -597,19 +592,10 @@ class Orchestrator:
return
if not batch.samples:
self.consecutive_empty_batches += 1
get_logger().warning(
f"Step {step}: empty train batch after {len(batch.episodes)} finalized episodes "
f"(consecutive empty batches: "
f"{self.consecutive_empty_batches}/{MAX_CONSECUTIVE_EMPTY_BATCHES})"
f"Step {step}: skipping empty train batch after {len(batch.episodes)} finalized episodes"
)
if self.consecutive_empty_batches >= MAX_CONSECUTIVE_EMPTY_BATCHES:
raise RuntimeError(
f"{self.consecutive_empty_batches} consecutive empty train batches — "
"check algorithm credit and task difficulty."
)
return
self.consecutive_empty_batches = 0
effective = batch.cohort.effective
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
if effective.num_traces and n_trainable / effective.num_traces <= 0.1:
+9 -14
View File
@@ -25,8 +25,6 @@ from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, min_
from prime_rl.transports.batch import TrainingSample
from prime_rl.utils.logger import get_logger
MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS = 10
def payload_tokens(samples: list[TrainingSample], trace: vf.Trace | None = None) -> int:
"""Token cost of one trainer-bound trace."""
@@ -315,9 +313,9 @@ class TrainSink:
self._drop_stale(samples_by_trace)
# A group's traces share one dispatch version, so the insertion sweep
# voids all or none of them. A fully-voided group shipped nothing —
# advance the zero-output budget instead of resetting it, or a stalled
# advance the zero-output tally instead of resetting it, or a stalled
# trainer plus a tight bound could void groups forever without ever
# tripping the abort.
# surfacing the warning.
if not any(trace_id in self.pending_batch for trace_id in samples_by_trace):
self._record_zero_output(group, [], n_owed)
return
@@ -333,7 +331,7 @@ class TrainSink:
def _record_zero_output(self, group: list[vf.Episode], survivors: list[vf.Trace], n_owed: int) -> None:
"""``n_owed`` counts the group's full episode budget (arrived +
cancelled), so dropped groups advance the zero-output budget at the
cancelled), so dropped groups advance the zero-output tally at the
same rate as fully-delivered ones."""
if self.batch_size is not None:
returned_traces = sum(len(episode.traces) for episode in group)
@@ -342,9 +340,12 @@ class TrainSink:
survivor_tokens = sum(trace.num_total_tokens for trace in survivors)
episode_tokens = sum(episode.num_total_tokens for episode in group)
self.zero_output_units += survivor_tokens or episode_tokens or self.config.seq_len * n_owed
self._check_zero_output_budget()
self._warn_zero_output()
def _check_zero_output_budget(self) -> None:
def _warn_zero_output(self) -> None:
"""Warn once per batch-equivalent of finalized units that shipped no
payload, so a run that produces no training signal stays visible in the
logs without aborting."""
target = self.batch_size if self.batch_size is not None else self.token_batch_size
assert target is not None
windows = self.zero_output_units // target
@@ -353,14 +354,8 @@ class TrainSink:
self.reported_zero_output_windows = windows
get_logger().warning(
f"No admitted train payload after {self.zero_output_units} finalized units "
f"(consecutive zero-output batch equivalents: "
f"{windows}/{MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS})"
f"({windows} zero-output batch equivalents)"
)
if windows >= MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS:
raise RuntimeError(
f"{windows} consecutive zero-output batch equivalents — "
"check the curriculum admission policy, task difficulty, and staleness drops."
)
def process_batch(self) -> TrainBatch:
items = list(self.pending_batch.items())
@@ -73,6 +73,7 @@ LLMD_EOF
echo "Starting $tag on $LOCAL_IP:$port" | tee "$log"
local -a cmd=(vllm-router --policy "$policy" --host 0.0.0.0 --port "$port"
--request-id-headers x-session-id
--request-timeout-secs {{ router.request_timeout_secs }}
--prometheus-port "$((port + 21000))"
--worker-startup-timeout-secs 4200 --log-level debug)
if [ "$mode" = pd ]; then
@@ -60,11 +60,11 @@ export EVAL_DONE=$LAUNCHER_DIR/.sft_eval_done_$SLURM_JOB_ID
mkdir -p "$LAUNCHER_DIR"
rm -f "$TRAINER_DONE"{% if online_eval %} "$EVAL_DONE"{% endif %}
{% if prl_run_id %}
# Trainer and online-eval log to one shared W&B run. The trainer creates the run,
# and the online-eval process finalizes it after the final epoch.
export PRL_RUN_ID={{ prl_run_id }}
export PRL_RUN_NAME={{ run_name }}
{% if wandb_shared %}
# Trainer and online-eval log to one shared W&B run. The trainer creates the run,
# and the online-eval process finalizes it after the final epoch.
export WANDB_RUN_ID=$PRL_RUN_ID
export WANDB_SHARED_MODE=1
export WANDB_SHARED_PRIMARY=trainer
@@ -32,6 +32,7 @@ MANDATORY_SAVE_NAMESPACES = frozenset({"deepep"})
MANDATORY_SAVE_OPERATIONS = frozenset(
{
"aten::topk",
"prime_rl::fp8_indexer",
"prime_rl::record_moe_routing_statistics",
}
)
+2
View File
@@ -520,6 +520,8 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
reshard_after_forward=config.reshard_after_forward,
shard_placement_fn=shard_placement_fn,
)
# Keep the router reduction from waiting for the expert reduction's input buffer.
block_mlp.router.set_reduce_scatter_max_input_buffers(2)
fully_shard(
transformer_block,
-17
View File
@@ -143,23 +143,6 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
"""
return state_dict
@classmethod
def convert_layer_to_vllm_kernel(
cls,
state_dict: dict[str, Tensor],
layer_idx: int,
quantize_fp8: bool = False,
) -> dict[str, Tensor]:
"""
Convert a single layer's state dict from PrimeRL format to vLLM kernel format.
Args:
state_dict: Layer weights in PrimeRL format.
layer_idx: Layer index to convert.
quantize_fp8: Whether to emit FP8 (e4m3) kernel weights with per-block scales.
"""
raise NotImplementedError(f"convert_layer_to_vllm_kernel is not implemented for {cls.__name__}")
def init_buffers_post_meta(self) -> None:
"""
Initialize buffers that are not in the state dict after loading with meta device.
@@ -128,6 +128,7 @@ from dataclasses import dataclass
import torch
import torch.distributed as dist
import torch.distributed._functional_collectives as funcol
from torch import Tensor, nn
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
@@ -540,8 +541,8 @@ class DeepseekV4Indexer(nn.Module):
n_entries = compressed_kv.shape[1]
cos, sin = packed.position_embeddings[self.compressor.rope_layer_type]
q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim).transpose(1, 2)
q = apply_rotary_pos_emb_interleaved(q, cos, sin).transpose(1, 2)
q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim)
q = apply_rotary_pos_emb_interleaved(q, cos, sin, unsqueeze_dim=2)
w = self.weights_proj(hidden_states)
layout = packed.compression_layouts[self.compressor.compress_rate]
@@ -712,17 +713,21 @@ class DeepseekV4Attention(nn.Module):
hidden_shape = (*input_shape, -1, self.head_dim) # (b, t, h, d), the query view
cos, sin = packed.position_embeddings[self.rope_layer_type] # (1, t, qk_rope_head_dim // 2) each
q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) # (b, t, r)
# Normalizing before the transpose keeps the input contiguous for the quack kernel.
q = self.q_b_norm(self.q_b_proj(q_residual).view(*hidden_shape)).transpose(1, 2) # (b, h, t, d)
q = apply_rotary_pos_emb_interleaved(q, cos, sin)
kv = self.kv_norm(self.kv_proj(hidden_states)) # (b, t, d)
kv = kv.view(*kv.shape[:2], 1, self.head_dim) # (b, t, 1, d)
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin, unsqueeze_dim=2)
if self.cp_context.cp_enabled:
kv = gather_for_cp(kv, self.cp_context.cp_group) # (b, T, 1, d)
kv = kv.transpose(1, 2) # (b, 1, T, d)
# Launch on NCCL's communication stream; query/compressor work does not read KV.
kv = torch.ops._c10d_functional.all_gather_into_tensor(
kv.movedim(1, 0).contiguous(),
self.cp_context.cp_world_size,
self.cp_context.cp_group.group_name,
)
q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) # (b, t, r)
# Keep the query in the sparse kernel's (batch, tokens, heads, dim) layout.
q = self.q_b_norm(self.q_b_proj(q_residual).view(*hidden_shape))
q = apply_rotary_pos_emb_interleaved(q, cos, sin, unsqueeze_dim=2)
compressed = (
self.compressor(
@@ -736,6 +741,9 @@ class DeepseekV4Attention(nn.Module):
else None
)
compressed_kv, top_k_indices = compressed if compressed is not None else (None, None)
if self.cp_context.cp_enabled:
kv = funcol.wait_tensor(kv).movedim(0, 1).contiguous() # (b, T, 1, d)
kv = kv.transpose(1, 2) # (b, 1, T, d)
inputs = SparseAttnInputs.build(
kv=kv,
compressed_kv=compressed_kv,
@@ -743,7 +751,7 @@ class DeepseekV4Attention(nn.Module):
window_indices=packed.window_indices,
)
attn_output, _ = dsv4_sparse_attn(
q.transpose(1, 2).contiguous(),
q,
inputs.kv_buf,
inputs.indices,
self.sinks,
-25
View File
@@ -37,28 +37,3 @@ def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Te
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
return quantized, scales.float().contiguous()
def quantize_to_vllm_kernel_format(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
"""Quantize a weight into the FP8 layout used by vLLM kernels.
Hopper kernels consume the regular blockwise scale grid. On SM100, vLLM's
DeepGEMM kernels instead use UE8M0 scales in an architecture-specific packed
layout. Reuse vLLM's own post-processing so tensors sent over the kernel
weight-transfer path have the same representation as the loaded parameters.
"""
quantized, scales = quantize_to_fp8_blockwise(weight, block_size)
if not weight.is_cuda or torch.cuda.get_device_capability(weight.device) != (10, 0):
return quantized, scales
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
deepgemm_post_process_fp8_weight_block,
)
return deepgemm_post_process_fp8_weight_block(
wq=quantized,
ws=scales,
quant_block_shape=(block_size, block_size),
use_e8m0=True,
)
@@ -6,11 +6,7 @@ parameters retain their names in both formats.
from __future__ import annotations
import torch
from torch import Tensor
from prime_rl.trainer.models.conversion_ops import ConvOp
from prime_rl.trainer.models.fp8 import quantize_to_vllm_kernel_format
from prime_rl.trainer.models.glm4_moe.converting_glm4_moe import glm_moe_layer_ops
@@ -19,123 +15,3 @@ def conversion_chain(config) -> list[ConvOp]:
for layer_idx in range(config.num_hidden_layers):
ops.extend(glm_moe_layer_ops(layer_idx))
return ops
def convert_tt_layer_to_vllm_kernel(
state_dict: dict[str, Tensor],
layer_idx: int,
quantize_fp8: bool = False,
) -> dict[str, Tensor]:
"""Convert a single GLM layer from PrimeRL format to vLLM kernel format."""
out: dict[str, Tensor] = {}
prefix = f"model.layers.{layer_idx}"
def add(name: str, tensor: Tensor) -> None:
out[name] = tensor
def add_maybe_fp8(name: str, tensor: Tensor) -> None:
if quantize_fp8 and tensor.ndim == 2:
fp8_weight, scale = quantize_to_vllm_kernel_format(tensor)
out[name] = fp8_weight
scale_name = name.removesuffix(".weight") + ".weight_scale_inv"
out[scale_name] = scale
return
out[name] = tensor
for name in [f"{prefix}.input_layernorm.weight", f"{prefix}.post_attention_layernorm.weight"]:
if name in state_dict:
add(name, state_dict[name])
q_a_key = f"{prefix}.self_attn.q_a_proj.weight"
kv_a_key = f"{prefix}.self_attn.kv_a_proj_with_mqa.weight"
if q_a_key in state_dict and kv_a_key in state_dict:
add_maybe_fp8(
f"{prefix}.self_attn.fused_qkv_a_proj.weight", torch.cat([state_dict[q_a_key], state_dict[kv_a_key]], dim=0)
)
for suffix in ["q_a_layernorm.weight", "kv_a_layernorm.weight"]:
key = f"{prefix}.self_attn.{suffix}"
if key in state_dict:
add(key, state_dict[key])
for suffix in ["q_b_proj.weight", "kv_b_proj.weight", "o_proj.weight"]:
key = f"{prefix}.self_attn.{suffix}"
if key in state_dict:
add_maybe_fp8(key, state_dict[key])
indexer_wq_b_key = f"{prefix}.self_attn.indexer.wq_b.weight"
if indexer_wq_b_key in state_dict:
add_maybe_fp8(indexer_wq_b_key, state_dict[indexer_wq_b_key])
indexer_wk_key = f"{prefix}.self_attn.indexer.wk.weight"
indexer_weights_proj_key = f"{prefix}.self_attn.indexer.weights_proj.weight"
if indexer_wk_key in state_dict and indexer_weights_proj_key in state_dict:
add(
f"{prefix}.self_attn.indexer.wk_weights_proj.weight",
torch.cat([state_dict[indexer_wk_key], state_dict[indexer_weights_proj_key]], dim=0),
)
for suffix in ["indexer.k_norm.weight", "indexer.k_norm.bias"]:
key = f"{prefix}.self_attn.{suffix}"
if key in state_dict:
add(key, state_dict[key])
gate_key = f"{prefix}.mlp.gate_proj.weight"
up_key = f"{prefix}.mlp.up_proj.weight"
down_key = f"{prefix}.mlp.down_proj.weight"
if gate_key in state_dict and up_key in state_dict:
add_maybe_fp8(f"{prefix}.mlp.gate_up_proj.weight", torch.cat([state_dict[gate_key], state_dict[up_key]], dim=0))
if down_key in state_dict:
add_maybe_fp8(f"{prefix}.mlp.down_proj.weight", state_dict[down_key])
router_key = f"{prefix}.mlp.router.gate.weight"
if router_key in state_dict:
add(f"{prefix}.mlp.gate.weight", state_dict[router_key])
selection_bias_key = f"{prefix}.mlp.router.selection_bias"
if selection_bias_key in state_dict:
add(f"{prefix}.mlp.gate.e_score_correction_bias", state_dict[selection_bias_key])
w1_key = f"{prefix}.mlp.experts.gate_proj"
w2_key = f"{prefix}.mlp.experts.down_proj"
w3_key = f"{prefix}.mlp.experts.up_proj"
if w1_key in state_dict and w2_key in state_dict and w3_key in state_dict:
w1 = state_dict[w1_key]
w2 = state_dict[w2_key]
w3 = state_dict[w3_key]
w13 = torch.cat([w1, w3], dim=1)
if quantize_fp8:
w13_fp8: list[Tensor] = []
w13_scales: list[Tensor] = []
w2_fp8: list[Tensor] = []
w2_scales: list[Tensor] = []
for expert_idx in range(w1.shape[0]):
expert_w13_fp8, expert_w13_scales = quantize_to_vllm_kernel_format(w13[expert_idx])
expert_w2_fp8, expert_w2_scales = quantize_to_vllm_kernel_format(w2[expert_idx])
w13_fp8.append(expert_w13_fp8)
w13_scales.append(expert_w13_scales)
w2_fp8.append(expert_w2_fp8)
w2_scales.append(expert_w2_scales)
out[f"{prefix}.mlp.experts.w13_weight"] = torch.stack(w13_fp8)
out[f"{prefix}.mlp.experts.w13_weight_scale_inv"] = torch.stack(w13_scales)
out[f"{prefix}.mlp.experts.w2_weight"] = torch.stack(w2_fp8)
out[f"{prefix}.mlp.experts.w2_weight_scale_inv"] = torch.stack(w2_scales)
else:
out[f"{prefix}.mlp.experts.w13_weight"] = w13
out[f"{prefix}.mlp.experts.w2_weight"] = w2
sw1_key = f"{prefix}.mlp.shared_expert.gate_proj.weight"
sw2_key = f"{prefix}.mlp.shared_expert.down_proj.weight"
sw3_key = f"{prefix}.mlp.shared_expert.up_proj.weight"
if sw1_key in state_dict and sw2_key in state_dict and sw3_key in state_dict:
sw1 = state_dict[sw1_key]
sw2 = state_dict[sw2_key]
sw3 = state_dict[sw3_key]
if sw1.ndim == 3:
sw1 = sw1.squeeze(0)
sw2 = sw2.squeeze(0)
sw3 = sw3.squeeze(0)
add_maybe_fp8(f"{prefix}.mlp.shared_experts.gate_up_proj.weight", torch.cat([sw1, sw3], dim=0))
add_maybe_fp8(f"{prefix}.mlp.shared_experts.down_proj.weight", sw2)
return out
@@ -14,10 +14,7 @@ from transformers.utils.deprecation import deprecate_kwarg
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.glm_moe_dsa.configuration_glm_moe_dsa import GlmMoeDsaConfig, _index_cache_skip_topk
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import (
conversion_chain,
convert_tt_layer_to_vllm_kernel,
)
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import conversion_chain
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import GlmMoeDsaAttention, SparseMlaAttentionArgs
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import FeedForward
@@ -153,12 +150,6 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
def conversion_chain(cls, config):
return conversion_chain(config)
@classmethod
def convert_layer_to_vllm_kernel(
cls, state_dict: dict[str, Tensor], layer_idx: int, quantize_fp8: bool = False
) -> dict[str, Tensor]:
return convert_tt_layer_to_vllm_kernel(state_dict, layer_idx, quantize_fp8=quantize_fp8)
@auto_docstring
class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
@@ -22,9 +22,9 @@ def _per_token_group_quant_fp8(
group_size,
y_num_columns,
y_row_stride,
eps,
fp8_min,
fp8_max,
eps: tl.constexpr,
fp8_min: tl.constexpr,
fp8_max: tl.constexpr,
use_ue8m0: tl.constexpr,
BLOCK: tl.constexpr,
):
@@ -97,7 +97,7 @@ def per_token_group_quant_fp8(
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=8, num_stages=3),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=8, num_stages=3),
],
key=["S_Q", "S_K"],
key=["S_Q", "S_K_BUCKET", "H", "D"],
)
@triton.jit
def _triton_fp8_indexer_kernel(
@@ -116,6 +116,7 @@ def _triton_fp8_indexer_kernel(
stride_ws,
H: tl.constexpr,
D: tl.constexpr,
S_K_BUCKET: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
@@ -168,7 +169,16 @@ def _triton_fp8_indexer_kernel(
tl.store(out_ptrs, acc, mask=out_mask)
def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
@torch.library.custom_op("prime_rl::fp8_indexer", mutates_args=())
def fp8_indexer(
q: torch.Tensor,
k: torch.Tensor,
w: torch.Tensor,
ks: torch.Tensor,
ke: torch.Tensor,
topk: int,
weight_scale: float = 1.0,
) -> torch.Tensor:
"""Triton FP8 indexer: UE8M0 quantization + fused scoring kernel + topk.
Args:
@@ -221,6 +231,9 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
w.stride(0),
H=H,
D=D,
# Packed document tails change S_k between batches. Reuse tuning within
# a size bucket; exact S_k still controls strides and all bounds masks.
S_K_BUCKET=triton.next_power_of_2(S_k),
)
actual_topk = min(topk, S_k)
@@ -236,3 +249,8 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
indices = indices.masked_fill(out_of_range, S_k)
return indices.to(torch.int32)
@fp8_indexer.register_fake
def _fp8_indexer_fake(q, k, w, ks, ke, topk, weight_scale=1.0):
return q.new_empty((q.shape[0], topk), dtype=torch.int32)
@@ -6,7 +6,8 @@ import torch
import triton
import triton.language as tl
FP8_MAX = 448.0
FP8_MAX = tl.constexpr(448.0)
FP8_MIN = tl.constexpr(-448.0)
MIN_SCALE = 1e-4
GROUP_ALIGNMENT = 128
@@ -188,11 +189,11 @@ def _per_token_fp8_kernel(
mask=mask,
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x), axis=1)
scale = tl.maximum(amax / 448.0, 1e-4)
amax = tl.maximum(tl.max(tl.abs(x), axis=1), 1e-10)
scale = tl.math.div_rn(amax, FP8_MAX)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[:, None]
y = tl.clamp(tl.math.div_rn(x, scale[:, None]), FP8_MIN, FP8_MAX)
tl.store(
out_ptr + row_offsets_i64[:, None] * stride_ym + col_offsets_i64[None, :] * stride_yn,
y.to(tl.float8e4nv),
@@ -242,11 +243,11 @@ def _grouped_per_token_fp8_kernel(
mask=valid_rows[:, None] & valid_cols[None, :],
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x), axis=1)
scale = tl.maximum(amax / 448.0, 1e-4)
amax = tl.maximum(tl.max(tl.abs(x), axis=1), 1e-10)
scale = tl.math.div_rn(amax, FP8_MAX)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[:, None]
y = tl.clamp(tl.math.div_rn(x, scale[:, None]), FP8_MIN, FP8_MAX)
tl.store(
out_ptr + dst_rows_i64[:, None] * stride_ym + col_offsets_i64[None, :] * stride_yn,
y.to(tl.float8e4nv),
@@ -295,11 +296,11 @@ def _grouped_per_channel_fp8_kernel(
mask=valid_rows[:, None] & valid_cols[None, :],
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x), axis=0)
scale = tl.maximum(amax / 448.0, 1e-4)
amax = tl.maximum(tl.max(tl.abs(x), axis=0), 1e-10)
scale = tl.math.div_rn(amax, FP8_MAX)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[None, :]
y = tl.clamp(tl.math.div_rn(x, scale[None, :]), FP8_MIN, FP8_MAX)
flat_base = block_start.to(tl.int64) * BLOCK_K * cols
if K_MAJOR:
out_ptrs = out_ptr + flat_base + col_offsets_i64[:, None] * aligned_m + row_offsets_i64[None, :]
@@ -355,7 +356,7 @@ def _grouped_per_block_fp8_kernel(
other=0.0,
).to(tl.float32)
amax = tl.max(tl.abs(x))
scale = tl.maximum(amax / 448.0, 1e-4)
scale = tl.maximum(amax / FP8_MAX, 1e-4)
if USE_UE8M0:
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale
@@ -426,7 +427,7 @@ def per_token_cast_to_fp8_triton(
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_M=8,
BLOCK_M=32,
BLOCK_K=gran_k,
num_warps=4,
)
@@ -453,7 +454,7 @@ def grouped_per_token_cast_to_fp8_triton(
)
if block_to_group.numel() == 0:
return out, sf
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 8, ceil_div(x.size(1), gran_k))
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 32, ceil_div(x.size(1), gran_k))
_grouped_per_token_fp8_kernel[grid](
x,
block_to_group,
@@ -470,7 +471,7 @@ def grouped_per_token_cast_to_fp8_triton(
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_M=8,
BLOCK_M=32,
BLOCK_K=gran_k,
GROUP_BLOCK_M=GROUP_ALIGNMENT,
num_warps=4,
@@ -496,7 +497,8 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
if block_to_group.numel() == 0:
return out, sf.T
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
block_n = 16
grid = (block_to_group.numel(), ceil_div(x.size(1), block_n))
_grouped_per_channel_fp8_kernel[grid](
x,
block_to_group,
@@ -514,8 +516,8 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
USE_UE8M0=use_ue8m0,
K_MAJOR=True,
BLOCK_K=gran_k,
BLOCK_N=128,
num_warps=4,
BLOCK_N=block_n,
num_warps=2,
)
return out, sf.T
@@ -538,7 +540,8 @@ def grouped_per_channel_cast_to_fp8_rowmajor_triton(
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
if block_to_group.numel() == 0:
return out, sf
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
block_n = 64
grid = (block_to_group.numel(), ceil_div(x.size(1), block_n))
_grouped_per_channel_fp8_kernel[grid](
x,
block_to_group,
@@ -556,7 +559,7 @@ def grouped_per_channel_cast_to_fp8_rowmajor_triton(
USE_UE8M0=use_ue8m0,
K_MAJOR=False,
BLOCK_K=gran_k,
BLOCK_N=128,
BLOCK_N=block_n,
num_warps=4,
)
return out, sf
@@ -672,7 +675,7 @@ def per_token_cast_to_fp8_tp_triton(
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
BLOCK_M=8,
BLOCK_M=32,
BLOCK_K=gran_k,
num_warps=4,
)
@@ -105,8 +105,8 @@ class NemotronHMamba2(nn.Module):
bias=config.use_conv_bias,
)
self.dt_bias = nn.Parameter(torch.empty(self.num_heads))
self.A_log = nn.Parameter(torch.log(torch.arange(1, self.num_heads + 1, dtype=torch.float32)))
self.D = nn.Parameter(torch.ones(self.num_heads, dtype=torch.float32))
self.A_log = nn.Parameter(torch.arange(1, self.num_heads + 1, dtype=torch.get_default_dtype()).log())
self.D = nn.Parameter(torch.ones(self.num_heads))
self.norm = GatedRMSNorm(
self.intermediate_size,
group_size=self.intermediate_size // self.num_groups,
@@ -142,7 +142,7 @@ class NemotronHMamba2(nn.Module):
conv_weight = self.conv1d.weight
conv_bias = self.conv1d.bias
state_decay = -torch.exp(self.A_log.float())
skip = self.D
skip = self.D.float()
dt_bias = self.dt_bias
norm_weight = self.norm.weight
+55 -11
View File
@@ -1,13 +1,14 @@
import json
import uuid
from collections import defaultdict
from typing import Any, Literal, TypedDict, cast
from typing import Any, Callable, Literal, TypedDict, cast
import numpy as np
import torch
from datasets import Dataset, interleave_datasets, load_dataset
from jaxtyping import Bool, Int
from renderers.base import MultiModalData, PlaceholderRange, Renderer, build_training_sample
from renderers import AutoRendererConfig, RendererConfig
from renderers.base import MultiModalData, PlaceholderRange, Renderer, build_training_sample, create_renderer
from torch import Tensor
from torch.distributed.checkpoint.stateful import Stateful
from torch.utils.data import IterableDataset, get_worker_info
@@ -204,13 +205,53 @@ def _truncate_mm_data(mm: MultiModalData, cut: int) -> MultiModalData:
return MultiModalData(mm_hashes=new_hashes, mm_placeholders=new_placeholders, mm_items=new_items)
def with_reasoning_effort(config: RendererConfig, reasoning_effort: Any) -> RendererConfig:
"""Copy ``config`` with its ``reasoning_effort`` field set, validated by the config class."""
if isinstance(config, AutoRendererConfig):
raise ValueError(
"A reasoning_effort column requires a typed renderer config (e.g. [renderer] name = 'qwen3.8'), "
"not renderer.name = 'auto'"
)
if "reasoning_effort" not in type(config).model_fields:
raise ValueError(f"Renderer {config.name!r} has no reasoning_effort field, but a row sets {reasoning_effort!r}")
return type(config).model_validate({**config.model_dump(), "reasoning_effort": reasoning_effort})
class RendererResolver:
"""Picks the renderer for a dataset row.
A ``reasoning_effort`` column overrides the configured renderer's field of
the same name per row. Renderer configs are frozen, so renderers are cached
per config and rows that resolve to the same config share one instance.
"""
def __init__(self, tokenizer: PreTrainedTokenizer, config: RendererConfig, processor: Any | None = None):
self.tokenizer = tokenizer
self.config = config
self.processor = processor
self.renderers: dict[RendererConfig, Renderer] = {}
def __call__(self, example: dict) -> Renderer:
config = self.config
reasoning_effort = example.get("reasoning_effort")
if reasoning_effort is not None:
config = with_reasoning_effort(config, reasoning_effort)
renderer = self.renderers.get(config)
if renderer is None:
renderer = create_renderer(self.tokenizer, config)
if self.processor is not None and hasattr(renderer, "_processor"):
renderer._processor = self.processor
self.renderers[config] = renderer
return renderer
class SFTDataset(StatefulIterableDataset):
"""A dataset wrapping a HF SFT dataset with prompt/completion or raw messages format."""
def __init__(
self,
dataset: Dataset,
renderer: Renderer,
renderers: Callable[[dict], Renderer],
shuffle: bool = True,
seed: int = 0,
seq_len: int = 128,
@@ -224,7 +265,7 @@ class SFTDataset(StatefulIterableDataset):
self.logger = get_logger()
self.dataset = dataset
self.num_examples = len(self.dataset)
self.renderer = renderer
self.renderers = renderers
self.shuffle = shuffle
self.seed = seed
self.seq_len = seq_len
@@ -311,8 +352,9 @@ class SFTDataset(StatefulIterableDataset):
# body-only path: the message content is trained, not the role
# scaffolding (e.g. <|im_start|>assistant) the harness emits.
content_sft_roles = {role for role in ("user", "system", "tool") if getattr(self.loss_mask_config, role)}
renderer = self.renderers(example)
sample = build_training_sample(
self.renderer,
renderer,
messages,
role_to_mask=role_to_mask,
tools=tools,
@@ -352,7 +394,7 @@ class SFTDataset(StatefulIterableDataset):
if mm.mm_items:
mm = _truncate_mm_data(mm, cut)
if was_mm_truncated and not set(self.renderer.get_stop_token_ids()) & set(target_ids):
if was_mm_truncated and not set(renderer.get_stop_token_ids()) & set(target_ids):
return None
if sum(loss_mask[: self.seq_len]) == 0:
@@ -365,7 +407,7 @@ class SFTDataset(StatefulIterableDataset):
f"input_ids, loss_mask and target_ids must have the same length, but got {len(input_ids)=}, {len(loss_mask)=}, {len(target_ids)=}"
)
assert sum(loss_mask) > 0, "There are no tokens in this sample that contribute to the loss"
assert set(self.renderer.get_stop_token_ids()) & set(target_ids), (
assert set(renderer.get_stop_token_ids()) & set(target_ids), (
"A renderer stop token must be present in target_ids"
)
@@ -650,7 +692,8 @@ def setup_dataset(
*,
max_epochs: int | None = None,
raw_dataset: Dataset | None = None,
renderer: Renderer | None = None,
renderer_config: RendererConfig | None = None,
processor: Any | None = None,
multimodal: bool = False,
) -> StatefulIterableDataset:
if config.type == "fake":
@@ -663,13 +706,14 @@ def setup_dataset(
non_dp_size=non_dp_size,
)
elif config.type == "sft":
if renderer is None:
raise ValueError("SFT data requires a renderer.")
if renderer_config is None:
raise ValueError("SFT data requires a renderer config.")
if raw_dataset is None:
raw_dataset = load_sft_dataset(config)
renderers = RendererResolver(tokenizer, renderer_config, processor=processor)
return SFTDataset(
raw_dataset,
renderer,
renderers,
shuffle=config.shuffle,
seed=config.seed,
seq_len=config.seq_len,
+11 -14
View File
@@ -6,7 +6,6 @@ import asyncio
from contextlib import nullcontext
from datetime import timedelta
from renderers.base import create_renderer
from torch.nn import CrossEntropyLoss
# Import environment before any other imports
@@ -154,16 +153,6 @@ def train(config: SFTConfig):
if config.model.vlm is not None and processor is None:
raise ValueError(f"[model.vlm] is set but no multimodal processor could be loaded for {config.model.name!r}")
# Fake data never renders messages, so a model without a hand-coded renderer
# can still be used to benchmark step time / memory. Validation data is
# always real, so it needs the renderer even when training data is fake.
renderer = None
if config.data.type != "fake" or config.val is not None:
renderer = create_renderer(tokenizer, config.renderer)
if processor is not None and hasattr(renderer, "_processor"):
renderer._processor = processor
logger.debug(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
optimizer, gradient_manager = setup_optimizer(
@@ -192,12 +181,19 @@ def train(config: SFTConfig):
# Set up the dataset and dataloader
logger.info(f"Initializing data ({config.data})")
multimodal = config.model.vlm is not None
dataset = setup_dataset(tokenizer, config.data, config.model.cp, renderer=renderer, multimodal=multimodal)
dataset = setup_dataset(
tokenizer,
config.data,
config.model.cp,
renderer_config=config.renderer,
processor=processor,
multimodal=multimodal,
)
dataloader = setup_dataloader(dataset, config.data)
val_raw_dataset = None
if config.val is not None:
logger.info(f"Loading validation dataset ({config.val.data.name})")
logger.info(f"Loading validation dataset ({config.val.data})")
val_raw_dataset = load_sft_dataset(config.val.data)
# Optionally, resume training from a checkpoint
@@ -360,7 +356,8 @@ def train(config: SFTConfig):
config.model.cp,
max_epochs=1,
raw_dataset=val_raw_dataset,
renderer=renderer,
renderer_config=config.renderer,
processor=processor,
multimodal=multimodal,
)
val_dataloader = setup_dataloader(val_dataset, config.val.data)
+2 -22
View File
@@ -114,16 +114,6 @@ def preprocess_layer_checkpoint(
return revert_weight_conversion(model, layer_state_dict)
def preprocess_layer_quantized(
model: nn.Module,
layer_state_dict: dict[str, Tensor],
layer_idx: int,
) -> dict[str, Tensor]:
if layer_idx < 0:
return layer_state_dict
return model.convert_layer_to_vllm_kernel(layer_state_dict, layer_idx, quantize_fp8=True)
class NCCLBroadcaster:
def __init__(
self,
@@ -133,12 +123,10 @@ class NCCLBroadcaster:
world_size: int,
device: int | str | torch.device,
timeout: int,
quantize_in_weight_transfer: bool = False,
):
self.logger = get_logger()
self.world = get_world()
self.dtype = torch.bfloat16
self.quantize_in_weight_transfer = quantize_in_weight_transfer
if self.world.is_master:
disable_nccl_p2p_if_unavailable()
@@ -163,16 +151,10 @@ class NCCLBroadcaster:
broadcast_integer(num_state_dict_to_send, self.communicator)
self.logger.debug(f"Broadcasting {num_state_dict_to_send} layer state dicts")
preprocess_fn: Callable[[nn.Module, dict[str, Tensor], int], dict[str, Tensor]]
if self.quantize_in_weight_transfer:
preprocess_fn = preprocess_layer_quantized
else:
preprocess_fn = preprocess_layer_checkpoint
keep_in_fp32 = getattr(model, "keep_in_fp32_for_weight_transfer", None)
for layer_id, layer_state_dict in filter_state_dict_by_layers(state_dict, num_layers, layer_prefix):
layer_state_dict = resolve_dtensors(layer_state_dict, keep_in_fp32, self.dtype)
layer_state_dict = preprocess_fn(model, layer_state_dict, layer_id)
layer_state_dict = preprocess_layer_checkpoint(model, layer_state_dict, layer_id)
if self.world.is_master:
broadcast_state_dict(layer_state_dict, self.communicator)
@@ -194,14 +176,13 @@ class NCCLWeightSender(WeightSender):
config.inference_world_size + 1,
device,
config.timeout,
quantize_in_weight_transfer=config.quantize_in_weight_transfer,
)
@torch.no_grad()
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
# The master enters only after the receiver acknowledged the handshake,
# but all ranks must be held back until then: the broadcast preparation
# (DTensor resolution, quantization) enqueues collectives on non-master
# (DTensor resolution, checkpoint conversion) enqueues collectives on non-master
# ranks, and if those start before the receiver has paused inference,
# the collectives sit unmatched until NCCL's watchdog kills the process.
if self.world.world_size > 1:
@@ -221,7 +202,6 @@ class NCCLWeightReceiver(WeightReceiver):
port=self.config.port,
timeout=self.config.timeout,
inference_world_size=self.config.inference_world_size,
quantize_in_weight_transfer=self.config.quantize_in_weight_transfer,
)
async def receive(self, step: int) -> None:
+1 -1
View File
@@ -213,7 +213,7 @@ def test_dynamo_nccl_lifecycle_initializes_and_updates_weights(tmp_path):
asyncio.run(admin.initialize_nccl(host="trainer", port=29501, timeout=10, inference_world_size=1))
asyncio.run(admin.update_weights(tmp_path / "step_1", transport="nccl", step=1))
assert collective_rpc.await_args_list[0].kwargs["args"] == ["trainer", 29501, 0, 1, 10, False, "default"]
assert collective_rpc.await_args_list[0].kwargs["args"] == ["trainer", 29501, 0, 1, 10, "default"]
assert collective_rpc.await_args_list[1].kwargs["args"] == [(tmp_path / "step_1").as_posix()]
assert [call.args[1] for call in post.await_args_list] == ["/pause", "/resume"]
assert admin._nccl_initialization_state == "ready"
+6 -8
View File
@@ -4,7 +4,8 @@ The full happy-path is owned upstream by vLLM's
``vllm/entrypoints/serve/disagg`` test suite. We only cover the prime-RL
deltas here:
* ``serialize_routed_experts`` round-trips a compact raw-byte payload.
* The subclass attaches its overrides without monkey-patching the parent.
* The subclass overrides ``serve_tokens_full_generator`` without
monkey-patching the parent.
* ``post_process`` swaps in the compact routed_experts while preserving
the rest of the upstream response (``usage`` included).
"""
@@ -13,8 +14,8 @@ from __future__ import annotations
import numpy as np
import pybase64
from vllm.entrypoints.openai.engine.protocol import UsageInfo
from vllm.entrypoints.scale_out.token_in_token_out.protocol import GenerateResponse, GenerateResponseChoice
from vllm.entrypoints.serve.engine.protocol import UsageInfo
from prime_rl.inference.vllm.routed_experts import serialize_routed_experts
from prime_rl.inference.vllm.serving_tokens import (
@@ -35,12 +36,9 @@ async def _empty_request_outputs():
yield
def test_subclass_only_overrides_serve_tokens():
assert PrimeRlServingTokens.serve_tokens is not PrimeRlServingTokens.__mro__[1].serve_tokens
assert (
PrimeRlServingTokens.serve_tokens_full_generator
is not PrimeRlServingTokens.__mro__[1].serve_tokens_full_generator
)
def test_subclass_overrides_serve_tokens_full_generator():
upstream = PrimeRlServingTokens.__mro__[1]
assert PrimeRlServingTokens.serve_tokens_full_generator is not upstream.serve_tokens_full_generator
def test_serialize_routed_experts_uses_compact_raw_payload():
-1
View File
@@ -81,7 +81,6 @@ def test_admin_plane_initializes_nccl():
"rank_offset": 0,
"inference_world_size": 1,
"timeout": 1200,
"quantize_in_weight_transfer": False,
},
)
asyncio.run(admin_plane.aclose())
+1
View File
@@ -140,6 +140,7 @@ def test_to_namespace_resolves_parsers():
assert ns.tool_call_parser == "deepseek_v32"
assert ns.reasoning_parser == "deepseek_r1"
assert ns.enable_auto_tool_choice is True
assert ns.enable_ep_weight_filter is True
def test_to_namespace_none_strips_parser_attrs_from_namespace():
@@ -63,6 +63,10 @@ def test_selective_policy_saves_default_and_custom_targets():
_selective_checkpoint_policy(context, torch.ops.aten.topk.default, targets=custom_targets)
is CheckpointPolicy.MUST_SAVE
)
assert (
_selective_checkpoint_policy(context, torch.ops.prime_rl.fp8_indexer.default, targets=custom_targets)
is CheckpointPolicy.MUST_SAVE
)
@pytest.mark.parametrize("mode", ["full", "selective"])
@@ -99,6 +103,7 @@ def test_mandatory_policy_only_retains_non_replayable_ops():
context = SelectiveCheckpointContext(is_recompute=False)
assert _mandatory_checkpoint_policy(context, torch.ops.aten.topk.default) is CheckpointPolicy.MUST_SAVE
assert _mandatory_checkpoint_policy(context, torch.ops.prime_rl.fp8_indexer.default) is CheckpointPolicy.MUST_SAVE
assert (
_mandatory_checkpoint_policy(context, torch.ops.prime_rl.record_moe_routing_statistics.default)
is CheckpointPolicy.MUST_SAVE
@@ -1246,6 +1246,12 @@ def test_context_parallel_shards_reproduce_the_whole_row(layer_idx, cp_world_siz
for cp_rank, chunk in enumerate(chunks):
gather, pending = _fake_gather_for_cp(projections, chunks, cp_rank)
monkeypatch.setattr(dsv4_attention, "gather_for_cp", gather)
monkeypatch.setattr(
torch.ops._c10d_functional,
"all_gather_into_tensor",
lambda tensor, group_size, group_name: gather(tensor.movedim(0, 1), None).movedim(1, 0).contiguous(),
)
monkeypatch.setattr(dsv4_attention.funcol, "wait_tensor", lambda tensor: tensor)
module.cp_context = CPContext(MagicMock(), cp_rank, cp_world_size, "ring")
packed = _packed_context(doc_lens, torch.float32, V4FLASH_CONFIG, cp_rank=cp_rank, cp_world_size=cp_world_size)
+22
View File
@@ -47,3 +47,25 @@ def test_token_tp_cast_matches_materialized_transpose(rows, cols):
assert tp_q.is_contiguous()
assert torch.equal(tp_q.view(torch.uint8), ref_q.view(torch.uint8))
assert torch.equal(tp_s, ref_s)
@pytest.mark.parametrize(
"rows,cols,input_scale",
[(256, 256, 1.0), (256, 512, 0.3), (512, 256, 0.02), (1024, 768, 0.02), (384, 128, 0.005)],
)
def test_token_cast_matches_vllm_cuda_quant(rows, cols, input_scale):
"""The per-token cast is *bit-identical* to vLLM's production CUDA quantizer."""
pytest.importorskip("vllm")
from vllm.model_executor.layers.quantization.utils.fp8_utils import per_token_group_quant_fp8
torch.manual_seed(rows + cols)
x = torch.randn(rows, cols, device="cuda", dtype=torch.bfloat16) * input_scale
assert x.is_contiguous()
ref_q, ref_s = per_token_group_quant_fp8(x, 128, use_ue8m0=False)
q, s = per_token_cast_to_fp8_triton(x, False)
assert q.shape == ref_q.shape == (rows, cols)
assert s.shape == ref_s.shape == (rows, cols // 128)
assert torch.equal(s, ref_s)
assert torch.equal(q.view(torch.uint8), ref_q.view(torch.uint8))
@@ -1,68 +0,0 @@
import torch
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import convert_tt_layer_to_vllm_kernel
def _build_prime_layer_state(layer_idx: int = 0) -> dict[str, torch.Tensor]:
prefix = f"model.layers.{layer_idx}"
return {
f"{prefix}.self_attn.q_a_proj.weight": torch.randn(4, 6),
f"{prefix}.self_attn.kv_a_proj_with_mqa.weight": torch.randn(3, 6),
f"{prefix}.self_attn.q_b_proj.weight": torch.randn(5, 6),
f"{prefix}.self_attn.kv_b_proj.weight": torch.randn(7, 6),
f"{prefix}.self_attn.o_proj.weight": torch.randn(6, 5),
f"{prefix}.self_attn.indexer.wq_b.weight": torch.randn(4, 6),
f"{prefix}.self_attn.indexer.wk.weight": torch.randn(4, 6),
f"{prefix}.self_attn.indexer.k_norm.weight": torch.randn(6),
f"{prefix}.self_attn.indexer.k_norm.bias": torch.randn(6),
f"{prefix}.self_attn.indexer.weights_proj.weight": torch.randn(2, 6),
f"{prefix}.mlp.gate_proj.weight": torch.randn(8, 6),
f"{prefix}.mlp.up_proj.weight": torch.randn(8, 6),
f"{prefix}.mlp.down_proj.weight": torch.randn(6, 8),
f"{prefix}.mlp.router.gate.weight": torch.randn(4, 6),
f"{prefix}.mlp.router.selection_bias": torch.randn(4),
f"{prefix}.mlp.experts.gate_proj": torch.randn(2, 3, 6),
f"{prefix}.mlp.experts.up_proj": torch.randn(2, 3, 6),
f"{prefix}.mlp.experts.down_proj": torch.randn(2, 6, 3),
f"{prefix}.mlp.shared_expert.gate_proj.weight": torch.randn(3, 6),
f"{prefix}.mlp.shared_expert.up_proj.weight": torch.randn(3, 6),
f"{prefix}.mlp.shared_expert.down_proj.weight": torch.randn(6, 3),
}
def test_convert_tt_layer_to_vllm_kernel_no_fp8():
state = _build_prime_layer_state()
out = convert_tt_layer_to_vllm_kernel(state, layer_idx=0, quantize_fp8=False)
assert "model.layers.0.self_attn.fused_qkv_a_proj.weight" in out
assert out["model.layers.0.self_attn.fused_qkv_a_proj.weight"].shape == (7, 6)
assert "model.layers.0.self_attn.indexer.wk_weights_proj.weight" in out
assert out["model.layers.0.self_attn.indexer.wk_weights_proj.weight"].shape == (6, 6)
assert "model.layers.0.self_attn.indexer.wk.weight" not in out
assert "model.layers.0.self_attn.indexer.weights_proj.weight" not in out
assert "model.layers.0.mlp.gate_up_proj.weight" in out
assert out["model.layers.0.mlp.gate_up_proj.weight"].shape == (16, 6)
assert "model.layers.0.mlp.experts.w13_weight" in out
assert out["model.layers.0.mlp.experts.w13_weight"].shape == (2, 6, 6)
assert "model.layers.0.mlp.experts.w2_weight" in out
assert out["model.layers.0.mlp.experts.w2_weight"].shape == (2, 6, 3)
assert "model.layers.0.mlp.gate.weight" in out
assert "model.layers.0.mlp.gate.e_score_correction_bias" in out
def test_convert_tt_layer_to_vllm_kernel_with_fp8():
state = _build_prime_layer_state()
out = convert_tt_layer_to_vllm_kernel(state, layer_idx=0, quantize_fp8=True)
assert out["model.layers.0.self_attn.fused_qkv_a_proj.weight"].dtype == torch.float8_e4m3fn
assert out["model.layers.0.self_attn.fused_qkv_a_proj.weight_scale_inv"].dtype == torch.float32
assert out["model.layers.0.self_attn.indexer.wk_weights_proj.weight"].dtype == torch.float32
assert "model.layers.0.self_attn.indexer.wk.weight_scale_inv" not in out
assert out["model.layers.0.mlp.experts.w13_weight"].dtype == torch.float8_e4m3fn
assert out["model.layers.0.mlp.experts.w13_weight_scale_inv"].dtype == torch.float32
assert out["model.layers.0.mlp.experts.w2_weight"].dtype == torch.float8_e4m3fn
assert out["model.layers.0.mlp.experts.w2_weight_scale_inv"].dtype == torch.float32
@@ -125,6 +125,17 @@ def test_nemotron_h_context_parallel_setup_finds_wrapped_mamba_layer():
assert mamba_layer.mamba.cp_context.cp_world_size == 2
def test_nemotron_h_mamba_parameters_follow_default_dtype():
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
with torch.device("meta"), default_dtype(torch.bfloat16):
model = NemotronHForCausalLM(config)
mamba = model.model.layers[0].mamba
assert isinstance(mamba, NemotronHMamba2)
assert mamba.A_log.dtype == torch.bfloat16
assert mamba.D.dtype == torch.bfloat16
def test_nemotron_h_no_latent_projection():
"""Verify model works without latent projections (moe_latent_size=None)."""
prime_config = NemotronHConfig(
+1 -1
View File
@@ -181,7 +181,7 @@ def test_dataloader_shards_across_ranks_and_workers(
)
dataset = SFTDataset(
raw_dataset,
dummy_renderer,
lambda _: dummy_renderer,
shuffle=False,
seq_len=config.seq_len,
non_dp_size=non_dp_size,
+18 -18
View File
@@ -51,7 +51,7 @@ def test_drop_null_fields_preserves_tool_call_arguments(arguments):
def test_init_sft_dataset(build_dummy_dataset, dummy_renderer):
"""Tests basic initialization."""
dataset = build_dummy_dataset("a", 1)
sft_dataset = SFTDataset(dataset, dummy_renderer)
sft_dataset = SFTDataset(dataset, lambda _: dummy_renderer)
assert sft_dataset is not None
@@ -59,7 +59,7 @@ def test_raise_error_if_no_prompt_and_completion(build_dummy_dataset):
"""Tests that an error is raised if no supported SFT message fields are provided."""
dataset = Dataset.from_list([{"text": "a0"}])
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
sft_dataset = SFTDataset(dataset, create_renderer(tokenizer))
sft_dataset = SFTDataset(dataset, lambda _: create_renderer(tokenizer))
with pytest.raises(ValueError):
next(iter(sft_dataset))
@@ -70,7 +70,7 @@ def test_sft_first_exhausted(build_dummy_dataset, dummy_renderer, max_epochs: in
b = build_dummy_dataset("b", 2)
ds = [a, b]
dataset = interleave_datasets(ds, stopping_strategy="first_exhausted")
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=max_epochs)
dataset = SFTDataset(dataset, lambda _: dummy_renderer, shuffle=False, max_epochs=max_epochs)
num_samples = 0
sampling_order = []
for x in dataset:
@@ -86,7 +86,7 @@ def test_sft_all_exhausted(build_dummy_dataset, dummy_renderer, max_epochs: int)
b = build_dummy_dataset("b", 2)
ds = [a, b]
dataset = interleave_datasets(ds, stopping_strategy="all_exhausted")
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=max_epochs)
dataset = SFTDataset(dataset, lambda _: dummy_renderer, shuffle=False, max_epochs=max_epochs)
num_samples = 0
sampling_order = []
for x in dataset:
@@ -120,7 +120,7 @@ def test_sft_all_exhausted_with_probs(build_dummy_dataset, dummy_renderer, probs
b = build_dummy_dataset("b", int(10e3))
ds = [a, b]
dataset = interleave_datasets(ds, stopping_strategy="all_exhausted", probabilities=probs)
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=1)
dataset = SFTDataset(dataset, lambda _: dummy_renderer, shuffle=False, max_epochs=1)
num_samples = 0
sampling_freq = []
for x in dataset:
@@ -140,7 +140,7 @@ def test_sft_all_exhausted_with_probs(build_dummy_dataset, dummy_renderer, probs
def test_sft_dataset_state(build_dummy_dataset, dummy_renderer):
"""Tests the state of the dataset within and across epochs."""
dataset = build_dummy_dataset("", 4)
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=2)
dataset = SFTDataset(dataset, lambda _: dummy_renderer, shuffle=False, max_epochs=2)
dataiter = iter(dataset)
# Initial state
@@ -166,7 +166,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset, dummy_renderer):
"""Tests resuming the dataset from checkpoint in between epochs."""
dataset = SFTDataset(
build_dummy_dataset("", 4),
dummy_renderer,
lambda _: dummy_renderer,
shuffle=False,
max_epochs=2,
)
@@ -186,7 +186,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset, dummy_renderer):
del dataset
dataset = SFTDataset(
build_dummy_dataset("", 4),
dummy_renderer,
lambda _: dummy_renderer,
shuffle=False,
max_epochs=2,
)
@@ -204,7 +204,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset, dummy_renderer):
del dataset
dataset = SFTDataset(
build_dummy_dataset("", 4),
dummy_renderer,
lambda _: dummy_renderer,
shuffle=False,
max_epochs=2,
)
@@ -235,7 +235,7 @@ def test_multiturn_loss_mask():
]
)
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B") # Properly handles multi-turn think
dataset = SFTDataset(dataset, create_renderer(tokenizer), max_examples=1)
dataset = SFTDataset(dataset, lambda _: create_renderer(tokenizer), max_examples=1)
sample = next(iter(dataset))
print_sample(sample["input_ids"], sample["loss_mask"], tokenizer)
@@ -298,7 +298,7 @@ def test_multiturn_loss_mask_with_tools():
dataset = Dataset.from_list([tool_example])
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B") # Properly handles multi-turn think
dataset = SFTDataset(dataset, create_renderer(tokenizer), max_examples=1)
dataset = SFTDataset(dataset, lambda _: create_renderer(tokenizer), max_examples=1)
sample = next(iter(dataset))
print_sample(sample["input_ids"], sample["loss_mask"], tokenizer)
@@ -325,12 +325,12 @@ def test_messages_rows_are_equivalent_to_empty_prompt_completion():
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B")
messages_dataset = SFTDataset(
Dataset.from_list([{"messages": messages}]),
create_renderer(tokenizer),
lambda _: create_renderer(tokenizer),
max_examples=1,
)
split_dataset = SFTDataset(
Dataset.from_list([{"prompt": [], "completion": messages}]),
create_renderer(tokenizer),
lambda _: create_renderer(tokenizer),
max_examples=1,
)
@@ -351,12 +351,12 @@ def test_messages_take_precedence_over_prompt_and_completion():
messages_dataset = SFTDataset(
Dataset.from_list([row]),
create_renderer(tokenizer),
lambda _: create_renderer(tokenizer),
max_examples=1,
)
expected_dataset = SFTDataset(
Dataset.from_list([{"prompt": [], "completion": row["messages"]}]),
create_renderer(tokenizer),
lambda _: create_renderer(tokenizer),
max_examples=1,
)
@@ -372,12 +372,12 @@ def test_null_messages_falls_back_to_prompt_and_completion():
mixed_row_dataset = SFTDataset(
Dataset.from_list([{"messages": None, "prompt": prompt, "completion": completion}]),
create_renderer(tokenizer),
lambda _: create_renderer(tokenizer),
max_examples=1,
)
expected_dataset = SFTDataset(
Dataset.from_list([{"prompt": prompt, "completion": completion}]),
create_renderer(tokenizer),
lambda _: create_renderer(tokenizer),
max_examples=1,
)
@@ -399,7 +399,7 @@ def test_vlm_truncation_does_not_append_trainable_eos(monkeypatch, dummy_rendere
)
monkeypatch.setattr(sft_data, "build_training_sample", fake_build_training_sample)
dataset = SFTDataset(Dataset.from_list([]), dummy_renderer, seq_len=2, multimodal=True)
dataset = SFTDataset(Dataset.from_list([]), lambda _: dummy_renderer, seq_len=2, multimodal=True)
assert dataset._process({"messages": [{"role": "assistant", "content": "ignored"}]}) is None
Generated
+140 -218
View File
@@ -17,27 +17,26 @@ exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for
exclude-newer-span = "P7D"
[options.exclude-newer-package]
vllm = false
verifiers = false
harbor = "2026-08-11T00:00:00Z"
prime-traces = false
prime-pydantic-config = false
vllm-router = false
dion = false
prime-runs = false
flash-attn-3 = false
prime-tunnel = false
fastokens = false
deep-gemm = false
prime-evals = false
torchao = false
tokenspeed-mla = false
nixl-cu13 = false
deep-ep = false
prime-sandboxes = false
renderers = false
prime-kernels = false
deep-gemm = false
dion = false
fastokens = false
flash-attn-3 = false
harbor = "2026-08-11T00:00:00Z"
nixl-cu13 = false
prime = false
prime-evals = false
prime-kernels = false
prime-pydantic-config = false
prime-runs = false
prime-sandboxes = false
prime-traces = false
prime-tunnel = false
renderers = false
tokenspeed-mla = false
torchao = false
verifiers = false
vllm-router = false
[manifest]
members = [
@@ -94,6 +93,7 @@ members = [
"multiswe",
"nl2repobench",
"numina",
"officeqa-pro-v2",
"oolong-pairs",
"oolong-real",
"oolong-synth",
@@ -127,6 +127,7 @@ members = [
"terminal-bench-2",
"terminal-lego",
"tmax",
"trace-cheating-recall-500",
"triviaqa",
"unscramble",
"uuid-ctf",
@@ -1404,7 +1405,7 @@ requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
[[package]]
name = "deepseek-prover"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/lean/deepseek_prover" }
dependencies = [
{ name = "verifiers" },
@@ -1612,7 +1613,7 @@ wheels = [
[[package]]
name = "enterprise-ops-gym"
version = "0.2.0"
version = "0.2.1"
source = { editable = "deps/prime-envs/environments/tool_use/enterprise_ops_gym" }
dependencies = [
{ name = "datasets" },
@@ -1900,7 +1901,7 @@ dependencies = [
[[package]]
name = "flashinfer-python"
version = "0.6.16.post3"
version = "0.6.18"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "apache-tvm-ffi" },
@@ -1920,9 +1921,9 @@ dependencies = [
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
{ name = "tqdm" },
]
sdist = { url = "https://files.pythonhosted.org/packages/c2/46/17045cb47b7b93fcb4e5303e398e6b129b86239930ac0875942a83d8b962/flashinfer_python-0.6.16.post3.tar.gz", hash = "sha256:9b146cfcc1454c80f3f99444db48013b3eadaeb32f2a399bd76c9471ecb72f04", size = 11076656, upload-time = "2026-08-08T01:14:16.408Z" }
sdist = { url = "https://files.pythonhosted.org/packages/3e/72/12066c5f42a49e7eabe6ec445ac73c59785480bba1b763bd7e0a512f13c1/flashinfer_python-0.6.18.tar.gz", hash = "sha256:70a2074d78cb17ed39c98e5ed47f626c6e8bb29015cf028c49cbf8f2629405a1", size = 13286160, upload-time = "2026-08-29T02:09:18.376Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/9d/dc/5367cb601fc9190cc75b4c141f5f7e9a224d1c26a1e983151823e02a25b3/flashinfer_python-0.6.16.post3-py3-none-any.whl", hash = "sha256:caf686b9b079abe1c9d65ab505698bd325e8072de40afd822f2c74f2ac3bc601", size = 15836034, upload-time = "2026-08-08T01:14:13.709Z" },
{ url = "https://files.pythonhosted.org/packages/31/7d/3dae45fc293cd5f16cefe4dcf59683d964ca8faf2303ed7fff54f4bca490/flashinfer_python-0.6.18-py3-none-any.whl", hash = "sha256:d5d26edb48f8def0bf28b2c94415aef7f0754e2cd9e3cb3d6e7081262d068aad", size = 18347767, upload-time = "2026-08-29T02:09:15.868Z" },
]
[[package]]
@@ -1949,7 +1950,7 @@ wheels = [
[[package]]
name = "forth-lang"
version = "0.2.0"
version = "0.2.1"
source = { editable = "deps/prime-envs/environments/code/forth_lang" }
dependencies = [
{ name = "verifiers" },
@@ -2069,12 +2070,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/a0/61/5c78b91c3143ed5c14207f463aecfc8f9dbb5092fb2869baf37c273b2705/gitdb-4.0.12-py3-none-any.whl", hash = "sha256:67073e15955400952c6565cc3e707c554a4eea2e428946f7a4c162fab9bd9bcf", size = 62794, upload-time = "2025-01-02T07:20:43.624Z" },
]
[[package]]
name = "gitignore-parser"
version = "0.1.13"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/e5/51/e391a1a4238f18d0abb47be479b07af265ad4519022cf51b7da47ef82487/gitignore_parser-0.1.13.tar.gz", hash = "sha256:c7e10c8190accb8ae57fb3711889e73a9c0dbc04d4222b91ace8a4bf64d2f746", size = 5603, upload-time = "2025-08-25T06:33:22.704Z" }
[[package]]
name = "gitpython"
version = "3.1.50"
@@ -2089,7 +2084,7 @@ wheels = [
[[package]]
name = "goedel-pset"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/lean/goedel_pset" }
dependencies = [
{ name = "verifiers" },
@@ -2546,7 +2541,7 @@ wheels = [
[[package]]
name = "i3-code"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/code/i3_code" }
dependencies = [
{ name = "orjson" },
@@ -2561,7 +2556,7 @@ requires-dist = [
[[package]]
name = "i3-logic"
version = "0.2.0"
version = "0.2.1"
source = { editable = "deps/prime-envs/environments/reasoning/i3_logic" }
dependencies = [
{ name = "markdown" },
@@ -2578,7 +2573,7 @@ requires-dist = [
[[package]]
name = "i3-math"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/math/i3_math" }
dependencies = [
{ name = "verifiers" },
@@ -2589,7 +2584,7 @@ requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
[[package]]
name = "i3-science"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/science/i3_science" }
dependencies = [
{ name = "verifiers" },
@@ -2728,6 +2723,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },
]
[[package]]
name = "instanttensor"
version = "0.2.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
]
sdist = { url = "https://files.pythonhosted.org/packages/27/8e/b209471a5a73a7ef1dad7365e05adf4c95b20fadc16fc9aea10ceaba1fc8/instanttensor-0.2.0.tar.gz", hash = "sha256:acafa964f9ba6d2e342d8ffcb7e68bacc6d59d60e2fda222dc1333045cd50c9c", size = 3112592, upload-time = "2026-09-13T19:10:18.043Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/77/10/23c738a0b3568a4dadd7604ffe1f47612969b74db1e6708b074625b83838/instanttensor-0.2.0-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eefde9b121cd3a2699bd079a19cba5c0a74f23cc1fa2dd8e186a12910f89408e", size = 6089973, upload-time = "2026-09-13T19:10:00.355Z" },
{ url = "https://files.pythonhosted.org/packages/f8/02/90a64c81360d473d07f36dde68eb47d043bf442a24c9c91232643f8c0928/instanttensor-0.2.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:879e8b524b391ed916b8412ef82c3ab40d933ad8d038f40b340d0bd58b7894d3", size = 6178704, upload-time = "2026-09-13T19:10:03.313Z" },
]
[[package]]
name = "interegular"
version = "0.3.3"
@@ -2995,7 +3003,7 @@ wheels = [
[[package]]
name = "kimina"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/lean/kimina" }
dependencies = [
{ name = "verifiers" },
@@ -3142,18 +3150,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e9/61/f75cd1fa54d8434276126034aed54dd120747de9a8fa013cdd79545ccbeb/latex2sympy2_extended-1.11.0-py3-none-any.whl", hash = "sha256:aebb77d52ce269e25028e4bea89ddb14d242ba36bcf7b636496fb5fd9728d234", size = 209050, upload-time = "2026-01-10T01:43:19.458Z" },
]
[[package]]
name = "linkify-it-py"
version = "2.1.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "uc-micro-py" },
]
sdist = { url = "https://files.pythonhosted.org/packages/2e/c9/06ea13676ef354f0af6169587ae292d3e2406e212876a413bf9eece4eb23/linkify_it_py-2.1.0.tar.gz", hash = "sha256:43360231720999c10e9328dc3691160e27a718e280673d444c38d7d3aaa3b98b", size = 29158, upload-time = "2026-03-01T07:48:47.683Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/b4/de/88b3be5c31b22333b3ca2f6ff1de4e863d8fe45aaea7485f591970ec1d3e/linkify_it_py-2.1.0-py3-none-any.whl", hash = "sha256:0d252c1594ecba2ecedc444053db5d3a9b7ec1b0dd929c8f1d74dce89f86c05e", size = 19878, upload-time = "2026-03-01T07:48:46.098Z" },
]
[[package]]
name = "litellm"
version = "1.95.0"
@@ -3272,7 +3268,7 @@ dependencies = [
[[package]]
name = "longcot-env"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/long_context/longcot_env" }
dependencies = [
{ name = "longcot" },
@@ -3302,7 +3298,7 @@ requires-dist = [
[[package]]
name = "longpdfs"
version = "0.0.1"
version = "0.0.2"
source = { editable = "deps/prime-envs/environments/long_context/longpdfs" }
dependencies = [
{ name = "verifiers" },
@@ -3349,11 +3345,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" },
]
[package.optional-dependencies]
linkify = [
{ name = "linkify-it-py" },
]
[[package]]
name = "markupsafe"
version = "3.0.3"
@@ -3381,7 +3372,7 @@ wheels = [
[[package]]
name = "math-env"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/math/math_env" }
dependencies = [
{ name = "verifiers" },
@@ -3474,7 +3465,7 @@ wheels = [
[[package]]
name = "mcp-atlas"
version = "0.4.0"
version = "0.4.1"
source = { editable = "deps/prime-envs/environments/tool_use/mcp_atlas" }
dependencies = [
{ name = "datasets" },
@@ -3502,18 +3493,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f5/4c/c78d78c3d52b0ac594ad7cc8ef5972adfe070e3597a8a4c6ce0cd39196ea/mcp_types-2.0.0-py3-none-any.whl", hash = "sha256:6b2de797ca2797f568b79529e1b25948e34de511bcc0bd82fef1039a6d1b8eb0", size = 69649, upload-time = "2026-07-28T13:45:30.713Z" },
]
[[package]]
name = "mdit-py-plugins"
version = "0.6.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "markdown-it-py" },
]
sdist = { url = "https://files.pythonhosted.org/packages/59/fc/f8d0863f8862f25602c0404d75568e89fb6b4109804645e5cdfb1be5cf56/mdit_py_plugins-0.6.1.tar.gz", hash = "sha256:a2bca0f039f39dbd35fb74ae1b5f998608c437463371f0ff7f49a19a17a114d0", size = 56114, upload-time = "2026-05-13T09:03:38.91Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a5/69/6da5581c6a7fede7dc261bf4e67d6adca4196f176b43288b55b3db395b6e/mdit_py_plugins-0.6.1-py3-none-any.whl", hash = "sha256:214c82fb2ac524472ab6a5bcab1de80f73b50443e187f401bfd77efbc7c6481d", size = 66663, upload-time = "2026-05-13T09:03:37.76Z" },
]
[[package]]
name = "mdurl"
version = "0.1.2"
@@ -3609,7 +3588,7 @@ wheels = [
[[package]]
name = "mmk12"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/multimodal/mmk12" }
dependencies = [
{ name = "pillow" },
@@ -3862,7 +3841,7 @@ wheels = [
[[package]]
name = "multiswe"
version = "0.1.2"
version = "0.1.4"
source = { editable = "deps/prime-envs/environments/swe/multiswe" }
dependencies = [
{ name = "multi-swe-bench" },
@@ -4027,7 +4006,7 @@ wheels = [
[[package]]
name = "numina"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/lean/numina" }
dependencies = [
{ name = "verifiers" },
@@ -4350,6 +4329,22 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/be/9c/92789c596b8df838baa98fa71844d84283302f7604ed565dafe5a6b5041a/oauthlib-3.3.1-py3-none-any.whl", hash = "sha256:88119c938d2b8fb88561af5f6ee0eec8cc8d552b7bb1f712743136eb7523b7a1", size = 160065, upload-time = "2025-06-19T22:48:06.508Z" },
]
[[package]]
name = "officeqa-pro-v2"
version = "0.1.0"
source = { editable = "deps/prime-envs/environments/search/officeqa_pro_v2" }
dependencies = [
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
{ name = "verifiers" },
]
[package.metadata]
requires-dist = [
{ name = "huggingface-hub", specifier = ">=0.34.0" },
{ name = "verifiers", specifier = ">=0.3.1" },
]
[[package]]
name = "onnxruntime"
version = "1.28.0"
@@ -4470,7 +4465,7 @@ requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
[[package]]
name = "openswe"
version = "0.1.3"
version = "0.1.5"
source = { editable = "deps/prime-envs/environments/swe/openswe" }
dependencies = [
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
@@ -4728,7 +4723,7 @@ wheels = [
[[package]]
name = "patterned-needle-in-haystack"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/long_context/patterned_needle_in_haystack" }
dependencies = [
{ name = "nltk" },
@@ -4886,47 +4881,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e6/88/bdb244e40284ded3632a9f88c23bc80230bd7b2ae4a8b7f2cc91adead7a8/preshed-3.0.13-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2e77bed56aded7cbe5d28d6bd2178bc5b13eda0e0e464dab205fb578fa915000", size = 1919236, upload-time = "2026-03-23T08:56:42.616Z" },
]
[[package]]
name = "prime"
version = "0.6.19"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "build" },
{ name = "cryptography" },
{ name = "gitignore-parser" },
{ name = "httpx" },
{ name = "prime-evals" },
{ name = "prime-sandboxes" },
{ name = "prime-tunnel" },
{ name = "pydantic" },
{ name = "pyyaml" },
{ name = "rich" },
{ name = "textual" },
{ name = "textual-plot" },
{ name = "toml" },
{ name = "tomli" },
{ name = "typer" },
{ name = "verifiers" },
]
sdist = { url = "https://files.pythonhosted.org/packages/54/01/d355265be49ec5bd5ce602791e572e266c315ba9087c1a9e77911781a99d/prime-0.6.19.tar.gz", hash = "sha256:cbf33d5050e3795373842b9b89be0ee2b11a9ae9bbdcda080272eb0d982276c2", size = 711104, upload-time = "2026-07-17T17:41:09.283Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/5e/ad/67705b41b441513cc09de0a6134b8584d436efba8bc8b4ddeb4a3bbca768/prime-0.6.19-py3-none-any.whl", hash = "sha256:c2a4ee9252cd1a54fa6bcec2958a09ad4374077c68d461071d1ca699a9f4dda2", size = 473362, upload-time = "2026-07-17T17:41:07.35Z" },
]
[[package]]
name = "prime-evals"
version = "0.2.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx" },
{ name = "pydantic" },
{ name = "tenacity" },
]
sdist = { url = "https://files.pythonhosted.org/packages/1b/e6/8c84619b09ecfb9484ba9b14bf57de3e9417a08e0b3695bd054b181efca8/prime_evals-0.2.3.tar.gz", hash = "sha256:4b22f9057a8765c85f2e91c795d78e48015ae6d30439f24aea9e8396b2c3f016", size = 14417, upload-time = "2026-06-05T00:39:56.145Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e9/f8/41c4a4bc7a03ece28b1c4f39d45a5c362ebaa0895a161db83c591f10e6b6/prime_evals-0.2.3-py3-none-any.whl", hash = "sha256:e5217f36d360baedf2c10dd49abe7be504932bf8249a35c9f7abad12d0c0299a", size = 13575, upload-time = "2026-06-05T00:39:54.901Z" },
]
[[package]]
name = "prime-kernels"
version = "0.1.0+cu130torch2.13.0"
@@ -5006,10 +4960,10 @@ dependencies = [
{ name = "openai" },
{ name = "orjson" },
{ name = "pandas" },
{ name = "prime" },
{ name = "prime-pydantic-config" },
{ name = "prime-rl-configs" },
{ name = "prime-runs", extra = ["train"] },
{ name = "prime-sandboxes" },
{ name = "prometheus-client" },
{ name = "psutil" },
{ name = "pyarrow" },
@@ -5056,8 +5010,8 @@ all = [
{ name = "torchdata", marker = "sys_platform == 'linux'" },
{ name = "torchtitan", marker = "sys_platform == 'linux'" },
{ name = "torchvision", marker = "sys_platform == 'linux'" },
{ name = "vllm", version = "0.28.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm", version = "0.28.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm", version = "0.29.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm", version = "0.29.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
]
@@ -5106,8 +5060,8 @@ gpu = [
{ name = "torchdata", marker = "sys_platform == 'linux'" },
{ name = "torchtitan", marker = "sys_platform == 'linux'" },
{ name = "torchvision", marker = "sys_platform == 'linux'" },
{ name = "vllm", version = "0.28.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm", version = "0.28.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm", version = "0.29.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm", version = "0.29.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
]
kernels = [
{ name = "prime-kernels", version = "0.1.0+cu130torch2.13.0", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
@@ -5165,7 +5119,6 @@ requires-dist = [
{ name = "orjson", specifier = ">=3.10" },
{ name = "orjson", specifier = ">=3.11.0" },
{ name = "pandas", specifier = ">=2.0" },
{ name = "prime", specifier = ">=0.6.19" },
{ name = "prime-kernels", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'kernels'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl" },
{ name = "prime-kernels", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'kernels'" },
{ name = "prime-kernels", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'kernels'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl" },
@@ -5178,6 +5131,7 @@ requires-dist = [
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.3" },
{ name = "prime-sandboxes", specifier = ">=0.3.0" },
{ name = "prometheus-client", specifier = ">=0.20.0" },
{ name = "psutil", specifier = ">=7.0.0" },
{ name = "pyarrow", specifier = ">=21.0.0" },
@@ -5203,9 +5157,9 @@ requires-dist = [
{ name = "uvicorn", marker = "extra == 'dashboard'", specifier = ">=0.30" },
{ name = "uvloop", specifier = ">=0.21.0" },
{ name = "verifiers", extras = ["harbor"], editable = "deps/verifiers" },
{ name = "vllm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.28.0" },
{ name = "vllm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "vllm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.29.0" },
{ name = "vllm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" },
{ name = "vllm-router", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'disagg'" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" },
@@ -5269,7 +5223,7 @@ train = [
[[package]]
name = "prime-sandboxes"
version = "0.2.39"
version = "0.3.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiofiles" },
@@ -5281,36 +5235,36 @@ dependencies = [
{ name = "pyqwest" },
{ name = "tenacity" },
]
sdist = { url = "https://files.pythonhosted.org/packages/59/8c/0bf89180addb74f75e41fbf6fa06c5401ea802b69ec0b565330562270be2/prime_sandboxes-0.2.39.tar.gz", hash = "sha256:7ff6c23aa2c96985a9129d977d532c0ae2fb6afb6d394dac746393ce0c53b597", size = 103161, upload-time = "2026-08-19T23:09:27.921Z" }
sdist = { url = "https://files.pythonhosted.org/packages/b6/46/2d118d8bbb901b729f3bc0678725eb28088d757a872db04cffa1492d0208/prime_sandboxes-0.3.0.tar.gz", hash = "sha256:c99075ed82a9bbfe5a453cee84b9f09565a7f6b07fd5ace072401cce59a1fe08", size = 132759, upload-time = "2026-09-18T01:32:31.263Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/db/a5/8a2a1aefecfc58ca926d6b21e8302a127884bf2a45952ed390b5f702eeda/prime_sandboxes-0.2.39-py3-none-any.whl", hash = "sha256:3ea355158473c1697f9ef6ec2a07f3189e9a2555c80d1c88e1f7e22979772e0a", size = 58161, upload-time = "2026-08-19T23:09:26.69Z" },
{ url = "https://files.pythonhosted.org/packages/5f/04/c77c7f260babf93978f912b85511e76f63a3cfa5bb11a8c34108177d5825/prime_sandboxes-0.3.0-py3-none-any.whl", hash = "sha256:19078ff508fa72de8f565422918faf367e2831ed8a2f26a5a6a98110e4062941", size = 71441, upload-time = "2026-09-18T01:32:30.062Z" },
]
[[package]]
name = "prime-traces"
version = "0.0.3"
version = "0.0.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx" },
{ name = "pydantic" },
]
sdist = { url = "https://files.pythonhosted.org/packages/8c/77/13fa99c0fb71909f2f35d048d9724efb9ae432484e47f12386b1542815e8/prime_traces-0.0.3.tar.gz", hash = "sha256:4071833db77a606ccbb718e5c73f2dfaf63982fe801aa096daed0bc605da554f", size = 50874, upload-time = "2026-08-27T19:46:44.672Z" }
sdist = { url = "https://files.pythonhosted.org/packages/5f/5d/d3646fb34d4f3cf4caf2064eb3830c4da5c18a3ecd3292ce9e85eb04398f/prime_traces-0.0.4.tar.gz", hash = "sha256:713b59984292304bd4e99a55998b7d69373f22b5205a7e097ef0d0d8e531561c", size = 50935, upload-time = "2026-09-04T16:51:10.488Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ce/9a/5a917de29a3a839c0ba36d445e3af562f744d9716b509571be643a01476c/prime_traces-0.0.3-py3-none-any.whl", hash = "sha256:0838f60651f1ed38371e383bd88b954e461d20ac424874e694bc83358934f5f3", size = 38345, upload-time = "2026-08-27T19:46:43.396Z" },
{ url = "https://files.pythonhosted.org/packages/b6/55/de30cc732631522f5f12cb590b63b80cb1c6ca004ad81762d94ee7dda256/prime_traces-0.0.4-py3-none-any.whl", hash = "sha256:68f2b527d266f9c3d02f6c86a1713309a58a61b81e1be6be43948e1dd2456d8f", size = 38409, upload-time = "2026-09-04T16:51:09.201Z" },
]
[[package]]
name = "prime-tunnel"
version = "0.1.10"
version = "0.1.11"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx" },
{ name = "pydantic" },
{ name = "tenacity" },
]
sdist = { url = "https://files.pythonhosted.org/packages/bf/26/7324b5b9ec117c21fc9320214bf04ecbe9144ee87ef48c7d6d6c3e3d3f7f/prime_tunnel-0.1.10.tar.gz", hash = "sha256:8bf575af659bcc107a98b0b5ec1ba3e958ea72ead535ced03c443134a1ad07ea", size = 15305, upload-time = "2026-06-17T00:01:02.392Z" }
sdist = { url = "https://files.pythonhosted.org/packages/de/c7/55c21d8e1abfb66d3a0dc0e25b89abb506b0a49605fb4b0040590af82136/prime_tunnel-0.1.11.tar.gz", hash = "sha256:cd93e78824ef824b45e636f5f506898bc7f9a6c913fd5095ab1df2233a49b949", size = 15889, upload-time = "2026-09-04T17:09:25.258Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a9/b9/d767b4f6c7ce72b54aaba834b97f97c3c494f1865a37f8b5b9acfb1b2a68/prime_tunnel-0.1.10-py3-none-any.whl", hash = "sha256:6a1cb49a14cfc9622db5cae90665ebe7e7e8cd5d84e963e8c3572bce85288400", size = 16319, upload-time = "2026-06-17T00:01:01.095Z" },
{ url = "https://files.pythonhosted.org/packages/d0/7f/6ea38563db9414ed208758de6e8dc557b20e245787e42568f89531fc6717/prime_tunnel-0.1.11-py3-none-any.whl", hash = "sha256:19c5e02e389e5e61fff1507f07c46db9b05ad01424ff3b6a0cbe66187c957f61", size = 16676, upload-time = "2026-09-04T17:09:24.157Z" },
]
[[package]]
@@ -5353,7 +5307,7 @@ requires-dist = [
[[package]]
name = "prolog"
version = "0.5.0"
version = "0.5.1"
source = { editable = "deps/prime-envs/environments/reasoning/prolog" }
dependencies = [
{ name = "verifiers" },
@@ -5998,7 +5952,7 @@ wheels = [
[[package]]
name = "r2e-gym"
version = "0.1.2"
version = "0.1.4"
source = { editable = "deps/prime-envs/environments/swe/r2e_gym" }
dependencies = [
{ name = "verifiers" },
@@ -6296,7 +6250,7 @@ wheels = [
[[package]]
name = "scaleswe"
version = "0.1.2"
version = "0.1.4"
source = { editable = "deps/prime-envs/environments/swe/scaleswe" }
dependencies = [
{ name = "verifiers" },
@@ -6826,7 +6780,7 @@ requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.1
[[package]]
name = "swelego"
version = "0.1.2"
version = "0.1.4"
source = { editable = "deps/prime-envs/environments/swe/swelego" }
dependencies = [
{ name = "verifiers" },
@@ -6837,7 +6791,7 @@ requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
[[package]]
name = "swerebench-v2"
version = "0.1.2"
version = "0.1.4"
source = { editable = "deps/prime-envs/environments/swe/swerebench_v2" }
dependencies = [
{ name = "verifiers" },
@@ -6853,7 +6807,7 @@ source = { git = "https://github.com/SWE-bench/SWE-smith.git?rev=9b74ac0#9b74ac0
[[package]]
name = "swesmith-env"
version = "0.1.3"
version = "0.1.5"
source = { editable = "deps/prime-envs/environments/swe/swesmith_env" }
dependencies = [
{ name = "swebench" },
@@ -7010,7 +6964,7 @@ requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.1
[[package]]
name = "terminal-lego"
version = "0.1.1"
version = "0.1.2"
source = { editable = "deps/prime-envs/environments/terminal/terminal_lego" }
dependencies = [
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
@@ -7042,50 +6996,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/26/b4/9a9ba65154aff853c75b3d7324319d168ad9c69c6097f4aa3c16da7d9ef3/textarena-0.7.4-py3-none-any.whl", hash = "sha256:684784e78278e518066f67557ee93b47c238d16cbbd15d3abdaa3147562d3024", size = 1073570, upload-time = "2025-10-16T14:41:53.965Z" },
]
[[package]]
name = "textual"
version = "8.2.7"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "markdown-it-py", extra = ["linkify"] },
{ name = "mdit-py-plugins" },
{ name = "platformdirs" },
{ name = "pygments" },
{ name = "rich" },
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/9b/7a/c519db0aba5024f86e71e9631810bfdd6866ed2c8695bd7fa34b90e7ef59/textual-8.2.7.tar.gz", hash = "sha256:658f568ff81e30ed43890c3e07520390e5cf1b4763822006e060656b0a88f105", size = 1859249, upload-time = "2026-05-19T10:52:49.531Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a8/f5/c1e18bc0707300a0e90204343abbf7d7acd6fb7ebe03a6d4893b99a234b8/textual-8.2.7-py3-none-any.whl", hash = "sha256:4caaa13a90bc4cf9c6c862c067ccd34fe84e9c161710a2a907a8026313b6bd73", size = 731129, upload-time = "2026-05-19T10:52:51.773Z" },
]
[[package]]
name = "textual-hires-canvas"
version = "0.14.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "numpy" },
{ name = "textual" },
]
sdist = { url = "https://files.pythonhosted.org/packages/20/f0/13f2a30ab7950cc3d5d5a2c893fbe3d40b4d129fd2cd30313260181578c4/textual_hires_canvas-0.14.0.tar.gz", hash = "sha256:0fa512492ddd2cd6c2a970a6beea58f5350f4cf25f40ad14ffd9fa86c6458769", size = 1251440, upload-time = "2026-01-10T22:16:56.708Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/85/ea/e7e6d0f749395d61ca2ab8cda2f3c4e6613800b6b0d0b21f9d1d180c4d42/textual_hires_canvas-0.14.0-py3-none-any.whl", hash = "sha256:8cd67d656387220684449e837dd5809b6c00c5dfee8e4b494414b5837cb5a804", size = 19825, upload-time = "2026-01-10T22:16:54.69Z" },
]
[[package]]
name = "textual-plot"
version = "0.10.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "numpy" },
{ name = "textual" },
{ name = "textual-hires-canvas" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a0/c2/13f9f747e83cd0b740d1bf310e89a006316cfb5acb4e5a4136c12f96340b/textual_plot-0.10.1.tar.gz", hash = "sha256:503db96d849134293228419324eb15efbadf1f1927a2e0a229b54e7a7e5d5292", size = 2451096, upload-time = "2026-02-01T13:27:43.658Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/2a/36/75eba496995e6f9a001cd601972eab753203167dfcccfbf1816e3959d28d/textual_plot-0.10.1-py3-none-any.whl", hash = "sha256:74ff3a8b2d84bd71b3a9abbac95139ff952f190e6bac60c7091911c63a1863ba", size = 50409, upload-time = "2026-02-01T13:27:41.013Z" },
]
[[package]]
name = "thinc"
version = "8.3.13"
@@ -7166,7 +7076,7 @@ wheels = [
[[package]]
name = "tmax"
version = "0.1.0"
version = "0.1.2"
source = { editable = "deps/prime-envs/environments/terminal/tmax" }
dependencies = [
{ name = "verifiers", extra = ["harbor"] },
@@ -7475,6 +7385,24 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/16/e1/3079a9ff9b8e11b846c6ac5c8b5bfb7ff225eee721825310c91b3b50304f/tqdm-4.67.3-py3-none-any.whl", hash = "sha256:ee1e4c0e59148062281c49d80b25b67771a127c85fc9676d3be5f243206826bf", size = 78374, upload-time = "2026-02-03T17:35:50.982Z" },
]
[[package]]
name = "trace-cheating-recall-500"
version = "0.1.0"
source = { editable = "deps/prime-envs/environments/judges/trace_cheating_recall_500" }
dependencies = [
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
{ name = "orjson" },
{ name = "verifiers" },
]
[package.metadata]
requires-dist = [
{ name = "huggingface-hub", specifier = ">=0.34.0" },
{ name = "orjson", specifier = ">=3.10.0" },
{ name = "verifiers", specifier = ">=0.3.1" },
]
[[package]]
name = "traitlets"
version = "5.15.0"
@@ -7677,15 +7605,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/93/4f/c43a0a8f0c66fd40a1d6cc47332a5a1d1043e9b331f7070ea701b91a7598/tyro-1.0.13-py3-none-any.whl", hash = "sha256:a0bdb8462c551dd84fc00a76916ce4d37e879c84eefaf34e2165312407cc6c09", size = 185221, upload-time = "2026-04-14T18:21:54.328Z" },
]
[[package]]
name = "uc-micro-py"
version = "2.0.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/78/67/9a363818028526e2d4579334460df777115bdec1bb77c08f9db88f6389f2/uc_micro_py-2.0.0.tar.gz", hash = "sha256:c53691e495c8db60e16ffc4861a35469b0ba0821fe409a8a7a0a71864d33a811", size = 6611, upload-time = "2026-03-01T06:31:27.526Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/61/73/d21edf5b204d1467e06500080a50f79d49ef2b997c79123a536d4a17d97c/uc_micro_py-2.0.0-py3-none-any.whl", hash = "sha256:3603a3859af53e5a39bc7677713c78ea6589ff188d70f4fee165db88e22b242c", size = 6383, upload-time = "2026-03-01T06:31:26.257Z" },
]
[[package]]
name = "unidiff"
version = "0.7.5"
@@ -7697,7 +7616,7 @@ wheels = [
[[package]]
name = "unscramble"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/reasoning/unscramble" }
dependencies = [
{ name = "verifiers" },
@@ -7717,7 +7636,7 @@ wheels = [
[[package]]
name = "uuid-ctf"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/reasoning/uuid_ctf" }
dependencies = [
{ name = "verifiers" },
@@ -7765,7 +7684,7 @@ wheels = [
[[package]]
name = "verbatim-copy"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/long_context/verbatim_copy" }
dependencies = [
{ name = "faker" },
@@ -7821,7 +7740,6 @@ ta = [
requires-dist = [
{ name = "aiohttp", specifier = ">=3.14.1" },
{ name = "anthropic", specifier = ">=1.0.0" },
{ name = "datasets", marker = "extra == 'lean'", specifier = ">=3.3.0,<6.0.0" },
{ name = "gepa", specifier = ">=0.0.6" },
{ name = "h11", specifier = ">=0.16.0" },
{ name = "harbor", marker = "python_full_version >= '3.12' and extra == 'harbor'", specifier = "==0.21.0" },
@@ -7837,8 +7755,8 @@ requires-dist = [
{ name = "openai", specifier = ">=2.54.0,<3.0.0" },
{ name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" },
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.3" },
{ name = "prime-runs", specifier = ">=0.1.2" },
{ name = "prime-sandboxes", specifier = ">=0.2.39" },
{ name = "prime-runs", specifier = ">=0.1.3" },
{ name = "prime-sandboxes", specifier = ">=0.3.0" },
{ name = "prime-tunnel", specifier = ">=0.1.8" },
{ name = "pydantic", specifier = ">=2.12.3" },
{ name = "pyzmq", specifier = ">=27.1.0" },
@@ -7850,7 +7768,7 @@ requires-dist = [
{ name = "typing-extensions", specifier = ">=4.12.2" },
{ name = "uvicorn", specifier = ">=0.52.0" },
]
provides-extras = ["harbor", "lean", "modal", "openenv", "ta"]
provides-extras = ["harbor", "modal", "openenv", "ta"]
[package.metadata.requires-dev]
dev = [
@@ -7885,7 +7803,7 @@ examples = [
[[package]]
name = "virl39k"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/multimodal/virl39k" }
dependencies = [
{ name = "huggingface-hub", version = "1.16.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
@@ -7916,8 +7834,8 @@ wheels = [
[[package]]
name = "vllm"
version = "0.28.0"
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl" }
version = "0.29.0"
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl" }
resolution-markers = [
"platform_machine == 'aarch64' and sys_platform == 'linux'",
]
@@ -7939,6 +7857,7 @@ dependencies = [
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" } },
{ name = "humming-kernels", extra = ["cu13"] },
{ name = "ijson" },
{ name = "instanttensor" },
{ name = "jsonschema" },
{ name = "lark" },
{ name = "llguidance" },
@@ -7998,7 +7917,7 @@ dependencies = [
{ name = "xgrammar" },
]
wheels = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:817b8181f7f61b4a62dc1d5d9ab39f2bfb60a6cb86c29879a78a147b85756787" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:e6b0dfc2b6fd307315e9b34b73cd2bfe7b6b08958eda721828e61732bba426b0" },
]
[package.metadata]
@@ -8007,7 +7926,7 @@ requires-dist = [
{ name = "anthropic", specifier = ">=0.71.0" },
{ name = "apache-tvm-ffi", specifier = "==0.1.11" },
{ name = "av", marker = "extra == 'audio'" },
{ name = "b12x", marker = "extra == 'b12x'", specifier = "==1.2.4" },
{ name = "b12x", marker = "extra == 'b12x'", specifier = "==1.2.6" },
{ name = "blake3" },
{ name = "cachetools" },
{ name = "cbor2" },
@@ -8020,11 +7939,12 @@ requires-dist = [
{ name = "fastsafetensors", specifier = ">=0.3.3" },
{ name = "fastsafetensors", marker = "extra == 'fastsafetensors'", specifier = ">=0.3.3" },
{ name = "filelock", specifier = ">=3.16.1" },
{ name = "flashinfer-python", specifier = "==0.6.16.post3" },
{ name = "flashinfer-python", specifier = "==0.6.18" },
{ name = "helion", marker = "extra == 'helion'", specifier = "==1.4.0" },
{ name = "huggingface-hub", specifier = ">=1.27.0" },
{ name = "huggingface-hub", specifier = ">=1.28.0" },
{ name = "humming-kernels", extras = ["cu13"], specifier = "==0.1.12" },
{ name = "ijson" },
{ name = "instanttensor", specifier = ">=0.1.9" },
{ name = "instanttensor", marker = "extra == 'instanttensor'", specifier = ">=0.1.9" },
{ name = "jsonschema", specifier = ">=4.23.0" },
{ name = "lark", specifier = "==1.2.2" },
@@ -8096,7 +8016,7 @@ requires-dist = [
{ name = "torchcodec", specifier = ">=0.14" },
{ name = "torchvision", specifier = "==0.28.0" },
{ name = "tqdm" },
{ name = "transformers", specifier = ">=5.5.3" },
{ name = "transformers", specifier = ">=5.10.4" },
{ name = "typing-extensions", specifier = ">=4.10" },
{ name = "vllm-gguf-plugin", marker = "extra == 'extra-quant'", specifier = ">=0.0.2" },
{ name = "watchfiles" },
@@ -8107,8 +8027,8 @@ provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttens
[[package]]
name = "vllm"
version = "0.28.0"
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl" }
version = "0.29.0"
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl" }
resolution-markers = [
"platform_machine == 'x86_64' and sys_platform == 'linux'",
]
@@ -8130,6 +8050,7 @@ dependencies = [
{ name = "huggingface-hub", version = "1.28.0", source = { registry = "https://pypi.org/simple" } },
{ name = "humming-kernels", extra = ["cu13"] },
{ name = "ijson" },
{ name = "instanttensor" },
{ name = "jsonschema" },
{ name = "lark" },
{ name = "llguidance" },
@@ -8189,7 +8110,7 @@ dependencies = [
{ name = "xgrammar" },
]
wheels = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:addb0ffdaafd8155d75e9b3f5ddb3da28fdee9e8a7097ede91f7db2e9e1a3889" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:09d48617fc2be9c6cdcd5db480651ab0d84817b257204f2cc2e3ecbb70bbb635" },
]
[package.metadata]
@@ -8198,7 +8119,7 @@ requires-dist = [
{ name = "anthropic", specifier = ">=0.71.0" },
{ name = "apache-tvm-ffi", specifier = "==0.1.11" },
{ name = "av", marker = "extra == 'audio'" },
{ name = "b12x", marker = "extra == 'b12x'", specifier = "==1.2.4" },
{ name = "b12x", marker = "extra == 'b12x'", specifier = "==1.2.6" },
{ name = "blake3" },
{ name = "cachetools" },
{ name = "cbor2" },
@@ -8211,11 +8132,12 @@ requires-dist = [
{ name = "fastsafetensors", specifier = ">=0.3.3" },
{ name = "fastsafetensors", marker = "extra == 'fastsafetensors'", specifier = ">=0.3.3" },
{ name = "filelock", specifier = ">=3.16.1" },
{ name = "flashinfer-python", specifier = "==0.6.16.post3" },
{ name = "flashinfer-python", specifier = "==0.6.18" },
{ name = "helion", marker = "extra == 'helion'", specifier = "==1.4.0" },
{ name = "huggingface-hub", specifier = ">=1.27.0" },
{ name = "huggingface-hub", specifier = ">=1.28.0" },
{ name = "humming-kernels", extras = ["cu13"], specifier = "==0.1.12" },
{ name = "ijson" },
{ name = "instanttensor", specifier = ">=0.1.9" },
{ name = "instanttensor", marker = "extra == 'instanttensor'", specifier = ">=0.1.9" },
{ name = "jsonschema", specifier = ">=4.23.0" },
{ name = "lark", specifier = "==1.2.2" },
@@ -8287,7 +8209,7 @@ requires-dist = [
{ name = "torchcodec", specifier = ">=0.14" },
{ name = "torchvision", specifier = "==0.28.0" },
{ name = "tqdm" },
{ name = "transformers", specifier = ">=5.5.3" },
{ name = "transformers", specifier = ">=5.10.4" },
{ name = "typing-extensions", specifier = ">=4.10" },
{ name = "vllm-gguf-plugin", marker = "extra == 'extra-quant'", specifier = ">=0.0.2" },
{ name = "watchfiles" },
@@ -8551,7 +8473,7 @@ requires-dist = [
[[package]]
name = "wikispeedia"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/reasoning/wikispeedia" }
dependencies = [
{ name = "verifiers" },