Compare commits

...
Author SHA1 Message Date
faresobeidandGitHub c5406f8d09 perf(examples): use cudnn_flashmla DSA backend in GLM-5.3 RL example (#3968)
Sets `dsa_backend = "cudnn_flashmla"` for the trainer in the GLM-5.3 RL
example (`examples/advanced/glm-5.3/swe.toml`). The SFT example already
uses it (#3829); the RL example still ran the TileLang forward and
backward.

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

## Sampling flow

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

## Shared parameters

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

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

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

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

## Training ownership

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

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

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

## Dependency

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

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

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

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

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

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

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

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> CI-only security remediation with intentional cache busting (slower
first builds); no application runtime code changes, but GHCR images
built before the fix may need a separate provenance/rebuild decision.
> 
> **Overview**
> Remediates **CVE-2026-93318** in the GHCR image build workflow by
making the BuildKit builder version fixed and breaking reuse of
artifacts produced before the patch.
> 
> **BuildKit pin:** `docker/setup-buildx-action` now sets `driver-opts`
to `moby/buildkit:v0.33.1` (digest-pinned) so self-hosted
`image-builder` runners do not keep serving a stale local
`buildx-stable-1` builder.
> 
> **Cache and deps lineage:** Shared registry cache refs move to
`dependency-buildcache-v2-*` and `application-buildcache-v2-*` so layers
written by pre-v0.33.1 builders are not imported. Dependency base tags
gain a `-v2-` epoch (`deps-${key}-v2-${suffix}`) so existing
`deps-${key}` images are not reused as the runtime base when only
Dockerfile/lock inputs are unchanged.
> 
> The first build per platform after merge is expected to be cold (no
old cache import); published runtime tags are unchanged—only CI
remediation naming and builder configuration.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0310e6d89608d9d34fd0c1a4c0e9a5c6ba5261bf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-09 08:22:03 -07:00
Konstantin DunasandGitHub 88faa6dc22 feat(sft): warn when renderer is not prefix stable (#3953)
Warn when SFT constructs a renderer that does not guarantee prefix
stability. The warning explains that each conversation is rendered once
into one training sample, that N assistant turns are not expanded into N
samples, and that earlier reasoning may be omitted by the template.
Cached renderers warn only on construction; stable renderers stay quiet.
Custom renderers without the capability are conservatively treated as
unknown.

Pin `deps/renderers` to merged main revision `41f9290`, which includes
https://github.com/PrimeIntellect-ai/renderers/pull/184. It provides the
resolved capability and the manual, opt-in witness audit. Sample
construction is unchanged.

Validation: all **73 SFT dataset tests passed**, including
stable/unstable renderer selection and cache-warning behavior. Prime-rl
unit-test CI passed on the preceding revision; this update changes only
the renderer gitlink to the merged revision. Dependency requirements are
unchanged apart from renderer Python >=3.11, compatible with prime-rl
Python 3.12. The manually invoked renderer audit passes **59 tests** and
is excluded from normal CI discovery.
2026-10-09 11:53:24 +02:00
Florian BrandandGitHub 083b8fe9ec ci: reduce GPU usage and parallelize test setup (#3944)
Reduce CI time and GPU usage by selecting the relevant test suites for
each PR, moving hosted eval to CPU, and running independent setup steps
in parallel.

- Select GPU unit tests, SFT, RL, and hosted eval from changed paths
before allocating runners. Shared runtime and dependency changes retain
broad coverage; pushes to `main` and manual runs execute the full suite.
- Keep RL/SFT coverage for checkpoint converters, dashboard code, and
the shared dashboard smoke helper.
- Run `gsm8k_eval` on `ubuntu-latest` because it uses hosted inference.
- Run public submodule initialization and `uv` setup concurrently, then
wait for both before installing dependencies. Keep dependency caching
keyed on `uv.lock` and the five-job limit on GPU integration tests.
- Cancel superseded CPU and style runs on the same PR.
- Give the GPU workflow read-only contents access and the test selector
PR read access.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Path-based GPU job gating can skip integration coverage on PRs if
filters miss a dependency; full suite still runs on main and manual
dispatch.
> 
> **Overview**
> **GPU CI now picks which jobs to run from the PR diff**, instead of
always running the full GPU unit + integration matrix on every non-draft
PR. A new **Select tests** job uses path filters for unit, SFT, RL, and
eval; pushes to `main` and `workflow_dispatch` still run everything.
RL/SFT integration scenarios are built dynamically (still capped at
`max-parallel: 5` on `prime-rl-2xh200`).
> 
> **`gsm8k_eval` is split out** into a dedicated job on `ubuntu-latest`
(hosted inference), so it no longer consumes GPU runners. Integration
pytest invocations use `tests/integration/test_${{ matrix.test }}.py`
from the dynamic matrix rather than per-row `pytest_args`.
> 
> **Setup and queueing tweaks:** submodule init and `setup-uv` run in
parallel in CPU/GPU jobs; CPU and style workflows cancel in-progress
runs per PR; GPU workflow gets `workflow_dispatch`, read-only
`contents`, and PR-scoped concurrency cancel. `docs/development.md`
documents the new triggers and runner split.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
20da35f30de85b2b18cf82e29598846a1228ca12. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 17:17:55 -07:00
853208336e feat(sft): pad to a multiple of cp and remove fp8 indexer dynamism (#3948)
SFT now pads packed rows only to a multiple of cp, as RL does, instead
of to `seq_len`. The fp8 indexer drops its autotuning, which
re-benchmarked configs on every new row length and made unpadded rows
slower than padded ones on DeepSeek-V4 (#3726).

- The indexer pads keys to a multiple of 16 and runs one fixed config,
within 1.05x of the best.
- Every rank, including RL on DeepSeek-V4 and GLM-5, runs that config
with bitwise-identical top-k.
- SFT and RL throughput count trained tokens, not `seq_len` × rows or
the first row × count.
- The SFT `seq_len % (2 * cp)` check is gone: CP only needs `seq_len %
cp`, which configs enforce.

Same samples per arm, time summed over steps 5 to 20, one H200 node:

| Workload | Padding on main | main | This PR | Speedup |
|---|---|---|---|---|
| DeepSeek-V4-Flash 6L, scaleswe, 256K rows, cp 8 | 19.8% | 61.2 s |
38.2 s | 1.60x |
| GLM-4.5-Air 8L, math, 131K rows, dp 4 cp 2 | 7.3% | 223.8 s | 200.1 s
| 1.12x |
| GLM-4.5-Air 8L, scaleswe, 131K rows, dp 4 cp 2 | 19.7% | 701.0 s |
623.0 s | 1.13x |

On DeepSeek-V4, the 1.60x exceeds the 1.25x that removing 19.8% of
tokens predicts because two effects multiply: main's token-0 pads crowd
onto the same experts, and the padding itself costs compute. The
DeepSeek-V4 ablation section below separates the two.

On GLM with scaleswe, removing 19.7% of the tokens would predict about
1.25x, but it measured 1.13x. Its 4 data-parallel ranks now get rows of
different lengths, and each step likely waits for the rank with the
longest rows.

Loss matches main to within 1e-3 per step. This overlaps
https://github.com/PrimeIntellect-ai/prime-rl/pull/3932 in
`CatDataset._finalize_pack`. Harness:
[`benchmarks/scripts/sft_pad_to_cp/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/0ed0e78b33e8533d7fd1e0d603759dc2ab50e5dd/benchmarks/scripts/sft_pad_to_cp)
(removed before merge).

## DeepSeek-V4 ablation

Each row changes one thing on the DeepSeek-V4 workload above, to
separate the cost of the padding length, of token-0 pads crowding onto
the same experts, and of indexer re-tuning:

| Arm | Time | Speedup vs main |
|---|---|---|
| main: pads every row to `seq_len` with token 0 | 61.2 s | 1.00x |
| main, but pads with the row's own tokens (#3932) | 49.6 s | 1.23x |
| pads only to a multiple of cp, indexer still autotuned | 73.6 s |
0.83x |
| pads only to a multiple of cp, fixed-config indexer (this PR) | 38.2 s
| **1.60x** |

## Alternatives considered

- Bucketing the autotune key on `next_power_of_2(S_q)` reached 1.47x on
DeepSeek-V4. Each bucket kept its first row's config (up to 1.44x slower
later), short rows paid extra tunes, and each rank still tuned on its
own rows, so ranks could run different kernels.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 19:13:22 -04:00
Konstantin DunasandGitHub 31281d88f9 feat(sft): pass per-message loss selection to renderers (#3950)
SFT samples can contain prefilled assistant turns that must remain in
context without becoming training targets. Read an optional
`message_loss_mask` dataset column and pass it directly to
`renderers.build_training_sample`; for a user/assistant/user/assistant
conversation, `[0, 0, 0, 1]` trains only the final assistant turn.

The renderer owns token attribution and mask validation, including GLM's
assistant-generated closing markers. prime-rl performs no owner walking
or template-specific mask reconstruction. Selection only removes
existing loss targets and preserves input/target token IDs. Missing or
null masks preserve normal supervision; fully masked samples follow the
existing skip behavior.

`data.columns.message_loss_mask` supports renamed columns. For
prompt/completion rows, the mask covers their concatenated message list.
This API reads a separate column; datasets with inline
`messages[].trainable_mask` need conversion before use.

Pins `deps/renderers` to upstream main commit
`e3ace557545274385abb30435975c134c7c2429d`, which merges
https://github.com/PrimeIntellect-ai/renderers/pull/181. The renderer
dependency is now merged.

Validation:
- Signed pin update `838828713` points to the merged renderer commit.
Its Git tree is identical to the previously tested renderer head; no
source changes accompany the pin update.
- The following tests and checks passed on signed implementation commit
`7e0800051`:
- 73 SFT dataset tests passed, including real GLM-5 and Qwen3
tokenizers, both dataset layouts, custom column names,
missing/null/all-enabled masks, excluded initial/final turns, fully
masked samples, and invalid values/lengths.
- Ruff 0.13.0 lint and formatting checks passed for the changed Python
files; `git diff --check` passed.
- CPU tests ran in an isolated Python 3.12 environment with Transformers
5.6.2 and PyTorch 2.14.1. No GPU training run performed.
- Commit signature verified locally.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes which tokens receive loss during SFT when datasets supply
masks; incorrect masks could silently train the wrong turns, though
behavior is opt-in and heavily tested against real renderers.
> 
> **Overview**
> Adds **optional per-message SFT loss selection** via a dataset
`message_loss_mask` column (0/1 or booleans, one entry per resolved
message—including prompt+completion rows). The trainer forwards the
column to `build_training_sample` so renderers drop supervision on
excluded turns **without changing token IDs** (e.g. `[0, 0, 0, 1]` keeps
context but trains only the last assistant reply). Missing/null masks
behave as today; all-zero masks still skip the sample.
> 
> **Config and docs:** `SFTColumnsConfig.message_loss_mask` defaults to
`"message_loss_mask"` and can be remapped (e.g. `"selection"`); dataset
init errors if a remap points at a missing column. `docs/training.md`
documents the format and semantics.
> 
> **Tests:** Coverage for GLM-5 and Qwen3, both dataset layouts, custom
column names, partial masks, fully masked rows, and invalid mask
values/lengths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
838828713529afa49a57cf441071f946ec195cdf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-09 00:36:22 +02:00
samsjaandGitHub bc250759bf fix(ci): uv cache on h200 runners, drop phantom 4xa6000 job, cap fan-out (#3909)
## Why

Since **Sep 2** the `4xa6000` runner has been offline. Since then,
`benchmark_regression` has queued on a dead label on **every single GPU
Tests run**, hit GitHub's 24h self-hosted queue timeout, and failed the
workflow. There has not been one green GPU Tests run in over a month, so
the per-PR GPU check is permanently red and real regressions hide in the
noise. Measured over Sep 29-Oct 6: all 28 completed runs failed at
exactly 1440 +/- 1 min, and 20+ phantom `benchmark_regression` jobs were
sitting in the queue at any time.

## What changes

1. **uv cache on the GPU jobs** (`enable-cache: true`, keyed on
`uv.lock`, mirroring `cpu_tests.yaml`) — each h200 pod currently
re-resolves and re-downloads the full dependency set from PyPI on every
job.
2. **`benchmark_regression` removed from the PR matrix.** It cannot
simply move to `prime-rl-2xh200`: the test unconditionally runs a 1-GPU
**and** a 4-GPU benchmark (a 2-GPU pod cannot host the latter), and it
asserts against A6000-captured baselines with a 15% tolerance (H200
results would blow through it). It belongs on benchmark hardware
(`benchmarks.yaml`) or behind a 4-GPU scale set when one exists — happy
to re-add once either exists.
3. **`max-parallel: 5` on the integration matrix** — a concrete per-PR
ceiling:
- 9 integration jobs + unit-tests = **6 h200 pods peak per PR**, 2 waves
- at current job durations (~10-15 min each) a PR finishes in ~25-35 min
- with 2-3 PRs in flight: <= ~18 pods steady-state; the ARC scale set
`maxRunners` (suggest 16-20) is the complementary global cap
4. `docs/development.md` CI table updated to match (also adds
`gsm8k_eval`, which was missing, and the current runner).

## Result

GPU Tests runs **only** on the `prime-rl-2xh200` scale set, and every PR
gets a real green or red within ~30-60 min instead of a guaranteed 24h
failure.

## Not in this PR (follow-ups)

- Bake git/uv into the CI image to kill the per-job `apt-get install
git`
- PVC-backed `~/.cache/uv` mount to avoid per-pod cache archive
downloads
- Nightly Tests still target a `research-cluster` runner that does not
exist — needs the same treatment or a cron disable

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> CI workflow and documentation only; no runtime or auth changes.
Benchmark regression no longer runs on every PR until re-homed to
suitable hardware.
> 
> **Overview**
> **GPU Tests** is adjusted so PR runs can finish on live hardware
instead of timing out on a dead runner label.
> 
> Both GPU jobs now enable **uv dependency caching** keyed on `uv.lock`
(same pattern as `cpu_tests.yaml`), cutting repeated PyPI
resolves/downloads on each H200 pod. The integration matrix **drops
`benchmark_regression`** (it targeted offline `4xa6000` hardware and
cannot run meaningfully on 2×H200), and adds **`max-parallel: 5`** so at
most five integration jobs run at once per PR. **`docs/development.md`**
updates the CI table to list the current integration scenarios
(`gsm8k_eval` included), `max-parallel`, and **`prime-rl-2xh200`** as
the runner.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8207cc05d9a731a4c5d7c561354284f1a79792d4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 15:18:58 -07:00
1983d8dfed chore: bump verifiers to main (#3934)
## Summary

- Bump `deps/verifiers` from `1fa2bbc42` to main `da75527ca`. This pulls
in the Harbor adapter changes from PrimeIntellect-ai/verifiers#2808:
  - Honor reward-file precedence and select named rewards explicitly.
  - Resolve separate verifier definitions by Harbor image precedence.
  - Align the adapter with Harbor 0.24.0 and reject multi-step tasks.
- Move the `harbor` upload cutoff in `[tool.uv.exclude-newer-package]`
from 2026-08-11 to 2026-10-08, which matches `deps/verifiers`. verifiers
now pins `harbor==0.24.0`, which the old cutoff excluded.
- Relock: `harbor` 0.21.0 → 0.24.0, and `semver` 3.1.0 is new.

`deps/prime-envs` is already at its main head (`89dcc7ffc`). The current
verifiers pin already has the network notice
(PrimeIntellect-ai/verifiers#2769), so this bump supersedes #3734.

## Verification

- `uv sync --all-extras --all-packages --locked` succeeds.
- `uv run pytest -m "not gpu" tests/unit`: 663 passed.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Lockfile and uv policy changes only; risk is mainly behavioral shifts
from Harbor 0.24.0 and updated verifiers Harbor adapter usage in
eval/training paths.
> 
> **Overview**
> Updates dependency resolution so **`harbor` 0.24.0** (via the
`verifiers[harbor]` pin) can install under uv’s rolling
**exclude-newer** policy by moving the bounded **`harbor` cutoff** from
`2026-08-11` to **`2026-10-08`** in `pyproject.toml`, mirrored in
`uv.lock`.
> 
> The lockfile refresh bumps **`harbor` 0.21.0 → 0.24.0**, records new
transitive deps **`jsonschema`** and **`semver`**, and aligns the
verifiers harbor extra specifier to **`==0.24.0`**. This pairs with the
verifiers main bump described in the PR (Harbor adapter alignment and
reward/verifier precedence behavior), even though those code changes
live outside this diff.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
69e62c1fc116896ce99c79dbfc454959c748cb47. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:18:33 -07:00
26681fc6c7 fix(models): pass contiguous router-replay experts to compiled layers (#3947)
On torch 2.13.0 with compile and router replay, some MoE layers silently
replay layer 0's routing instead of their own from the second training
step on. This PR calls `.contiguous()` on each layer's routed-experts
slice, which removes the bug.

Each decoder layer `l` receives `routed_experts[:, :, l]`, a view into
one shared int32 tensor with axes (batch, sequence, layer, expert slot).
When `top_k` is not a multiple of 4, that view starts at a byte offset
that is not 16-byte aligned for some layers (odd layers on DeepSeek V4,
`top_k = 6`).

Inductor copies a misaligned input into a fresh aligned buffer, which
starts at offset 0. Once automatic dynamic shapes recompile the layer,
AOTAutograd mistakenly applies that offset 0 to the original shared
tensor when it rebuilds the layer's routed-experts output. Offset 0 of
the shared tensor holds layer 0's experts. A contiguous slice is its own
aligned tensor, so Inductor never makes the copy.

- Applied to the eight models that passed the raw view. `glm4_moe`
already called `.contiguous()`.
- Fixed upstream in pytorch/pytorch#191002 (torch 2.14.0 and 2.14.1, no
2.13.x release). The copy is cheap, so it can stay after an upgrade.
- Models with `top_k = 8` (Qwen3-30B-A3B, Trinity-Mini, GLM-4.5-Air)
were unaffected.

DeepSeek V4 Flash RL probe (compile on, router replay on, lr 0),
mismatch KL mean, lower is better:

| trainer | step 1 | steps 2-10 |
|---|---|---|
| compiled, strided slice (main) | 0.0008 | 0.022-0.11 |
| compiled, contiguous slice (this PR) | 0.0009 | 0.0007-0.0025 |

With compile off, the same probe spans 0.0008-0.0032 over steps 1-10.

## Verification

A standalone torch reproducer was added in
66641b0b0b31da76082edaadd70b4f601b13a53a and removed again at the end of
this branch, so main never carries it. Run it on one CUDA device from
that commit with `TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 uv run python
tools/repro_misaligned_replay_alias.py`. In earlier runs it printed `BUG
REPRODUCED` on torch 2.13.0 and was clean on the 2.14.0.dev20260809 and
2.16.0.dev20261008 nightlies.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 17:03:55 -04:00
Florian BrandandGitHub 6b0906c900 fix(eval): preserve sibling trace verdicts when an episode fails (#3824) 2026-10-08 12:12:16 -07:00
JannikStandGitHub 5e963f027a fix(monitors): send online-eval metrics to the parent training run (#3941)
Hosted runs with online evals score real rewards but the run dashboard
shows no `eval` metric group (ENG-6573).

The dashboard's `eval` group is built from the run's own metric keys
(`eval/{env}/...`). The orchestrator's in-process evals reach it through
the train monitor, but when evals run in a process of their own (SFT
online evals) the metrics are dropped: `PrimeEvalMonitor.log_metrics`
was a deliberate no-op.

- `PrimeEvalMonitor` now attaches to the parent training run via
`$RUN_ID` and forwards each epoch's `eval/...` metrics there.
- The eval process never reports the parent run's status: the SDK's
atexit crash hook is unregistered and `finalize()` only drains the
queue. Without that, an eval process exiting while the trainer is still
going would mark the whole run failed.
- No parent attached without `$RUN_ID`, so a standalone `prime eval` is
unchanged.

Note the ticket proposes exposing `environmentshub/resolve` on the
platform's internal API instead. That's a separate gap: it silences the
`EnvironmentResolutionError` warning and would create per-epoch
Evaluation records, but it does not produce the `eval` metric group, and
it needs four more `/evaluations` routes that the internal surface also
lacks.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how eval processes interact with the parent platform run
(metrics + SDK lifecycle hooks); mistakes could misreport run status or
drop metrics, but behavior is gated on $RUN_ID and explicitly avoids
finishing the parent.
> 
> **Overview**
> Fixes hosted runs where **SFT online evals** compute rewards but the
run dashboard never shows the **`eval`** metric group (keys like
`eval/{env}/...`).
> 
> **`PrimeEvalMonitor`** now attaches a metrics-only handle to the
parent training run when **`$RUN_ID`** is set, and **`log_metrics`**
forwards sanitized epoch aggregates there instead of being a no-op.
Standalone **`prime eval`** (no **`$RUN_ID`**) is unchanged.
> 
> Lifecycle is guarded so the eval subprocess cannot poison the parent
run: the SDK **atexit** hook on the attached parent is **unregistered**,
and **`finalize()`** only **`flush`**es the upload queue—never finishes
or reports status on the trainer’s run.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
892035628173119b14a591b2975a5b6176f4c357. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 19:44:51 +02:00
72834b3b52 feat(trainer): prepare RL micro batches on a background thread pool (#3917)
This is an alternative to #3907. The RL trainer decoded and preprocessed
each micro batch's images on the main thread right before its forward
pass, leaving the GPU idle. `WorkerPool`, a small ordered thread pool
configured by `data.num_workers` like torch's DataLoader, now prepares
micro batches ahead of the loop through a single `prepare_micro_batch`
hook.

- `num_workers` defaults to 0, which prepares on the main thread as
before, and one thread gives the full speedup. Here it counts threads,
unlike SFT's DataLoader processes.
- An earlier version used forked worker processes. They pickle data
through `/dev/shm`, risk copy-on-write memory, and were 0.6 s/step
slower than a thread.
- Pinned memory and `non_blocking` copies are left to a follow-up that
first removes the per-micro-step CUDA syncs.

Qwen3.5-9B trainer-only on 4 H200s, mock micro batches of 1024 px JPEGs
(about 1 s of CPU decoding each), median s/step, lower is better
(benchmark code added in
[`331fc83fe`](https://github.com/PrimeIntellect-ai/prime-rl/commit/331fc83fed9ff8b6fb435df5207a07e37b08c0e5)
and removed in the next commit):

| Arm | main thread | prepared ahead | time saved |
|---|---|---|---|
| this PR, 1 thread | 24.98 | 18.86 | 24.5% |
| this PR, 1 thread, optimizer CPU offload | 26.56 | 20.24 | 23.8% |
| earlier process version, 2 workers | 24.79 | 19.02 | 23.3% |
| #3907 (thread with pinned memory) | 24.98 | 18.63 | 25.4% |

Every arm matches the main-thread baseline bit for bit in loss and grad
norm. Host memory stays flat over 30 steps, 0.3 GiB above the baseline
for the prefetched images.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 12:15:19 -04:00
faresobeidandGitHub 0bcb868e91 fix(configs): size the single-node NCCL transfer group after the DP fill (#3841)
## Summary
Two bugs in how `rl` sets `weight_broadcast.inference_world_size` on
main:

1. **World size computed before the DP fill.**
`auto_setup_weight_broadcast` set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
before `auto_setup_deployment` fills the single-node inference GPUs with
DP ranks. With `num_infer_gpus = 4` and `data_parallel_size` unset, the
NCCL group was sized for 1 inference worker while vLLM started 4, so the
first weight update cannot form the group.
2. **A single-node SLURM job cannot re-parse its `rl.json`** (since
#3788). The resolved `rl.json` always contains
`weight_broadcast.inference_world_size` (default 1), and #3788's guard
rejects any config that sets it. So `rl @ rl.json` in the single-node
sbatch fails validation for every NCCL config.

## Fix
- Single-node: set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
right after the DP fill in `auto_setup_deployment` (non-filesystem
only). Multi-node already sets it there.
- `auto_setup_weight_broadcast` copies `weight_broadcast` to the trainer
and orchestrator without touching the world size, and the guard is
removed. The top-level value is now only passed through: `rl` overwrites
it whenever it knows the inference size.

This also fixes what #3924 fixes.

## Behavior change
Yes (bug fixes).
- Resolved configs for every TOML in `configs/`, `examples/`, `k8s/`
that parses as `RLConfig` (41 of 78) are identical before and after,
except `trainer`/`orchestrator.weight_broadcast.inference_world_size`
goes from 1 to 4 in `examples/basic/hendrycks-sanity/rl.toml` and
`configs/ci/nightly/multimodal_color_codeword.toml` (4 infer GPUs, DP
unset).
- Re-parsing the dumped config (as the single-node sbatch does) fails on
main for all 18 single-node NCCL configs and passes for all of them
here.
- With `inference = None` and NCCL against external servers, a user-set
`weight_broadcast.inference_world_size` is now passed through instead of
rejected.

## Checks
- `pytest tests/unit/test_configs.py tests/unit/orchestrator -m "not
gpu"`: 298 passed
- `ruff check`, `ruff format --check`: clean
- New test `test_single_node_nccl_resolved_json_roundtrips`: dumps a
single-node NCCL config like `rl`'s `write_config`, re-parses it, and
checks it is equal. It fails on main with the guard error.
- `rl @ examples/basic/reverse-text/rl.toml --deployment.num-infer-gpus
2 --slurm.partition all --dry-run`, then re-parse the written `rl.json`:
fails on main, passes here (world size 2).
- GPU (one node): running: `rl @ examples/basic/hendrycks-sanity/rl.toml
--max-steps 3` on main and on this branch, plus the rendered single-node
sbatch for reverse-text (2 infer GPUs) run end to end.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes when NCCL weight broadcast groups are sized for single-node
runs; mis-sizing previously caused deadlocks or init failures during
weight updates.
> 
> **Overview**
> Fixes incorrect **NCCL/NIXL** `inference_world_size` on single-node RL
runs when vLLM **data parallel size** is inferred from `num_infer_gpus`
rather than set explicitly.
> 
> **`auto_setup_weight_broadcast`** no longer derives
`trainer`/`orchestrator.weight_broadcast.inference_world_size` from
`data_parallel_size × tensor_parallel_size` (which ran before DP was
filled) and no longer rejects a user-set `inference_world_size`.
**`auto_setup_deployment`** (single-node) now sets
`inference_world_size` to `dp × tensor_parallel_size` immediately after
the DP/`api_server_count` fill, so the in-memory transfer group matches
every inference GPU that joins NCCL.
> 
> Unit tests assert the resolved world size (2 infer GPUs → size 2) and
that a dumped `rl.json` round-trips unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f5553f5c5dd2f91aa11003338ef13e285a6c9ee6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 12:56:47 +01:00
faresobeidandGitHub 746d8a96d0 chore(models): drop rms_norm re-export, move fp8 quantizer into its tool (#3858)
## Summary
- Delete `trainer/models/layers/rms_norm.py`. It only re-exported
`RMSNorm`/`RMSNormConfig` from `layers/norms.py`, and nothing imported
it.
- Move `quantize_to_fp8_blockwise` from `trainer/models/fp8.py` into
`tools/convert_bf16_to_fp8.py`, its only user.
`tools/convert_dcp_to_fp8.py` still imports it through
`convert_bf16_to_fp8`. While moving it, the 9-line zero-pad block
becomes `F.pad(weight, (0, pad_cols, 0, pad_rows)).contiguous()`; the
output is bitwise identical to the old function (bf16/fp16/fp32, padded
and unpadded shapes, contiguous and transposed inputs).

## Behavior change
None.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dead-code removal and relocating a tool-only quantizer; no trainer
inference or training path changes.
> 
> **Overview**
> Removes dead trainer surface area and keeps FP8 checkpoint conversion
self-contained in the tooling layer.
> 
> **`trainer/models/layers/rms_norm.py`** is deleted (it only
re-exported `RMSNorm` / `RMSNormConfig` with no importers).
**`trainer/models/fp8.py`** is removed and
**`quantize_to_fp8_blockwise`** now lives in
**`tools/convert_bf16_to_fp8.py`**, which was its only consumer;
**`convert_dcp_to_fp8.py`** continues to pull quantization helpers from
that script. Padding inside the moved helper uses **`F.pad`** instead of
manual zero-fill, with the same blockwise e4m3 logic otherwise
unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c35ca75057037c6d98f0080bdffae8efd24e2f85. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 12:46:12 +01:00
faresobeidandGitHub 765bbeba7b fix(launch): default TRITON_CACHE_DIR to a node-local path (#3877)
Processes that share `~/.triton` on a shared filesystem can hang or
crash (seen with Nemotron-H, where many ranks compile the Mamba Triton
kernels at once; reproduced below with Qwen3.5 and GLM-4.5-Air).

This PR adds `TRITON_CACHE_DIR = /tmp/triton-<uid>` to
`DEFAULT_COMMON_ENV_VARS`. It is per-user because `/tmp` is shared by
all users on a node. Like the other launcher defaults, it reaches every
launched component: the local `rl`/`sft`/`inference` launchers (also
used by the single-node sbatch scripts) and the trainer, orchestrator,
inference (incl. prefill/decode), and online-eval env blocks of the
multi-node and inference sbatch scripts. `[env_vars]` (or a component's
`env_vars`) overrides it; a value exported in the shell or `.env` does
not. It also removes the `TRITON_CACHE_DIR` overrides from six example
configs (glm-4.5-air swe/swe-budget/search/terminal, glm-5.3 and
qwen3-30b-a3b sft h200 base): they pointed every user at the same `/tmp`
dir and are now covered by the default. `docs/scaling.md` says so in one
paragraph.

vLLM 0.31's own default: when `TRITON_CACHE_DIR` is unset, its Inductor
adaptor points it at
`$VLLM_CACHE_ROOT/torch_compile_cache/<hash>/rank_<i>_<j>/triton_cache`
(`~/.cache/vllm` by default, so usually on the shared home). That only
covers Triton kernels compiled after torch.compile initializes, and it
is still on the shared filesystem. vLLM keeps a `TRITON_CACHE_DIR` that
is already set, so with this PR vLLM uses `/tmp/triton-<uid>` too.

### Measured cost (one H200 node, vLLM 0.31 venv, Triton 3.7.1)

Each run starts from a fresh process with the same config. "Ready" is
launch → first trainer step logged (Qwen) or launch → `/health` OK
(GLM). For GLM, the first generated token came 1.3–2 s after ready in
every run that came up. Inductor's cache dir was emptied before each run
except the warm node-local one.

| Triton cache | Qwen3.5-4B SFT, 8 GPUs, compiled blocks (step 1 time) |
GLM-4.5-Air vLLM TP8 |
|---|---|---|
| shared, cold (today on a new cluster / after a Triton or torch update)
| **failed 2/2**: `FileNotFoundError` on a cache file that another rank
was writing (`causal_conv1d_fwd_kernel.llir`, `l2norm_fwd_kernel.ptx`) |
**failed 2/2**: 4 of 8 ranks hit `FileNotFoundError` in the cache during
Inductor autotune, the other 4 hung in a collective until killed (1st
run). The 2nd run crashed instead of hanging. |
| shared, warm | not measured cleanly (see below) | 344 s |
| node-local, cold (this PR, first job on a node) | 233 s (step 1: 91
s), 164 kernels compiled | 375 s with vLLM's compile cache warm (106
kernels); 465 s if vLLM's cache is also cold (87 kernels) |
| node-local, warm (this PR, later jobs on the same node) | 138 s (step
1: 8.3 s) | 344 s |

- A cold node-local cache costs about **95 s per node for Qwen3.5** (FLA
+ Inductor kernels) and about **31 s for GLM-4.5-Air inference** when
vLLM's own compile cache is warm. Warm node-local and warm shared take
the same time.
- The rest of the GLM startup does not depend on the Triton cache: about
3.5 min of Python imports and process spawn from the shared venv, 13 s
to load weights.
- vLLM: `VLLM_CACHE_ROOT` (`~/.cache/vllm`, shared home) holds vLLM's
AOT/Inductor artifacts. With this PR it stays shared. On a new node,
vLLM loads those artifacts (`torch.compile` 0.6 s instead of 30 s), and
the Triton binaries are compiled into `/tmp/triton-<uid>` (106 kernels,
+31 s). `TORCHINDUCTOR_CACHE_DIR` (default `/tmp/torchinductor_<user>`,
already node-local) stayed empty in these runs. Inductor's Triton
kernels go to `TRITON_CACHE_DIR`.
- A crash on the shared cache can also break later starts. After the
first failed GLM run, the shared vLLM cache only had AOT artifacts from
the 4 ranks that got through. On the next start, those 4 ranks loaded
the artifacts and the other 4 recompiled, so the ranks diverged and hung
(Triton cache warm-ish, 60 kernels). For the same reason the Qwen
"shared, warm" run started from a partial cache and failed again. The
warm-shared GLM number comes from a shared dir seeded with a complete
cache.

### Possible middle ground (not implemented)

Because the cold cost is above 1 min per node for FLA-heavy models, a
run could seed the node-local cache from a shared read-only copy at job
start. For example, on each node before the components start:
`[ -n "$TRITON_CACHE_SEED" ] && cp -rn "$TRITON_CACHE_SEED"/.
"$TRITON_CACHE_DIR"/`
The seed would be a warm `/tmp/triton-<uid>` copied once to the shared
FS. Triton keys entries by source, compiler, and GPU, so stale entries
are never reused, only skipped. Only reads hit the shared FS, so the
concurrent-write race does not occur. I left it out to keep this PR
minimal.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Launch-time env default only; behavior is overridable via config and
fixes known multi-rank Triton cache races, with a one-time cold-compile
cost on each node.
> 
> **Overview**
> **Sets a global launcher default** so every trainer, orchestrator, and
inference process gets `TRITON_CACHE_DIR=/tmp/triton-<uid>` via
`DEFAULT_COMMON_ENV_VARS`, avoiding concurrent Triton kernel writes
under `~/.triton` on a shared filesystem (hangs / `FileNotFoundError`
under multi-rank compile).
> 
> **Removes redundant `[env_vars]` overrides** from six GLM-4.5-Air RL
and GLM-5.3 / Qwen3-30B SFT example configs that previously pinned
Triton cache paths under `/tmp`; those runs now inherit the per-user
node-local default (still overridable through config `env_vars`).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f21642046ea59cab0b9460863560b4df825f29c0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
2026-10-08 11:59:17 +01:00
faresobeidandGitHub fec3acd8e7 chore(orchestrator): fold GenerationSource into TrainEnv (#3838)
## Summary
Fold `GenerationSource` into `TrainEnv`, its only owner. Move
`connect_frozen_client` from `algo/base.py` to `clients.py`, so `algo`
no longer imports `clients` lazily. Give `TrainEnv` `setup()`/`aclose()`
so orchestrator setup and teardown no longer reach into its parts.

## What changed
- `orchestrator/generation_source.py` is deleted. `TrainEnv` (`envs.py`)
now holds `clients`, `renderer_config`, `connected` (the frozen source
clients it connected) and `uses_live_policy`. Dropping `logprobs` for
frozen sources happens in `TrainEnv.__init__`.
- `TrainEnv.setup()` connects the frozen generation source and runs
`algorithm.setup()` concurrently. `TrainEnv.aclose()` closes `connected`
and `algorithm.connected`, never the shared policy clients.
- `connect_frozen_client` is a plain function in `clients.py`, next to
`check_inference_ready`. `algo/base.py` imports it at module level. It
is no longer re-exported from `prime_rl.orchestrator.algo`.
- `dispatcher.py` reads the `TrainEnv` directly at the four former
`generation_source` call sites. `orchestrator.py` calls `env.setup()`
and `env.aclose()`.
- `docs/algorithms.md` and the `algo/__init__.py` docstrings refer to
`TrainEnv`.

## Behavior change
None.

## Checks run
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 297 passed.
- `ruff check`, `ruff format --check`: clean.
- Equivalence script, old `GenerationSource` (`origin/main`) vs new
`TrainEnv`, on 4 configs: policy, policy with `top_p=0.9`, sft with a
frozen `sampling.source`, opd with a frozen teacher. Identical
`sampling_args`, `requires_sampling_masks` and `uses_live_policy`. After
`setup()`, the same generation clients (policy object, or the frozen
endpoint with the same train client config) and the same algorithm
clients. Teardown closes the same clients.
- GPU smoke on one node (vLLM 0.31): reverse-text RL (15 steps), sft
with a frozen `sampling.source` (5 steps), opd with a frozen teacher (5
steps). All three ran to "Training finished" and exited 0.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Internal orchestrator refactor with stated behavioral equivalence and
no changes to training algorithms or dispatch semantics beyond
indirection.
> 
> **Overview**
> **Refactors train rollout sourcing** by deleting `GenerationSource`
and moving its responsibilities onto `TrainEnv`: inference `clients`,
live-vs-frozen policy detection (`uses_live_policy`), sampling-arg
tweaks (e.g. dropping `logprobs` for frozen endpoints), and frozen-pool
connection in `setup()`.
> 
> `TrainEnv.setup()` now connects frozen `sampling.source` endpoints and
runs `algorithm.setup()` together; `TrainEnv.aclose()` closes only
env-owned clients (`connected` + algorithm pools), not the shared policy
pool. The orchestrator and dispatcher call these surfaces instead of
reaching into a nested `generation_source`.
> 
> `connect_frozen_client` moves from `algo/base.py` to `clients.py`
(next to `check_inference_ready`); it is no longer re-exported from
`prime_rl.orchestrator.algo`. Docs and package docstrings now describe
`TrainEnv` as owning the sampling half of the algorithm config.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e89ca1a663ae6ae808b05ff3326ce9ed63c9b467. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 11:52:10 +01:00
Florian BrandandGitHub adda4731fe fix(eval): salt inference caches only when policy weights change (#3825)
Apply a policy-version cache salt only when inference weights can change
during a run. Standalone evaluations and frozen-model requests omit the
training salt; live RL rollouts and online evaluation retain it so
caches distinguish policy versions.

## Before

The dispatcher added the policy version as `cache_salt` to every request
using the live policy source. Standalone evaluation used that same
source path, so fixed-weight evaluations received a training cache salt
even though no weight updates occurred. Frozen-model requests already
omitted it.

```mermaid
flowchart TD
    Standalone["Standalone evaluation with fixed weights"] --> Live["Live policy source"]
    Training["RL or online evaluation with changing weights"] --> Live
    Live --> Salt["Always add policy-version cache_salt"]
    Salt --> Request["Verifiers provider request"]
    Frozen["Frozen model source"] --> Plain["Omit training cache_salt"]
    Plain --> Request
```

## After

```mermaid
flowchart TD
    Request["Prime-RL dispatcher builds request sampling"] --> Mode{"Live policy source with changing weights?"}
    Mode -->|"Yes: RL or online evaluation"| Salt["Set cache_salt to policy version"]
    Mode -->|"No: standalone evaluation or frozen model"| Plain["Omit training cache_salt"]
    Salt --> Client["Verifiers client builds provider request"]
    Plain --> Client
    Client --> Provider["Inference provider"]
```

The dispatcher records whether policy weights can change. The standalone
evaluator disables version salting, SFT online evaluation enables it,
and RL orchestration keeps it enabled. The request decision also checks
whether the source uses the live policy.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Narrow behavior change to cache salting on eval paths; RL and online
eval keep prior salting via the default flag.
> 
> **Overview**
> Adds a **`policy_weights_change`** flag on `Dispatcher` so inference
**`cache_salt`** (policy version) is only attached when weights can
actually change during the run.
> 
> **Standalone eval** (`EvalConfig`) sets the flag to **false**, so
fixed-weight evaluation no longer invalidates prefix caches on every
training policy version. **SFT online eval** and **RL orchestration**
(default **true**) still salt live-sourced requests so caches stay
correct across weight updates.
> 
> The cache decision is now **`live_sourced and policy_weights_change`**
instead of salting all live policy paths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5a2d7d9652740106e63fee31a6e79da13816dae7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 01:52:39 -07:00
Florian BrandandGitHub a3f1f892c5 fix(eval): preserve empty outcomes and exclude zero-turn traces from training (#3809)
Keep successful empty environment outcomes in evaluation results. A
trace-less episode or clean zero-turn trace retains the verdict returned
by Verifiers, while training and curriculum logic exclude zero-turn
traces.

## Before

The dispatcher changed successful trace-less episodes into
`EmptyEpisode` failures. Clean, non-timeout zero-turn traces became
`EmptyTrajectory` failures, marking both the trace and episode
unsuccessful. Evaluation therefore recorded a failure even when the
environment had returned success, while training and curriculum filters
relied on those injected errors to exclude empty traces.

```mermaid
flowchart TD
    Env["Verifiers returns an empty successful outcome"] --> Dispatch["Prime-RL dispatcher"]
    Dispatch --> Episode["No traces: inject EmptyEpisode"]
    Dispatch --> Trace["Clean zero-turn trace: inject EmptyTrajectory"]
    Episode --> Failed["Rewrite outcome as failed"]
    Trace --> Failed
    Failed --> Eval["Evaluation records a failure"]
    Failed --> Training["Training and curriculum filter injected errors"]
```

## After

```mermaid
flowchart TD
    Env["Verifiers environment returns an episode"] --> Dispatch["Prime-RL dispatcher preserves empty outcome verdicts"]
    Dispatch --> Eval["Evaluation records and metrics"]
    Dispatch --> Filter["Training trace eligibility"]
    Filter --> Empty["Zero turns: no training sample"]
    Filter --> Sample["Eligible trace with sampled tokens: training sample"]
    Dispatch --> Curriculum["Curriculum ignores zero-turn traces and admits only trainable groups"]
```

Remove the synthetic `EmptyEpisode` and `EmptyTrajectory` errors.
`iter_trainable_traces()` filters empty traces alongside failed and
untrainable traces before advantages are assigned, so the advantage gate
needs no separate zero-turn check. Difficulty sampling also excludes
zero-turn traces. Empty groups finish without producing a trainer
payload, and mixed groups retain their eligible traces. Curriculum
admission also requires a trainable trace, so groups without training
samples cannot inflate admission metrics. Sampler observations of
completed turns are retained even when token metadata is unavailable.
Verifiers' no-agent validation and training timeout handling remain in
place.

[#3824](https://github.com/PrimeIntellect-ai/prime-rl/pull/3824) applies
the same ownership rule to partially failed episodes: preserve
environment results, then decide training eligibility explicitly.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes evaluation outcome recording and which rollouts feed
training/curriculum admission, which can shift eval metrics and training
batch composition without touching auth or data stores.
> 
> **Overview**
> Stops the dispatcher from **injecting** `EmptyEpisode` /
`EmptyTrajectory` errors on successful trace-less or zero-turn outcomes,
so **evaluation keeps Verifiers’ success verdict** instead of recording
synthetic failures.
> 
> Training and curriculum now **exclude zero-turn traces explicitly**:
`iter_trainable_traces()` skips `num_turns == 0`, difficulty-pool reward
updates require `num_turns > 0`, and curriculum admission requires
**both** passing gates **and** at least one trainable trace via
`iter_trainable_traces()`. Scored rollouts without token/advantage
metadata can still update sampler difficulty; groups with no trainable
samples no longer count as admitted.
> 
> Tests cover mixed groups with non-trainable traces, empty-only groups,
and reward-only observations for the sampler.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8582fb8c18e7cb4aa0dc7af58c6e0a4474bd7b40. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 01:51:52 -07:00
Florian BrandandGitHub e6acff78aa chore: align network prompt dependency pins (#3929) 2026-10-07 19:45:14 -07:00
72 changed files with 1057 additions and 600 deletions
+20 -5
View File
@@ -192,6 +192,12 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
with:
# CVE-2026-93318: pin the BuildKit builder to the patched release so
# the version is deterministic on the self-hosted runners (otherwise
# the rolling moby/buildkit:buildx-stable-1 tag is used, and a
# persistent runner may keep a stale local copy of it).
driver-opts: image=moby/buildkit:v0.33.1@sha256:cec9f139f45e93c5c69c60f8b07cfad9f43f4ef6b6a6cd917527fea5ff2e3dea
- name: Set up uv
uses: astral-sh/setup-uv@v7
@@ -207,7 +213,12 @@ jobs:
run: |
set -euo pipefail
key=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py fingerprint .)
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-${SUFFIX}"
# deps-v2: remediation epoch for CVE-2026-93318 — the fingerprint
# hashes only Dockerfile/lock inputs, not the workflow or BuildKit
# version, so pre-fix deps-${key} images would otherwise be reused
# as the runtime base instead of being rebuilt by the pinned v0.33.1
# builder.
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-v2-${SUFFIX}"
digest=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py resolve "$image")
echo "image=${image}" >> "$GITHUB_OUTPUT"
echo "digest=${digest}" >> "$GITHUB_OUTPUT"
@@ -222,8 +233,10 @@ jobs:
file: ./Dockerfile.cuda
target: dependencies
outputs: type=image,push=true,compression=zstd,compression-level=3
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
# builders (cache writers since 2026-08-16) must not be re-imported.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: ${{ steps.dependency.outputs.image }}
@@ -240,8 +253,10 @@ jobs:
RENDERERS_PRETEND_VERSION=${{ steps.dependency.outputs.renderers }}
PYDANTIC_CONFIG_PRETEND_VERSION=${{ steps.dependency.outputs.pydantic_config }}
outputs: type=image,push=true,compression=zstd,compression-level=3
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
# builders (cache writers since 2026-08-16) must not be re-imported.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
+14 -9
View File
@@ -6,6 +6,10 @@ on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
unit-tests:
name: Unit tests
@@ -15,15 +19,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run tests
+156 -47
View File
@@ -5,20 +5,103 @@ on:
branches: [main]
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
changes:
name: Select tests
runs-on: ubuntu-latest
if: github.event_name != 'pull_request' || github.event.pull_request.draft == false
permissions:
pull-requests: read
outputs:
unit: ${{ github.event_name != 'pull_request' || steps.filter.outputs.unit == 'true' }}
integration: ${{ steps.matrix.outputs.tests }}
eval: ${{ github.event_name != 'pull_request' || steps.filter.outputs.eval == 'true' }}
steps:
- uses: dorny/paths-filter@v4
id: filter
if: github.event_name == 'pull_request'
with:
filters: |
unit:
- &runtime
- '.github/workflows/gpu_tests.yaml'
- '{pyproject.toml,uv.lock,.python-version,.gitmodules}'
- 'deps/**'
- 'packages/**/pyproject.toml'
- 'packages/prime-rl-configs/src/prime_rl/configs/{trainer,shared,__init__}.py'
- 'packages/prime-rl-configs/src/prime_rl/utils/**'
- 'src/prime_rl/*.py'
- 'src/prime_rl/{trainer,multimodal,transports,utils}/**'
- 'tests/{__init__.py,conftest.py,utils.py}'
- 'tests/integration/{__init__.py,conftest.py}'
- 'tests/unit/{train,inference}/**'
- 'src/prime_rl/inference/**'
sft:
- *runtime
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
- 'src/prime_rl/dashboard/**'
- 'tests/integration/dashboard_smoke.py'
- 'packages/prime-rl-configs/src/prime_rl/configs/{sft,eval,monitors}.py'
- 'src/prime_rl/entrypoints/{sft,dashboard}.py'
- 'src/prime_rl/monitors/**'
- 'src/prime_rl/eval/{online,runner}.py'
- 'tests/integration/test_reverse_text_sft{,_lora}.py'
- 'configs/ci/integration/reverse-text-sft{,-lora}/**'
rl:
- *runtime
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
- 'src/prime_rl/dashboard/**'
- 'tests/integration/dashboard_smoke.py'
- 'packages/prime-rl-configs/src/prime_rl/configs/{rl,orchestrator,inference,env_server,algorithm,eval,monitors}.py'
- 'src/prime_rl/entrypoints/{rl,trainer,inference,orchestrator,env_server,dashboard}.py'
- 'src/prime_rl/{inference,orchestrator,monitors}/**'
- 'src/prime_rl/eval/{online,runner}.py'
- 'tests/integration/test_reverse_text{,_lora,_moe,_rl_opd,_rl_sft}.py'
- 'tests/integration/test_alphabet_sort.py'
- 'configs/ci/integration/reverse-text{,-lora,-moe,-rl-opd,-rl-sft}/**'
- 'configs/ci/integration/alphabet_sort.toml'
eval:
- *runtime
- 'packages/prime-rl-configs/src/prime_rl/configs/{eval,orchestrator,inference,env_server,algorithm,monitors}.py'
- 'src/prime_rl/{eval,orchestrator,monitors}/**'
- 'src/prime_rl/entrypoints/{eval,env_server}.py'
- 'tests/integration/test_gsm8k_eval.py'
- 'configs/ci/integration/gsm8k-eval.toml'
- name: Build integration matrix
id: matrix
env:
# Main and manual runs retain the full suite.
RUN_ALL: ${{ github.event_name != 'pull_request' }}
SFT: ${{ steps.filter.outputs.sft || 'false' }}
RL: ${{ steps.filter.outputs.rl || 'false' }}
run: |
tests=$(jq -cn --argjson all "$RUN_ALL" --argjson sft "$SFT" --argjson rl "$RL" '[
if $all or $sft then "reverse_text_sft", "reverse_text_sft_lora" else empty end,
if $all or $rl then
"reverse_text", "reverse_text_rl_opd", "reverse_text_rl_sft",
"alphabet_sort", "reverse_text_lora", "reverse_text_moe"
else empty end
]')
echo "tests=$tests" >> "$GITHUB_OUTPUT"
unit-tests:
name: Unit tests
needs: changes
runs-on: prime-rl-2xh200
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
timeout-minutes: 45
if: github.event_name == 'push' || github.event.pull_request.draft == false
if: needs.changes.outputs.unit == 'true'
steps:
- name: Install Git
run: |
@@ -29,12 +112,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run unit tests
@@ -50,46 +137,20 @@ jobs:
integration-tests:
name: Integration tests (${{ matrix.test }})
runs-on: ${{ matrix.runner }}
needs: changes
runs-on: prime-rl-2xh200
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
timeout-minutes: 60
if: github.event_name == 'push' || github.event.pull_request.draft == false
if: needs.changes.outputs.integration != '[]'
strategy:
fail-fast: false
# Bound per-PR fan-out: at most 5 integration jobs at a time (plus unit-tests),
# i.e. 6 h200 pods per PR. Tune together with the ARC scale set maxRunners.
max-parallel: 5
matrix:
include:
- test: reverse_text_sft
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_sft.py"
- test: reverse_text_sft_lora
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
- test: reverse_text
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text.py"
- test: reverse_text_rl_opd
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
- test: reverse_text_rl_sft
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
- test: alphabet_sort
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_alphabet_sort.py"
- test: reverse_text_lora
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_lora.py"
- test: reverse_text_moe
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py"
- test: gsm8k_eval
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_gsm8k_eval.py"
test: ${{ fromJSON(needs.changes.outputs.integration) }}
steps:
- name: Install Git
run: |
@@ -100,12 +161,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run integration tests
@@ -120,7 +185,7 @@ jobs:
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
VLLM_WORKER_MULTIPROC_METHOD: spawn
run: uv run pytest -vvs ${{ matrix.pytest_args }}
run: uv run pytest -vvs tests/integration/test_${{ matrix.test }}.py
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v7
@@ -129,3 +194,47 @@ jobs:
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
eval-tests:
name: Integration tests (gsm8k_eval)
needs: changes
if: needs.changes.outputs.eval == 'true'
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
submodules: false
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run eval tests
env:
USERNAME_CI: CI_RUNNER
WANDB_MODE: offline
HF_TOKEN: ${{ secrets.HF_TOKEN }}
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
GITHUB_REF_NAME: ${{ github.ref_name }}
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
run: uv run pytest -vvs tests/integration/test_gsm8k_eval.py
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: gsm8k_eval-logs
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
+4
View File
@@ -9,6 +9,10 @@ on:
# This will trigger the workflow for pull requests to any branch
types: [opened, synchronize, reopened]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
ruff:
name: Ruff
+1 -1
+1 -1
+1 -1
View File
@@ -139,7 +139,7 @@ algo.type = "echo"
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
At runtime, each env's `TrainEnv` (`prime_rl.orchestrator.envs`) resolves the `sampling.source` model into the inference pool used for train episodes, and its resolved config builds one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
+4
View File
@@ -173,6 +173,10 @@ env.agent.runtime.type = "subprocess"
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — holds defaults for its sources. Every field that a group and its sources both have is a default: `env`, `sampling`, `select` and `group_size`, plus `algo` on the train group and `interval` on the eval groups of a training run. Each source inherits the fields that its group sets. One rule applies to all of them: nested blocks merge key by key, a source's own values win, and a block whose `type` (e.g. of `algo`) differs from the group's is the source's alone.
Sampling parameters use Verifiers' shared normalization: `max_tokens` and `max_completion_tokens` name the same limit, and `extra_body` parameters merge like top-level parameters. Agent overrides apply after source defaults; an explicit null clears an inherited parameter. Resolved sampling is recorded on each trace.
For live-policy training, set distribution parameters (`temperature`, `top_p`, `top_k`) on the source's `sampling` block. Every agent in that source, including non-trainable roles, may override only `max_tokens`, `reasoning_effort`, and `chat_template_kwargs`. These rules are checked when loading the config; evaluation and frozen-model sources allow general agent sampling overrides.
```toml
[orchestrator.train]
group_size = 16
+1 -1
View File
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
| Workflow | Trigger | What runs | Where |
|---|---|---|---|
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | relevant changes in non-draft PRs; full suite on push to `main` or manual dispatch | `pytest tests/unit -m gpu`, plus RL/SFT integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_sft_lora`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `alphabet_sort`) with `max-parallel: 5`; separate hosted `gsm8k_eval` job | self-hosted `prime-rl-2xh200` k8s scale set (2xH200); `ubuntu-latest` for test selection and hosted eval |
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
+2 -2
View File
@@ -82,7 +82,7 @@ Every source's env server is spawned by the eval process unless the source sets
## Resume
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: the episodes that landed rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch) and only the rollouts still owed run. Errored episodes and the ones the interruption cut off run again.
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: saved episodes with `episode.ok` rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch), and only the rollouts still owed run. Failed episodes and the ones the interruption cut off run again. Saved records that fail schema validation stop the resume before the current stream is archived.
```bash
uv run eval @ eval.toml --run.name my-eval
@@ -92,7 +92,7 @@ uv run eval @ eval.toml --run.name my-eval --resume
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
A landed episode counts toward the task with its `task.key`, so `select` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
A landed episode counts toward a selected task in the same source when their content hashes (`task.hash`) match. A task whose content changes runs again even if its public `task.key` stays the same. `select` and `group_size` may change between launches: each selected occurrence keeps up to `group_size` matching episodes, and only its missing rollouts run. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Each selected occurrence owns a separate group containing its restored and new rollouts, even when the same task is selected more than once, so pass@k and the dashboard see one group per selected occurrence. Use `--clean` to start over instead.
## Monitors
+4
View File
@@ -159,6 +159,10 @@ messages = "conversation"
tools = "schemas"
```
**Per-message loss selection.** An optional `message_loss_mask` column contains one boolean or integer 0/1 per message. For example, `[0, 0, 0, 1]` on a user/assistant/user/assistant conversation trains only the final assistant turn while retaining the full context. For prompt-completion rows, the mask covers the concatenated prompt and completion messages. Zero excludes a message; one preserves the normal role and renderer loss settings. A missing or null mask leaves those settings unchanged. The renderer applies selection without changing token IDs, including ownership of assistant closing tokens. Invalid mask lengths or entries raise an error.
To read a differently named column, set `data.columns.message_loss_mask = "selection"`.
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column in OpenAI function-calling format. Each row's value can be either a list of dicts or a JSON-encoded string of a list.
Renderer-backed SFT reads template controls from the typed `[renderer]` config in the SFT TOML. For example:
@@ -5,10 +5,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-search"
partition = "all"
@@ -23,11 +23,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
partition = "all"
-5
View File
@@ -19,11 +19,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-swe"
partition = "all"
@@ -6,10 +6,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-terminal"
partition = "all"
@@ -2,7 +2,6 @@ clean = true
[env_vars]
HF_HOME = "/home/huggingface"
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "zai-org/GLM-5.3-BF16"
+1
View File
@@ -89,6 +89,7 @@ attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
ep = 8
dsa_backend = "cudnn_flashmla"
[trainer.model.quantization]
type = "fp8"
@@ -2,7 +2,6 @@ clean = true
[env_vars]
HF_HOME = "/home/huggingface"
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
@@ -6,6 +6,7 @@ import verifiers.v1 as vf
from pydantic import AliasChoices, BaseModel, Field, SerializeAsAny, TypeAdapter, ValidationError, model_validator
from pydantic.fields import FieldInfo
from renderers import AutoRendererConfig, RendererConfig
from verifiers.v1.configs.agent import agent_config_fields
from prime_rl.configs.algorithm import (
AlgoConfig,
@@ -90,70 +91,6 @@ class TrainSamplingConfig(BaseConfig):
)
return self
def to_sampling_args(self) -> dict[str, Any]:
"""Convert to OAI-compatible sampling args dict, omitting None values."""
args: dict[str, Any] = {
"temperature": self.temperature,
"top_p": self.top_p,
"logprobs": True,
}
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens
# top_k rides extra_body (like EvalSamplingConfig), overriding the sentinel.
extra_body = dict(self.extra_body)
if self.top_k is not None:
extra_body["top_k"] = self.top_k
if extra_body:
args["extra_body"] = extra_body
return args
class EvalSamplingConfig(BaseConfig):
temperature: float | None = Field(None, ge=0, le=2.0)
"""Sampling temperature. None defers to the inference server default."""
top_p: float | None = None
"""Nucleus sampling threshold. None defers to the inference server default."""
top_k: int | None = None
"""Top-k sampling. None defers to the inference server default."""
min_p: float | None = Field(None, ge=0)
"""Min-p sampling threshold. None defers to the inference server default."""
max_completion_tokens: int | None = None
"""Maximum output tokens per turn. None defers to the inference server default."""
reasoning_effort: Literal["minimal", "low", "medium", "high"] | None = None
"""Reasoning effort constraint for reasoning models."""
extra_body: dict[str, Any] = {}
"""Extra body parameters forwarded to the inference server."""
def to_sampling_args(self) -> dict[str, Any]:
"""Convert to OAI-compatible sampling args dict. Only includes non-None fields."""
args: dict[str, Any] = {}
if self.temperature is not None:
args["temperature"] = self.temperature
if self.top_p is not None:
args["top_p"] = self.top_p
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens
if self.reasoning_effort is not None:
args["reasoning_effort"] = self.reasoning_effort
extra_body = dict(self.extra_body)
if self.top_k is not None:
extra_body["top_k"] = self.top_k
if self.min_p is not None:
extra_body["min_p"] = self.min_p
if extra_body:
args["extra_body"] = extra_body
return args
class EnvConfig(BaseConfig):
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
@@ -316,9 +253,37 @@ class TrainSourceConfig(EnvConfig):
"""User-authored task sampler and admission gates. The default cycles
through the taskset and admits every finalized group."""
@model_validator(mode="after")
def validate_policy_sampling(self):
if self.algo.sampling.source != "policy":
return self
# The source owns the distribution replayed by the trainer; agents may
# change generation limits and rendering without changing that distribution.
agent_options = {"max_tokens", "reasoning_effort", "chat_template_kwargs"}
supported = (
agent_options
| TrainSamplingConfig.model_fields.keys()
| {"min_p", "logprobs", "return_token_ids", "cache_salt"}
)
sampling = vf.SamplingConfig(**self.sampling.model_dump(exclude_none=True))
if unsupported := sampling.model_dump(exclude_none=True).keys() - supported:
raise ValueError(
f"Policy source '{self.resolved_name}' has unsupported sampling parameters: {sorted(unsupported)}"
)
for name, agent in agent_config_fields(self.env).items():
if agent.sampling is None:
continue
if unsupported := agent.sampling.model_dump(exclude_unset=True).keys() - agent_options:
raise ValueError(
f"Agent '{name}' in policy source '{self.resolved_name}' sets sampling {sorted(unsupported)}. "
"Set distribution parameters on the source's sampling config; agent sampling only supports "
f"{sorted(agent_options)}."
)
return self
class EvalSourceConfig(EnvConfig):
sampling: EvalSamplingConfig = EvalSamplingConfig()
sampling: vf.SamplingConfig = vf.SamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
group_size: int = Field(1, ge=1)
@@ -409,7 +374,7 @@ class EvalSourcesConfig(SourceGroupConfig):
source: list[EvalSourceConfig] = Field(default_factory=list)
"""Evaluation sources."""
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
sampling: vf.SamplingConfig = Field(default_factory=vf.SamplingConfig)
"""Sampling that every eval source inherits; can differ from training sampling."""
select: vf.SelectConfig = vf.SelectConfig()
@@ -433,17 +433,8 @@ class RLConfig(BaseConfig):
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
"have no disk artifact to load from."
)
if "inference_world_size" in self.weight_broadcast.model_fields_set:
raise ValueError("weight_broadcast.inference_world_size is set automatically by rl; remove it.")
update = {}
if self.weight_broadcast.type != "filesystem":
update["inference_world_size"] = (
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
if self.inference
else 1
)
self.trainer.weight_broadcast = self.weight_broadcast.model_copy(update=update)
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy(update=update)
self.trainer.weight_broadcast = self.weight_broadcast.model_copy()
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy()
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
return self
@@ -659,6 +650,11 @@ class RLConfig(BaseConfig):
dp = self.inference.vllm.data_parallel_size
if self.inference.vllm.api_server_count < dp and not self.inference.vllm.enable_lora:
self.inference.vllm.api_server_count = dp
if self.weight_broadcast.type != "filesystem":
# Every inference GPU joins the in-memory transfer group, so size it after the DP fill.
world_size = dp * self.inference.vllm.tensor_parallel_size
self.trainer.weight_broadcast.inference_world_size = world_size
self.orchestrator.weight_broadcast.inference_world_size = world_size
elif self.deployment.type == "multi_node": # multi-node
self.orchestrator.num_train_workers = (
@@ -101,6 +101,9 @@ class SFTColumnsConfig(BaseConfig):
tools: str = "tools"
"""Column with the tool schemas in OpenAI function-calling format."""
message_loss_mask: str = "message_loss_mask"
"""Optional column of booleans or integer 0/1 flags, one per resolved message (prompt + completion for split rows). Zero excludes a message from loss; one preserves its normal supervision. Missing or null masks leave supervision unchanged."""
renderer: dict[str, str] = {"reasoning_effort": "reasoning_effort"}
"""Per-sample renderer arguments as ``renderer field = dataset column``, e.g. ``reasoning_effort = "effort"``. A row's non-null value overrides the ``[renderer]`` setting; rows and datasets without the column use it unchanged."""
@@ -612,6 +612,9 @@ class DataLoaderConfig(BaseConfig):
fake: FakeDataLoaderConfig | None = None
"""Use a fake data loader sampling random micro-batches (for debugging)."""
num_workers: int = Field(0, ge=0)
"""Number of background threads that prepare micro batches ahead of the training loop, analogous to torch DataLoader's ``num_workers`` but with threads instead of processes. 0 prepares them on the main thread."""
class TrainerConfig(BaseConfig):
model: ModelConfig = ModelConfig()
+2 -2
View File
@@ -225,9 +225,9 @@ requires-dist = [
]
[tool.uv.exclude-newer-package]
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
# verifiers pins harbor==0.24.0, published inside the rolling window;
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
harbor = "2026-08-11T00:00:00Z"
harbor = "2026-10-08T00:00:00Z"
tokenspeed-mla = false
# vLLM 0.31.0 pins flashinfer-python 0.7.0.post1, published inside the rolling window
flashinfer-python = false
+5 -6
View File
@@ -8,6 +8,8 @@ rollouts still owed run (``prime_rl.eval.resume``)."""
from __future__ import annotations
import verifiers.v1 as vf
from prime_rl import monitors
from prime_rl.configs.eval import EvalConfig
from prime_rl.eval import resume
@@ -24,7 +26,7 @@ class Eval:
async def run(self) -> None:
config = self.config
landed: list[dict] = []
landed: list[vf.WireEpisode] = []
if config.resume:
# read and set aside before the monitors start: the resumed attempt writes a fresh stream
landed = resume.take_landed(config.run_dir)
@@ -41,17 +43,14 @@ class Eval:
)
resume.stamp_config(config.run_dir, dump_resolved_config(config))
await self.runner.setup()
restored: list = []
fired, restored = self.runner.eval_source.trigger(0, completed=landed)
if config.resume:
restored, owed, groups = resume.plan(landed, self.runner.eval_envs)
self.runner.eval_source.restore(owed, groups)
get_logger().info(
f"Resuming from the trace stream: {len(restored)} episodes restored, "
f"{sum(sum(counts.values()) for counts in owed.values())} rollouts owed"
f"{sum(request.rollouts or 0 for request in self.runner.eval_source.queue)} rollouts owed"
)
await self.runner.start()
fired = self.runner.eval_source.trigger(0)
await self.runner.run_epoch(fired, 0, restored=restored)
await self.runner.drain()
+1 -1
View File
@@ -178,7 +178,7 @@ class OnlineEval:
# Trigger before the reload: the dispatcher only schedules eval in PREFER_EVAL,
# so nothing dispatches until ``run_epoch`` switches modes below.
fired = runner.eval_source.trigger(step, force=force)
fired, _ = runner.eval_source.trigger(step, force=force)
self.last_step = max(self.last_step, step)
if reload_weights:
+14 -50
View File
@@ -1,20 +1,18 @@
"""Resume an interrupted eval from its trace stream.
The stream records what landed, so it is what a resume continues from. The run's ok
episodes are read back and rejoin the epoch as if they had just arrived - through the
monitors, so the rebuilt stream, the epoch's metrics and the platform upload cover the
whole epoch - and only the rollouts still owed run. Errored episodes and the in-flight
The stream records what landed, so it is what a resume continues from. Successful
episodes rejoin the epoch through the monitors as if they had just arrived,
so the rebuilt stream, the epoch's metrics and the platform upload cover the
whole epoch - and only the rollouts still owed run. Failed episodes and the in-flight
ones the interruption cut off are owed again.
A landed episode counts toward the task with its ``task.key``, so a resumed run may
select more or fewer examples or rollouts per example than the interrupted one: the
kept episodes are matched to the new selection and the rest is owed. The resumed
config is not checked against the interrupted one: any of it may be overridden.
The shared Verifiers rollout planner matches these episodes to the current tasks
by content hash. The resumed config is not checked against the interrupted one:
any of it may be overridden.
"""
from __future__ import annotations
from collections import Counter, defaultdict
from collections.abc import Iterator
from pathlib import Path
@@ -23,7 +21,6 @@ import verifiers.v1 as vf
from prime_rl.monitors.file.traces import get_trace_stream
from prime_rl.monitors.file.traces.chunks import chunk_numbers, open_chunk
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.utils.pathing import get_file_monitor_dir
CONFIG_NAME = "eval.json"
@@ -57,52 +54,19 @@ def archives(run_dir: Path) -> list[Path]:
return sorted(monitors.glob("file.attempt_*"), key=lambda path: int(path.name.rsplit("_", 1)[1]))
def take_landed(run_dir: Path) -> list[dict]:
"""The ok eval episodes the run has landed, each once, from every attempt's stream.
def take_landed(run_dir: Path) -> list[vf.WireEpisode]:
"""Successful episodes from every attempt; the planner deduplicates them.
The current file monitor directory joins the archives so the resumed attempt writes a
fresh stream, plan and metrics; nothing is deleted."""
current = get_file_monitor_dir(run_dir)
stream = get_trace_stream(run_dir).relative_to(current)
landed: dict[str, dict] = {}
landed: list[vf.WireEpisode] = []
for directory in [*archives(run_dir), current]:
if (directory / stream).is_dir():
for record in read_records(directory / stream):
if record.get("ok"):
landed.setdefault(record["id"], record)
episode = vf.WireEpisode.model_validate(record)
if episode.ok and "traces" in record:
landed.append(episode)
if current.is_dir():
current.rename(current.with_name(f"file.attempt_{len(archives(run_dir)) + 1}"))
return list(landed.values())
def plan(
landed: list[dict], eval_envs: EvalEnvs
) -> tuple[list[vf.WireEpisode], dict[str, dict[str, int]], dict[str, dict[str, str]]]:
"""Match the landed episodes to the run's tasks: the episodes to keep, in stream
order, the rollouts still owed per env and task key, and the group id a task's kept
episodes carry, so the owed ones complete that group rather than open another."""
targets: dict[str, Counter[str]] = {}
for env in eval_envs:
targets[env.name] = Counter(task.key for task in env.examples)
for key in targets[env.name]:
targets[env.name][key] *= env.config.group_size
kept: list[vf.WireEpisode] = []
counts: dict[str, Counter[str]] = defaultdict(Counter)
groups: dict[str, dict[str, str]] = defaultdict(dict)
for record in landed:
env_name = record["env"].get("name") or record["env"]["id"]
key = record["task"]["key"]
if counts[env_name][key] >= targets.get(env_name, Counter())[key]:
continue
kept.append(vf.WireEpisode.model_validate(record))
counts[env_name][key] += 1
if (group := record.get("group") or {}).get("id"):
groups[env_name].setdefault(key, group["id"])
owed = {
env_name: {
key: target - counts[env_name][key]
for key, target in target_counts.items()
if target > counts[env_name][key]
}
for env_name, target_counts in targets.items()
}
return kept, owed, dict(groups)
return landed
+2 -1
View File
@@ -105,7 +105,7 @@ class EvalRunner:
# Pessimistic per-episode token cost for the controller's starting cap,
# only used when the engine doesn't report its max context length.
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.source) or 8192
fallback_cost = max((source.sampling.max_tokens or 0) for source in config.source) or 8192
self.concurrency = ConcurrencyController(config.concurrency, fallback_cost=fallback_cost)
self.dispatcher = Dispatcher(
train_envs=None,
@@ -114,6 +114,7 @@ class EvalRunner:
eval_source=self.eval_source,
policy_clients=self.clients,
policy=self.policy,
policy_weights_change=isinstance(config, SFTOnlineEvalConfig),
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
+45 -2
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
import atexit
import fcntl
import os
import time
@@ -251,7 +252,12 @@ class PrimeEvalMonitor(Monitor):
evaluation per env and step, opened when the epoch starts (``log_eval_plan``), fed
every episode as it lands (``log_episodes``) and finished with the epoch's aggregates
(``log_eval_epoch``), so the platform page follows the run from its first episode.
Metrics are not forwarded; the evaluation is the epoch."""
Under a managed launch ($RUN_ID) the epoch's ``eval/{env}/...`` metrics ALSO go to
the parent training run, which is what the run dashboard groups into its `eval`
section. The orchestrator's in-process evals reach it through the train monitor, but
an eval process of its own (SFT online evals) has no other way there, so without
this the run shows every metric group except the one its evals produced."""
config: PrimeEvalMonitorConfig
@@ -268,6 +274,7 @@ class PrimeEvalMonitor(Monitor):
# (env, step) -> its open evaluation; None once opening it failed, so the epoch's
# episodes do not retry the platform on every arrival
self.runs: dict[tuple[str, int], pr.Run | None] = {}
self.parent: pr.Run | None = None
self._lock = asyncio.Lock()
self.evaluation_id = os.getenv(EVAL_ID_VAR)
if self.evaluation_id and len(self.sources) != 1:
@@ -277,6 +284,7 @@ class PrimeEvalMonitor(Monitor):
)
if self.mode == "online":
self.logger.info("Streaming eval epochs to the Prime platform")
self.parent = await asyncio.to_thread(self._attach_parent)
if output_dir is not None:
# Merge, not overwrite: when the eval process shares the
# trainer's run dir (SFT online evals), the train record's
@@ -294,8 +302,39 @@ class PrimeEvalMonitor(Monitor):
else:
self.logger.info(f"Platform evaluations disabled ({pr.MODE_ENV}=disabled)")
def _attach_parent(self) -> pr.Run | None:
"""The parent training run this eval process belongs to, for metrics only.
Blocking: runs in a worker thread.
Attaching is a local handle, not a request, so a run that turns out to be
unreachable costs the eval nothing. The caller owns the run's lifecycle: we
drop the SDK's atexit crash hook, because an eval process that exits while the
trainer is still going would otherwise report the WHOLE run failed."""
run_id = os.getenv("RUN_ID")
if not run_id:
return None
run = pr.init(
kind="train",
mode=self.mode,
base_url=_base_url(),
id=run_id,
finish_timeout=FINISH_TIMEOUT,
)
atexit.unregister(run._atexit_hook) # the SDK's own unregister handle
self.logger.info(f"Logging eval metrics to parent training run {run.id}")
return run
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
pass
"""An epoch's aggregates (``eval/{env}/...``) onto the parent training run.
Only there: a standalone eval has no parent, and the per-epoch evaluation
carries its own aggregates through ``log_eval_epoch``."""
if self.parent is None:
return
metrics, dropped = sanitize(metrics)
if dropped:
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
# A queue put that can block briefly under backpressure - off the loop.
await asyncio.to_thread(self.parent.log_metrics, metrics, step=step)
def open(self, env_name: str, step: int, expected: int | None) -> pr.Run:
"""Open the platform evaluation of one epoch. Blocking: runs in a worker thread."""
@@ -400,3 +439,7 @@ class PrimeEvalMonitor(Monitor):
await asyncio.to_thread(run.finish, status=pr.RunStatus.CANCELLED, error="interrupted")
except Exception as e:
self.logger.warning(f"Failed to close the {env_name} (Step {step}) evaluation: {type(e).__name__}: {e}")
if self.parent is not None:
# Drain only. The parent run belongs to the trainer and the platform: an
# eval process must never report its status, not even a clean completion.
await asyncio.to_thread(self.parent.flush, FINISH_TIMEOUT)
+4 -5
View File
@@ -2,8 +2,8 @@
The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm
is — a bundle of sampling and the per-token training signal. This package
turns the signal half into runtime objects (the sampling half is the env's
:class:`~prime_rl.orchestrator.generation_source.GenerationSource`):
turns the signal half into runtime objects (the sampling half is interpreted by
:class:`~prime_rl.orchestrator.envs.TrainEnv`):
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``, ``debug``) — each named
@@ -22,7 +22,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_client
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.orchestrator.algo.debug import DebugAlgorithm
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
@@ -56,7 +56,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
cls = ALGORITHM_CLASSES[config.type]
# The Algorithm is the runtime of the algorithm config's training signal
# (its sibling GenerationSource interprets the sampling half). Every algorithm is
# (its TrainEnv interprets the sampling half). Every algorithm is
# handed the live policy pool — opsd self-distills against it, others may
# judge against it or ignore it. Other models (a frozen teacher, a hint
# renderer) are built from the algorithm's own config in setup().
@@ -75,7 +75,6 @@ __all__ = [
"RAEAlgorithm",
"SFTDistillAlgorithm",
"build_algorithm",
"connect_frozen_client",
"assign_advantages",
"stamp_loss_routing",
]
+2 -26
View File
@@ -2,41 +2,17 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.orchestrator.clients import InferenceClient
async def connect_frozen_client(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferenceClient:
"""Connect to an externally hosted frozen model and wait for it."""
from prime_rl.orchestrator.clients import InferenceClient, check_inference_ready
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
if renderer_config is not None:
clients = InferenceClient(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
clients = InferenceClient(config, model_name=config.name)
await check_inference_ready(config, config.name)
return clients
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
def iter_trainable_traces(episodes: list[vf.Episode]):
"""Yield clean trainable traces that contain sampled tokens."""
for episode in episodes:
for trace in episode.traces:
if trace.has_error or not trace.agent.trainable:
if not episode.ok or trace.has_error or not trace.agent.trainable or trace.num_turns == 0:
continue
if any(any(node.mask) for node in trace.nodes):
yield episode, trace
+2 -3
View File
@@ -696,11 +696,10 @@ def _distribute_group(
def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBatch:
"""
Pad a micro batch with the given padding size sample
Return the padded micro batch.
Pad a micro batch with loss-masked tokens up to the next multiple of `pad_to_multiple_of`.
Args:
micro_batch: The micro batch to pad.
padding_size: The number of padding tokens to add.
pad_to_multiple_of: The multiple to pad the sequence length up to.
Returns:
The padded micro batch.
"""
+16
View File
@@ -20,6 +20,7 @@ from verifiers.v1.configs.client import (
resolve_headers,
)
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.logger import get_logger
@@ -228,6 +229,21 @@ async def check_inference_ready(client_config: ClientConfig, model_name: str) ->
await admin.aclose()
async def connect_frozen_client(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferenceClient:
"""Connect to an externally hosted frozen model and wait for it."""
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
if renderer_config is not None:
clients = InferenceClient(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
clients = InferenceClient(config, model_name=config.name)
await check_inference_ready(config, config.name)
return clients
def setup_client(
client_config: ClientConfig,
client_type: str = "openai_chat_completions",
+3 -2
View File
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any
import verifiers.v1 as vf
from prime_rl.orchestrator.algo.base import iter_trainable_traces
from prime_rl.orchestrator.curriculum.gates import AdmissionGate
from prime_rl.orchestrator.curriculum.samplers import TaskSampler
@@ -48,7 +49,7 @@ class Curriculum:
self.gates[name] = gate
def on_result(self, group: list[vf.Episode]) -> bool:
"""Observe every result, evaluate every gate, and combine with AND."""
"""Observe every result and admit trainable groups that pass every gate."""
if not group:
raise ValueError("Cannot report an empty rollout group")
task_keys = {episode.task.key for episode in group}
@@ -63,7 +64,7 @@ class Curriculum:
if not isinstance(decision, bool):
raise TypeError(f"AdmissionGate {name!r}.admit() must return bool, got {type(decision).__name__}")
decisions.append(decision)
return all(decisions)
return all(decisions) and any(iter_trainable_traces(group))
def state_dict(self) -> dict[str, Any]:
return {
@@ -27,7 +27,7 @@ class AdvRangeGate(AdmissionGate):
advantage
for episode in group
for trace in episode.traces
if not trace.has_error and trace.agent.trainable
if episode.ok and not trace.has_error and trace.agent.trainable
for node in trace.nodes
for advantage in node.advantages or []
]
@@ -68,7 +68,7 @@ class DifficultyPoolSampler(TaskSampler):
trace.reward
for episode in group
for trace in episode.traces
if not trace.has_error and trace.agent.trainable
if episode.ok and not trace.has_error and trace.agent.trainable and trace.num_turns > 0
]
if not rewards:
return
+19 -25
View File
@@ -143,9 +143,11 @@ class Dispatcher:
max_off_policy_steps: int,
run_id: str,
run_name: str | None,
policy_weights_change: bool = True,
on_episode_complete: Callable[[int], None] | None = None,
) -> None:
self.policy = policy
self.policy_weights_change = policy_weights_change
self.progress = progress
self.train_envs = train_envs
self.eval_envs = eval_envs
@@ -214,10 +216,10 @@ class Dispatcher:
"""``(clients, model_name, is_live)`` for *train* rollouts of this env —
eval always uses the policy."""
assert self.train_envs is not None # train groups only exist when train is configured
source = self.train_envs.get(env_name).generation_source
if source.uses_live_policy:
return source.clients, self.policy.model_name, True
return source.clients, source.clients.model_name, False
env = self.train_envs.get(env_name)
if env.uses_live_policy:
return env.clients, self.policy.model_name, True
return env.clients, env.clients.model_name, False
@property
def inflight_train_count(self) -> int:
@@ -316,7 +318,7 @@ class Dispatcher:
return [
(self.progress.step - 1) - meta.policy_version
for meta in self.inflight.values()
if meta.kind == "train" and self.train_envs.get(meta.env_name).generation_source.uses_live_policy
if meta.kind == "train" and self.train_envs.get(meta.env_name).uses_live_policy
]
# ── lifecycle ──────────────────────────────────────────────────────────
@@ -423,7 +425,7 @@ class Dispatcher:
gid
for gid, group in self.groups.items()
if group.kind == "train"
and self.train_envs.get(group.env_name).generation_source.uses_live_policy
and self.train_envs.get(group.env_name).uses_live_policy
and group.policy_version_at_start < min_version
]
cancelled = 0
@@ -556,10 +558,8 @@ class Dispatcher:
if env_collection is None:
return False
env = env_collection.get(group.env_name)
# Frozen-sourced train rollouts hit a frozen pool; salting per policy
# version would invalidate its prefix cache every weight update for
# no reason.
if live_sourced:
# Only endpoints receiving policy weight updates need a cache salt.
if live_sourced and self.policy_weights_change:
cache_salt = str(group.policy_version_at_start)
else:
cache_salt = None
@@ -665,10 +665,6 @@ class Dispatcher:
)
return
if not episode.traces and episode.ok:
episode.ok = False
episode.errors.append(vf.Error(type="EmptyEpisode", message="Episode returned with no traces"))
for trace in episode.traces:
if trace.is_timeout and not trace.has_error and meta.kind == "train":
# Training keeps a timed-out rollout out of the batch: an error,
@@ -676,14 +672,6 @@ class Dispatcher:
trace.errors.append(vf.Error(type="Timeout", message=f"Trace stopped by {trace.stop_condition}"))
trace.ok = False
episode.ok = False
if not trace.has_error and not trace.is_timeout and trace.num_turns == 0:
# Empty trajectory: promote to an explicit error so the sink
# treats it like any other failure (``has_error`` reads ``ok``).
# A timed-out eval trace with no turns stays a timeout: scored, no samples.
trace.errors.append(vf.Error(type="EmptyTrajectory", message="Trace returned with no trajectory steps"))
trace.ok = False
episode.ok = False
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
if trace.has_error:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if trace.last_error is not None:
@@ -691,8 +679,14 @@ class Dispatcher:
f"Trace failed in group {meta.group_id} ({meta.env_name}) — "
f"{trace.last_error.type}: {trace.last_error.message}"
)
if not episode.ok and not episode.traces:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if not episode.ok:
if not any(trace.has_error for trace in episode.traces):
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
error = episode.last_error
get_logger().warning(
f"Episode failed in group {meta.group_id} ({meta.env_name})"
+ (f" — {error.type}: {error.message}" if error is not None else "")
)
if self.on_episode_complete is not None and meta.started_at > 0:
self.on_episode_complete(episode.num_total_tokens)
await self.emit_episode(meta, group, episode)
@@ -722,7 +716,7 @@ class Dispatcher:
live_policy = meta.kind == "eval"
if meta.kind == "train":
assert self.train_envs is not None
live_policy = self.train_envs.get(meta.env_name).generation_source.uses_live_policy
live_policy = self.train_envs.get(meta.env_name).uses_live_policy
policy = vf.PolicySpan(start=policy_version, end=self.policy.version) if live_policy else None
work: vf.WorkInfo = (
vf.EvalWorkInfo(step=meta.step, policy=policy)
+42 -27
View File
@@ -26,11 +26,13 @@ from pathlib import Path
from typing import Generic, TypeVar
import verifiers.v1 as vf
from renderers import RendererConfig
from verifiers.v1.serve import EnvClient
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
from prime_rl.orchestrator.generation_source import GenerationSource
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import env_address_file
@@ -65,7 +67,7 @@ class Env:
self.address_file = address_file
"""Where a launcher-managed server publishes its address; read when ``address``
is None."""
self.sampling_args: dict = {}
self.sampling = vf.SamplingConfig()
self.num_tasks: int | None = 0
"""Task count; ``None`` means the selected tasks never end."""
self.tasks: Iterator[vf.Task] | None = None
@@ -108,10 +110,10 @@ class Env:
get_logger().info(f"Env {self.name} ready in {format_time(time.perf_counter() - t0)} (num_tasks={num_tasks})")
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
sampling = {**self.sampling_args}
sampling = self.sampling
if cache_salt is not None:
sampling["extra_body"] = {**sampling.get("extra_body", {}), "cache_salt": cache_salt}
return vf.SamplingConfig(**sampling)
sampling = sampling.model_copy(update={"cache_salt": cache_salt})
return sampling
async def run(
self,
@@ -121,25 +123,16 @@ class Env:
task_data: dict,
on_delta: Callable[[dict], None] | None = None,
) -> vf.WireEpisode:
"""Run and return one typed episode. A failed multi-trace episode marks
its otherwise-clean traces failed so partial episodes never train.
"""Run and return the native typed episode.
``on_delta`` sees each delta of the env server's stream — a turn or a phase
change of one of the episode's traces — as it lands."""
episode = await self.env_client.run(
return await self.env_client.run(
task_data=task_data,
client=client,
model=model_name,
sampling=self._sampling(cache_salt),
on_delta=on_delta,
)
for trace in episode.traces:
if not episode.ok and trace.ok:
error = episode.last_error or vf.Error(
type="EpisodeFailed", message="A sibling trace in this episode failed"
)
trace.errors = [*trace.errors, error]
trace.ok = False
return episode
class TrainEnv(Env):
@@ -150,17 +143,39 @@ class TrainEnv(Env):
config: TrainSourceConfig,
address: str | None,
address_file: Path,
generation_source: GenerationSource,
clients: InferenceClient,
renderer_config: RendererConfig | None,
algorithm: Algorithm,
):
super().__init__(config, address, address_file)
self.generation_source = generation_source
# Train rollouts are generated from `clients`: the policy, or the frozen
# `sampling.source` connected in setup() with the renderer (token-in/out) client.
self.clients = clients
self.renderer_config = renderer_config
self.connected: InferenceClient | None = None
self.algorithm = algorithm
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
# Truncated policy sampling must ship the sampling masks the trainer replays.
self.requires_sampling_masks = (
config.sampling.truncates_distribution() and config.algo.sampling.source == "policy"
self.uses_live_policy = config.algo.sampling.source == "policy"
self.sampling = vf.SamplingConfig(
**config.sampling.model_dump(exclude_none=True),
# Only policy rollouts need sampling logprobs for importance ratios.
logprobs=True if self.uses_live_policy else None,
)
# Truncated policy sampling must ship the sampling masks the trainer replays.
self.requires_sampling_masks = config.sampling.truncates_distribution() and self.uses_live_policy
async def setup(self) -> None:
async def connect_source() -> None:
source = self.config.algo.sampling.source
if isinstance(source, FrozenModelConfig):
self.connected = await connect_frozen_client(source, renderer_config=self.renderer_config)
self.clients = self.connected
await asyncio.gather(connect_source(), self.algorithm.setup())
async def aclose(self) -> None:
for clients in (self.connected, self.algorithm.connected):
if clients is not None:
await clients.aclose()
class EvalEnv(Env):
@@ -168,7 +183,7 @@ class EvalEnv(Env):
def __init__(self, config: EvalSourceConfig, address: str | None, address_file: Path):
super().__init__(config, address, address_file)
self.sampling_args = config.sampling.to_sampling_args()
self.sampling = config.sampling
self.examples: list[vf.Task] = []
async def start(self) -> None:
@@ -218,9 +233,8 @@ class Envs(Generic[EnvT]):
class TrainEnvs(Envs[TrainEnv]):
"""Collection of training environments, each paired with its
:class:`GenerationSource` and runtime :class:`Algorithm`, built from the env's
resolved algorithm config."""
"""Collection of training environments, each with its runtime
:class:`Algorithm`, built from the env's resolved algorithm config."""
def __init__(
self,
@@ -238,7 +252,8 @@ class TrainEnvs(Envs[TrainEnv]):
config,
addresses[("train", config.resolved_name)],
env_address_file(config_dir, "train", config.resolved_name),
GenerationSource(config.algo.sampling, clients, renderer_config),
clients,
renderer_config,
build_algorithm(config.algo, clients),
)
self._envs[env.name] = env
+26 -27
View File
@@ -6,15 +6,18 @@ including startup. The dispatcher pulls via ``next_task()`` until
from __future__ import annotations
from collections import deque
import uuid
from collections import defaultdict, deque
from collections.abc import Iterable
from itertools import zip_longest
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from verifiers.v1.utils.eval import plan_rollouts
from prime_rl.orchestrator.types import TaskRequest
if TYPE_CHECKING:
import verifiers.v1 as vf
from prime_rl.orchestrator.envs import EvalEnvs
@@ -42,54 +45,50 @@ class EvalSource:
self.intervals[env.name] = intervals[env.name] if intervals is not None else 1
self.queue: deque[TaskRequest] = deque()
self.owed: dict[str, dict[str, int]] | None = None
self.groups: dict[str, dict[str, str]] = {}
# A fresh run evaluates the base policy. Resumed runs apply interval
# rules to the loaded checkpoint and later policies.
self.first_trigger = not is_resumed
def restore(self, owed: dict[str, dict[str, int]], groups: dict[str, dict[str, str]]) -> None:
"""Rollouts the next trigger still owes per env and task key, the rest having
landed before a resume; a task without an entry is complete. ``groups`` is the
group id the landed rollouts of a task carry, which the owed ones join."""
self.owed = owed
self.groups = groups
def trigger(self, step: int, *, force: bool = False) -> list[str]:
"""Fire eligible envs for ``step`` and return their names. On resume
def trigger(
self, step: int, *, force: bool = False, completed: Iterable[vf.WireEpisode] = ()
) -> tuple[list[str], list[vf.WireEpisode]]:
"""Fire eligible envs and return their names and matched saved episodes. On resume
``first_trigger`` is False, so the startup/base eval doesn't re-run.
``force`` fires every env regardless of interval (e.g. the evals process's
final-checkpoint eval)."""
is_first, self.first_trigger = self.first_trigger, False
if is_first and self.skip_first_step:
return []
return [], []
fired = [
name
for name, interval in self.intervals.items()
if (is_first or force or step % interval == 0) and self.tasks_by_env[name]
]
owed, self.owed = self.owed, None
saved: dict[str, list[vf.WireEpisode]] = defaultdict(list)
for episode in completed:
saved[episode.env.name or episode.env.id].append(episode)
restored: list[vf.WireEpisode] = []
# Round-robin across fired envs (A₁, B₁, A₂, B₂, …) so the
# dispatcher rotates at example granularity. ``try_schedule``'s
# continue-group branch still keeps each example's group_size
# rollouts back-to-back, so per-example prefix-cache locality holds
iters = [iter(self.tasks_by_env[name]) for name in fired]
iters = [iter(plan_rollouts(self.tasks_by_env[name], self.group_sizes[name], saved[name])) for name in fired]
for round_tasks in zip_longest(*iters):
for env_name, task in zip(fired, round_tasks, strict=True):
if task is None:
for env_name, planned in zip(fired, round_tasks, strict=True):
if planned is None:
continue
rollouts = self.group_sizes[env_name]
if owed is not None:
# duplicate tasks share a key: each takes up to a group of what the key owes
rollouts = min(rollouts, owed[env_name].get(task.key, 0))
owed[env_name][task.key] = owed[env_name].get(task.key, 0) - rollouts
task, kept, rollouts = planned
# Each selected occurrence owns one group, including its restored episodes.
group = vf.GroupInfo(id=str(uuid.uuid4()))
for episode in kept:
episode.group = group
restored.extend(kept)
if rollouts > 0:
group_id = self.groups.get(env_name, {}).get(task.key)
self.queue.append(
TaskRequest(env_name=env_name, task=task, step=step, rollouts=rollouts, group_id=group_id)
TaskRequest(env_name=env_name, task=task, step=step, rollouts=rollouts, group_id=group.id)
)
return fired
return fired, restored
def next_task(self) -> TaskRequest | None:
"""Pop the next eval task, or ``None`` when the queue is empty."""
@@ -1,49 +0,0 @@
"""Resolve the model source used to generate an env's train episodes."""
from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import FrozenModelConfig, SamplingConfig
from prime_rl.orchestrator.algo import connect_frozen_client
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.orchestrator.clients import InferenceClient
class GenerationSource:
"""One env's generation model and inference clients.
``clients`` is what train rollouts are generated from: the policy clients,
swapped for a connected frozen endpoint in :meth:`setup` when the source is
an inline frozen model. A frozen source *generates* rollouts, so it uses
the renderer (token-in/out) client (built from ``renderer_config``) — the
rollout must carry tokens for training."""
def __init__(self, config: SamplingConfig, clients: InferenceClient, renderer_config: RendererConfig | None = None):
assert config.source is not None, "sampling.source must be resolved by config validation"
self.config = config
self.clients: InferenceClient = clients
self.renderer_config = renderer_config
self.connected: InferenceClient | None = None # frozen clients connected in setup(); closed at shutdown
async def setup(self) -> None:
"""Connect clients to a frozen generation source and wait for
readiness. Must run before dispatching."""
if isinstance(self.config.source, FrozenModelConfig):
self.clients = await connect_frozen_client(self.config.source, renderer_config=self.renderer_config)
self.connected = self.clients
@property
def uses_live_policy(self) -> bool:
return self.config.source == "policy"
def sampling_args(self, args: dict) -> dict:
"""Source-specific sampling-arg overrides. Sampling logprobs are only
needed for importance ratios on policy-sampled tokens — frozen
endpoints may reject the knob."""
if not self.uses_live_policy:
args.pop("logprobs", None)
return args
+4 -9
View File
@@ -282,10 +282,7 @@ class Orchestrator:
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
# Build + ready pools for each env's frozen generation source and the
# algorithm's frozen reference model
await asyncio.gather(
*(env.generation_source.setup() for env in self.train_envs),
*(env.algorithm.setup() for env in self.train_envs),
)
await asyncio.gather(*(env.setup() for env in self.train_envs))
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
@@ -769,7 +766,7 @@ class Orchestrator:
if self.resume_step == step and self.config.eval is not None and not self.config.eval.retrigger_on_resume:
return
is_final = self.config.max_steps is not None and step >= self.config.max_steps
fired = self.eval_source.trigger(step, force=is_final)
fired, _ = self.eval_source.trigger(step, force=is_final)
if not fired:
return
self.eval_triggered_steps.add(step)
@@ -1024,11 +1021,9 @@ class Orchestrator:
if self.admin_plane is not None:
await self.admin_plane.aclose()
if self.train_envs is not None:
get_logger().debug("Stopping generation source and algorithm clients")
get_logger().debug("Stopping train env clients")
for env in self.train_envs:
for clients in (env.generation_source.connected, env.algorithm.connected):
if clients is not None:
await clients.aclose()
await env.aclose()
get_logger().info("Stopping orchestrator components")
t0 = time.perf_counter()
+1 -1
View File
@@ -255,7 +255,7 @@ class TrainSink:
return
samples_by_trace: dict[str, list[TrainingSample]] = {}
temperature = env.sampling_args["temperature"]
temperature = env.config.sampling.temperature
for trace in survivors:
samples = await asyncio.to_thread(trace_to_samples, trace, env_name=env_name)
for sample in samples:
+1 -1
View File
@@ -24,7 +24,7 @@ class WeightWatcher:
policy: Policy,
observers: list[VersionObserver],
ckpt_step: int = 0,
poll_interval: float = 1.0,
poll_interval: float = 0.1,
) -> None:
self.receiver = receiver
self.policy = policy
@@ -367,7 +367,9 @@ class AfmoeModel(AfmoePreTrainedModel):
for layer_idx, decoder_layer in enumerate(self.layers):
mask = causal_mask_mapping[decoder_layer.attention_type] if causal_mask_mapping is not None else None
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
@@ -267,7 +267,9 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
mhc_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous()
for layer_idx, decoder_layer in enumerate(self.layers):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
mhc_states = decoder_layer(
mhc_states,
input_ids=input_ids,
-39
View File
@@ -1,39 +0,0 @@
import torch
from torch import Tensor
def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
"""Quantize a 2D tensor to FP8 e4m3 with per-block scales."""
if weight.ndim != 2:
raise ValueError(f"FP8 quantization expects a 2D tensor, got shape={tuple(weight.shape)}")
rows, cols = weight.shape
pad_rows = (block_size - rows % block_size) % block_size
pad_cols = (block_size - cols % block_size) % block_size
if pad_rows or pad_cols:
padded = torch.zeros(
rows + pad_rows,
cols + pad_cols,
dtype=weight.dtype,
device=weight.device,
)
padded[:rows, :cols] = weight
else:
padded = weight.contiguous()
padded_rows, padded_cols = padded.shape
blocks = padded.view(
padded_rows // block_size,
block_size,
padded_cols // block_size,
block_size,
).permute(0, 2, 1, 3)
fp8_max = torch.finfo(torch.float8_e4m3fn).max
max_abs = blocks.float().abs().amax(dim=(2, 3))
scales = (max_abs / fp8_max).clamp(min=1e-12)
blocks_fp8 = (blocks.float() / scales[:, :, None, None]).clamp(-fp8_max, fp8_max).to(torch.float8_e4m3fn)
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
return quantized, scales.float().contiguous()
@@ -241,7 +241,9 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
cached_indices = None
use_index_cache = getattr(self.config, "use_index_cache", False)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states, next_cached_indices = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
@@ -148,7 +148,7 @@ class GptOssModel(GptOssPreTrainedModel):
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers):
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
layer_routed_experts = routed_experts[:, :, layer_idx].contiguous() if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
position_embeddings,
@@ -12,6 +12,7 @@ import triton.language as tl
FP8_MAX = 448.0
FP8_MIN = -448.0
FP8_EPS = 1e-10
KEY_ALIGNMENT = 16
@triton.jit
@@ -88,17 +89,6 @@ def per_token_group_quant_fp8(
return x_q, x_s
@triton.autotune(
configs=[
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 64}, num_warps=8, num_stages=2),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=8, num_stages=2),
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_BUCKET", "H", "D"],
)
@triton.jit
def _triton_fp8_indexer_kernel(
Q_fp8,
@@ -116,7 +106,6 @@ 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,
):
@@ -201,6 +190,8 @@ def fp8_indexer(
q_flat = q.reshape(S_q * H, D).contiguous()
q_fp8, q_scales = per_token_group_quant_fp8(q_flat, group_size=D, use_ue8m0=True)
S_k_aligned = triton.cdiv(S_k, KEY_ALIGNMENT) * KEY_ALIGNMENT
k = torch.nn.functional.pad(k, (0, 0, 0, S_k_aligned - S_k))
k_fp8, k_scales = per_token_group_quant_fp8(k.contiguous(), group_size=D, use_ue8m0=True)
q_fp8 = q_fp8.view(S_q, H, D).permute(1, 0, 2).contiguous()
@@ -209,12 +200,10 @@ def fp8_indexer(
q_scales = q_scales.view(S_q, H)
w = w * q_scales
logits = torch.empty(S_q, S_k, dtype=torch.float32, device=device)
logits = torch.empty(S_q, S_k_aligned, dtype=torch.float32, device=device)
grid = lambda meta: (
triton.cdiv(S_q, meta["BLOCK_M"]),
triton.cdiv(S_k, meta["BLOCK_N"]),
)
BLOCK_M, BLOCK_N = 64, 128
grid = (triton.cdiv(S_q, BLOCK_M), triton.cdiv(S_k_aligned, BLOCK_N))
_triton_fp8_indexer_kernel[grid](
q_fp8,
k_fp8,
@@ -224,16 +213,17 @@ def fp8_indexer(
ks,
ke,
S_q,
S_k,
S_k_aligned,
q_fp8.stride(0),
q_fp8.stride(1),
k_fp8.stride(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),
BLOCK_M=BLOCK_M,
BLOCK_N=BLOCK_N,
num_warps=4,
num_stages=2,
)
actual_topk = min(topk, S_k)
@@ -329,7 +329,9 @@ class LagunaModel(LagunaPreTrainedModel):
}
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
attention_mask=causal_mask_mapping[self.config.layer_types[layer_idx]],
@@ -1,3 +0,0 @@
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
__all__ = ["RMSNorm", "RMSNormConfig"]
@@ -177,7 +177,9 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
@@ -192,7 +192,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
torch._dynamo.mark_dynamic(cu_seqlens, 0)
for layer_idx, decoder_layer in enumerate(self.layers):
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
layer_routed_experts = routed_experts[:, :, layer_idx].contiguous() if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
cu_seqlens,
@@ -210,7 +210,9 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
+3 -18
View File
@@ -112,7 +112,7 @@ class ParallelDims:
# Create all the submesh here to ensure all required process groups are
# initialized:
# Mesh for data loading (no communication on this mesh)
# Mesh for data loading and per-step token counts
dp_mesh_dim_names = []
# Mesh for param sharding
dp_shard_cp_mesh_dim_names = []
@@ -172,7 +172,7 @@ class ParallelDims:
# Create all the submesh here to ensure all required process groups are
# initialized:
# Mesh for data loading (no communication on this mesh)
# Mesh for data loading and per-step token counts
dp_mesh_dim_names = []
# Mesh for param sharding
dp_shard_cp_mesh_dim_names = []
@@ -263,13 +263,6 @@ class ParallelDims:
def non_data_parallel_size(self):
return self.cp * self.pp
@cached_property
def seq_len_divisor(self):
# Context Parallel requires that seq_len be divisible by 2 * CP degree,
# when load balancing is enabled (by default).
# https://github.com/pytorch/pytorch/blob/4f62dcc/torch/distributed/tensor/experimental/_attention.py#L1246
return self.cp * 2
@cached_property
def logger(self):
return get_logger()
@@ -309,7 +302,7 @@ def resolve_ep(config: ModelConfig) -> None:
get_logger().info(f"EP auto: world_size={world_size}, dp_replicate={dp_replicate} -> resolved ep={resolved_ep}")
def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> ParallelDims:
def get_parallel_dims(config: ModelConfig) -> ParallelDims:
assert isinstance(config.ep, int), (
f"config.ep must be resolved to an int before get_parallel_dims; got {config.ep!r}. "
"Call resolve_ep(config) first."
@@ -325,12 +318,4 @@ def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> Parall
world_size=dist.get_world_size(),
)
# Validate sequence length against parallel dimensions requirements
if seq_len is not None and seq_len % parallel_dims.seq_len_divisor != 0:
raise ValueError(
f"Sequence length ({seq_len}) must be divisible by "
f"seq_len_divisor ({parallel_dims.seq_len_divisor}) for the given parallel dimensions. "
f"This requirement comes from context parallel (CP={config.cp})."
)
return parallel_dims
+24 -2
View File
@@ -1,5 +1,5 @@
from pathlib import Path
from typing import TypedDict
from typing import Any, NotRequired, TypedDict
import numpy as np
import torch
@@ -7,6 +7,8 @@ from jaxtyping import Bool, Float, Int
from torch import Tensor
from prime_rl.configs.trainer import FakeDataLoaderConfig
from prime_rl.multimodal import ForwardPolicy, MultimodalAdapter
from prime_rl.trainer.multimodal import materialize_mm_refs
from prime_rl.trainer.world import get_world
from prime_rl.transports.batch import (
BatchReceiver,
@@ -47,8 +49,11 @@ class TensorMicroBatch(TypedDict):
# maximum mask size. A row containing only -1 has no mask.
sampling_mask: Int[Tensor, "batch seq mask"] | None
# Materialized immediately before this microbatch's forward pass.
# Multimodal inputs. The data loader sets mm_refs (undecoded image references), and prepare_micro_batch
# replaces them with mm_kwargs (CPU tensors for the vision encoder) and mm_forward_policy.
mm_refs: MMRefs | None
mm_kwargs: NotRequired[dict[str, Tensor] | None]
mm_forward_policy: NotRequired[ForwardPolicy | None]
# mm_token_type_ids: token type per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: Int[Tensor, "batch seq"] | None
@@ -172,6 +177,23 @@ class FakeDataLoader:
}
def prepare_micro_batch(
micro_batch: TensorMicroBatch, processor: Any | None, mm_adapter: MultimodalAdapter | None
) -> TensorMicroBatch:
"""Prepare a micro batch for the training loop. Currently only multimodal samples need preparation."""
micro_batch["mm_kwargs"] = None
micro_batch["mm_forward_policy"] = None
mm_refs = micro_batch.get("mm_refs")
if mm_refs is not None:
if processor is None or mm_adapter is None:
raise ValueError("Received multimodal samples but [model.vlm] is not set")
materialized = materialize_mm_refs(mm_refs, processor, mm_adapter)
micro_batch["mm_kwargs"] = materialized.kwargs
micro_batch["mm_forward_policy"] = materialized.forward_policy
micro_batch["mm_refs"] = None
return micro_batch
class DataLoader:
"""Receives packed micro batches from the orchestrator, one stream per DP rank."""
+17 -17
View File
@@ -1,6 +1,7 @@
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before import
from contextlib import nullcontext
from functools import partial
import time
import asyncio
from datetime import timedelta
@@ -17,7 +18,7 @@ from prime_rl.trainer.ckpt import Progress, setup_ckpt_manager
from prime_rl.trainer.optim import setup_optimizer
from prime_rl.trainer.scheduler import setup_scheduler
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader, prepare_micro_batch
from prime_rl.utils.cp import (
gather_for_cp,
gather_for_cp_wo_grad,
@@ -37,7 +38,6 @@ from prime_rl.trainer.rl.loss import (
shift_tensor_right,
)
from prime_rl.multimodal import get_multimodal_adapter
from prime_rl.trainer.multimodal import materialize_mm_refs
from prime_rl.trainer.rl.annotations import AnnotationWriter
from prime_rl.trainer.model import (
forward,
@@ -71,6 +71,7 @@ from prime_rl.utils.heartbeat import Heartbeat
from prime_rl import monitors
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.worker_pool import WorkerPool
from prime_rl.utils.pathing import resolve_latest_ckpt_step
from prime_rl.utils.utils import clean_exit
@@ -147,6 +148,8 @@ def train(config: TrainerConfig):
if processor is None:
raise ValueError("Multimodal training requires a model image processor")
mm_adapter = get_multimodal_adapter(model.config.model_type)
prepare = partial(prepare_micro_batch, processor=processor, mm_adapter=mm_adapter)
micro_batch_workers = WorkerPool(config.data.num_workers)
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
raise ValueError("Packed multimodal training requires model support")
@@ -336,7 +339,9 @@ def train(config: TrainerConfig):
cp_size = parallel_dims.cp
step_tokens_per_expert = 0
for micro_step, micro_batch in enumerate(micro_batches):
step_local_num_tokens = 0
for micro_step, micro_batch in enumerate(micro_batch_workers(prepare, micro_batches)):
step_local_num_tokens += micro_batch["input_ids"].shape[1]
input_ids = micro_batch["input_ids"].to("cuda")
position_ids = micro_batch["position_ids"].to("cuda")
advantages = micro_batch["advantages"].to("cuda")
@@ -365,17 +370,10 @@ def train(config: TrainerConfig):
micro_batch["sampling_mask"].to("cuda") if micro_batch["sampling_mask"] is not None else None
)
mm_kwargs = None
mm_forward_policy = None
mm_refs = micro_batch.get("mm_refs")
if mm_refs is not None:
if processor is None or mm_adapter is None:
raise ValueError("Received multimodal samples but [model.vlm] is not set")
materialized = materialize_mm_refs(mm_refs, processor, mm_adapter)
mm_kwargs = {key: value.to("cuda") for key, value in materialized.kwargs.items()}
mm_forward_policy = materialized.forward_policy
micro_batch["mm_refs"] = None
del materialized, mm_refs
mm_kwargs = micro_batch.pop("mm_kwargs")
if mm_kwargs is not None:
mm_kwargs = {key: value.to("cuda") for key, value in mm_kwargs.items()}
mm_forward_policy = micro_batch.pop("mm_forward_policy")
mm_token_type_ids = (
micro_batch["mm_token_type_ids"].to("cuda")
if micro_batch.get("mm_token_type_ids") is not None
@@ -631,9 +629,10 @@ def train(config: TrainerConfig):
if is_moe_model:
tensor_stats.update(get_expert_load_stats(step_tokens_per_expert, dp_cp_group))
# Compute step metrics
num_local_tokens = seq_len * batch_size
num_tokens = parallel_dims.get_mesh("dp").size() * num_local_tokens
# The dp mesh excludes cp, whose ranks hold the same rows.
global_num_tokens = torch.tensor(step_local_num_tokens, dtype=torch.int64, device="cuda")
dist.all_reduce(global_num_tokens, op=dist.ReduceOp.SUM, group=parallel_dims.get_mesh("dp").get_group())
num_tokens = global_num_tokens.item()
progress.total_tokens += num_tokens
progress.total_samples += batch_size
perf_counter = get_perf_counter(model, seq_len)
@@ -732,6 +731,7 @@ def train(config: TrainerConfig):
if gradient_manager is not None:
gradient_manager.close()
micro_batch_workers.close()
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
logger.success("RL trainer finished")
+16 -9
View File
@@ -249,6 +249,13 @@ class RendererResolver:
renderer = create_renderer(self.tokenizer, config)
if self.processor is not None and hasattr(renderer, "_processor"):
renderer._processor = self.processor
if not getattr(renderer, "is_prefix_stable", False):
get_logger().warning(
f"SFT renderer {type(renderer).__name__} does not guarantee prefix stability. "
"SFT renders each conversation once to produce one training sample; "
"it does not expand N assistant turns into N samples. Depending on the template, "
"reasoning from earlier turns may be omitted from the training sample."
)
self.renderers[config] = renderer
return renderer
@@ -279,7 +286,7 @@ class SFTDataset(StatefulIterableDataset):
# Default names are optional: a dataset carries either messages or
# prompt/completion, and tools only for tool use. A name set in the
# config must exist.
for field in ("messages", "prompt", "completion", "tools"):
for field in ("messages", "prompt", "completion", "tools", "message_loss_mask"):
column = getattr(columns, field)
if column != field and column not in dataset.column_names:
raise ValueError(f"data.columns.{field} is {column!r}, but the dataset has only {dataset.column_names}")
@@ -342,9 +349,7 @@ class SFTDataset(StatefulIterableDataset):
case _:
raise ValueError(f"Invalid message role: {message['role']}")
# Defer to the renderer's sampled_mask by default: a role filter would
# drop sampled stop markers attributed to the next message (e.g. GLM's
# turn-closing <|user|> / <|observation|>).
# Let the renderer identify sampled targets when assistant loss is enabled.
role_to_mask = None if self.loss_mask_config.assistant else should_mask
# Non-assistant roles are opted into the loss via the renderer's
@@ -359,6 +364,7 @@ class SFTDataset(StatefulIterableDataset):
tools=tools,
content_sft_roles=content_sft_roles or None,
ensure_final_stop=True,
message_loss_mask=example.get(self.columns.message_loss_mask),
)
input_ids = list(sample.token_ids)
loss_mask = list(sample.loss_mask)
@@ -474,12 +480,13 @@ class SFTDataset(StatefulIterableDataset):
class CatDataset(StatefulIterableDataset):
"""Concatenate text and multimodal samples into one fixed-length row."""
"""Pack samples into rows of at most `seq_len` tokens, padded to a multiple of `pad_to_multiple_of`."""
def __init__(self, dataset: StatefulIterableDataset, seq_len: int):
def __init__(self, dataset: StatefulIterableDataset, seq_len: int, pad_to_multiple_of: int):
self.logger = get_logger()
self.dataset = dataset
self.seq_len = seq_len
self.pad_to_multiple_of = pad_to_multiple_of
self.pending_sample: Sample | None = None
def state_dict(self) -> dict:
@@ -583,7 +590,7 @@ class CatDataset(StatefulIterableDataset):
if kept > 0:
result["seq_lens"].append(kept)
remaining -= kept
pad_len = seq_len - len(result["input_ids"])
pad_len = -len(result["input_ids"]) % self.pad_to_multiple_of
if pad_len > 0:
result["input_ids"].extend([0] * pad_len)
result["position_ids"].extend(range(pad_len))
@@ -753,8 +760,8 @@ def setup_dataset(
raise ValueError(f"Invalid dataset type: {config.type}")
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfig) -> StatefulDataLoader:
packing_dataset = CatDataset(dataset, config.seq_len * config.micro_batch_size)
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfig, cp: int) -> StatefulDataLoader:
packing_dataset = CatDataset(dataset, config.seq_len * config.micro_batch_size, pad_to_multiple_of=cp)
return StatefulDataLoader(
packing_dataset,
batch_size=1,
+10 -12
View File
@@ -113,7 +113,7 @@ def train(config: SFTConfig):
resolve_ep(config.model)
# Initialize parallel dimensions
parallel_dims = get_parallel_dims(config.model, config.data.seq_len)
parallel_dims = get_parallel_dims(config.model)
total_micro_batches = config.data.batch_size * config.model.cp
micro_batches_per_step = world.world_size * config.data.micro_batch_size
@@ -192,7 +192,7 @@ def train(config: SFTConfig):
processor=processor,
multimodal=multimodal,
)
dataloader = setup_dataloader(dataset, config.data)
dataloader = setup_dataloader(dataset, config.data, config.model.cp)
val_raw_dataset = None
if config.val is not None:
@@ -257,7 +257,7 @@ def train(config: SFTConfig):
if cp_enabled:
# CP requires the sequence length to be divisible by cp_size. CatDataset
# pads every pack to seq_len; shard_for_cp raises on violations.
# pads every pack to a multiple of it; shard_for_cp raises on violations.
defer_vlm_cp_to_model = (
mm_kwargs is not None and "image_grid_thw" in mm_kwargs and config.model.cp_style == "ulysses"
)
@@ -345,7 +345,7 @@ def train(config: SFTConfig):
processor=processor,
multimodal=multimodal,
)
val_dataloader = setup_dataloader(val_dataset, config.val.data)
val_dataloader = setup_dataloader(val_dataset, config.val.data, config.model.cp)
# No train/eval switch: no dropout in these models, and toggling would trigger torch.compile recompilation
mean_loss, nan_count = run_eval_loop(val_dataloader)
@@ -451,7 +451,9 @@ def train(config: SFTConfig):
)
step_tokens_per_expert = 0
step_local_num_tokens = 0
for micro_step, micro_batch in enumerate(micro_batches):
step_local_num_tokens += micro_batch["input_ids"].shape[1]
if config.log.log_data:
print_sample(
micro_batch["input_ids"].flatten().tolist(), micro_batch["loss_mask"].flatten().tolist(), tokenizer
@@ -549,14 +551,10 @@ def train(config: SFTConfig):
if memory_profiler is not None:
memory_profiler.step()
# Compute step metrics. CP shards the same sequences across cp ranks
# (sequence-sharded data parallelism on the seq dim), so the unique
# training tokens per step is dp_size * (batch_per_dp_rank * seq).
# The `dp` mesh excludes cp by construction (parallel_dims.py), mirroring
# the RL trainer's accounting (rl/train.py).
dp_size = parallel_dims.get_mesh("dp").size()
num_local_tokens = config.data.seq_len * (config.data.batch_size // dp_size)
num_tokens = dp_size * num_local_tokens
# The dp mesh excludes cp, whose ranks hold the same rows.
global_num_tokens = torch.tensor(step_local_num_tokens, dtype=torch.int64, device="cuda")
dist.all_reduce(global_num_tokens, op=dist.ReduceOp.SUM, group=parallel_dims.get_mesh("dp").get_group())
num_tokens = global_num_tokens.item()
progress.total_tokens += num_tokens
dataset_progress = get_dataset_progress(dataloader)
progress.total_samples = dataset_progress["step"]
+1 -1
View File
@@ -153,7 +153,7 @@ class WeightReceiver(ABC):
while not sender_ready.exists():
if cancelled is not None and cancelled():
raise asyncio.CancelledError
await asyncio.sleep(0.2)
await asyncio.sleep(0.1)
def _ack(self, step: int) -> None:
"""Acknowledge the offered version — unblocks the waiting trainer."""
+2
View File
@@ -22,6 +22,8 @@ DEFAULT_COMMON_ENV_VARS: dict[str, str] = {
"PYTHONUNBUFFERED": "1",
"OMP_NUM_THREADS": "1",
"GIT_LFS_SKIP_SMUDGE": "1",
# Processes sharing ~/.triton on a shared FS hang or crash. Per-user because /tmp is shared by all users.
"TRITON_CACHE_DIR": f"/tmp/triton-{os.getuid()}",
}
DEFAULT_TRAINER_ENV_VARS: dict[str, str] = {
+55
View File
@@ -0,0 +1,55 @@
from collections import deque
from collections.abc import Callable, Iterable, Iterator
from concurrent.futures import Future, ThreadPoolExecutor
from typing import TypeVar
T = TypeVar("T")
R = TypeVar("R")
class WorkerPool:
"""Persistent background threads that map a function over an iterator in order, or the calling thread when ``num_workers`` is 0.
``map_fn`` runs concurrently on up to ``num_workers`` threads, so it must be thread-safe.
"""
def __init__(self, num_workers: int):
self.num_workers = num_workers
self.executor: ThreadPoolExecutor | None = None
if num_workers > 0:
# Threads share the trainer's memory, so items and results pass by reference: no pickling,
# no /dev/shm copies, and no forked copy-on-write memory, unlike worker processes.
self.executor = ThreadPoolExecutor(max_workers=num_workers, thread_name_prefix="worker-pool")
def __call__(self, map_fn: Callable[[T], R], items: Iterable[T]) -> Iterator[R]:
"""Yield ``map_fn(item)`` in input order, with at most ``2 * num_workers`` items submitted but not yet yielded.
The factor 2 plays the role of torch DataLoader's ``prefetch_factor`` (batches loaded ahead per worker),
hard-coded to its torch default for simplicity. Any bound above ``num_workers`` keeps every worker busy while
the caller holds a result; the extra slack absorbs items that take unusually long.
"""
if self.executor is None:
yield from map(map_fn, items)
return
max_in_flight = 2 * self.num_workers
pending: deque[Future[R]] = deque()
try:
for item in items:
pending.append(self.executor.submit(map_fn, item))
if len(pending) >= max_in_flight:
yield pending.popleft().result()
while pending:
yield pending.popleft().result()
finally:
for future in pending:
future.cancel()
def close(self) -> None:
if self.executor is not None:
self.executor.shutdown(cancel_futures=True)
def __enter__(self) -> "WorkerPool":
return self
def __exit__(self, *exc_info: object) -> None:
self.close()
+87 -27
View File
@@ -1,6 +1,11 @@
import uuid
from types import SimpleNamespace
import orjson
import pytest
import verifiers.v1 as vf
from pydantic import ValidationError
from verifiers.v1.utils.eval import plan_rollouts
from prime_rl.eval import resume
from prime_rl.monitors.file.traces import get_trace_stream
@@ -21,6 +26,7 @@ def _env(name: str, task_keys: list[str], *, group_size: int = 1) -> SimpleNames
def _record(env: str, key: str, *, ok: bool = True, group: str | None = None) -> dict:
return {
"id": uuid.uuid4().hex,
"env": {"id": env, "name": env},
"task": {"type": "Task", "data": {"idx": 0}, "key": key, "hash": key},
"group": {"id": group or f"group-{key}"},
@@ -29,38 +35,64 @@ def _record(env: str, key: str, *, ok: bool = True, group: str | None = None) ->
}
def test_plan_keeps_landed_rollouts_up_to_the_target_and_owes_the_rest() -> None:
envs = [_env("math", ["m0", "m1", "m2"], group_size=2), _env("code", ["c0"])]
landed = [
_record("math", "m0"),
_record("math", "m0"),
_record("math", "m0"), # a third rollout of m0 exceeds group_size 2
_record("math", "m1"),
_record("math", "m9"), # no longer selected (select.limit shrank)
_record("code", "c0", ok=False), # errored: owed again
]
@pytest.mark.parametrize(
"hashes,rollouts,landed,expected_kept,expected_missing",
[
(["a", "b"], 2, [], [[], []], [2, 2]),
(["a"], 1, [("e1", "a")], [["e1"]], [0]),
(["changed"], 1, [("e1", "a")], [[]], [1]),
(["a"], 3, [("e1", "a"), ("e2", "a")], [["e1", "e2"]], [1]),
(["a"], 1, [("e1", "a"), ("e2", "a")], [["e1"]], [0]),
(["a", "a"], 2, [("e1", "a")], [["e1"], []], [1, 2]),
(["a", "changed"], 1, [("e1", "a"), ("e2", "a")], [["e1"], []], [0, 1]),
(["a"], 2, [("e1", "a"), ("e1", "a")], [["e1"]], [1]),
(["a"], 1, [("e1", "removed")], [[]], [1]),
([], 1, [("e1", "a")], [], []),
],
)
def test_plan_keeps_landed_rollouts_up_to_the_target_and_owes_the_rest(
hashes, rollouts, landed, expected_kept, expected_missing
) -> None:
tasks = [SimpleNamespace(key="stable-key", hash=content_hash) for content_hash in hashes]
episodes = []
for episode_id, content_hash in landed:
row = _record("math", "stable-key")
row["id"] = episode_id
row["task"]["hash"] = content_hash
episodes.append(vf.WireEpisode.model_validate(row))
kept, owed, groups = resume.plan([record for record in landed if record["ok"]], envs)
plan = plan_rollouts(tasks, rollouts, episodes)
assert [(episode.env.name, episode.task.key) for episode in kept] == [
("math", "m0"),
("math", "m0"),
("math", "m1"),
]
assert owed == {"math": {"m1": 1, "m2": 2}, "code": {"c0": 1}}
# the owed rollout of m1 completes the group its landed rollout opened
assert groups == {"math": {"m0": "group-m0", "m1": "group-m1"}}
assert [task for task, _, _ in plan] == tasks
assert [[episode.id for episode in kept] for _, kept, _ in plan] == expected_kept
assert [missing for _, _, missing in plan] == expected_missing
assert all(len(kept) + missing == rollouts for _, kept, missing in plan)
def test_trigger_queues_only_owed_rollouts() -> None:
source = EvalSource([_env("math", ["m0", "m1", "m2"], group_size=2), _env("code", ["c0"])])
source.restore({"math": {"m1": 1, "m2": 2}, "code": {}}, {"math": {"m1": "group-m1"}})
source = EvalSource([_env("math", ["m0", "m1", "m1"], group_size=2), _env("code", ["m1"])])
episodes = [vf.WireEpisode.model_validate(_record("math", key)) for key in ["m0", "m0", "m1"]]
assert source.trigger(0) == ["math", "code"]
assert [(request.env_name, request.task.key, request.rollouts, request.group_id) for request in source.queue] == [
("math", "m1", 1, "group-m1"),
("math", "m2", 2, None),
fired, restored = source.trigger(0, completed=episodes)
assert fired == ["math", "code"]
requests = list(source.queue)
assert [(request.env_name, request.task.key, request.rollouts) for request in requests] == [
("code", "m1", 1),
("math", "m1", 1),
("math", "m1", 2),
]
assert restored == episodes
assert len({request.group_id for request in requests}) == 3
assert restored[-1].group.id == requests[1].group_id
assert restored[0].group == restored[1].group
assert restored[0].group != restored[-1].group
assert all(str(uuid.UUID(request.group_id)) == request.group_id for request in requests)
# Saved episodes affect only this epoch; later triggers plan every rollout again.
source.queue.clear()
assert source.trigger(1) == (["math", "code"], [])
assert [request.rollouts for request in source.queue] == [2, 1, 2, 2]
def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
@@ -71,11 +103,39 @@ def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
stream.close()
land("m0", "m1")
assert [record["id"] for record in resume.take_landed(tmp_path)] == ["m0", "m1"]
assert [episode.id for episode in resume.take_landed(tmp_path)] == ["m0", "m1"]
assert not get_file_monitor_dir(tmp_path).exists()
assert [path.name for path in resume.archives(tmp_path)] == ["file.attempt_1"]
# the resumed attempt re-logged one episode and landed a new one before it died
land("m0", "m2")
assert [record["id"] for record in resume.take_landed(tmp_path)] == ["m0", "m1", "m2"]
landed = resume.take_landed(tmp_path)
source = EvalSource([_env("math", ["m0", "m1", "m2"], group_size=2)])
_, kept = source.trigger(0, completed=landed)
assert [episode.id for episode in kept] == ["m0", "m1", "m2"]
assert [request.rollouts for request in source.queue] == [1, 1, 1]
assert [path.name for path in resume.archives(tmp_path)] == ["file.attempt_1", "file.attempt_2"]
@pytest.mark.parametrize("ok", [True, False])
@pytest.mark.parametrize("traces,valid", [([], True), (None, False), ([{}], False)])
def test_resume_validates_saved_episodes(tmp_path, ok, traces, valid) -> None:
record = {**_record("math", "m0", ok=ok), "id": "saved", "traces": traces}
stream = ChunkedJsonl(get_trace_stream(tmp_path), max_bytes=1 << 20, compress=False)
for row in [{key: value for key, value in record.items() if key != "traces"}, record]:
stream.append(orjson.dumps(row, option=orjson.OPT_APPEND_NEWLINE))
stream.close()
if not valid:
with pytest.raises(ValidationError):
resume.take_landed(tmp_path)
assert get_file_monitor_dir(tmp_path).is_dir()
assert resume.archives(tmp_path) == []
return
landed = resume.take_landed(tmp_path)
source = EvalSource([_env("math", ["m0"], group_size=2)])
_, restored = source.trigger(0, completed=landed)
assert [episode.id for episode in restored] == (["saved"] if ok else [])
assert [request.rollouts for request in source.queue] == [1 if ok else 2]
@@ -110,6 +110,7 @@ def _build_episode(
task=trace.task,
group=vf.GroupInfo(id="group"),
traces=[trace],
ok=True,
)
return episode
@@ -9,6 +9,7 @@ from verifiers.v1.types import AssistantMessage, ToolMessage, UserMessage
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
from prime_rl.orchestrator.algo import EchoAlgorithm, assign_advantages, stamp_loss_routing
from prime_rl.orchestrator.algo.base import iter_trainable_traces
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.transports.batch.types import TrainingSample
@@ -201,10 +202,33 @@ def _make_episode() -> vf.Episode:
task=trace.task,
group=vf.GroupInfo(id="group"),
traces=[trace],
ok=True,
)
return episode
@pytest.mark.parametrize("failure", ["participant", "untrainable_participant", "environment"])
def test_trainable_traces_exclude_failed_episodes_without_changing_verdicts(failure):
good = _make_episode()
good.errors = [vf.Error(type="RecoveredError", message="Previous attempt failed")]
good.traces[0].errors = list(good.errors)
failed = _make_episode()
failed.ok = False
if failure == "environment":
failed.errors = [vf.Error(type="EnvError", message="Finalization failed")]
else:
sibling = failed.traces[0].model_copy(deep=True)
sibling.id = "failed-sibling"
sibling.ok = False
sibling.errors = [vf.Error(type="AgentError", message="Participant failed")]
sibling.agent.trainable = failure == "participant"
failed.traces.append(sibling)
before = failed.model_dump()
assert list(iter_trainable_traces([failed, good])) == [(good, good.traces[0])]
assert failed.model_dump() == before
def test_assign_advantages_full_length_stream():
# The advantage stream is full-length-N: 0.0 on prompt + non-trainable
# positions, the rl credit on trainable (mask True) tokens.
+21 -2
View File
@@ -42,7 +42,7 @@ def make_rollout(
)
]
if advantages is not None
else []
else [vf.MessageNode(message=vf.AssistantMessage(content="answer"), sampled=True)]
)
trace = vf.Trace(
task=vf.TraceTask(
@@ -61,6 +61,7 @@ def make_rollout(
task=trace.task,
group=vf.GroupInfo(id=str(uuid.uuid4())),
traces=[trace],
ok=True,
)
return [episode]
@@ -111,7 +112,12 @@ def test_train_source_composes_sampler_and_all_gates_with_state_and_metrics() ->
source = TrainSource([env])
sampled = source.next_task(step=1).task
assert source.on_result(make_rollout(sampled, reward=0.25, advantages=[0.0])) is False
empty = make_rollout(sampled, reward=1.0)
empty[0].traces[0].nodes[0].sampled = False
group = make_rollout(sampled, reward=0.25, advantages=[0.0])
failed = make_rollout(sampled, reward=1.0, advantages=[1.0])
failed[0].ok = False
assert source.on_result(group + failed + empty) is False
assert source.metrics() == {
"curriculum/test/admission_rate": 0.0,
"curriculum/test/sampler/pool/unseen": 2.0,
@@ -127,6 +133,19 @@ def test_train_source_composes_sampler_and_all_gates_with_state_and_metrics() ->
"admit": {},
}
assert source.on_result(empty) is False
assert source.metrics()["curriculum/test/admission_rate"] == 0.0
assert source.curricula["test"].sampler.task_rewards == {sampled.key: 0.25}
# A scored rollout without token metadata still informs task difficulty.
assert source.on_result(make_rollout(sampled, reward=0.5)) is False
assert source.metrics()["curriculum/test/admission_rate"] == 0.0
assert source.curricula["test"].sampler.task_rewards == {sampled.key: 0.5}
assert source.on_result(make_rollout(sampled, reward=0.75, advantages=[1.0])) is True
assert source.metrics()["curriculum/test/admission_rate"] == 1.0
assert source.curricula["test"].sampler.task_rewards == {sampled.key: 0.75}
def test_difficulty_pools_stack_with_advantage_gate_and_resume_sampling() -> None:
tasks = [make_task(i) for i in range(3)]
+89 -4
View File
@@ -4,6 +4,7 @@ from typing import Annotated, Literal, get_args
import pytest
import tomli_w
import verifiers.v1 as vf
from pydantic import BaseModel, Field, ValidationError
from pydantic_config import ConfigFileError
from renderers import custom_renderer_config
@@ -17,6 +18,7 @@ from prime_rl.configs.orchestrator import (
RLOnlineEvalConfig,
ScheduledEvalConfig,
TrainConfig,
TrainSourceConfig,
)
from prime_rl.configs.orchestrator import (
ModelConfig as OrchestratorModelConfig,
@@ -462,11 +464,25 @@ def test_env_algo_inherits_the_group_algo():
assert [env.algo.type for env in reloaded.train.source] == ["grpo", "echo", "echo"]
def test_sources_inherit_the_group_fields_they_leave_unset():
@pytest.mark.parametrize("group_token_key", ["max_tokens", "max_completion_tokens"])
@pytest.mark.parametrize("source_token_key", ["max_tokens", "max_completion_tokens"])
@pytest.mark.parametrize("source_token_limit", [200, None])
@pytest.mark.parametrize("nested_sampling", [False, True])
def test_sources_inherit_the_group_fields_they_leave_unset(
group_token_key, source_token_key, source_token_limit, nested_sampling
):
overrides = {source_token_key: source_token_limit, "top_k": 20}
config = EvalConfig.model_validate(
{
"r": 4,
"sampling": {"temperature": 0.5, "extra_body": {"a": 1}},
"sampling": {
group_token_key: 100,
"temperature": 3.0,
"reasoning_effort": "xhigh",
"top_k": 40,
"frequency_penalty": 0.5,
"extra_body": {"a": 1},
},
"select": {"limit": 8, "include": {"idx": [":100"]}},
"env": {"retries": {"max_retries": 3}},
"source": [
@@ -475,7 +491,11 @@ def test_sources_inherit_the_group_fields_they_leave_unset():
"name": "b",
"env": {"taskset": {"id": "gsm8k"}},
"group_size": 2,
"sampling": {"extra_body": {"b": 2}},
"sampling": {
**({} if nested_sampling else overrides),
"reasoning_effort": "max",
"extra_body": {"b": 2, **(overrides if nested_sampling else {})},
},
"select": {"include": {"names": ["x"]}},
},
],
@@ -483,7 +503,18 @@ def test_sources_inherit_the_group_fields_they_leave_unset():
)
a, b = config.source
assert (a.group_size, b.group_size) == (4, 2)
assert b.sampling.temperature == 0.5 and b.sampling.extra_body == {"a": 1, "b": 2}
assert isinstance(a.sampling, vf.SamplingConfig) and isinstance(b.sampling, vf.SamplingConfig)
assert a.sampling.max_tokens == 100 and b.sampling.max_tokens == source_token_limit
assert a.sampling.reasoning_effort == "xhigh" and a.sampling.top_k == 40
assert b.sampling.model_dump(exclude_none=True) == {
**({"max_tokens": source_token_limit} if source_token_limit is not None else {}),
"temperature": 3.0,
"reasoning_effort": "max",
"top_k": 20,
"frequency_penalty": 0.5,
"a": 1,
"b": 2,
}
assert b.select.limit == 8 and b.select.include.idx == [":100"] and b.select.include.names == ["x"]
assert a.env.retries.max_retries == 3 and b.env.retries.max_retries == 3
reloaded = EvalConfig.model_validate(config.model_dump(mode="json"))
@@ -564,6 +595,39 @@ def test_policy_sources_accept_different_top_p_values():
assert [source.sampling.top_k for source in config.train.source] == [512, 512]
@pytest.mark.parametrize("frozen", [False, True])
@pytest.mark.parametrize(
"sampling,agent_sampling,rejected",
[
({}, {}, False),
({"top_p": 0.9}, {"max_completion_tokens": 200, "reasoning_effort": "high"}, False),
({}, {"extra_body": {"chat_template_kwargs": {"enable_thinking": True}}}, False),
({}, {"temperature": 1.0}, True),
({}, {"temperature": None}, True),
({}, {"extra_body": {"top_k": 20}}, True),
({}, {"frequency_penalty": 0.5}, True),
({}, {"extra_body": {"frequency_penalty": 0.5}}, True),
({"extra_body": {"frequency_penalty": 0.5}}, {}, True),
],
)
def test_policy_sampling_is_validated_before_rollouts(sampling, agent_sampling, rejected, frozen):
source = {
"env": {"taskset": {"id": "reverse-text"}, "agent": {"sampling": agent_sampling}},
"sampling": sampling,
}
if frozen:
source["algo"] = {
"type": "sft",
"sampling": {"source": {"name": "teacher", "base_url": "http://localhost:8000/v1"}},
}
if rejected and not frozen:
with pytest.raises(ValidationError, match="sampling"):
TrainSourceConfig.model_validate(source)
else:
config = TrainSourceConfig.model_validate(source)
assert TrainSourceConfig.model_validate_json(config.model_dump_json()) == config
def test_policy_sources_reject_mixed_top_k_capture():
with pytest.warns(UserWarning, match="defaulting top_k"):
with pytest.raises(ValidationError, match="cannot mix top_k > 0 and top_k = -1"):
@@ -604,10 +668,31 @@ def test_single_node_auto_inference_ports_follow_server_port():
assert config.inference is not None
assert config.inference.vllm.data_parallel_size == 2
assert config.trainer.weight_broadcast.inference_world_size == 2
assert config.orchestrator.weight_broadcast.inference_world_size == 2
assert config.inference.backend_port == 8101
assert config.orchestrator.model.client.admin_base_url == ["http://localhost:8101/v1"]
def test_single_node_nccl_resolved_json_roundtrips(tmp_path):
"""The resolved rl.json re-parses (as a SLURM launch does) to the same config."""
import json
config = RLConfig.model_validate(
{
"trainer": {},
"orchestrator": {},
"inference": {"vllm": {"tensor_parallel_size": 1}},
"deployment": {"type": "single_node", "gpus_per_node": 4, "num_train_gpus": 2, "num_infer_gpus": 2},
}
)
path = tmp_path / "rl.json"
path.write_text(json.dumps(dump_resolved_config(config, exclude={"slurm", "dry_run", "clean"})))
reloaded = cli(RLConfig, args=["@", str(path)])
assert reloaded.trainer.weight_broadcast.inference_world_size == 2
assert reloaded == config
def test_multi_node_auto_inference_parallelism():
config = RLConfig.model_validate(
{
+5 -4
View File
@@ -19,7 +19,7 @@ def setup_fake_dataloader(config: FakeDataConfig, non_dp_size: int = 1):
seed=config.seed,
non_dp_size=non_dp_size,
)
return dataset, setup_dataloader(dataset, config)
return dataset, setup_dataloader(dataset, config, cp=1)
def test_fake_dataset_single_rank_state():
@@ -88,7 +88,7 @@ def test_fake_dataset_single_rank_resume():
# Reload dataloader
state_dict = dataloader.state_dict()
dataloader = setup_dataloader(dataset, config)
dataloader = setup_dataloader(dataset, config, cp=1)
dataloader.load_state_dict(state_dict)
dataiter = iter(dataloader)
@@ -110,7 +110,8 @@ def test_fake_dataset_single_rank_state_with_packing():
micro_batch = next(dataiter)
num_packed_examples = len(micro_batch["input_ids"][micro_batch["loss_mask"]].unique())
step += num_packed_examples
assert micro_batch["input_ids"].shape == (1, 128)
assert micro_batch["input_ids"].shape[0] == 1
assert micro_batch["input_ids"].shape[1] <= 128
assert micro_batch["seq_lens"].sum() == micro_batch["input_ids"].shape[1]
worker_state = dataloader.state_dict()["_snapshot"]["_worker_snapshots"]["worker_0"]["dataset_state"]
pending_sample = worker_state.get("pending_sample")
@@ -186,7 +187,7 @@ def test_dataloader_shards_across_ranks_and_workers(
seq_len=config.seq_len,
non_dp_size=non_dp_size,
)
return setup_dataloader(dataset, config)
return setup_dataloader(dataset, config, cp=1)
dataloader = setup_epoch_dataloader()
dataiter = iter(dataloader)
+85 -11
View File
@@ -443,6 +443,7 @@ def test_cat_dataset_packs_multimodal_samples():
),
],
seq_len=5,
pad_to_multiple_of=1,
)
packed = next(iter(dataset))
@@ -467,23 +468,24 @@ def test_cat_dataset_packs_text_and_multimodal_samples_together():
mm_token_type_ids=[0, 1],
),
_sft_sample([4]),
_sft_sample([5, 6]),
_sft_sample([5, 6, 7, 8, 9, 10]),
],
seq_len=5,
seq_len=9,
pad_to_multiple_of=3,
)
dataiter = iter(dataset)
packed = next(dataiter)
text_pack = next(dataiter)
assert packed["input_ids"] == [1, 2, 3, 4, 0]
assert packed["loss_mask"] == [True, True, True, True, False]
assert packed["seq_lens"] == [1, 2, 2]
assert packed["input_ids"] == [1, 2, 3, 4, 0, 0]
assert packed["loss_mask"] == [True, True, True, True, False, False]
assert packed["seq_lens"] == [1, 2, 3]
assert packed["mm_kwargs"] is not None
assert packed["mm_token_type_ids"] == [0, 0, 1, 0, 0]
assert text_pack["input_ids"] == [5, 6, 0, 0, 0]
assert text_pack["loss_mask"] == [True, True, False, False, False]
assert text_pack["seq_lens"] == [5]
assert packed["mm_token_type_ids"] == [0, 0, 1, 0, 0, 0]
assert text_pack["input_ids"] == [5, 6, 7, 8, 9, 10]
assert text_pack["loss_mask"] == [True] * 6
assert text_pack["seq_lens"] == [6]
assert text_pack["mm_kwargs"] is None
assert text_pack["mm_token_type_ids"] is None
@@ -508,6 +510,10 @@ class EffortRenderer:
def __init__(self, tokenizer, config):
self.config = config
@property
def is_prefix_stable(self):
return self.config.reasoning_effort == "low"
def render(self, messages, **kwargs):
return RenderedTokens(token_ids=[0, 1], message_indices=[-1, 0], sampled_mask=[False, True])
@@ -528,8 +534,21 @@ def custom_renderer_config(tmp_path):
def test_renderer_resolver_applies_renderer_columns_to_custom_renderer(custom_renderer_config):
resolver = sft_data.RendererResolver(tokenizer=None, config=custom_renderer_config)
default = resolver({"messages": [], "reasoning_effort": None})
high = resolver({"messages": [], "reasoning_effort": "high"})
warnings = []
logger = sft_data.get_logger()
sink = logger.add(lambda message: warnings.append(str(message)), level="WARNING", format="{message}")
try:
default = resolver({"messages": [], "reasoning_effort": None})
assert warnings == []
high = resolver({"messages": [], "reasoning_effort": "high"})
assert resolver({"reasoning_effort": "high"}) is high
assert len(warnings) == 1
assert "does not guarantee prefix stability" in warnings[0]
assert "one training sample" in warnings[0]
assert "does not expand N assistant turns into N samples" in warnings[0]
assert "reasoning from earlier turns may be omitted" in warnings[0]
finally:
logger.remove(sink)
assert default.config.reasoning_effort == "low"
assert high.config.reasoning_effort == "high"
@@ -569,6 +588,8 @@ def test_sft_dataset_reads_mapped_message_columns(dummy_renderer):
with pytest.raises(ValueError, match="'messages' column"):
next(iter(SFTDataset(dataset, lambda _: dummy_renderer)))
with pytest.raises(ValueError, match="data.columns.message_loss_mask"):
SFTDataset(dataset, lambda _: dummy_renderer, columns=SFTColumnsConfig(message_loss_mask="selection"))
with pytest.raises(ValueError, match="data.columns.prompt"):
SFTDataset(dataset, lambda _: dummy_renderer, columns=SFTColumnsConfig(prompt="question"))
@@ -594,3 +615,56 @@ def test_sft_dataset_passes_tools_through_from_the_mapped_column(dummy_renderer)
next(iter(SFTDataset(dataset, lambda _: RecordingRenderer(), columns=SFTColumnsConfig(tools="schemas"))))
assert seen == [[], tools]
@pytest.mark.parametrize("model", ["zai-org/GLM-5", "Qwen/Qwen3-0.6B"])
@pytest.mark.parametrize("layout", ["messages", "prompt_completion"])
@pytest.mark.parametrize("column", ["message_loss_mask", "selection"])
@pytest.mark.parametrize("mask", [None, [True, True, True, True], [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0]])
def test_sft_message_selection(model, layout, column, mask):
from prime_rl.configs.sft import SFTColumnsConfig
tokenizer = AutoTokenizer.from_pretrained(model)
renderer = create_renderer(tokenizer)
messages = [
{"role": "user", "content": "Question"},
{"role": "assistant", "content": "Prefilled"},
{"role": "user", "content": "Follow up"},
{"role": "assistant", "content": "Answer"},
]
row = {"messages": messages} if layout == "messages" else {"prompt": messages[:2], "completion": messages[2:]}
baseline = SFTDataset(Dataset.from_list([row]), lambda _: renderer)._process(row)
row[column] = mask
dataset = SFTDataset(
Dataset.from_list([row]), lambda _: renderer, columns=SFTColumnsConfig(message_loss_mask=column)
)
sample = dataset._process(row)
if mask == [0, 0, 0, 0]:
assert sample is None
return
assert sample["input_ids"] == baseline["input_ids"]
assert sample["target_ids"] == baseline["target_ids"]
if mask is None or all(mask):
assert sample["loss_mask"] == baseline["loss_mask"]
return
trained = tokenizer.decode([token for token, keep in zip(sample["target_ids"], sample["loss_mask"]) if keep])
if mask[1]:
assert "Prefilled" in trained
assert "Answer" not in trained
if model == "zai-org/GLM-5":
assert trained == "Prefilled<|user|>"
else:
assert "Prefilled" not in trained
assert "Answer" in trained
if model == "zai-org/GLM-5":
assert trained == "Answer<|endoftext|>"
assert "Question" not in trained
assert "Follow up" not in trained
@pytest.mark.parametrize("mask", [[], [1, 0], ["0"], [2], [None]])
def test_sft_rejects_invalid_message_selection(dummy_renderer, mask):
row = {"messages": [{"role": "assistant", "content": "Answer"}], "message_loss_mask": mask}
dataset = SFTDataset(Dataset.from_list([row]), lambda _: dummy_renderer)
with pytest.raises(ValueError, match="message_loss_mask"):
dataset._process(row)
+46
View File
@@ -0,0 +1,46 @@
import itertools
import time
import pytest
from prime_rl.utils.worker_pool import WorkerPool
def _slowest_first(item: int) -> int:
time.sleep(0.05 / (item + 1))
return item
def _fail_on_two(item: int) -> int:
if item == 2:
raise KeyError(item)
return item
@pytest.mark.parametrize("num_workers", [0, 2])
def test_worker_pool_preserves_order(num_workers: int):
with WorkerPool(num_workers) as workers:
assert list(workers(_slowest_first, range(6))) == list(range(6))
@pytest.mark.parametrize("num_workers", [0, 2])
def test_worker_pool_propagates_worker_exception(num_workers: int):
with WorkerPool(num_workers) as workers, pytest.raises(KeyError):
list(workers(_fail_on_two, range(4)))
@pytest.mark.parametrize("num_workers", [0, 2])
def test_worker_pool_reads_input_lazily(num_workers: int):
pulled = []
def source():
for item in itertools.count():
pulled.append(item)
yield item
consumed = 4
with WorkerPool(num_workers) as workers:
assert list(itertools.islice(workers(lambda item: item, source()), consumed)) == list(range(consumed))
max_in_flight = 2 * num_workers
assert len(pulled) == (consumed + max_in_flight - 1 if num_workers else consumed)
+29 -2
View File
@@ -20,8 +20,8 @@ from pathlib import Path
import torch
from safetensors import safe_open
from safetensors.torch import save_file
from prime_rl.trainer.models.fp8 import quantize_to_fp8_blockwise
from torch import Tensor
from torch.nn import functional as F
# Module-name substrings that stay unquantized: norms, embeddings, output head,
# MoE router gates, GatedDeltaNet low-rank projections, MTP/indexer projections,
@@ -41,6 +41,33 @@ SKIP_SUBSTRINGS = (
)
def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
"""Quantize a 2D tensor to FP8 e4m3 with per-block scales."""
if weight.ndim != 2:
raise ValueError(f"FP8 quantization expects a 2D tensor, got shape={tuple(weight.shape)}")
rows, cols = weight.shape
pad_rows = (block_size - rows % block_size) % block_size
pad_cols = (block_size - cols % block_size) % block_size
padded = F.pad(weight, (0, pad_cols, 0, pad_rows)).contiguous()
padded_rows, padded_cols = padded.shape
blocks = padded.view(
padded_rows // block_size,
block_size,
padded_cols // block_size,
block_size,
).permute(0, 2, 1, 3)
fp8_max = torch.finfo(torch.float8_e4m3fn).max
max_abs = blocks.float().abs().amax(dim=(2, 3))
scales = (max_abs / fp8_max).clamp(min=1e-12)
blocks_fp8 = (blocks.float() / scales[:, :, None, None]).clamp(-fp8_max, fp8_max).to(torch.float8_e4m3fn)
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
return quantized, scales.float().contiguous()
def should_quantize(name: str, tensor: torch.Tensor) -> bool:
return (
name.endswith(".weight")
Generated
+66 -16
View File
@@ -24,7 +24,7 @@ fastokens = false
flash-attn-3 = false
flash-mla = false
flashinfer-python = false
harbor = "2026-08-11T00:00:00Z"
harbor = "2026-10-08T00:00:00Z"
nixl-cu13 = false
prime = false
prime-evals = false
@@ -113,12 +113,14 @@ members = [
"pi-programbench",
"pi-swe-sweep",
"pi-terminal-bench-2",
"pi-terminalbench2-1",
"pinchbench",
"prime-rl",
"prolog",
"proofnet",
"proposer-solver",
"proverbench",
"ptx-remote",
"putnambench",
"r2e-gym",
"recursive-task-synthesis",
@@ -2206,7 +2208,7 @@ wheels = [
[[package]]
name = "harbor"
version = "0.21.0"
version = "0.24.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "dirhash" },
@@ -2214,6 +2216,7 @@ dependencies = [
{ name = "filelock" },
{ name = "httpx" },
{ name = "jinja2" },
{ name = "jsonschema" },
{ name = "litellm" },
{ name = "packaging" },
{ name = "pathspec" },
@@ -2224,6 +2227,7 @@ dependencies = [
{ name = "pyyaml" },
{ name = "requests" },
{ name = "rich" },
{ name = "semver" },
{ name = "shortuuid" },
{ name = "supabase" },
{ name = "tenacity" },
@@ -2231,9 +2235,9 @@ dependencies = [
{ name = "typer" },
{ name = "uvicorn" },
]
sdist = { url = "https://files.pythonhosted.org/packages/d1/30/c854dcf2b6cbc67f97265e1fd07de02b29419007d4258cded336c23d6356/harbor-0.21.0.tar.gz", hash = "sha256:93f7c2e4b150b2983a90b226c61daf071c35a9dd0f76e1053413d9ee0d738395", size = 1690211, upload-time = "2026-08-10T20:52:34.767Z" }
sdist = { url = "https://files.pythonhosted.org/packages/82/7d/16e21cfd52938260dce71ff77ec1ed156bd8c327642760fe66163b0cd3ce/harbor-0.24.0.tar.gz", hash = "sha256:6c5185e6a76abc677ed3f95e688dc0dbf8597e4fa50847cb9a37a4448c91b1e5", size = 2090577, upload-time = "2026-10-05T05:04:46.252Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/2a/a4/b3e8aafbc0a002501c11c91958fc31a5098c2bd9376c46225af615373329/harbor-0.21.0-py3-none-any.whl", hash = "sha256:c77d779a03f1a9e8ecb3c449e17f39a9728b82238832f1fd28632eb9426c0a21", size = 1896665, upload-time = "2026-08-10T20:52:32.305Z" },
{ url = "https://files.pythonhosted.org/packages/9e/63/0e3d788e8d1ed116125507c6a01e3fb95cf82be71f2ea7040a1458709d21/harbor-0.24.0-py3-none-any.whl", hash = "sha256:23b7ba616a3aae4eff561ced5e2c51c7186f2981e53a770dea9c689d3969877c", size = 2331740, upload-time = "2026-10-05T05:04:42.088Z" },
]
[[package]]
@@ -4719,7 +4723,7 @@ requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.2
[[package]]
name = "pi-officeqa-pro-v2"
version = "0.1.4"
version = "0.1.5"
source = { editable = "deps/prime-envs/environments/search/pi_officeqa_pro_v2" }
dependencies = [
{ name = "verifiers" },
@@ -4741,7 +4745,7 @@ requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.2
[[package]]
name = "pi-swe-sweep"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/swe/pi_swe_sweep" }
dependencies = [
{ name = "verifiers", extra = ["harbor"] },
@@ -4761,6 +4765,17 @@ dependencies = [
[package.metadata]
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.1" }]
[[package]]
name = "pi-terminalbench2-1"
version = "0.2.2"
source = { editable = "deps/prime-envs/environments/terminal/pi_terminalbench2_1" }
dependencies = [
{ name = "verifiers", extra = ["harbor"] },
]
[package.metadata]
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.2.dev162" }]
[[package]]
name = "pillow"
version = "12.3.0"
@@ -5264,7 +5279,7 @@ train = [
[[package]]
name = "prime-sandboxes"
version = "0.4.1"
version = "0.4.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiofiles" },
@@ -5276,9 +5291,9 @@ dependencies = [
{ name = "pyqwest" },
{ name = "tenacity" },
]
sdist = { url = "https://files.pythonhosted.org/packages/66/31/5ad18141756a8cdbff89061426cbb8816aafb513de935caa8e8f875c8819/prime_sandboxes-0.4.1.tar.gz", hash = "sha256:53f7577dc9070e3b8e30db360f9e3cce3bcc35f8765b26f24f64dbc3c7763b06", size = 134242, upload-time = "2026-10-01T01:58:55.117Z" }
sdist = { url = "https://files.pythonhosted.org/packages/d8/1b/01e02c9d2346956f5ed77d269f836905a017ad796a4b4c719debd8942dc4/prime_sandboxes-0.4.3.tar.gz", hash = "sha256:a2169182f74307485c73f897e224c978eba3276133ddb40715be4d346594c487", size = 140588, upload-time = "2026-10-08T00:24:03.668Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/af/c9/72067996420188928a6d5e05af46d60530edf24d78ca2d5bbf9fcef247cf/prime_sandboxes-0.4.1-py3-none-any.whl", hash = "sha256:1a1bb96afacc66d690815be82c0b7af180ea141421b7d180b4a0adbada4f38f0", size = 72136, upload-time = "2026-10-01T01:58:53.63Z" },
{ url = "https://files.pythonhosted.org/packages/e1/5f/d0b5cd1dabdb6e5cb1ab5d84c8ba9a96e2a9a0be8913ec9db9177c9645fb/prime_sandboxes-0.4.3-py3-none-any.whl", hash = "sha256:dd26007838c25b5d38a8b7af0514c07027b783406c0ea5b9fcf0eb74a45139bd", size = 75515, upload-time = "2026-10-08T00:24:02.208Z" },
]
[[package]]
@@ -5296,16 +5311,16 @@ wheels = [
[[package]]
name = "prime-tunnel"
version = "0.1.11"
version = "0.1.14"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx" },
{ name = "pydantic" },
{ name = "tenacity" },
]
sdist = { url = "https://files.pythonhosted.org/packages/de/c7/55c21d8e1abfb66d3a0dc0e25b89abb506b0a49605fb4b0040590af82136/prime_tunnel-0.1.11.tar.gz", hash = "sha256:cd93e78824ef824b45e636f5f506898bc7f9a6c913fd5095ab1df2233a49b949", size = 15889, upload-time = "2026-09-04T17:09:25.258Z" }
sdist = { url = "https://files.pythonhosted.org/packages/db/7d/8d8cdd03aada223acc53d4de49cf7f195d7656705a0f3d2339051890a9f1/prime_tunnel-0.1.14.tar.gz", hash = "sha256:4968787d8702578b213204d2524c3525985cd0362f50841af5fa2465d0d4e2cb", size = 22378, upload-time = "2026-10-09T00:16:40.263Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d0/7f/6ea38563db9414ed208758de6e8dc557b20e245787e42568f89531fc6717/prime_tunnel-0.1.11-py3-none-any.whl", hash = "sha256:19c5e02e389e5e61fff1507f07c46db9b05ad01424ff3b6a0cbe66187c957f61", size = 16676, upload-time = "2026-09-04T17:09:24.157Z" },
{ url = "https://files.pythonhosted.org/packages/b8/d4/51e2b8fea13709edf3a6b94fb81d27a0eb3da11b339d870ace41de813dbb/prime_tunnel-0.1.14-py3-none-any.whl", hash = "sha256:a0e21f2b9ff61cf07c038486ddc541fe07326c65e703aaf4c795fae460ac6402", size = 19345, upload-time = "2026-10-09T00:16:38.845Z" },
]
[[package]]
@@ -5464,6 +5479,32 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" },
]
[[package]]
name = "ptx-remote"
version = "0.1.0"
source = { editable = "deps/prime-envs/environments/code/ptx_remote" }
dependencies = [
{ name = "httpx" },
{ name = "pydantic" },
{ name = "verifiers" },
]
[package.optional-dependencies]
server = [
{ name = "fastapi" },
{ name = "uvicorn" },
]
[package.metadata]
requires-dist = [
{ name = "fastapi", marker = "extra == 'server'", specifier = ">=0.115" },
{ name = "httpx", specifier = ">=0.27" },
{ name = "pydantic", specifier = ">=2" },
{ name = "uvicorn", marker = "extra == 'server'", specifier = ">=0.30" },
{ name = "verifiers", specifier = ">=0.3.2.dev150" },
]
provides-extras = ["server"]
[[package]]
name = "ptyprocess"
version = "0.7.0"
@@ -6338,6 +6379,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/65/94/7698add8f276dbab7a9de9fb6b0e02fc13ee61d51c7c3f85ac28b65e1239/scipy-1.17.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f590cd684941912d10becc07325a3eeb77886fe981415660d9265c4c418d0bea", size = 37625856, upload-time = "2026-02-23T00:19:00.307Z" },
]
[[package]]
name = "semver"
version = "3.1.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/92/f5/e1dfe8e1d91c54ce212fd93916eb01fd1c590f413be0a0978c39a97aa1bb/semver-3.1.0.tar.gz", hash = "sha256:14bc073439513d7773662a338f4db9829cf16c12b74b9568e2d2689975fbd7fc", size = 304162, upload-time = "2026-09-12T18:38:14.045Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/be/02/bce7a1d70e9d0f6ea8623c16386138c251b5855af6cd3a11433d3fba4e66/semver-3.1.0-py3-none-any.whl", hash = "sha256:6e4998f8b4762acdfea85f9bfd5b4032e0bb50038dc04bf82011b42d5d1145c5", size = 18783, upload-time = "2026-09-12T18:38:12.457Z" },
]
[[package]]
name = "senior-swe-bench"
version = "0.1.1"
@@ -7753,7 +7803,7 @@ requires-dist = [
{ name = "e2b", marker = "extra == 'e2b'", specifier = ">=2.35.0,<3" },
{ 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" },
{ name = "harbor", marker = "python_full_version >= '3.12' and extra == 'harbor'", specifier = "==0.24.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "httpx2", specifier = ">=2.12.0" },
{ name = "loguru", specifier = ">=0.7.0" },
@@ -7766,9 +7816,9 @@ requires-dist = [
{ name = "openai", specifier = ">=2.54.0,<3.0.0" },
{ name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" },
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.3" },
{ name = "prime-runs", specifier = ">=0.1.3" },
{ name = "prime-sandboxes", specifier = ">=0.4.1" },
{ name = "prime-tunnel", specifier = ">=0.1.8" },
{ name = "prime-runs", specifier = ">=0.1.4" },
{ name = "prime-sandboxes", specifier = ">=0.4.2" },
{ name = "prime-tunnel", specifier = ">=0.1.14" },
{ name = "pydantic", specifier = ">=2.12.3" },
{ name = "pyzmq", specifier = ">=27.1.0" },
{ name = "renderers", extras = ["multimodal"], specifier = ">=0.1.12.dev2" },