Compare commits

...
Author SHA1 Message Date
88f5e6def1 feat: bump vllm-router to 0.2.2 (#3718)
## Summary

- Bump `vllm-router` from 0.2.1 to
[0.2.2](https://github.com/PrimeIntellect-ai/router/releases/tag/v0.2.2)
(amd64 and arm64 release wheels).
- The new router picks up PrimeIntellect-ai/router#58. The default
health-check interval drops from 60s to 20s, and every health-check
cycle refreshes `/v1/models`. Workers that are still loading at startup
no longer stay under `unknown` and miss model-filtered traffic for
minutes.

## Verification

- `uv lock` resolves with `vllm-router v0.2.1 -> v0.2.2`.
- Installed router reports version `0.2.2` and
`RouterArgs.health_check_interval_secs == 20`.
- Ran 5 steps of `configs/basic/reverse-text/rl.toml` single-node on
SLURM (H200) through the router: 5/5 steps, 0% rollout errors, no
tracebacks.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the disaggregated inference routing dependency only, but the
new router changes health-check timing and worker/model discovery
behavior on the critical vLLM serving path.
> 
> **Overview**
> Upgrades the pinned **`vllm-router`** wheels from **0.2.1** to
**0.2.2** for Linux **x86_64** and **aarch64** in `pyproject.toml`, with
matching **`uv.lock`** updates (version, download URLs, and wheel
hashes).
> 
> Installs that use the **`disagg`** extra (and related GPU/disagg
resolution paths) will pull the new router release instead of 0.2.1. No
in-repo application code changes—only dependency resolution.
> 
> The **0.2.2** router (PrimeIntellect-ai/router#58) shortens the
default health-check interval (**60s → 20s**), refreshes
**`/v1/models`** on each health cycle, and avoids workers staying
**`unknown`** while still loading at startup (so model-filtered traffic
is not skipped for long periods).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f8087add142c2f5a8b27b669902335c60d186cc1. 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-09-29 10:04:06 -07:00
JannikStandGitHub 9eacd477f1 fix(docs): reword bare '<=' in scaling.md to avoid MDX parse error (#3713)
## What
A bare `<= 8` in the Expert Parallelism prose of `docs/scaling.md` (line
97) is parsed by MDX as the start of an HTML tag, failing compilation
with:

> `Unexpected character '=' (U+003D) before name, expected a character
that can start a name, such as a letter, '$', or '_'`

This breaks the Mintlify build of the page imported into **public-docs
PR #219** — the preview deploy 404s `/prime-rl/scaling`, so merging #219
before this fix would publish the broken page.

## Change
Reworded `and is <= 8` → `and is at most 8` (one line). Rewording was
chosen over an inline-expression escape (`{'<='}`) because it is robust
in both MDX pipelines and reads naturally in the sentence. Audited the
rest of the file for bare `<`/`>`/`{`/`}` outside code spans: the only
other occurrences are a `>` blockquote (line 185) and an inline `>`
(line 152), both valid MDX; every remaining `<`/`{`/`}` sits inside
backtick code spans.

## Verification
- Compiled with `@mdx-js/mdx@3` (same compiler family Mintlify pins):
  - pre-fix file: `MDX FAIL: Unexpected character '=' ...`
  - fixed file: `MDX OK`
- Rendered meaning is identical to the original sentence.

Blocks #219 (public-docs) — merge this first, then re-run the #219
preview build.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation-only wording change with no runtime or config behavior
impact.
> 
> **Overview**
> Fixes **Mintlify/MDX compilation** for the Expert Parallelism section
in `docs/scaling.md` by rephrasing the EP auto-resolution rule so prose
no longer contains a bare **`<= 8`**, which MDX treats as the start of
an HTML tag and fails to parse.
> 
> The sentence now says the chosen EP degree **is at most 8** instead of
**`is <= 8`**; meaning is unchanged. This unblocks the public-docs
preview for `/prime-rl/scaling` (merge before dependent doc PRs).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fda404ad8bea01b8afbd24b16f32c38d98846d65. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-29 08:04:05 +02:00
JannikStandGitHub 40d130d8f1 feature: prime monitor for SFT trainer (#3614)
## Motivation

Hosted SFT runs (the dedicated FFT path) currently report nothing to the
platform: `SFTConfig.monitors` was the base `MonitorsConfig` (wandb/file
only), so a hosted SFT trainer has no platform run — no metrics, no
billing surface, no "view on platform" link. RL runs get all of this
through `PrimeTrainMonitor` (wired in the RL orchestrator); this PR
gives the SFT trainer the same platform integration.

## What it adds

- **Config**: `SFTConfig.monitors` is now `TrainMonitorsConfig`, so
`[monitors.prime]` (and `--monitors.prime`) is a valid SFT config block.
`monitors.prime.name` defaults to `run.name`, mirroring the
orchestrator's and eval config's name inheritance.
- **Monitor**: `PrimeTrainMonitor.init` learns the SFT registration
shape — base model, no environments (SFT trains on a dataset),
`TrainingSpec(max_steps, batch_size, seq_len)` from the data block, no
rollouts per example, full resolved config dumped to the platform run
record. The RL registration path is unchanged.
- **Trainer** (`trainer/sft/train.py`): passes `monitors.prime` to
`monitors.setup` and calls `monitors.finalize()` after training,
matching the RL trainer's call sites. The existing per-step metric
logging (train loss/perplexity, `optim/lr`, grad norm, throughput,
progress, time) and `[val]` losses now fan out to the platform unchanged
— the platform's existing internal RFT endpoints work as-is.
- **Launcher** (`entrypoints/sft.py`): `build_online_eval_config`
converts the trainer's `TrainMonitorsConfig` into `EvalMonitorsConfig`
for the online-eval process (the platform monitor switches to the
evaluation flavor under the same name). Without this, an `[eval]` +
`[monitors.prime]` run would fail `SFTOnlineEvalConfig` validation.
- **Docs**: platform-monitoring section covers `sft`; SFT launch section
links to it.

Env surface mirrors RL exactly: the monitor reads `$RUN_ID` (attach to
the launcher-pre-created platform run), `$PRIME_API_BASE` and
`$PRIME_API_KEY` — the values the fft chart injects into trainer pods —
and `PRIME_RUNS_MODE=disabled` stays the opt-out. No trainer-side usage
POST is needed: RL's per-step `PI_USAGE_*` billing posts were removed in
#3275; usage/GPU-hours for hosted runs is derived platform-side from the
run record, which the SFT monitor now registers (config dump includes
the deployment topology).

## Tests

- `uv run pytest tests/unit/train/sft/test_prime_monitor.py` — 6 passed
(mocked `prime_runs.init`: registration kwargs for SFT, name
inheritance, W&B project passthrough, `monitors.setup` fan-out of
metrics + finalize, online-eval monitors conversion). This file is
torch-free and runs on macOS.
- `uv run pytest tests/unit/test_configs.py` — identical result to a
clean `origin/main` baseline (67 pre-existing failures on this macOS env
from missing GPU/harness packages — env-dependent, unrelated to this
change; diff of failing tests verified identical).
- `uv run sft @ <minimal sft.toml> --dry-run --monitors.prime` —
resolves; `monitors.prime.name` inherits `run.name` in the resolved
config dump.
- `uv run ruff check` / `ruff format --check` — clean.

Note: the fft validator service picks this schema change up
automatically once a GHCR image is built from a commit containing this
PR (per-image schema venvs install `prime-rl-configs` from the image's
commit). No validator-side change needed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches platform run lifecycle and cross-process shared state on the
run directory; training continues if dashboard record persistence fails,
but incorrect merging could break platform links for SFT+online-eval
runs.
> 
> **Overview**
> Adds **`--monitors.prime` / `[monitors.prime]`** to SFT so hosted runs
register on Prime Lab, stream trainer metrics (including validation),
and call **`monitors.finalize()`** on exit—same flag shape as RL, with
**no rollout episode uploads**.
> 
> **Config wiring:** `SFTConfig.monitors` is **`TrainMonitorsConfig`**;
online eval uses **`EvalMonitorsConfig`** plus
**`build_online_eval_monitors`** so the launcher maps the trainer’s
platform block to **`PrimeEvalMonitorConfig`** for the eval subprocess.
**`monitors.prime.name`** defaults to **`run.name`**. SFT online eval
shares the trainer’s **`run_dir`**; the dashboard platform JSON is
updated via **locked merge**, not separate dirs.
> 
> **`PrimeTrainMonitor`:** For **`SFTConfig`**, registration sends
dataset **`TrainingSpec`** (`max_steps`, `batch_size`, `seq_len`), empty
environments, and the resolved config dump. Docs clarify **best-effort**
finalize (SIGKILL/OOM may skip crash reporting).
> 
> **Concurrency:** Platform **`run.json`** writes use **PID-suffixed
temp files**, a **persistent flock lock** with bounded timeout,
**`update_platform_record` / `_merge_platform_record`**, and
**`asyncio.to_thread`** so eval + trainer don’t clobber each other’s
dashboard link. Lock/storage failures are **logged and skipped**, not
fatal.
> 
> New unit tests cover SFT registration, monitor fan-out, eval monitor
conversion, record merge/lock behavior.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bc33cb262d141c2d788acc5694aec85aea7b9ad4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-29 07:10:43 +02:00
Scott CabrinhaandGitHub 7027f65e5f fix(docker): pin the NIXL wheel build backend (#3720)
## Problem

Image builds on `main` have failed since #3667 merged. Every
`build_image.yaml` run since 2026-09-28 dies in the
`INCLUDE_NIXL_FROM_SOURCE` step, so no amd64/arm64 image is published.
The failing command is the step's own linkage check — the wheel builds
and installs fine:

```
ldd .../.nixl_cu13.mesonpy.libs/plugins/libplugin_UCX.so | grep -q /opt/ucx/lib/libucp.so
```

## Cause

The NIXL wheel build is not reproducible: NIXL's `[build-system]
requires` is an unpinned list, so pip's build isolation resolves the
newest backends at build time.

`meson-python 0.22.0` (uploaded 2026-09-26 08:33Z — after the
from-source images were built 09-25 01:53Z/02:11Z and validated on FFT,
before the first failing main build 09-28 02:35Z) added "support for
removing build RPATH entries added by Meson" plus RPATH/relocation
fixes. NIXL links UCX with bare `-L/opt/ucx/lib -lucp -lucs -luct` and
sets no `install_rpath`, so Meson's build-tree RPATH (the
`RUNPATH=/opt/ucx/lib` the step's comment and the FFT pods' runtime
check rely on) was the only thing making the installed libraries resolve
the image's UCX. 0.22.0 drops it, the check fails, and the registry
image would not resolve `/opt/ucx` at runtime either.

Evidence: identical step text passes on the 09-25 branch builds and
fails on every build from 09-28; the wheels differ by ~3 KB
(rpath/metadata, not content); `origin/main`'s step is unchanged, so the
failure persists.

## Fix

Constrain `meson-python==0.21.1` for the NIXL wheel via `pip wheel
--build-constraint` — the backend the from-source images were validated
with. Same pin in `scripts/install_nixl_from_source.sh`, whose SLURM
path builds the same wheel and drifts the same way.

Also make the linkage check diagnostic: it now prints `readelf -d`
RUNPATH and the `ldd` output before exiting, instead of `grep -q`
failing with no output (the failure above was silent).

## Notes

- Verified without a full image build: the step's shell, joined the way
Docker joins continuations, passes `sh -n` and `bash -n`; the check's
failure path prints diagnostics and exits 1; the skip path
(`INCLUDE_NIXL_FROM_SOURCE=0`) is unchanged.
- Verified with a real build: [run
36518545933](https://github.com/PrimeIntellect-ai/prime-rl/actions/runs/36518545933)
(amd64, `fix/nixl-build-constraints` @ 5e3cc4982) passed, image
`commit-5e3cc4982-amd64` pushed. The NIXL step ran
(`INCLUDE_NIXL_FROM_SOURCE=1`) and the linkage check passed; the wheel
is exactly the size of the wheels from the 2026-09-25 builds (3 467 198
bytes, vs 3 470 315 for the failing 0.22.0 build).
- The rest of NIXL's build-system set (`pybind11`, `patchelf`, `pyyaml`,
`build`, `setuptools`) stays unpinned; only the backend whose behaviour
broke is pinned. The constraint file is the lever if we want these
wheels fully reproducible.
- Durable alternative to the pin: set the RPATH explicitly at link time
(`-Wl,-rpath=/opt/ucx/lib` via Meson link args, or `patchelf
--add-rpath` on the installed libraries) so the artifact does not depend
on backend RPATH policy. Not included: it cannot be validated without a
full image build.
2026-09-28 22:47:13 -06:00
eligottsandGitHub d51d0bb84c Delegate prompt metadata to vLLM 0.30 (#3710) 2026-09-28 21:29:41 -07:00
17 changed files with 577 additions and 123 deletions
+15 -2
View File
@@ -144,6 +144,11 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
# (the PyPI wheel) first, so the fix would silently not apply. Libraries carry
# RUNPATH=/opt/ucx/lib, so no LD_LIBRARY_PATH is needed at runtime.
# Opt out via `--build-arg INCLUDE_NIXL_FROM_SOURCE=0`.
#
# NIXL's [build-system] requires are unpinned, so pip's build isolation picks up
# new backends as they are released. meson-python 0.22.0 stopped keeping Meson's
# build RPATH in wheel libraries, which dropped RUNPATH=/opt/ucx/lib and failed
# the linkage check below on every build. Pin the validated backend.
ARG INCLUDE_NIXL_FROM_SOURCE=1
ARG NIXL_VERSION=0.10.1
RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
@@ -151,11 +156,19 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
&& git clone --depth 1 --branch ${NIXL_VERSION} https://github.com/ai-dynamo/nixl.git /tmp/nixl \
&& cd /tmp/nixl \
&& uv run --no-project --with tomlkit python contrib/tomlutil.py --wheel-name nixl-cu13 pyproject.toml \
&& printf 'meson-python==0.21.1\n' > /tmp/nixl-build-constraints.txt \
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/tmp/nixl-whl \
--build-constraint /tmp/nixl-build-constraints.txt \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /tmp/nixl-whl/nixl_cu13-*.whl \
&& ldd /app/.venv/lib/python3.12/site-packages/.nixl_cu13.mesonpy.libs/plugins/libplugin_UCX.so | grep -q /opt/ucx/lib/libucp.so \
&& rm -rf /tmp/nixl /tmp/nixl-whl; \
&& PLUGIN=/app/.venv/lib/python3.12/site-packages/.nixl_cu13.mesonpy.libs/plugins/libplugin_UCX.so \
&& if ! ldd "$PLUGIN" | grep -q /opt/ucx/lib/libucp.so; then \
echo "ERROR: $PLUGIN does not link /opt/ucx/lib. RUNPATH and ldd output:" >&2; \
readelf -d "$PLUGIN" | grep -E 'RUNPATH|RPATH' >&2 || true; \
ldd "$PLUGIN" >&2; \
exit 1; \
fi \
&& rm -rf /tmp/nixl /tmp/nixl-whl /tmp/nixl-build-constraints.txt; \
fi
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
+1 -1
+1 -1
View File
@@ -94,7 +94,7 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is <= 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is at most 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
```toml
[trainer.model]
+6 -1
View File
@@ -182,6 +182,8 @@ uv run sft @ examples/basic/reverse-text/sft.toml --monitors.wandb
Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manages this for you — see [Scaling § SFT and Torchrun](scaling.md#sft-and-torchrun) for non-default layouts; multi-node SFT goes through [SLURM](scaling.md#slurm)).
`--monitors.prime` streams the run to the Prime Intellect platform — see [Platform Monitoring](#platform-monitoring).
### Online Evals
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `select` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
@@ -383,6 +385,7 @@ Register a run on the Prime Intellect platform (Prime Lab) and stream training m
```bash
uv run rl @ rl.toml --monitors.prime
uv run sft @ sft.toml --monitors.prime # same flag on the SFT trainer
```
Or set it in TOML:
@@ -392,7 +395,9 @@ Or set it in TOML:
name = "my-experiment"
```
The monitor is a thin layer over the [`prime-runs`](https://github.com/PrimeIntellect-ai/prime/tree/main/packages/prime-runs) SDK (installed as `prime-runs[train]`): it registers the run, streams per-step metrics, uploads every 10th step's episodes (full conversations with rewards and advantages) to the run's sample viewer, and closes the run out. A process that exits without finishing is reported as crashed. Uploaded episodes are keyed to the platform run by the SDK; the orchestrator's own run id (the launcher's `PRL_RUN_ID`) stays on W&B and in the local records.
The monitor is a thin layer over the [`prime-runs`](https://github.com/PrimeIntellect-ai/prime/tree/main/packages/prime-runs) SDK (installed as `prime-runs[train]`): it registers the run, streams per-step metrics, uploads every 10th step's episodes (full conversations with rewards and advantages) to the run's sample viewer, and closes the run out. Finalization is best-effort SDK delivery: a process that exits without finishing is reported crashed when the SDK's atexit hook runs, but an abrupt kill (SIGKILL, OOM, node loss) skips the report and a lost finalize is not retried — the platform owns the terminal state of attached (`RUN_ID`) and managed runs. Uploaded episodes are keyed to the platform run by the SDK; the orchestrator's own run id (the launcher's `PRL_RUN_ID`) stays on W&B and in the local records.
On `sft` the monitor registers the run with the dataset-batched training fields (`max_steps`, `batch_size`, `seq_len`) and streams the trainer's per-step metrics and validation losses; SFT has no rollouts, so no episodes are uploaded.
Requires `PRIME_API_KEY` (`prime login` or the env var) and a team (`PRIME_TEAM_ID`, or the team selected with `prime login`) enabled for external runs. A configured monitor must work: a missing key or a team outside the allowlist fails the launch. `PRIME_RUNS_MODE=disabled` keeps the monitor configured but opens no platform run; `RUN_ID=<id>` attaches to an external run a launcher already created instead of registering a new one. Currently internal-only.
@@ -4,7 +4,7 @@ from pathlib import Path
import verifiers.v1 as vf
from pydantic import AliasChoices, Field, model_validator
from prime_rl.configs.monitors import EvalMonitorsConfig, MonitorsConfig
from prime_rl.configs.monitors import EvalMonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
@@ -157,8 +157,14 @@ class SFTOnlineEvalConfig(ScheduledEvalConfig, ServedEvalConfig):
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
monitors: EvalMonitorsConfig = EvalMonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``).
``EvalMonitorsConfig``, not the base ``MonitorsConfig``: the launcher
converts the trainer's ``[monitors.prime]`` into a
``PrimeEvalMonitorConfig`` for the online-eval process, and the base
type would drop (or forbid) the prime block at the eval.json
dump/re-parse boundary."""
@model_validator(mode="after")
def auto_setup_broadcasts_dir(self):
@@ -10,7 +10,7 @@ from renderers.base import MODEL_RENDERER_MAP
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.monitors import TrainMonitorsConfig
from prime_rl.configs.shared import (
EnvVars,
HeartbeatConfig,
@@ -229,8 +229,8 @@ class SFTConfig(BaseConfig):
log: TrainerLogConfig = TrainerLogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
monitors: TrainMonitorsConfig = TrainMonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
run: RunConfig = Field(default_factory=RunConfig)
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
@@ -249,7 +249,8 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_run_identity(self):
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
default the run directory and W&B run name to it when not set explicitly."""
default the run directory, W&B run name and platform run name to it when not
set explicitly."""
if self.run.name is None:
dataset = str(getattr(self.data, "name", "")).split("/")[-1]
model = self.model.name.split("/")[-1]
@@ -259,6 +260,8 @@ class SFTConfig(BaseConfig):
self.run.dir = self.run.name
if self.monitors.wandb is not None and self.monitors.wandb.name is None:
self.monitors.wandb.name = self.run.name
if self.monitors.prime is not None and self.monitors.prime.name is None:
self.monitors.prime.name = self.run.name
return self
matmul_precision: Literal["highest", "high", "medium"] = "high"
@@ -107,7 +107,8 @@ def propagate_shared_fields(data: Any) -> Any:
# [monitors.file] leaf. (Bare empty ``[monitors.file]`` block enablement is at the end.)
propagate("monitors.file.path", "trainer.monitors.file.path", "orchestrator.monitors.file.path")
# [monitors.prime] leaf → orchestrator only (the trainer has no platform integration).
# [monitors.prime] leaf → orchestrator only (the RL trainer has no platform
# integration; the SFT trainer does, but it parses SFTConfig directly).
propagate("monitors.prime.name", "orchestrator.monitors.prime.name")
# [tokenizer]. ``chat_template`` also flows to ``inference.vllm`` (vLLM's
+2 -2
View File
@@ -270,8 +270,8 @@ torchao = [
dion = { git = "https://github.com/samsja/dion.git", rev = "6f9242d" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
+7 -1
View File
@@ -94,7 +94,13 @@ export LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:
WHEEL_DIR="$PROJECT_DIR/deps"
mkdir -p "$WHEEL_DIR"
uv pip install pip 2>/dev/null
"$PYTHON" -m pip wheel . --no-deps --wheel-dir="$WHEEL_DIR"
# NIXL's [build-system] requires are unpinned; meson-python 0.22.0 stopped
# keeping Meson's build RPATH in wheel libraries, which drops the link to the
# UCX built above. Constrain the backend to the version these wheels were
# validated with (same pin as Dockerfile.cuda).
printf 'meson-python==0.21.1\n' > "$WORKSPACE/nixl-build-constraints.txt"
"$PYTHON" -m pip wheel . --no-deps --wheel-dir="$WHEEL_DIR" \
--build-constraint "$WORKSPACE/nixl-build-constraints.txt"
WHEEL=$(ls "$WHEEL_DIR"/nixl_cu13-"$NIXL_VERSION"-*.whl | head -1)
echo "=== NIXL wheel built at: $WHEEL ==="
+17 -1
View File
@@ -9,6 +9,7 @@ from subprocess import Popen
from threading import Event, Thread
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.monitors import EvalMonitorsConfig, PrimeEvalMonitorConfig, TrainMonitorsConfig
from prime_rl.configs.orchestrator import OnlineEvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.shared import LogConfig
@@ -72,6 +73,16 @@ def resolve_resume_step(config: SFTConfig) -> int | None:
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
def build_online_eval_monitors(monitors: TrainMonitorsConfig) -> EvalMonitorsConfig:
"""The online-eval process's monitors: same W&B and file config as the trainer's,
with the platform monitor switched to the evaluation flavor under the same name."""
return EvalMonitorsConfig(
wandb=monitors.wandb,
file=monitors.file,
prime=PrimeEvalMonitorConfig(name=monitors.prime.name) if monitors.prime is not None else None,
)
def build_online_eval_config(config: SFTConfig) -> SFTOnlineEvalConfig:
"""The online-eval process's config: the resolved ``[eval]`` block with the run-level
fields filled from the SFT config. The launcher spawns the env servers itself; the
@@ -85,9 +96,14 @@ def build_online_eval_config(config: SFTConfig) -> SFTOnlineEvalConfig:
broadcasts_dir=get_broadcast_dir(config.run_dir),
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
# Same run dir as the trainer: the dashboard reads the eval's
# file-monitor artifacts from the run directory, so a separate
# output dir would hide them. The train-vs-eval record collision
# is resolved by record merging in prime_rl.monitors.prime, not
# by directory separation.
output_dir=config.run_dir,
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
monitors=config.monitors,
monitors=build_online_eval_monitors(config.monitors),
)
return SFTOnlineEvalConfig(**{**eval_config.model_dump(exclude=set(run_fields)), **run_fields})
+1
View File
@@ -47,6 +47,7 @@ class OnlineEval:
await monitors.setup(
producer="online-eval",
wandb=config.monitors.wandb,
prime=config.monitors.prime,
file=config.monitors.file,
output_dir=config.output_dir,
run_config=config,
+11 -67
View File
@@ -4,25 +4,19 @@ vLLM ships a generic tokens-in / tokens-out handler at
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
prefix-cache salting, lora dispatch, multimodal content parts and features,
prompt logprobs, priority, ``data_parallel_rank`` header routing, server-side
``max_tokens`` defaulting and ``usage`` reporting. We subclass it for the bits
still missing from the upstream handler:
1. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as ``{data, shape, start, dtype}`` base64 raw-byte
objects (the form the PD router can merge and the renderers parse) instead
of upstream's single ``.npy`` base64 string.
2. Prompt metadata — return the effective engine prompt and authoritative
multimodal placeholder ranges after expansion. Drop this once upstream's
response includes these fields.
``max_tokens`` defaulting, ``usage`` reporting, and expanded prompt metadata.
We subclass it for the one bit still missing from the upstream handler: compact
``routed_experts`` export. When the engine emits routing decisions, surface them
as ``{data, shape, start, dtype}`` base64 raw-byte objects (the form the PD
router can merge and the renderers parse) instead of upstream's single ``.npy``
base64 string.
Everything else delegates to upstream so we track future vLLM changes for free.
"""
from __future__ import annotations
from collections.abc import AsyncGenerator, AsyncIterable
from contextvars import ContextVar
from collections.abc import AsyncGenerator
from typing import Any
from vllm.entrypoints.generate.base.protocol import RequestResponseMetadata
@@ -30,7 +24,6 @@ from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateRequest,
GenerateResponse,
GenerateResponseChoice,
PlaceholderRangeInfo,
)
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
@@ -47,27 +40,6 @@ class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
class PrimeRlGenerateResponse(GenerateResponse):
choices: list[PrimeRlGenerateResponseChoice]
prompt_token_ids: list[int] | None = None
mm_placeholders: dict[str, list[PlaceholderRangeInfo]] | None = None
_response_mm_placeholders: ContextVar[dict[str, list[PlaceholderRangeInfo]] | None] = ContextVar(
"response_mm_placeholders", default=None
)
def _extract_mm_placeholders(
engine_input: Any,
) -> dict[str, list[PlaceholderRangeInfo]] | None:
if not isinstance(engine_input, dict) or engine_input.get("type") != "multimodal":
return None
return {
modality: [
PlaceholderRangeInfo(offset=placeholder.offset, length=placeholder.length)
for placeholder in sorted(ranges, key=lambda placeholder: placeholder.offset)
]
for modality, ranges in engine_input["mm_placeholders"].items()
}
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
@@ -82,29 +54,8 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
return PrimeRlGenerateResponse(**{**response.model_dump(exclude={"choices"}), "choices": choices})
class _PromptTokenIdsCapture:
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
self._source = source
self.prompt_token_ids: list[int] | None = None
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
async for output in self._source:
self.prompt_token_ids = output.prompt_token_ids
yield output
class PrimeRlServingTokens(ServingTokens):
"""ServingTokens with Prime's remaining response and PD extensions."""
def _log_inputs(
self,
request_id: str,
inputs: Any,
params: Any,
lora_request: Any,
) -> None:
_response_mm_placeholders.set(_extract_mm_placeholders(inputs))
super()._log_inputs(request_id, inputs, params, lora_request)
"""ServingTokens with compact routed experts."""
async def serve_tokens_full_generator( # type: ignore[override]
self,
@@ -122,22 +73,15 @@ class PrimeRlServingTokens(ServingTokens):
)
result_generator = routed_experts
prompt_capture = _PromptTokenIdsCapture(result_generator)
response = await super().serve_tokens_full_generator(
request,
prompt_capture,
result_generator,
request_id,
model_name,
request_metadata,
)
if not isinstance(response, GenerateResponse):
return response
if routed_experts is not None:
if routed_experts is not None and isinstance(response, GenerateResponse):
response = routed_experts.post_process(response)
else:
response = PrimeRlGenerateResponse(**response.model_dump())
response.prompt_token_ids = prompt_capture.prompt_token_ids
response.mm_placeholders = _response_mm_placeholders.get()
return response
+142 -18
View File
@@ -1,17 +1,22 @@
from __future__ import annotations
import asyncio
import fcntl
import os
import time
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Callable, Iterator
import orjson
import prime_runs as pr
from prime_sandboxes import Config as PrimeConfig
from prime_rl.configs.monitors import PrimeEvalMonitorConfig, PrimeTrainMonitorConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_platform_run_path
from prime_rl.utils.utils import sanitize
@@ -28,12 +33,18 @@ FINISH_TIMEOUT = 60.0
def write_platform_record(output_dir: Path, record: dict[str, Any]) -> None:
"""Leave the run's platform identity in the run directory for the dashboard's
"view on platform" link (atomic replace: a reader never sees a torn file)."""
"view on platform" link (atomic replace: a reader never sees a torn file).
The tmp file is pid-suffixed: the trainer and the online-eval process
share the run directory, and two writers sharing one tmp path can tear
each other's staged file mid-write."""
path = get_platform_run_path(output_dir)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".json.tmp")
tmp.write_bytes(orjson.dumps(record, option=orjson.OPT_INDENT_2))
tmp.replace(path)
tmp = path.with_suffix(f".json.tmp.{os.getpid()}")
try:
tmp.write_bytes(orjson.dumps(record, option=orjson.OPT_INDENT_2))
tmp.replace(path)
finally:
tmp.unlink(missing_ok=True)
def read_platform_record(output_dir: Path) -> dict[str, Any] | None:
@@ -41,6 +52,73 @@ def read_platform_record(output_dir: Path) -> dict[str, Any] | None:
return orjson.loads(path.read_bytes()) if path.is_file() else None
# Bounded wait for the record lock: a blocking flock(LOCK_EX) would stall the
# async event-loop thread for as long as the other writer holds the lock.
RECORD_LOCK_TIMEOUT = 10.0
RECORD_LOCK_POLL = 0.05
@contextmanager
def _platform_record_lock(output_dir: Path) -> Iterator[None]:
"""Cross-process read-modify-write lock for the platform record: the
trainer and the online-eval process merge into the SAME run.json, and an
unlocked read-modify-write lets one clobber the other's snapshot. POSIX
flock on a sibling .lock file. The lock file is NEVER unlinked: a waiting
writer can still hold the unlinked inode's lock while a new writer
creates and locks a fresh file — two simultaneous "exclusive" locks and
a lost merge; a stable lock inode is the whole guarantee. Acquisition is
BOUNDED (`RECORD_LOCK_TIMEOUT`), retried with non-blocking flock so the
async event-loop thread never blocks; `TimeoutError` past the bound.
Storage errors that make locking impossible (e.g. ENOLCK) raise
immediately instead of retrying."""
path = get_platform_run_path(output_dir)
path.parent.mkdir(parents=True, exist_ok=True)
lock_path = path.with_suffix(path.suffix + ".lock")
with open(lock_path, "a+b") as lock_file:
deadline = time.monotonic() + RECORD_LOCK_TIMEOUT
while True:
try:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except BlockingIOError:
if time.monotonic() >= deadline:
raise TimeoutError(f"platform record lock at {lock_path} still held after {RECORD_LOCK_TIMEOUT}s")
time.sleep(RECORD_LOCK_POLL)
try:
yield
finally:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
def _merge_platform_record(
output_dir: Path,
merge: Callable[[dict[str, Any]], dict[str, Any]],
) -> None:
"""Best-effort locked read-modify-write of the platform record: run
`merge` on the current record under the record lock and atomically
replace the file. The record only backs the dashboard's "view on
platform" link, so a lock or storage failure (TimeoutError, ENOLCK, ...)
is logged and SKIPPED, never fatal to training; the dashboard just misses
the link for that run."""
try:
with _platform_record_lock(output_dir):
write_platform_record(output_dir, merge(read_platform_record(output_dir) or {}))
except OSError:
get_logger().warning(
f"Failed to persist the platform record at {get_platform_run_path(output_dir)} "
f"(lock or storage error); the dashboard's platform link may be missing. "
f"Training continues."
)
def update_platform_record(output_dir: Path, update: dict[str, Any]) -> None:
"""Best-effort locked read-modify-write of the platform record: `update`
overlays the current record (preserving keys it doesn't set). Use for
every writer that shares the file — a naive overwrite drops concurrent
writers' keys."""
_merge_platform_record(output_dir, lambda record: {**record, **update})
def _base_url() -> str | None:
"""$PRIME_API_BASE historically points at the RFT API root (``.../api/v1/rft``);
the SDK takes the platform base URL. Unset means the SDK resolves it."""
@@ -54,8 +132,12 @@ class PrimeTrainMonitor(Monitor):
The run handle owns what ``TrainRun`` used to do by hand: the RFT
lifecycle (register or attach, finalize), the per-step metrics POSTs, the
every-10th-step Parquet sample uploads (presign -> PUT -> confirm), and
the terminal status — a process that exits without finalizing is reported
crashed by the SDK's atexit hook, replacing the old ``_mark_failed`` one.
the terminal status. Delivery is BEST-EFFORT: the SDK's atexit hook
reports a process that exits without finalizing, but an abrupt kill
(SIGKILL, OOM, node loss) skips the hook and a lost finalize is not
retried here — the platform owns the terminal state of attached
($RUN_ID) and managed runs. `FINISH_TIMEOUT` bounds the queued-upload
drain, not the SDK's finalize HTTP retries.
``init``/``finish`` do network I/O and run in worker threads; the log
calls are queue puts onto the SDK's uploader thread, which owns retries
@@ -69,9 +151,25 @@ class PrimeTrainMonitor(Monitor):
init_kwargs: dict[str, Any]
if run_id := os.getenv("RUN_ID"):
# A managed launch pre-created the platform run and injected its id -
# attach instead of registering a duplicate. The backend owns the run's
# failure marking then; a clean finish() still marks it completed.
# attach instead of registering a duplicate. The platform owns the
# attached run's failure/completion marking; a clean finish() is
# delivered best-effort and does not by itself mark it completed.
init_kwargs = {"id": run_id}
elif isinstance(config, SFTConfig):
# SFT trains on a dataset, not on environments, and has no rollouts - the
# platform run is registered without both.
init_kwargs = dict(
name=self.config.name,
model=config.model.name,
environments=[],
training=pr.TrainingSpec(
max_steps=config.max_steps or 0,
batch_size=config.data.batch_size,
seq_len=config.data.seq_len,
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
),
config=config.model_dump(exclude_none=True, mode="json"),
)
elif config is not None:
init_kwargs = dict(
name=self.config.name,
@@ -107,7 +205,15 @@ class PrimeTrainMonitor(Monitor):
attached = " (attached via $RUN_ID)" if self.run.attached else ""
self.logger.info(f"Logging metrics and episodes to platform run {self.run.id} ({self.run.url}){attached}")
if output_dir is not None:
write_platform_record(output_dir, {"kind": "train", "id": self.run.id, "url": self.run.url})
# Merge, not overwrite: a concurrent eval process (SFT
# online evals share the trainer's run dir) may already
# have written its evaluations record. Off the event
# loop: the flock retry must not stall it.
await asyncio.to_thread(
update_platform_record,
output_dir,
{"kind": "train", "id": self.run.id, "url": self.run.url},
)
else:
self.logger.info(f"Platform run disabled ({pr.MODE_ENV}=disabled)")
@@ -170,7 +276,19 @@ class PrimeEvalMonitor(Monitor):
if self.mode == "online":
self.logger.info("Streaming eval epochs to the Prime platform")
if output_dir is not None:
write_platform_record(output_dir, {"kind": "eval", "run_id": self.run_id, "evaluations": {}})
# Merge, not overwrite: when the eval process shares the
# trainer's run dir (SFT online evals), the train record's
# platform link (kind/id/url) must survive; a standalone
# eval keeps the plain eval-shaped record. Locked RMW.
def _eval_init_update(record: dict[str, Any]) -> dict[str, Any]:
if record.get("kind") == "train":
record.setdefault("evaluations", {})
record["run_id"] = self.run_id
return record
return {"kind": "eval", "run_id": self.run_id, "evaluations": {}}
# Off the event loop: the flock retry must not stall it.
await asyncio.to_thread(_merge_platform_record, output_dir, _eval_init_update)
else:
self.logger.info(f"Platform evaluations disabled ({pr.MODE_ENV}=disabled)")
@@ -229,13 +347,19 @@ class PrimeEvalMonitor(Monitor):
attached = f" (attached via ${EVAL_ID_VAR})" if run.attached else ""
self.logger.info(f"Streaming {env_name} (Step {step}) evaluation - {run.url}{attached}")
if self.output_dir is not None:
record = read_platform_record(self.output_dir) or {
"kind": "eval",
"run_id": self.run_id,
"evaluations": {},
}
record["evaluations"][env_name] = {"step": step, "id": run.id, "url": run.url}
write_platform_record(self.output_dir, record)
def _eval_epoch_update(record: dict[str, Any]) -> dict[str, Any]:
record.setdefault("kind", "eval")
record.setdefault("run_id", self.run_id)
record.setdefault("evaluations", {})[env_name] = {
"step": step,
"id": run.id,
"url": run.url,
}
return record
# Off the event loop: the flock retry must not stall it.
await asyncio.to_thread(_merge_platform_record, self.output_dir, _eval_epoch_update)
return run
async def log_eval_plan(self, env_name: str, step: int, expected: int) -> None:
+2
View File
@@ -80,6 +80,7 @@ def train(config: SFTConfig):
monitors.setup(
producer="trainer",
wandb=config.monitors.wandb,
prime=config.monitors.prime,
file=config.monitors.file,
output_dir=config.run_dir,
run_config=config,
@@ -676,6 +677,7 @@ def train(config: SFTConfig):
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
logger.success("SFT trainer finished")
asyncio.run(monitors.finalize())
def main():
+3 -9
View File
@@ -17,14 +17,13 @@ import pybase64
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateResponse,
GenerateResponseChoice,
PlaceholderRangeInfo,
)
from vllm.entrypoints.serve.engine.protocol import UsageInfo
from vllm.multimodal.inputs import PlaceholderRange
from prime_rl.inference.vllm.routed_experts import serialize_routed_experts
from prime_rl.inference.vllm.serving_tokens import (
PrimeRlServingTokens,
_extract_mm_placeholders,
_GenerateRoutedExpertsCapture,
)
@@ -79,16 +78,11 @@ def test_generate_response_post_process_preserves_prompt_metadata():
)
],
usage=usage,
prompt_token_ids=[10, 11, 12, 13],
mm_placeholders={"image": [PlaceholderRangeInfo(offset=1, length=2)]},
)
processed = capture.post_process(response)
processed.prompt_token_ids = [10, 11, 12, 13]
processed.mm_placeholders = _extract_mm_placeholders(
{
"type": "multimodal",
"mm_placeholders": {"image": [PlaceholderRange(offset=1, length=2)]},
}
)
assert processed.choices[0].routed_experts == compact_routed_experts
assert processed.model == "test-model"
+339
View File
@@ -0,0 +1,339 @@
"""The SFT trainer's platform wiring: registration shape and monitor fan-out.
``monitors.prime`` on ``SFTConfig`` must register the run with the dataset-batched
training fields (no environments, no rollouts) and flow the trainer's metrics and
finalize through the registered ``PrimeTrainMonitor`` like the RL orchestrator does.
"""
import asyncio
from types import SimpleNamespace
import pytest
from prime_rl import monitors
from prime_rl.configs.monitors import (
EvalMonitorsConfig,
FileMonitorConfig,
PrimeEvalMonitorConfig,
PrimeTrainMonitorConfig,
TrainMonitorsConfig,
WandbMonitorConfig,
)
from prime_rl.configs.sft import SFTConfig
from prime_rl.monitors.prime import PrimeTrainMonitor
@pytest.fixture
def prime_init(monkeypatch):
"""Replace the ``prime_runs`` SDK entry point with one that records its kwargs."""
calls = []
def fake_init(**kwargs):
calls.append(kwargs)
return SimpleNamespace(
id="run-123",
url="https://platform/training/run-123",
attached=False,
finished=False,
finish=lambda *args, **kwargs_: None,
log_metrics=lambda *args, **kwargs_: None,
log_episodes=lambda *args, **kwargs_: None,
)
monkeypatch.setattr("prime_rl.monitors.prime.pr.init", fake_init)
monkeypatch.delenv("RUN_ID", raising=False)
return calls
@pytest.fixture
def clear_monitors():
"""``monitors.setup`` registers into a module-global list; empty it after each test."""
yield
monitors.MONITORS.clear()
def _sft_config(overrides: dict | None = None) -> SFTConfig:
config = {
"model": {"name": "PrimeIntellect/Qwen3-0.6B"},
"data": {"type": "fake", "batch_size": 8, "seq_len": 64},
"max_steps": 10,
}
if overrides:
config.update(overrides)
return SFTConfig.model_validate(config)
def test_sft_prime_monitor_name_inherits_run_name():
config = _sft_config({"monitors": {"prime": {}}})
assert config.monitors.prime.name == config.run.name
def test_sft_prime_monitor_keeps_explicit_name():
config = _sft_config({"monitors": {"prime": {"name": "my-experiment"}}})
assert config.monitors.prime.name == "my-experiment"
def test_sft_registers_dataset_training_fields(prime_init):
config = _sft_config({"monitors": {"prime": {}}})
asyncio.run(PrimeTrainMonitor(config.monitors.prime).init(config=config, output_dir=None))
(call,) = prime_init
assert call["kind"] == "train"
assert call["name"] == config.run.name
assert call["model"] == "PrimeIntellect/Qwen3-0.6B"
# SFT trains on a dataset: no environments, no rollouts per example
assert call["environments"] == []
assert call["training"].max_steps == 10
assert call["training"].batch_size == 8
assert call["training"].seq_len == 64
assert call["training"].rollouts_per_example is None
assert call["config"]["model"]["name"] == "PrimeIntellect/Qwen3-0.6B"
def test_sft_registers_wandb_project(prime_init):
config = _sft_config(
{
"monitors": {
"wandb": {"project": "sft-tests"},
"prime": {},
}
}
)
asyncio.run(PrimeTrainMonitor(config.monitors.prime).init(config=config, output_dir=None))
assert prime_init[0]["training"].wandb_project == "sft-tests"
def test_online_eval_monitors_switch_prime_flavor():
"""The online-eval process parses EvalMonitorsConfig, whose ``prime`` field is the
evaluation flavor - the launcher converts the trainer's TrainMonitorsConfig."""
from prime_rl.entrypoints.sft import build_online_eval_monitors
monitors = build_online_eval_monitors(
TrainMonitorsConfig(
wandb=WandbMonitorConfig(project="sft-tests"),
file=FileMonitorConfig(),
prime=PrimeTrainMonitorConfig(name="my-run"),
)
)
assert isinstance(monitors, EvalMonitorsConfig)
assert isinstance(monitors.prime, PrimeEvalMonitorConfig)
assert monitors.prime.name == "my-run"
assert monitors.wandb.project == "sft-tests"
# Without a platform run the evals process gets no platform monitor either
bare = build_online_eval_monitors(TrainMonitorsConfig())
assert bare.prime is None
def test_sft_setup_registers_prime_monitor(prime_init, tmp_path, clear_monitors):
config = _sft_config({"monitors": {"prime": {}}})
asyncio.run(
monitors.setup(
prime=config.monitors.prime,
output_dir=tmp_path,
run_config=config,
)
)
assert monitors.get(PrimeTrainMonitor) is not None
# The trainer's per-step metrics fan out to the platform run, and finalize
# closes it out (drains the SDK's upload queue).
asyncio.run(monitors.log({"loss/mean": 1.0, "step": 1}, step=1))
asyncio.run(monitors.log({"val/loss": 0.5, "step": 1}, step=1))
asyncio.run(monitors.finalize())
def test_online_eval_config_keeps_prime_monitor():
"""SFTOnlineEvalConfig.monitors must be EvalMonitorsConfig so the
launcher-converted PrimeEvalMonitorConfig survives the eval.json
dump/re-parse boundary (base MonitorsConfig drops/forbids prime)."""
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.monitors import EvalMonitorsConfig, PrimeEvalMonitorConfig
from prime_rl.entrypoints.sft import build_online_eval_monitors
field = SFTOnlineEvalConfig.model_fields["monitors"]
assert field.annotation is EvalMonitorsConfig
train_monitors = TrainMonitorsConfig.model_validate({"prime": {"name": "r1"}})
eval_monitors = build_online_eval_monitors(train_monitors)
assert isinstance(eval_monitors.prime, PrimeEvalMonitorConfig)
assert eval_monitors.prime.name == "r1"
# The online-eval process passes the prime monitor to monitors.setup
# (src/prime_rl/eval/online.py) — same wiring as the standalone eval
# entrypoint. Read the source text (importing the module pulls torch,
# which this torch-free test env deliberately lacks).
from pathlib import Path
import prime_rl
online_src = Path(prime_rl.__path__[0], "eval", "online.py").read_text()
assert "prime=config.monitors.prime" in online_src
def test_online_eval_shares_trainer_run_dir_and_merges_records(tmp_path):
"""The online-eval process shares the trainer's run dir (the dashboard
reads its file-monitor artifacts from there), and the platform records
MERGE instead of clobbering each other: the trainer's kind="train"
link survives with the eval process's evaluations riding along."""
from prime_rl.entrypoints.sft import build_online_eval_config
from prime_rl.monitors.prime import (
read_platform_record,
write_platform_record,
)
config = _sft_config(
{
"eval": {
"interval": 50,
"source": [
{
"name": "rev",
"env": {"taskset": {"id": "harbor"}},
}
],
},
"inference": {},
}
)
eval_config = build_online_eval_config(config)
# Same run dir: dashboard visibility for the eval artifacts.
assert eval_config.output_dir == config.run_dir
assert eval_config.broadcasts_dir != eval_config.output_dir
# Simulate the trainer's record, then the eval process merging on top.
write_platform_record(tmp_path, {"kind": "train", "id": "run-1", "url": "https://x/run-1"})
record = read_platform_record(tmp_path) or {}
if record.get("kind") == "train":
record.setdefault("evaluations", {})
record["run_id"] = "run-1"
else:
record = {"kind": "eval", "run_id": "run-1", "evaluations": {}}
record.setdefault("evaluations", {})["rev"] = {"step": 5, "id": "ev-1", "url": "https://x/ev-1"}
write_platform_record(tmp_path, record)
merged = read_platform_record(tmp_path)
assert merged["kind"] == "train" # the train link survives
assert merged["id"] == "run-1"
assert merged["evaluations"]["rev"]["id"] == "ev-1"
def test_platform_record_lock_keeps_a_stable_inode(tmp_path):
"""The record lock must NEVER unlink its lock file: a writer waiting on
the flock can still hold the unlinked inode's lock while a later writer
creates and locks a fresh file - two simultaneous "exclusive" locks and
a lost merge. The lock file must persist with the SAME inode across
acquisitions, and the locked update helper must merge two sequential
writers into one record. (Interprocess contention is exercised by the
two-process update_platform_record probe; here the writers are
sequential.)"""
import os
from prime_rl.monitors.prime import _platform_record_lock, update_platform_record
from prime_rl.utils.pathing import get_platform_run_path
lock_path = get_platform_run_path(tmp_path).with_suffix(".json.lock")
inodes = []
for _ in range(2):
with _platform_record_lock(tmp_path):
# The lock file exists DURING the critical section, always.
assert lock_path.is_file()
inodes.append(os.stat(lock_path).st_ino)
# The lock file SURVIVES release, and every acquisition locked the same inode.
assert lock_path.is_file()
assert len(set(inodes)) == 1
# Two sequential locked updates merge instead of clobbering.
update_platform_record(tmp_path, {"kind": "train", "id": "run-1", "url": "https://x/run-1"})
update_platform_record(tmp_path, {"evaluations": {"rev": {"step": 5, "id": "ev-1", "url": "https://x/ev-1"}}})
from prime_rl.monitors.prime import read_platform_record
record = read_platform_record(tmp_path)
assert record["kind"] == "train"
assert record["id"] == "run-1"
assert record["evaluations"]["rev"]["id"] == "ev-1"
def test_record_persistence_runs_off_the_event_loop(prime_init, tmp_path, monkeypatch):
"""The record merge (bounded flock retry included) must run in a worker
thread via asyncio.to_thread, not on the event loop thread: contention
for the full lock bound would otherwise freeze the loop."""
import threading
from pathlib import Path
import prime_rl.monitors.prime as prime_module
seen_threads = []
real_merge = prime_module._merge_platform_record
def spy(output_dir, merge):
seen_threads.append(threading.get_ident())
return real_merge(output_dir, merge)
monkeypatch.setattr(prime_module, "_merge_platform_record", spy)
config = _sft_config({"monitors": {"prime": {}}})
asyncio.run(PrimeTrainMonitor(config.monitors.prime).init(config=config, output_dir=tmp_path))
assert seen_threads, "the record merge never ran"
assert threading.get_ident() not in seen_threads, "record merge ran on the caller thread"
# All three async write sites (train init, eval init, eval epoch) go
# through to_thread; only the sync helper stays callable directly.
import re
import prime_rl
src = Path(prime_rl.__path__[0], "monitors", "prime.py").read_text()
assert len(re.findall(r"asyncio\.to_thread\(\s*_merge_platform_record", src)) == 2
assert re.search(r"asyncio\.to_thread\(\s*update_platform_record", src)
from prime_rl.monitors.prime import read_platform_record
record = read_platform_record(tmp_path)
assert record["kind"] == "train"
assert record["id"] == "run-123"
def test_platform_record_lock_acquisition_is_bounded(tmp_path, monkeypatch):
"""flock(LOCK_EX) must never block the event-loop thread indefinitely:
while another process holds the lock, acquisition retries
non-blockingly and raises TimeoutError past the bound instead of
hanging."""
import fcntl
import prime_rl.monitors.prime as prime_module
monkeypatch.setattr(prime_module, "RECORD_LOCK_TIMEOUT", 0.2)
lock_path = prime_module.get_platform_run_path(tmp_path).with_suffix(".json.lock")
lock_path.parent.mkdir(parents=True, exist_ok=True)
with open(lock_path, "a+b") as held:
fcntl.flock(held.fileno(), fcntl.LOCK_EX)
with pytest.raises(TimeoutError, match="still held"):
with prime_module._platform_record_lock(tmp_path):
pass
def test_platform_record_persistence_is_best_effort(tmp_path, monkeypatch):
"""A storage failure on the OPTIONAL dashboard record (e.g. ENOLCK on a
filesystem without flock support) must not abort training: the write is
skipped with a warning, and no record is left behind."""
import errno
import prime_rl.monitors.prime as prime_module
def enolck(fd, op):
raise OSError(errno.ENOLCK, "No locks available")
monkeypatch.setattr(prime_module.fcntl, "flock", enolck)
# Must not raise: the platform record is best-effort.
prime_module.update_platform_record(tmp_path, {"kind": "train", "id": "run-1", "url": "https://x/run-1"})
assert prime_module.read_platform_record(tmp_path) is None
Generated
+12 -12
View File
@@ -4975,8 +4975,8 @@ all = [
{ name = "torchvision", marker = "sys_platform == 'linux'" },
{ name = "vllm", version = "0.30.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm", version = "0.30.0", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.2", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.2", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
]
dashboard = [
{ name = "fastapi" },
@@ -4989,8 +4989,8 @@ disagg = [
{ name = "deep-gemm", version = "2.5.0+891d57b", source = { url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "nixl", marker = "sys_platform == 'linux'" },
{ name = "nixl-cu13", marker = "sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.1", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.2", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "vllm-router", version = "0.2.2", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
]
dynamo = [
{ name = "ai-dynamo", marker = "sys_platform == 'linux'" },
@@ -5123,9 +5123,9 @@ requires-dist = [
{ name = "vllm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.30.0" },
{ name = "vllm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl" },
{ name = "vllm-router", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'disagg'" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "wandb", specifier = ">=0.26.1" },
{ name = "wandb-workspaces", specifier = ">=0.4.3" },
]
@@ -8157,8 +8157,8 @@ provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttens
[[package]]
name = "vllm-router"
version = "0.2.1"
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl" }
version = "0.2.2"
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl" }
resolution-markers = [
"platform_machine == 'aarch64' and sys_platform == 'linux'",
]
@@ -8171,7 +8171,7 @@ dependencies = [
{ name = "uvicorn" },
]
wheels = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:0420aba42df1c970a78e1c4d4062eb00498e397f2dd506bade39eb915bf807b6" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:4e12c3e9e8123556b261b2ed79998ad256698b7e64da5afe4fe69e733e49b2d3" },
]
[package.metadata]
@@ -8190,8 +8190,8 @@ provides-extras = ["dev"]
[[package]]
name = "vllm-router"
version = "0.2.1"
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl" }
version = "0.2.2"
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_x86_64.whl" }
resolution-markers = [
"platform_machine == 'x86_64' and sys_platform == 'linux'",
]
@@ -8204,7 +8204,7 @@ dependencies = [
{ name = "uvicorn" },
]
wheels = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:046591cac21424997600d30b500bbaa3c450601e8b2b4fad6db9d142d1c36a0e" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:2132bda10632efc5a726c69c7e3e7a18ea70731c5ca1ec2528227aa0fb634eb8" },
]
[package.metadata]