Compare commits

...
Author SHA1 Message Date
Mika SenghaasandGitHub b695a0aeda fix(inference): align DeepSeek V4 request tool placement (#3646)
## Summary

- attach request-level tools to the first existing DeepSeek V4 system
message
- preserve vLLM's existing synthetic-system behavior when a request has
no system message
- cover both paths and ensure the caller's messages are not mutated

vLLM 0.29's Python DeepSeek V4 tokenizer prepends a synthetic tool-only
system message even when the request already has a system prompt. That
differs from DeepSeek's reference encoder, vLLM's Rust renderer, and
prime-rl's training renderer, producing a different token prefix at
inference time.

This is a temporary compatibility patch for
[vllm-project/vllm#51856](https://github.com/vllm-project/vllm/pull/51856)
(upstream commit `2909ad8f`). That fix is expected to ship in vLLM 0.31,
at which point this monkey patch can be removed.

## Tests

- `pytest tests/unit/inference/test_deepseek_v4_tokenizer_patch.py -q` —
2 passed
- `ruff check src/prime_rl/inference/patches.py
tests/unit/inference/test_deepseek_v4_tokenizer_patch.py`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Inference-only tokenizer shim with idempotent guards; behavior is
covered by reference-encoding unit tests and should be removable after a
vLLM upgrade.
> 
> **Overview**
> Adds a temporary vLLM monkey patch so **DeepSeek V4 inference prompts
match the reference encoder and training renderer** when requests
include tools plus an existing system message.
> 
> On vLLM 0.29, the Python tokenizer **prepends a synthetic system block
for request-level tools**, putting `## Tools` before the caller’s system
text. The patch wraps `get_deepseek_v4_tokenizer` and
**`apply_chat_template`**: if the conversation already has a system
role, it shallow-copies the conversation, **attaches `tools` to the
first system message**, clears top-level `tools` so vLLM does not insert
the extra system message, and leaves **no-system** requests on stock
behavior. It is registered in **`apply_shared_vllm_patches`** and is
meant to be removed once the vLLM pin includes upstream **#51856**
(~0.31).
> 
> Unit tests assert rendered prompts match **`encode_messages`**, that
only one `## Tools` section appears, and that **input `messages` are not
mutated**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1acca7c9d1c503d0d497f05638d50e687ec714c8. 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 15:14:15 -07:00
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
35 changed files with 497 additions and 147 deletions
+4
View File
@@ -137,6 +137,10 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& \
/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
+1 -1
@@ -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)``.
@@ -311,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``."""
@@ -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):
@@ -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"
+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,
+59
View File
@@ -20,6 +20,7 @@ def apply_shared_vllm_patches():
monkey_patch_kv_xfer_finished_tolerate_freed()
monkey_patch_online_fp8_parameter_cast()
monkey_patch_deepseek_v4_allowed_layer_types()
monkey_patch_deepseek_v4_request_tools_placement()
monkey_patch_deepseek_v4_per_layer_rope()
monkey_patch_deepseek_v4_bf16_o_proj()
@@ -41,6 +42,64 @@ def monkey_patch_deepseek_v4_allowed_layer_types():
allow_deepseek_v4_layer_types()
def monkey_patch_deepseek_v4_request_tools_placement():
"""Attach request-level tools to the first existing DSV4 system message.
vLLM 0.29.0's Python DeepSeek-V4 tokenizer always prepends a synthetic
system message for request-level tools. That puts the tool schema before
an existing system prompt, unlike DeepSeek's reference encoder, vLLM's
Rust renderer, and prime-rl's training renderer. Upstream fixed this in
https://github.com/vllm-project/vllm/pull/51856 (commit 2909ad8f).
The fix is expected to ship in vLLM 0.31.
Wrap the tokenizer factory so existing-system requests take the corrected
path through the stock implementation: shallow-copy the conversation,
attach tools to its first system message, and suppress the stock synthetic
insertion. Requests without a system message retain the stock behavior.
Remove this patch once the vLLM pin includes the upstream fix (likely 0.31).
"""
import copy
from vllm.tokenizers import deepseek_v4 as dsv4_tokenizer
original_get_tokenizer = dsv4_tokenizer.get_deepseek_v4_tokenizer
if getattr(original_get_tokenizer, "_prime_rl_places_request_tools", False):
return
def _get_deepseek_v4_tokenizer(tokenizer):
wrapped = original_get_tokenizer(tokenizer)
tokenizer_cls = wrapped.__class__
original_apply_chat_template = tokenizer_cls.apply_chat_template
# Each factory call creates a fresh dynamic tokenizer subclass, but be
# defensive if vLLM starts caching that class in a future release.
if getattr(original_apply_chat_template, "_prime_rl_places_request_tools", False):
return wrapped
def _apply_chat_template(self, messages, tools=None, **kwargs):
if tools:
conversation = kwargs.get("conversation", messages)
system_idx = next(
(i for i, message in enumerate(conversation) if message.get("role") == "system"),
None,
)
if system_idx is not None:
conversation = conversation.copy()
conversation[system_idx] = copy.copy(conversation[system_idx])
conversation[system_idx]["tools"] = tools
kwargs["conversation"] = conversation
tools = None
return original_apply_chat_template(self, messages, tools=tools, **kwargs)
_apply_chat_template._prime_rl_places_request_tools = True
tokenizer_cls.apply_chat_template = _apply_chat_template
return wrapped
_get_deepseek_v4_tokenizer._prime_rl_places_request_tools = True
dsv4_tokenizer.get_deepseek_v4_tokenizer = _get_deepseek_v4_tokenizer
def monkey_patch_online_fp8_parameter_cast():
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
+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],
}
+1 -1
View File
@@ -333,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
+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"
@@ -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,
@@ -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,
@@ -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
@@ -0,0 +1,79 @@
import copy
from vllm.tokenizers.deepseek_v4_encoding import encode_messages
from prime_rl.inference.patches import monkey_patch_deepseek_v4_request_tools_placement
class _StubTokenizer:
def get_added_vocab(self):
return {}
def encode(self, text, **_kwargs):
return text
def _request_tools():
return [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}
]
def _tokenizer():
from vllm.tokenizers import deepseek_v4
monkey_patch_deepseek_v4_request_tools_placement()
return deepseek_v4.get_deepseek_v4_tokenizer(_StubTokenizer())
def _render(messages, tools):
return _tokenizer().apply_chat_template(
messages,
tools=tools,
tokenize=False,
thinking=True,
reasoning_effort="low",
)
def _reference(messages):
return encode_messages(messages, thinking_mode="thinking", reasoning_effort="low")
def test_request_tools_attach_to_first_existing_system_without_mutation():
messages = [
{"role": "user", "content": "This may precede the system message."},
{"role": "system", "content": "You are helpful.", "tools": []},
{"role": "system", "content": "A later system message."},
{"role": "user", "content": "Weather in Paris?"},
]
snapshot = copy.deepcopy(messages)
tools = _request_tools()
prompt = _render(messages, tools)
expected_messages = messages.copy()
expected_messages[1] = {**messages[1], "tools": tools}
assert prompt == _reference(expected_messages)
assert prompt.count("## Tools") == 1
assert messages == snapshot
def test_request_tools_synthesize_system_only_when_none_exists():
messages = [{"role": "user", "content": "Weather in Paris?"}]
tools = _request_tools()
prompt = _render(messages, tools)
assert prompt == _reference([{"role": "system", "tools": tools}, *messages])
@@ -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))
@@ -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(
Generated
+68 -33
View File
@@ -93,6 +93,7 @@ members = [
"multiswe",
"nl2repobench",
"numina",
"officeqa-pro-v2",
"oolong-pairs",
"oolong-real",
"oolong-synth",
@@ -126,6 +127,7 @@ members = [
"terminal-bench-2",
"terminal-lego",
"tmax",
"trace-cheating-recall-500",
"triviaqa",
"unscramble",
"uuid-ctf",
@@ -1403,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" },
@@ -1611,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" },
@@ -1948,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" },
@@ -2082,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" },
@@ -2539,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" },
@@ -2554,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" },
@@ -2571,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" },
@@ -2582,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" },
@@ -3001,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" },
@@ -3266,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" },
@@ -3296,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" },
@@ -3370,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" },
@@ -3463,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" },
@@ -3586,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" },
@@ -3839,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" },
@@ -4004,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" },
@@ -4327,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"
@@ -4447,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'" },
@@ -4705,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" },
@@ -5289,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" },
@@ -5934,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" },
@@ -6232,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" },
@@ -6762,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" },
@@ -6773,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" },
@@ -6789,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" },
@@ -6946,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'" },
@@ -7058,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"] },
@@ -7367,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"
@@ -7580,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" },
@@ -7600,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" },
@@ -7648,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" },
@@ -7704,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" },
@@ -7733,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 = [
@@ -7768,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'" },
@@ -8438,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" },