Compare commits

...
Author SHA1 Message Date
2b688edcf6 perf(dsa): cuDNN + FlashMLA kernels for GLM-5 sparse attention (model.dsa_backend) (#3829)
adding cudnn backward kernel for dsa, glm5 full training

- New `model.dsa_backend` flag: `tilelang` (default, old path) or
`cudnn_flashmla` (FlashMLA forward + cuDNN backward).
- GLM-5.3 SFT example: `base.toml` now uses `cudnn_flashmla`, and a new
`16k-12-node.toml` overlay runs 12 nodes at 16k (cp=1, no offloading,
fullgraph, full AC).

| Part | Old (`tilelang`) | New (`cudnn_flashmla`) | Kernel speedup
(H200) | Status |
|---|---|---|---|---|
| Sparse attention forward | TileLang | FlashMLA `flash_mla_sparse_fwd`
| 1.9–3.6× | Hopper tested; Blackwell built in the wheel, untested |
| Sparse attention backward | TileLang | cuDNN `dsa_bwd_sm90` | 3–4.7× |
Hopper tested; Blackwell wired in, untested |

Full GLM-5.3 (78 layers), H200, 16k.

**Fake data** (random init, balanced routing)

| setup | nodes | tok/s per GPU | MFU |
|---|---|---|---|
| original config (cp=2, offloading), `tilelang` | 8 | 465 | 22.3% |
| `16k-12-node.toml`, `tilelang` | 12 | 701 | 33.6% |
| `16k-12-node.toml`, `cudnn_flashmla` | 12 | 835 | 40.1% |

**Real weights + data** (INTELLECT-3-SFT-10K math, 12 nodes)

| `dsa_backend` | step | tok/s | MFU |
|---|---|---|---|
| `tilelang` | 31.2s | 50.4k | 25.2% |
| `cudnn_flashmla` | 24.2s | 64.9k | 32.5% |

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes sparse-attention forward/backward kernels and gradient
numerics (LSE/index flattening); `cudnn_flashmla` needs SM90+ and extra
deps, with SM100 paths noted as untested.
> 
> **Overview**
> Adds **`model.dsa_backend`** (`tilelang` default,
**`cudnn_flashmla`**) so GLM-5 DSA sparse MLA can use **FlashMLA sparse
prefill** forward and **cuDNN CuTe-DSL** backward instead of TileLang
for both directions. The trainer passes the setting through
`model_config` into `sparse_mla`, which now takes a `backend` argument;
autograd routes backward to the matching implementation and **normalizes
LSE to natural log** across paths (TileLang converts at the boundary).
> 
> Packaging adds **`nvidia-cudnn-frontend`** on the GPU extra, a
**`flash-mla`** optional extra (pinned x86_64 wheel), and lockfile
updates.
> 
> GLM-5.3 SFT examples: **`base.toml`** sets `dsa_backend =
"cudnn_flashmla"`; new **`16k-12-node.toml`** overlay documents 12-node
/ 16k training without CP or offloading; README expanded for both
setups.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0894aa8897544e3c2913b6a4274a3f9f7c6c9527. 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-04 21:54:55 -07:00
minh hoangandGitHub 883b8f32c5 feat(docker): reuse dependency images for fast Docker source builds (#3828) 2026-10-04 22:47:39 -06:00
faresobeidandGitHub 407e8ba223 refactor(algo): declare action_loss_type once on the config; drop finalize_group (#3845)
Two small cleanups in `orchestrator/algo/`. Item 4 of the orchestrator
review.

- `action_loss_type` is now declared once, on the algorithm config
classes. Before, it was declared on the config classes and again on the
runtime classes (`algo/base.py`, `sft.py`, `opd.py`, `opsd.py`), and
`build_algorithm` asserted that the two agreed. Now `Algorithm.__init__`
copies it from the config, so `train_sink`'s
`env.algorithm.action_loss_type` is unchanged.
- `Algorithm.finalize_group` is removed. It only called `score_group`,
and `train_sink` now calls `score_group` directly. `finalize_episode` is
kept: its "has sampled tokens" guard matters for `echo`, whose
`score_episode` does not filter on the mask.
- `docs/algorithms.md` is updated to match.

Behavior change: none. Every algorithm type gets the same loss routing
as before, because the old assert guaranteed that the config and runtime
values were equal.

## Checks
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 291 passed (`test_algorithms` covers the per-type
`action_loss_type`).
- `ruff check`, `ruff format --check`: clean.

GPU checks: none needed.

## Conflicts
`algo/base.py` and `algo/__init__.py`: #3802, #3803 (small). #3838 (fold
`GenerationSource`) also edits `algo/base.py` and `algo/__init__.py`
(`connect_frozen_client`), which needs a trivial rebase.
`train_sink.py:245`: #3652 rewrites `train_sink.py` (a one-line change
there).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Refactor-only: loss routing and group scoring call paths are unchanged
in effect; no auth, data, or trainer hot-path logic changes.
> 
> **Overview**
> **Single source of truth for loss routing:** runtime `Algorithm`
instances now take `action_loss_type` from the algorithm config in
`__init__` instead of duplicating it on each subclass and asserting
agreement in `build_algorithm`. Per-algorithm class variables on `OPD`,
`OPSD`, and `SFT` are removed; `train_sink` still reads
`env.algorithm.action_loss_type` when stamping samples.
> 
> **Thinner scoring API:** `Algorithm.finalize_group` is dropped and the
train sink calls `score_group` directly when a group has trainable
survivors. `finalize_episode` remains as the guarded entry point for
rollout-local `score_episode` (skips episodes with no trainable sampled
tokens).
> 
> **Docs:** `algorithms.md` is updated to describe this pipeline wiring
and config-owned `action_loss_type`.
> 
> No intended training behavior change—loss routing values are the same
as before when config and runtime matched.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1ebee7fec9fab8740b04de41e3aee9e89d4ca6d7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 16:56:44 -07:00
faresobeidandGitHub cf9962c13b refactor(orchestrator): fold packing.py into batch.py (#3842)
Moves `BatchPacker` (35 lines) from `orchestrator/packing.py` into
`orchestrator/batch.py` and deletes `packing.py`. The class only wraps
`build_bin_cost` and `prepare_batch`, which already live in `batch.py`.

Item 6 of the orchestrator review.

Behavior change: none (pure move; the import in `orchestrator.py` is
updated).

## Checks
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 291 passed
- `ruff check`, `ruff format --check`: clean
- `python -c "import prime_rl.orchestrator.orchestrator"` OK
- Equivalence: the class body is copied byte for byte (`git diff` shows
only the move and the import lines).

GPU checks: none needed.

## Conflicts
- #3840 (FLOP estimator): textual, in the `batch.py` imports only.
- #3652: its `Shipper` imports `BatchPacker` from `packing`, which
becomes a one-line change to `from prime_rl.orchestrator.batch import
BatchPacker`.
- #3819, #3836, #3794 touch other parts of `batch.py`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Pure file move and import path update with no logic changes to
training batch packing.
> 
> **Overview**
> **Colocates batch packing with the bin-packing helpers it already
delegates to.**
> 
> `BatchPacker` moves from `orchestrator/packing.py` into
`orchestrator/batch.py` next to `build_bin_cost` and `prepare_batch`;
`packing.py` is removed. The orchestrator now imports `BatchPacker` from
`batch` instead of `packing`. Class behavior and `pack()` semantics are
unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
986f5bf0f692cca69a2bf1d49bbec53b09ececef. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 16:50:30 -07:00
faresobeidandGitHub 34e26e39a5 chore(deps): drop duplicate and unused pyproject dependencies (#3856)
Removes duplicate and unused entries from `pyproject.toml` (rev-infra
P9). The set of installed packages does not change for any extra
combination (checked below).

| Removed | Reason |
|---|---|
| second `orjson>=3.10` in `dependencies` | Duplicate of
`orjson>=3.11.0` a few lines above. |
| `pandas>=2.0` | Nothing imports it: no `import pandas` / `pd.` in
`src/`, `tools/`, `scripts/`, `tests/`, `examples/`, `skills/`,
`packages/`. It was added for the nano bridge (7089ba1e4). It stays
installed because `datasets` depends on it. |
| `pyarrow>=21.0.0` | No direct use anywhere in those directories. The
one parquet writer, `tools/convert_traces_to_hf_dataset.py`, calls
`datasets.Dataset.to_parquet`, and `datasets` depends on `pyarrow`
itself. It stays installed. |
| `nixl-cu13==0.10.1` in the `disagg` extra | `disagg` already lists
`nixl`, and the `[[tool.uv.dependency-metadata]]` override for `nixl`
0.10.1 requires exactly `nixl-cu13==0.10.1`. The `gpu` extra keeps its
explicit pin, because `transports/weights/nixl/agent.py` imports
`nixl_cu13` directly. |
| `mamba-ssm` dependency group | Duplicate of the `gpu` extra entry,
which was added with the native Nemotron-H model (#3426). Every user of
the group also syncs `--extra gpu` or `--all-extras`, so I dropped
`--group mamba-ssm` from `Dockerfile.cuda` (2 places),
`scripts/docker-entrypoint.sh` and the `pre_run_command` in
`configs/advanced/nemotron-3-super/swe.toml`. The `[tool.uv.sources]`
git pin and the build dependencies for mamba-ssm stay. |

Behavior change:
- None for installs: same locked packages and versions.
- `uv sync --group mamba-ssm` no longer works; use `--extra gpu`, which
every repo caller already passes.
- `pandas` and `pyarrow` lose their direct lower bounds. They are still
pulled in by `datasets`.

## Checks
- `uv lock`: resolves 564 packages, the same set as before (568
`[[package]]` entries before and after). `uv lock --check` passes. The
`uv.lock` diff only touches prime-rl's own metadata. I reverted the
reordering of `[options.exclude-newer-package]` that my uv version
(0.12.10) introduced.
- I ran `uv export --frozen --all-packages` and compared the package
lists before and after, ignoring the `# via` comment lines. They are
identical for: no extras, `--extra disagg`, `--extra gpu`, `--extra
dashboard`, `--all-extras`, and `--all-extras --all-groups`. `--extra
disagg` still yields `nixl==0.10.1` and `nixl-cu13==0.10.1`, and
`--extra gpu` still yields `mamba-ssm` at the pinned rev.
- No Python changes, so no unit tests are affected. GPU: not needed. The
Docker image build in CI covers the Dockerfile and entrypoint edits.

## Conflicts
Text conflicts only in `pyproject.toml` / `uv.lock`, as with any
dependency PR. None of the open PRs that touch these files (e.g. #3829,
#3803, #3767, #3660) edit the lines removed here. A re-lock after rebase
is enough.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Metadata and sync-flag cleanup only; lockfile exports are unchanged
and runtime installs should match prior behavior.
> 
> **Overview**
> Cleans up **duplicate and redundant dependency declarations** in
`pyproject.toml` and aligns `uv.lock`, Docker, and Slurm sync commands
with the slimmer manifest. **No intended change to installed packages**
for existing extra combinations (`gpu`, `disagg`, `--all-extras`, etc.).
> 
> **Removed from core `dependencies`:** duplicate `orjson>=3.10`, unused
direct pins on `pandas` and `pyarrow` (they still come in via
`datasets`). **Removed from `disagg` extra:** explicit
`nixl-cu13==0.10.1` because `nixl` metadata already pulls that version;
the **`gpu` extra keeps** its explicit `nixl-cu13` pin for direct
imports. **Dropped the `mamba-ssm` dependency group** as a duplicate of
the `gpu` extra entry—`Dockerfile.cuda`, `scripts/docker-entrypoint.sh`,
and the Nemotron SWE `pre_run_command` no longer pass `--group
mamba-ssm`.
> 
> **Workflow note:** `uv sync --group mamba-ssm` alone is no longer
supported; use `--extra gpu` (or `--all-extras`), which callers already
use.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f0f2ff6b6365165a92be511c8029a47080f748e0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 16:49:27 -07:00
faresobeidandGitHub 8acaaf2baa docs(scaling): match ep="auto" to the code; NIXL wheel is nixl_cu13 (#3837)
Fixes two wrong statements in `docs/scaling.md` (from the whole-codebase
review, rev-infra P8 / rev-trainer §6). Docs only. No code or behavior
change.

- **`ep = "auto"`**: the doc said auto picks the largest divisor of
`num_experts` that divides the FSDP island, is a multiple of `cp`, and
is ≤ 8. The code (`trainer/parallel_dims.py:resolve_ep`) returns
`min(world_size // dp_replicate, 8)` for MoE models and 1 otherwise.
That matches the `ModelConfig.ep` docstring. The doc now describes what
the code does and says to set `ep` explicitly when the result does not
fit `cp` / `num_experts`.
- **NIXL wheel**: `scripts/install_nixl_from_source.sh` names the wheel
`nixl-cu13` (lines 85-88, 105). `docs/advanced.md:216` already says
`nixl_cu13-*.whl`, but `scaling.md` said `nixl_cu12-*.whl`, so that
install command did not match any file.

Checks: docs only. Compared against `resolve_ep` and the install script.

Conflicts with open PRs: none. No open PR touches `docs/scaling.md`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Documentation-only corrections to scaling and install instructions; no
runtime or training behavior changes.
> 
> **Overview**
> Updates **`docs/scaling.md`** so it matches current behavior—no code
changes.
> 
> **Expert parallelism (`ep = "auto"`)**: Replaces the old description
(largest valid divisor of `num_experts` subject to FSDP island, `cp`,
and cap 8) with what **`resolve_ep`** actually does: for MoE,
`min(world_size // dp_replicate, 8)`; for non-MoE, `1`. The doc now
notes that auto does not consider `num_experts` or `cp`, and that you
should set **`ep`** explicitly when the resolved value fails those
constraints.
> 
> **NIXL install**: Changes the documented wheel from
`deps/nixl_cu12-*.whl` to **`deps/nixl_cu13-*.whl`**, consistent with
`scripts/install_nixl_from_source.sh` and other docs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
778befd26ff787ee71cb7308071a26542c9cc470. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 16:12:04 -07:00
faresobeidandGitHub f42630873d chore: remove Kubernetes deployment path (Helm chart, trainer metrics server) (#3767)
Removes the Kubernetes deployment path. The Helm chart has had no
functional change since its initial additions (last own change
2026-08-12 was a docs fix), and supported multi-node deployment is SLURM
(see docs/scaling.md). The trainer `metrics_server` (Prometheus
`/metrics` + `/health`) only existed to serve the chart's
liveness/readiness probes.

## Removed
- `k8s/` Helm chart (and `COPY k8s` from `Dockerfile.cuda`)
- `src/prime_rl/utils/metrics_server.py` (`MetricsServer`,
`HealthServer`) and its unit test
- `MetricsServerConfig` (configs/shared.py), trainer `metrics_server`
field, and its setup/update/teardown in `trainer/rl/train.py`
- Kubernetes sections/mentions in README,
`examples/basic/reverse-text/README.md`, `docs/training.md`; `k8s/`
TOMLs dropped from `test_configs.py`
- Inference `liveness_timeout_seconds` docstring reworded neutrally; the
`/liveness` endpoint stays (used by SLURM/router health checks)

`prometheus-client` stays in `pyproject.toml`:
`orchestrator/inference_metrics.py` still uses its parser.

## Breaking changes
- Trainer configs that set `metrics_server` now fail validation.
- The Helm chart and `/app/k8s` in the image are gone.

## Validation
- `pytest tests/unit/test_configs.py -m "not gpu"` (205 passed)
- `ruff check .` and `ruff format --check .`
- No GPU on the machine used; GPU/integration tests not run.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking for anyone using the Helm chart or trainer `metrics_server`
config; training/runtime core paths are unchanged but deployment and
observability options shrink.
> 
> **Overview**
> **Removes the Kubernetes/Helm deployment path** and related trainer
observability that existed mainly for chart probes.
> 
> The entire `k8s/` Helm chart (StatefulSets, services, PVC,
reverse-text example values/TOMLs, and `k8s/README.md`) is deleted.
**`Dockerfile.cuda`** no longer copies `k8s/` into the image, and
docs/README/example copy now describe **Slurm-only** multi-node
deployment (K8s sections dropped from `reverse-text` README).
> 
> **Trainer Prometheus/health HTTP server is removed:**
`MetricsServerConfig`, the `metrics_server` trainer config field,
`src/prime_rl/utils/metrics_server.py`, RL trainer
startup/update/shutdown hooks, and unit tests. Configs that still set
`metrics_server` will fail validation.
> 
> **Minor doc tweaks:** inference `liveness_timeout_seconds` help text
is generic (not K8s-specific); `env-server` docs refer to externally
managed hosts instead of pods. Config validation tests only scan
`configs/` and `examples/` TOMLs, not `k8s/`.
> 
> Inference `/liveness` and `prometheus-client` elsewhere (e.g.
orchestrator) are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
42e89b437dc19ae11abd0172672b89b9f03e6c30. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 23:49:24 +01:00
faresobeidandGitHub 1eeea3a047 chore: remove legacy dead code (#3769)
Removes legacy leftovers that were last touched 2025-11 to 2026-02 or
were orphaned by features that are already gone. Behavior does not
change.

- **`orchestrator/patches.py`**: deletes the OpenAI chat-type
monkeypatches, which were written for verifiers 0.1.8. The orchestrator
and eval processes no longer parse `ChatCompletion` or message objects
in-process. Rollouts run in separate env-server processes, which never
applied the patch, and `prefill_logprobs` reads the raw
`httpx.Response`.
- **`FileSystemWeightUpdateWorker.init_broadcaster`**: deletes this
no-op stub. `/init_broadcaster` is only called by the NCCL and NIXL
transports, whose workers define their own method. The stub took no
arguments, so the route could never have dispatched to it anyway.
- **`prime_rl.utils.utils` pathing re-export**: deletes the shim (its
TODO asked for this) and points the remaining imports at
`prime_rl.utils.pathing`. The shim's file-wide `noqa: F401` was hiding
three unused imports in `utils.py`; they are removed too.
- **`tests/unit/inference/test_serving_chat_with_tokens.py`**: deletes
this empty file.
- **`ConcurrencyController.record_episode`**: now takes only `tokens`.
`env_name`, `kind` and `duration` are left over from the removed per-env
cost model and were ignored. The dispatcher's `on_episode_complete`
callback type now matches, and the `ConcurrencyConfig` docstring no
longer mentions "learned per-env episode costs".
- **`@deprecate_kwarg("past_key_value", ...)`**: removed from the llama,
glm4_moe and glm_moe_dsa decoder layers. These layers never accepted
`past_key_value(s)`, and transformers is pinned to 5.6.2. The signatures
still accept everything their callers pass.

## Breaking changes
- `from prime_rl.utils.utils import get_ckpt_dir` (and the other pathing
helpers) no longer works. Import them from `prime_rl.utils.pathing`.
- `ConcurrencyController.record_episode(tokens)` and the
`Dispatcher(on_episode_complete=...)` callback now take one argument.
- `prime_rl.orchestrator.patches` no longer exists.

## Validation
- `ruff check .` and `ruff format --check .`
- `pytest tests/unit/orchestrator tests/unit/eval tests/unit/inference
tests/unit/train/models tests/unit/utils tests/unit/test_configs.py -m
"not gpu"`: 417 passed, 154 deselected
- Import check of every modified module.
- GPU and integration tests were not run: this machine has no GPU.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Mostly deletions and import-path changes with documented API breaks;
adaptive concurrency still uses token counts for growth gating.
> 
> **Overview**
> This PR deletes unused orchestration and compatibility shims and
tightens a few callback signatures. Runtime behavior for supported
entrypoints is intended to stay the same.
> 
> **Removed OpenAI monkey-patches** — `orchestrator/patches.py` and
startup calls in the orchestrator and eval runner are gone. Rollouts no
longer parse `ChatCompletion` in those processes.
> 
> **Concurrency hooks** — `ConcurrencyController.record_episode` and the
dispatcher `on_episode_complete` callback now only receive **token
count**; leftover per-env cost-model args were unused.
`ConcurrencyConfig` docs now describe KV-pressure sizing only.
> 
> **Misc cleanup** — Drops
`FileSystemWeightUpdateWorker.init_broadcaster`, the
`prime_rl.utils.utils` re-export of pathing helpers (call sites import
`prime_rl.utils.pathing` directly), `@deprecate_kwarg` on custom decoder
layers, and an empty inference unit test file.
> 
> **Breaking for downstream imports** — `prime_rl.orchestrator.patches`
is removed; pathing helpers must be imported from
`prime_rl.utils.pathing`; `record_episode` / `on_episode_complete` take
a single `int` argument.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
079daae952aeae8c1e6dd1a009ec3d950d0f4767. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 23:47:00 +01:00
JannikStandGitHub d9adc1e867 fix(dashboard): use relative static/api paths for path-prefixed reverse proxy (#3814)
Platform is adding a reverse proxy for the dashboard (platform#5719)
that forwards the bare path upstream with no prefix, so every
browser-side reference needs to be relative, not absolute.

- `index.html`: dropped the leading `/` from the icon, stylesheet, brand
image, and script `src`/`href` paths.
- `app.js`: the `api()` fetch helper now strips a leading `/` before
calling `fetch`, and the `EventSource("/api/view/events")` call is
relative too.
- `style.css` already only used `data:` URIs, no change needed.

Verification: served the static files through a throwaway reverse proxy
mounted under a sub-path prefix (mirroring the proxy's bare-path
forwarding), confirmed the HTML/JS no longer contain absolute `/static`
or `/api` references, and confirmed requests like
`.../prefix/static/app.js` and `.../prefix/api/runs` correctly resolve
relative to the page and reach the upstream dashboard.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> URL resolution-only changes for static assets and API/SSE calls; no
server or auth logic touched.
> 
> **Overview**
> Makes the dashboard work when it is served behind a reverse proxy that
mounts it under a sub-path and forwards **bare** paths upstream (no
`/prefix` on upstream requests).
> 
> **`index.html`** switches icon, CSS, images, and script tags from
root-absolute (`/static/...`) to **relative** (`static/...`) so assets
resolve against the current page URL.
> 
> **`app.js`** strips a leading `/` in the shared `api()` `fetch` helper
so existing `api("/api/...")` callers emit relative `api/...` URLs, and
changes the live view **`EventSource`** from `/api/view/events` to
`api/view/events`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9efe2aa17fc084cf71491dabd88e9b039ff40555. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-04 01:49:10 +02:00
63 changed files with 619 additions and 1883 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
# .git stays: docker-editable-pretend-versions.sh reads .git/modules via the bind mount.
.git
**/.git
outputs
**/.venv
**/__pycache__
+46 -9
View File
@@ -172,7 +172,7 @@ jobs:
- name: Checkout
uses: actions/checkout@v7
with:
ref: ${{ needs.prepare.outputs.ref }}
ref: ${{ needs.prepare.outputs.full_sha }}
fetch-depth: 0
submodules: false
@@ -193,21 +193,55 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Set up uv
uses: astral-sh/setup-uv@v7
with:
version: "0.11.9"
enable-cache: false
- name: Resolve dependency image and package versions
id: dependency
env:
GH_TOKEN: ${{ github.token }}
SUFFIX: ${{ matrix.suffix }}
run: |
set -euo pipefail
key=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py fingerprint .)
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-${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"
bash scripts/docker-editable-pretend-versions.sh --github-output . >> "$GITHUB_OUTPUT"
- name: Build and push dependencies
id: dependencies
if: steps.dependency.outputs.digest == ''
uses: docker/build-push-action@v7
with:
context: .
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
platforms: ${{ matrix.platform }}
tags: ${{ steps.dependency.outputs.image }}
- name: Build and push
id: build
uses: docker/build-push-action@v7
with:
context: .
file: ./Dockerfile.cuda
# zstd compresses the multi-GB venv layers several times faster than gzip at a
# comparable ratio. No `force-compression`, so base-image layers are reused as-is
# rather than needlessly recompressed. Pulling zstd layers needs containerd >= 1.5
# or Docker >= 23.
target: runtime
build-args: |
DEPENDENCY_IMAGE=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ steps.dependencies.outputs.digest || steps.dependency.outputs.digest }}
VERIFIERS_PRETEND_VERSION=${{ steps.dependency.outputs.verifiers }}
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
# The per-job builder is ephemeral; mode=max caches builder-stage
# layers so warm builds skip the dependency sync.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=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
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
@@ -223,6 +257,8 @@ jobs:
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
DEPENDENCY_IMAGE: ${{ steps.dependency.outputs.image }}
DEPENDENCY_DIGEST: ${{ steps.dependencies.outputs.digest || steps.dependency.outputs.digest }}
PLATFORM: ${{ matrix.platform }}
SUFFIX: ${{ matrix.suffix }}
run: |
@@ -236,6 +272,7 @@ jobs:
echo "| **Image** | \`${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}-${SUFFIX}\` |"
echo "| **Commit** | \`${IMAGE_SHA}\` |"
echo "| **Digest** | \`${IMAGE_DIGEST}\` |"
echo "| **Dependencies** | \`${DEPENDENCY_IMAGE}@${DEPENDENCY_DIGEST}\` |"
} >> "$GITHUB_STEP_SUMMARY"
manifest:
+52 -78
View File
@@ -1,21 +1,27 @@
# syntax=docker/dockerfile:1
# ^ `COPY --exclude` (used to split the venv into parallel-compressible layers) needs
# Dockerfile syntax >= 1.19; `docker/dockerfile:1` resolves to the latest stable 1.x.
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
ARG DEPENDENCY_IMAGE=dependencies
FROM ghcr.io/astral-sh/uv:0.11.9@sha256:6b6fa841d71a48fbc9e2c55651c5ad570e01104d7a7d701f57b2b22c0f58e9b1 AS uv
FROM ubuntu:24.04@sha256:a853f94d226358a79c740cfc7bce0c289748f3fe3488d921d038ccd752c61b60 AS python-builder
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates python3.12 python3.12-venv \
&& rm -rf /var/lib/apt/lists/*
COPY --from=uv /uv /uvx /usr/local/bin/
ENV UV_PYTHON_PREFERENCE=only-system UV_LINK_MODE=copy
# Every pyproject.toml + uv.lock, so the dependency sync below caches
# independently of source edits.
FROM nvidia/cuda:13.0.1-base-ubuntu24.04 AS manifests
# .git is ~735 MB, changes every commit, and would land in the registry cache.
COPY --exclude=.git . /ctx
FROM python-builder AS manifests
COPY . /ctx
RUN mkdir -p /manifests \
&& cd /ctx \
&& find . -name .git -prune -o -type f -name pyproject.toml -exec cp --parents {} /manifests/ \; \
&& cp uv.lock /manifests/
# Build stage - multi-arch base (supports amd64 + arm64)
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04 AS builder
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04@sha256:8b2705ea7a8653ad3451b46ab835eced92d77b44e671b9cf3ad4f95fbb2efe5e AS builder
LABEL maintainer="prime intellect"
LABEL repository="prime-rl"
@@ -72,18 +78,12 @@ RUN git clone --depth 1 --branch v${UCX_VERSION} https://github.com/openucx/ucx.
&& make install \
&& rm -rf /tmp/ucx
# Download the latest installer
ADD https://astral.sh/uv/install.sh /uv-installer.sh
# Set install dir to location accessible to non-root users
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
COPY --from=uv /uv /uvx /usr/local/bin/
ENV PATH="/usr/local/bin:$PATH"
# Build .venv against the system CPython, so the venv's recorded interpreter
# matches the runtime interpreter and no bin/python relink is needed at runtime.
ENV UV_PYTHON_PREFERENCE=only-system
ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
# Explicity set venv dir inside /app so to ensure it gets copied over during
# the runtime stage's `COPY /app`
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
# Install Python dependencies
@@ -91,51 +91,11 @@ WORKDIR /app
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# Third-party deps only — source edits don't bust this layer. First-party
# editables install in the source-layer sync below. No build-context bind
# mount here: .git would bust the cache every commit.
# `--extra dashboard` (fastapi/uvicorn) is baked in so the fft chart's dashboard pod needs no runtime uv sync (see PR body).
# The runtime dependency image contains no first-party source or editable installs.
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
--no-install-package renderers \
--no-install-package prime-pydantic-config
COPY pyproject.toml /app/pyproject.toml
COPY uv.lock /app/uv.lock
COPY README.md /app/README.md
COPY src/ /app/src/
COPY packages/ /app/packages/
COPY deps/ /app/deps/
COPY configs /app/configs
COPY examples /app/examples
COPY k8s /app/k8s
COPY benchmarks/scripts /app/benchmarks/scripts
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
# Use submodule git metadata from the build context when present. Docker copies
# only the submodule .git pointer files into /app/deps, so we temporarily link
# /app/.git/modules to the read-only context before resolving versions.
ARG VERIFIERS_PRETEND_VERSION
ARG RENDERERS_PRETEND_VERSION
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
--mount=type=bind,source=.,target=/build-context,readonly \
if [ -d /build-context/.git/modules ]; then mkdir -p /app/.git && ln -s /build-context/.git/modules /app/.git/modules; fi \
&& \
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
&& \
if [ -L /app/.git/modules ]; then rm /app/.git/modules && rmdir /app/.git 2>/dev/null || true; fi \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" /app/deps/verifiers/pyproject.toml \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --locked --no-dev \
--no-install-local
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
# ships its own UCX which segfaults on prefill→decode KV transfer (#2883);
@@ -185,7 +145,7 @@ RUN find /usr/local/cuda-13.0/targets/*/lib \
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
# Runtime image
FROM nvidia/cuda:13.0.1-base-ubuntu24.04
FROM nvidia/cuda:13.0.1-base-ubuntu24.04@sha256:f8ef28f579ea42a44b415d2c5d46f788e6a9b395c6c83f2929416e1fc192c143 AS dependencies
ENV DEBIAN_FRONTEND=noninteractive
@@ -263,19 +223,12 @@ RUN userdel -r ubuntu 2>/dev/null || true; \
echo "appuser ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
# Install uv for development use
ADD https://astral.sh/uv/install.sh /uv-installer.sh
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
COPY --from=uv /uv /uvx /usr/local/bin/
USER appuser
ENV PATH="/usr/local/bin:$PATH"
WORKDIR /app
# Copy the application from the builder, splitting the venv's largest trees into their
# own layers. BuildKit compresses and pushes layers in parallel, so shipping the whole
# ~20 GB venv as one layer serialized the export behind a single compressor. Splitting
# also lets nodes pull the image in parallel. Keep the excludes below in sync with the
# per-tree copies above, or the data lands in the image twice.
# The volatile /app remainder goes last so a source edit re-pushes one layer,
# not all of them.
# Split the largest dependency trees so compression and pulls can run in parallel.
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/nvidia /app/.venv/lib/python3.12/site-packages/nvidia
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/torch /app/.venv/lib/python3.12/site-packages/torch
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/vllm /app/.venv/lib/python3.12/site-packages/vllm
@@ -283,17 +236,14 @@ COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packa
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so /app/.venv/lib/python3.12/site-packages/
COPY --from=builder /opt/ucx /opt/ucx
# Copy and set up entrypoint script
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
RUN chmod +x /app/docker-entrypoint.sh
COPY --from=builder --chown=appuser:appuser \
--exclude=.venv/lib/python3.12/site-packages/nvidia \
--exclude=.venv/lib/python3.12/site-packages/torch \
--exclude=.venv/lib/python3.12/site-packages/vllm \
--exclude=.venv/lib/python3.12/site-packages/flash_attn \
--exclude=.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so \
/app /app
--exclude=lib/python3.12/site-packages/nvidia \
--exclude=lib/python3.12/site-packages/torch \
--exclude=lib/python3.12/site-packages/vllm \
--exclude=lib/python3.12/site-packages/flash_attn \
--exclude=lib/python3.12/site-packages/flash_attn_2_cuda*.so \
/app/.venv /app/.venv
RUN /app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
# Place executables in the environment at the front of the path
ENV PATH="/app/.venv/bin:$PATH"
@@ -304,6 +254,30 @@ ENV LD_LIBRARY_PATH="/opt/ucx/lib:/opt/ucx/lib/ucx${LD_LIBRARY_PATH:+:${LD_LIBRA
ENV HF_HUB_ETAG_TIMEOUT=500
ENV HF_HUB_DOWNLOAD_TIMEOUT=300
# Use entrypoint for setup (ulimit, etc) but default to sleep infinity for K8s
FROM python-builder AS application-builder
WORKDIR /app
COPY pyproject.toml uv.lock README.md /app/
COPY src /app/src
COPY packages /app/packages
COPY deps /app/deps
COPY configs /app/configs
COPY examples /app/examples
COPY benchmarks/scripts /app/benchmarks/scripts
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
COPY scripts/docker_application.py /build/docker_application.py
ARG VERIFIERS_PRETEND_VERSION
ARG RENDERERS_PRETEND_VERSION
ARG PYDANTIC_CONFIG_PRETEND_VERSION
RUN --mount=type=cache,target=/root/.cache/uv \
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
&& uv run --no-project --python /usr/bin/python3.12 /build/docker_application.py /app /out/app
# COPY --link and numeric ownership let source builds reuse dependency blobs without unpacking them.
FROM ${DEPENDENCY_IMAGE} AS runtime
ARG USER_ID=1000
ARG GROUP_ID=1000
COPY --link --from=application-builder --chown=${USER_ID}:${GROUP_ID} /out/app /app
# Preserve the executable Git mode; --chmod disables BuildKit's linked-copy optimization.
COPY --link --chown=${USER_ID}:${GROUP_ID} scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
ENTRYPOINT ["/app/docker-entrypoint.sh"]
CMD ["sleep", "infinity"]
+2 -2
View File
@@ -35,7 +35,7 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
2. Performant: built to train 1T+ MoE models on 1000+ GPUs with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) for training and [vLLM](https://github.com/vllm-project/vllm) for inference, with FP8 inference, PD disaggregation, EP and CP parallelism, and more.
3. Native integration with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments through the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars), including built-in support for SWE and agentic environments.
4. End-to-end post-training: SFT, RL training, and evals.
5. Multi-node deployment with Slurm and Kubernetes support.
5. Multi-node deployment with Slurm support.
6. Multimodal support for VLMs such as Qwen3.5.
7. Hackable, modular, and extensible by design.
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.3/).
@@ -181,7 +181,7 @@ Follow this guide to learn the basics of prime-rl. You can train your own models
### Advanced Training: 32 - 2048 GPUs:
Follow this guide to train large models on hard reasoning and agentic tasks.
These guides are designed to be run from a Slurm cluster but can also be adapted to k8s deployments.
These guides are designed to be run from a Slurm cluster.
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
+2 -2
View File
@@ -9,8 +9,8 @@ PYTORCH_CUDA_ALLOC_CONF = "expandable_segments:True"
[slurm]
job_name = "nemotron-3-super-swe"
partition = "prod"
# Nemotron-H needs the mamba-ssm kernels; sync that group, then clear this run's orphaned sandboxes.
pre_run_command = 'uv sync --all-extras --all-packages --group mamba-ssm ; timeout 120 prime sandbox delete --label "nemotron-3-super-swe" -y || true'
# Sync the env (the gpu extra brings Nemotron-H's mamba-ssm kernels), then clear this run's orphaned sandboxes.
pre_run_command = 'uv sync --all-extras --all-packages ; timeout 120 prime sandbox delete --label "nemotron-3-super-swe" -y || true'
[deployment]
type = "multi_node"
+2 -2
View File
@@ -157,9 +157,9 @@ Algorithms operate on native verifier artifacts and annotate their message graph
- `async score_episode(episode)` — rollout-local scoring as one episode arrives.
- `async score_group(episodes)` — group-relative scoring after the cohort completes.
The pipeline drives these through `finalize_episode` and `finalize_group`. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
The pipeline calls `score_group` directly and `score_episode` through `finalize_episode`, which skips episodes with no trainable sampled tokens. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.train.algo.advantage`.
The algorithm config states which loss component its action tokens feed (`action_loss_type`, a class variable on each config class). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). Writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.train.algo.advantage`.
## Async / Off-Policy Training
+2 -2
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` 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:
`ep` defaults to `"auto"`. At startup it loads the model config to check whether the model is MoE. For MoE models it resolves to `min(world_size // dp_replicate, 8)`: the FSDP island size, capped at 8. For non-MoE models it resolves to 1 (no-op). `"auto"` does not look at `num_experts` or `cp`; the resolved degree must still be a multiple of `cp` and divide `num_experts`, so set it explicitly when it does not. Set `ep` to an explicit integer to override:
```toml
[trainer.model]
@@ -241,7 +241,7 @@ Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transf
```bash
bash scripts/install_nixl_from_source.sh
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
uv pip install --reinstall --no-deps deps/nixl_cu13-*.whl
bash scripts/install_modelexpress.sh
```
+1 -1
View File
@@ -37,7 +37,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-server` per source. |
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. on their own host) and the launcher expects the server to already run there. |
## RL Trainer
+12
View File
@@ -113,5 +113,17 @@ This will start a SFT run with the following configuration:
- The model is `zai-org/GLM-5.3-BF16`
- The data is `PrimeIntellect/INTELLECT-3-SFT-10K` (math split)
- 8 nodes at 131k context: CP 8, EP 8, full activation checkpointing with activation offloading, optimizer state offloaded to CPU
- DSA attention runs on the FlashMLA sparse forward and the cuDNN sparse backward (`model.dsa_backend = "cudnn_flashmla"`)
For a fake-data dry run, append [`fake.toml`](sft/h200/fake.toml) instead. You can use the same dashboard to monitor the SFT run.
### 12 nodes at 16k
For 16k-token samples, append [`16k-12-node.toml`](sft/h200/16k-12-node.toml) after the data overlay:
```bash
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml @ examples/advanced/glm-5.3/sft/h200/16k-12-node.toml
```
On 12 nodes the sharded model state fits in GPU memory without CP or any offloading. Each GPU runs one 16k sequence per step (batch 96), and transformer blocks compile with `fullgraph = true`. Full activation checkpointing stays on; peak memory is about 115 GiB per GPU.
@@ -0,0 +1,19 @@
# 12-node, 16k-token overlay: enough GPUs that the model state fits without CP or offloading,
# so each GPU runs one 16k sequence per micro-batch and blocks compile with fullgraph.
# Compose after the data overlay, e.g. base.toml @ math-10k.toml @ 16k-12-node.toml.
[model]
cp = 1
optim_cpu_offload = false
ac_offloading = "None"
[model.compile]
fullgraph = true
[data]
seq_len = 16384
batch_size = 96
micro_batch_size = 1
[deployment]
num_train_nodes = 12
@@ -10,6 +10,7 @@ attn = "flash_attention_2"
cp = 8
ep = 8
optim_cpu_offload = true
dsa_backend = "cudnn_flashmla"
[model.ac]
freq = 1
-120
View File
@@ -98,123 +98,3 @@ uv run eval @ examples/basic/reverse-text/eval.toml -m PrimeIntellect/Qwen3-0.6B
```
Way better! Now we get an **average reward of ~0.8**.
## Kubernetes Deployment
If you're running on Kubernetes, you can deploy this example using the provided Helm chart. The Helm chart automatically configures all components with proper networking and shared storage.
### Step 1: Deploy for SFT Training
The reverse-text example is configured with `autoStart: true` for RL training, but we need to run SFT first. Deploy with autoStart disabled:
```bash
cd k8s
helm install my-exp ./prime-rl -f ./prime-rl/examples/reverse-text.yaml \
--set orchestrator.autoStart=false \
--set inference.autoStart=false \
--set trainer.autoStart=false
# Check pods are ready
kubectl get pods -l app=prime-rl,example=reverse-text
# All pods should show 1/1 Running
```
### Step 2: Run SFT Training
Exec into the trainer pod and run SFT:
```bash
kubectl exec -it my-exp-trainer-0 -- bash
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs --run.name sft
# This will save DCP checkpoints to /data/outputs/sft/checkpoints/step_100
```
### Step 3: Deploy RL Training
Now upgrade the deployment to enable autoStart (uses the default `autoStart: true` from reverse-text.yaml):
```bash
# Exit the pod first (Ctrl+D)
cd k8s
helm upgrade my-exp ./prime-rl -f ./prime-rl/examples/reverse-text.yaml
# Check pods have restarted
kubectl get pods -l app=prime-rl,example=reverse-text
```
The RL components will automatically start. Monitor the logs:
```bash
# View inference server logs
kubectl logs -f my-exp-inference-0
# View orchestrator logs
kubectl logs -f my-exp-orchestrator-0
# View trainer logs
kubectl logs -f my-exp-trainer-0
```
### Alternative: Manual RL Training
If you prefer to run RL components manually, keep `autoStart: false` and exec into each pod:
```bash
# Terminal 1 - Inference
kubectl exec -it my-exp-inference-0 -- bash
uv run inference @ /app/k8s/prime-rl/examples/reverse-text/infer.toml
# Terminal 2 - Orchestrator
kubectl exec -it my-exp-orchestrator-0 -- bash
uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url '["'$INFERENCE_URL'"]'
# Terminal 3 - Trainer
kubectl exec -it my-exp-trainer-0 -- bash
uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml --output-dir /data/outputs
```
### Access Outputs and Checkpoints
All outputs are written to `/data/outputs` on the shared NFS storage:
```bash
# Exec into any pod to access outputs
kubectl exec -it my-exp-trainer-0 -- bash
ls -lh /data/outputs/weights/
ls -lh /data/outputs/rollouts/
```
### Step 4: Run Evaluation
To evaluate the trained RL model:
```bash
# Exec into trainer pod
kubectl exec -it my-exp-trainer-0 -- bash
# If inference server isn't running with the RL model, start it in another terminal:
kubectl exec -it my-exp-inference-0 -- bash
uv run inference --vllm.model /data/outputs/weights_hf/step_20
# Back in trainer pod, run evaluation
uv run eval @ examples/basic/reverse-text/eval.toml \
-m /data/outputs/weights_hf/step_20 \
--client.base-url $INFERENCE_URL
```
### Clean Up
```bash
helm uninstall my-exp
# Optionally delete shared data. The PVC is named <release-name>-shared-data:
kubectl delete pvc my-exp-shared-data
```
**What the Helm chart provides:**
- Predictably named pods: `<release-name>-trainer-0`, `<release-name>-inference-0`, `<release-name>-orchestrator-0`
- Shared NFS storage at `/data` for model checkpoints and outputs
- GPU resources (1 GPU per inference/trainer pod)
- Kubernetes services for component communication
- Auto-start capability with proper networking configured
See the [K8s deployment guide](../../../k8s/README.md) for more details on scaling, distributed training, and advanced configurations.
-72
View File
@@ -1,72 +0,0 @@
# Kubernetes Deployment with Helm
This directory contains a Helm chart for deploying prime-rl training infrastructure on Kubernetes clusters.
## Quick Start
```bash
# Deploy with the reverse-text example
helm install my-exp ./prime-rl -f ./prime-rl/examples/reverse-text.yaml
# Verify deployment
kubectl get pods -l app.kubernetes.io/instance=my-exp
# Exec into trainer and run training
kubectl exec -it my-exp-trainer-0 -- bash
cd /data && uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml
```
## Prerequisites
- Kubernetes cluster with GPU nodes
- [NVIDIA GPU Operator](https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/getting-started.html) installed
- [Helm 3.x](https://helm.sh/docs/intro/install/) installed
- Storage class that supports `ReadWriteMany` (e.g., NFS, CephFS)
## Chart Structure
```
prime-rl/
├── Chart.yaml
├── values.yaml # Default configuration
├── examples/
│ ├── reverse-text.yaml # Example values for reverse-text
│ └── reverse-text/ # Split orchestrator/inference/trainer configs the example runs
└── templates/
├── deployment.yaml # StatefulSets for orchestrator, inference, trainer
├── service.yaml # Headless services for pod discovery
└── pvc.yaml # Shared storage
```
## Configuration
See [values.yaml](./prime-rl/values.yaml) for all available options. Common overrides:
```bash
# Custom GPU allocation
helm install my-exp ./prime-rl \
--set inference.gpu.count=4 \
--set trainer.gpu.count=2
# With secrets for W&B/HF
kubectl create secret generic prime-rl-secrets \
--from-literal=wandb-api-key=YOUR_KEY \
--from-literal=hf-token=YOUR_TOKEN
helm install my-exp ./prime-rl \
--set config.secrets.enabled=true \
--set config.secrets.name=prime-rl-secrets
```
## Uninstalling
```bash
helm uninstall my-exp
# The PVC is named <release-name>-shared-data (see templates/pvc.yaml)
kubectl delete pvc my-exp-shared-data # Warning: deletes data!
```
## Learn More
- [Scaling guide](https://docs.primeintellect.ai/prime-rl/scaling) - Non-Kubernetes multi-node deployment (SLURM), parallelism, benchmarking
-16
View File
@@ -1,16 +0,0 @@
apiVersion: v2
name: prime-rl
description: A Helm chart for deploying PRIME-RL training infrastructure on Kubernetes
type: application
version: 0.1.0
appVersion: "main"
keywords:
- machine-learning
- reinforcement-learning
- training
- gpu
maintainers:
- name: Prime Intellect
url: https://github.com/PrimeIntellect-ai/prime-rl
sources:
- https://github.com/PrimeIntellect-ai/prime-rl
-44
View File
@@ -1,44 +0,0 @@
# Values for reverse_text example
# Small model (Qwen3-0.6B) - runs on single consumer GPU
config:
example: "reverse-text"
image:
tag: "main"
# Orchestrator - no GPU needed
orchestrator:
enabled: true
autoStart: true
command: "uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL ; sleep infinity"
resources:
requests:
memory: "1Gi"
cpu: "500m"
# Inference - 1 GPU
inference:
enabled: true
autoStart: true
command: "uv run inference @ /app/k8s/prime-rl/examples/reverse-text/infer.toml ; sleep infinity"
gpu:
enabled: true
count: 1
resources:
requests:
memory: "4Gi"
cpu: "1"
# Trainer - 1 GPU
trainer:
enabled: true
autoStart: true
command: "uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml --output-dir /data/outputs ; sleep infinity"
gpu:
enabled: true
count: 1
resources:
requests:
memory: "4Gi"
cpu: "1"
@@ -1,2 +0,0 @@
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -1,27 +0,0 @@
max_steps = 20
seq_len = 2048
batch_size = 128
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
[train]
group_size = 16
[train.sampling]
max_completion_tokens = 128
[[train.source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[renderer]
name = "prime-qwen3"
[ckpt] # Checkpoint at the end of training
@@ -1,14 +0,0 @@
max_steps = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
seq_len = 2048
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
[optim]
lr = 3e-6
[ckpt] # Checkpoint at the end of training
-59
View File
@@ -1,59 +0,0 @@
{{/*
Expand the name of the chart.
*/}}
{{- define "prime-rl.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Create a default fully qualified app name.
*/}}
{{- define "prime-rl.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "prime-rl.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Common labels
*/}}
{{- define "prime-rl.labels" -}}
helm.sh/chart: {{ include "prime-rl.chart" . }}
{{ include "prime-rl.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
{{/*
Selector labels
*/}}
{{- define "prime-rl.selectorLabels" -}}
app.kubernetes.io/name: {{ include "prime-rl.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{/*
Component labels
*/}}
{{- define "prime-rl.componentLabels" -}}
app: prime-rl
{{- if .Values.config.example }}
example: {{ .Values.config.example }}
{{- end }}
{{- end }}
-378
View File
@@ -1,378 +0,0 @@
{{- if .Values.orchestrator.enabled }}
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: {{ .Release.Name }}-orchestrator
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: orchestrator
spec:
serviceName: {{ .Release.Name }}-orchestrator-headless
replicas: {{ .Values.orchestrator.replicas }}
selector:
matchLabels:
{{- include "prime-rl.componentLabels" . | nindent 6 }}
role: orchestrator
template:
metadata:
labels:
{{- include "prime-rl.selectorLabels" . | nindent 8 }}
{{- include "prime-rl.componentLabels" . | nindent 8 }}
role: orchestrator
spec:
{{- with .Values.orchestrator.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
containers:
- name: prime-rl-orchestrator
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.orchestrator.autoStart }}
command: ["/bin/bash", "-c"]
args:
- {{ .Values.orchestrator.command }}
{{- else }}
command: ["sleep", "infinity"]
{{- end }}
ports:
- containerPort: {{ .Values.orchestrator.service.port }}
name: api
- containerPort: {{ .Values.orchestrator.service.ncclPort }}
name: nccl
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: ROLE
value: "orchestrator"
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.orchestrator.replicas }}"
{{- $releaseName := .Release.Name }}
{{- $namespace := .Values.namespace }}
{{- $port := int .Values.inference.service.port }}
{{- $replicas := int .Values.inference.replicas }}
{{- $urls := list }}
{{- range $i := until $replicas }}
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
{{- $urls = append $urls $url }}
{{- end }}
- name: INFERENCE_URL
value: {{ first $urls | quote }}
- name: ADMIN_INFERENCE_URLS
value: {{ $urls | join "," | quote }}
{{- with .Values.orchestrator.env }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- if .Values.config.secrets.enabled }}
- name: WANDB_API_KEY
valueFrom:
secretKeyRef:
name: {{ .Values.config.secrets.name }}
key: wandb-api-key
optional: true
- name: HF_TOKEN
valueFrom:
secretKeyRef:
name: {{ .Values.config.secrets.name }}
key: hf-token
optional: true
{{- end }}
resources:
{{- toYaml .Values.orchestrator.resources | nindent 10 }}
{{- if .Values.storage.enabled }}
volumeMounts:
- name: shared-data
mountPath: {{ .Values.storage.mountPath }}
{{- end }}
{{- if .Values.storage.enabled }}
volumes:
- name: shared-data
persistentVolumeClaim:
claimName: {{ .Release.Name }}-shared-data
{{- end }}
{{- end }}
---
{{- if .Values.inference.enabled }}
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: {{ .Release.Name }}-inference
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: inference
spec:
serviceName: {{ .Release.Name }}-inference-headless
replicas: {{ .Values.inference.replicas }}
podManagementPolicy: Parallel
selector:
matchLabels:
{{- include "prime-rl.componentLabels" . | nindent 6 }}
role: inference
template:
metadata:
labels:
{{- include "prime-rl.selectorLabels" . | nindent 8 }}
{{- include "prime-rl.componentLabels" . | nindent 8 }}
role: inference
spec:
{{- if .Values.inference.runtimeClassName }}
runtimeClassName: {{ .Values.inference.runtimeClassName }}
{{- end }}
containers:
- name: prime-rl-inference
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.inference.autoStart }}
command: ["/bin/bash", "-c"]
args:
- {{ .Values.inference.command }}
{{- else }}
command: ["sleep", "infinity"]
{{- end }}
ports:
- containerPort: {{ .Values.inference.service.port }}
name: api
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: ROLE
value: "inference"
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.inference.replicas }}"
{{- with .Values.inference.env }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- if .Values.config.secrets.enabled }}
- name: WANDB_API_KEY
valueFrom:
secretKeyRef:
name: {{ .Values.config.secrets.name }}
key: wandb-api-key
optional: true
- name: HF_TOKEN
valueFrom:
secretKeyRef:
name: {{ .Values.config.secrets.name }}
key: hf-token
optional: true
{{- end }}
resources:
requests:
{{- if .Values.inference.gpu.enabled }}
nvidia.com/gpu: {{ .Values.inference.gpu.count }}
{{- end }}
memory: {{ .Values.inference.resources.requests.memory }}
cpu: {{ .Values.inference.resources.requests.cpu }}
limits:
{{- if .Values.inference.gpu.enabled }}
nvidia.com/gpu: {{ .Values.inference.gpu.count }}
{{- end }}
{{- if .Values.inference.resources.limits }}
memory: {{ .Values.inference.resources.limits.memory }}
cpu: {{ .Values.inference.resources.limits.cpu }}
{{- end }}
{{- if and .Values.inference.probes .Values.inference.probes.enabled }}
startupProbe:
httpGet:
path: /health
port: {{ .Values.inference.service.port }}
periodSeconds: {{ .Values.inference.probes.startup.periodSeconds }}
failureThreshold: {{ .Values.inference.probes.startup.failureThreshold }}
timeoutSeconds: {{ .Values.inference.probes.startup.timeoutSeconds }}
livenessProbe:
httpGet:
path: /liveness
port: {{ .Values.inference.service.port }}
periodSeconds: {{ .Values.inference.probes.liveness.periodSeconds }}
failureThreshold: {{ .Values.inference.probes.liveness.failureThreshold }}
timeoutSeconds: {{ .Values.inference.probes.liveness.timeoutSeconds }}
readinessProbe:
httpGet:
path: /health
port: {{ .Values.inference.service.port }}
periodSeconds: {{ .Values.inference.probes.readiness.periodSeconds }}
failureThreshold: {{ .Values.inference.probes.readiness.failureThreshold }}
timeoutSeconds: {{ .Values.inference.probes.readiness.timeoutSeconds }}
{{- end }}
{{- if .Values.storage.enabled }}
volumeMounts:
- name: shared-data
mountPath: {{ .Values.storage.mountPath }}
{{- end }}
{{- if .Values.storage.enabled }}
volumes:
- name: shared-data
persistentVolumeClaim:
claimName: {{ .Release.Name }}-shared-data
{{- end }}
{{- end }}
---
{{- if .Values.trainer.enabled }}
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: {{ .Release.Name }}-trainer
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: trainer
spec:
serviceName: {{ .Release.Name }}-trainer-headless
replicas: {{ .Values.trainer.replicas }}
podManagementPolicy: Parallel
selector:
matchLabels:
{{- include "prime-rl.componentLabels" . | nindent 6 }}
role: trainer
template:
metadata:
labels:
{{- include "prime-rl.selectorLabels" . | nindent 8 }}
{{- include "prime-rl.componentLabels" . | nindent 8 }}
role: trainer
spec:
{{- if .Values.trainer.runtimeClassName }}
runtimeClassName: {{ .Values.trainer.runtimeClassName }}
{{- end }}
containers:
- name: prime-rl-trainer
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.trainer.autoStart }}
command: ["/bin/bash", "-c"]
args:
- {{ .Values.trainer.command }}
{{- else }}
command: ["sleep", "infinity"]
{{- end }}
ports:
- containerPort: {{ .Values.trainer.service.port }}
name: api
- containerPort: {{ .Values.trainer.service.ncclPort }}
name: nccl
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
- name: ROLE
value: "trainer"
- name: POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: STATEFUL_REPLICAS
value: "{{ .Values.trainer.replicas }}"
{{- if .Values.trainer.pytorchCudaAllocConf }}
- name: PYTORCH_CUDA_ALLOC_CONF
value: {{ .Values.trainer.pytorchCudaAllocConf | quote }}
{{- end }}
{{- $releaseName := .Release.Name }}
{{- $namespace := .Values.namespace }}
{{- $port := int .Values.inference.service.port }}
{{- $replicas := int .Values.inference.replicas }}
{{- $urls := list }}
{{- range $i := until $replicas }}
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
{{- $urls = append $urls $url }}
{{- end }}
- name: INFERENCE_URL
value: {{ first $urls | quote }}
- name: ADMIN_INFERENCE_URLS
value: {{ $urls | join "," | quote }}
{{- with .Values.trainer.env }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- if .Values.config.secrets.enabled }}
- name: WANDB_API_KEY
valueFrom:
secretKeyRef:
name: {{ .Values.config.secrets.name }}
key: wandb-api-key
optional: true
- name: HF_TOKEN
valueFrom:
secretKeyRef:
name: {{ .Values.config.secrets.name }}
key: hf-token
optional: true
{{- end }}
resources:
requests:
{{- if .Values.trainer.gpu.enabled }}
nvidia.com/gpu: {{ .Values.trainer.gpu.count }}
{{- end }}
memory: {{ .Values.trainer.resources.requests.memory }}
cpu: {{ .Values.trainer.resources.requests.cpu }}
limits:
{{- if .Values.trainer.gpu.enabled }}
nvidia.com/gpu: {{ .Values.trainer.gpu.count }}
{{- end }}
{{- if .Values.trainer.resources.limits }}
memory: {{ .Values.trainer.resources.limits.memory }}
cpu: {{ .Values.trainer.resources.limits.cpu }}
{{- end }}
{{- if and .Values.trainer.probes .Values.trainer.probes.enabled }}
startupProbe:
httpGet:
path: /health
port: {{ .Values.trainer.service.port }}
periodSeconds: {{ .Values.trainer.probes.startup.periodSeconds }}
failureThreshold: {{ .Values.trainer.probes.startup.failureThreshold }}
timeoutSeconds: {{ .Values.trainer.probes.startup.timeoutSeconds }}
livenessProbe:
httpGet:
path: /health
port: {{ .Values.trainer.service.port }}
periodSeconds: {{ .Values.trainer.probes.liveness.periodSeconds }}
failureThreshold: {{ .Values.trainer.probes.liveness.failureThreshold }}
timeoutSeconds: {{ .Values.trainer.probes.liveness.timeoutSeconds }}
readinessProbe:
httpGet:
path: /health
port: {{ .Values.trainer.service.port }}
periodSeconds: {{ .Values.trainer.probes.readiness.periodSeconds }}
failureThreshold: {{ .Values.trainer.probes.readiness.failureThreshold }}
timeoutSeconds: {{ .Values.trainer.probes.readiness.timeoutSeconds }}
{{- end }}
{{- if .Values.storage.enabled }}
volumeMounts:
- name: shared-data
mountPath: {{ .Values.storage.mountPath }}
{{- end }}
{{- if .Values.storage.enabled }}
volumes:
- name: shared-data
persistentVolumeClaim:
claimName: {{ .Release.Name }}-shared-data
{{- end }}
{{- end }}
-16
View File
@@ -1,16 +0,0 @@
{{- if .Values.storage.enabled }}
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: {{ .Release.Name }}-shared-data
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
spec:
accessModes:
{{- toYaml .Values.storage.accessModes | nindent 4 }}
storageClassName: {{ .Values.storage.storageClassName }}
resources:
requests:
storage: {{ .Values.storage.size }}
{{- end }}
-141
View File
@@ -1,141 +0,0 @@
{{- if .Values.orchestrator.enabled }}
{{- if .Values.orchestrator.service.enabled }}
apiVersion: v1
kind: Service
metadata:
name: {{ .Release.Name }}-orchestrator
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: orchestrator
spec:
type: {{ .Values.orchestrator.service.type }}
selector:
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: orchestrator
ports:
- port: {{ .Values.orchestrator.service.port }}
targetPort: api
protocol: TCP
name: api
- port: {{ .Values.orchestrator.service.ncclPort }}
targetPort: nccl
protocol: TCP
name: nccl
{{- end }}
---
apiVersion: v1
kind: Service
metadata:
name: {{ .Release.Name }}-orchestrator-headless
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: orchestrator
spec:
clusterIP: None # Headless service for StatefulSet
selector:
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: orchestrator
ports:
- port: {{ .Values.orchestrator.service.port }}
name: api
- port: {{ .Values.orchestrator.service.ncclPort }}
name: nccl
{{- end }}
---
{{- if .Values.inference.enabled }}
{{- if .Values.inference.service.enabled }}
apiVersion: v1
kind: Service
metadata:
name: {{ .Release.Name }}-inference
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: inference
spec:
type: {{ .Values.inference.service.type }}
selector:
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: inference
ports:
- port: {{ .Values.inference.service.port }}
targetPort: api
protocol: TCP
name: api
{{- end }}
{{- end }}
---
{{- if .Values.trainer.enabled }}
{{- if .Values.trainer.service.enabled }}
apiVersion: v1
kind: Service
metadata:
name: {{ .Release.Name }}-trainer
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: trainer
spec:
type: {{ .Values.trainer.service.type }}
selector:
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: trainer
ports:
- port: {{ .Values.trainer.service.port }}
targetPort: api
protocol: TCP
name: api
- port: {{ .Values.trainer.service.ncclPort }}
targetPort: nccl
protocol: TCP
name: nccl
{{- end }}
{{- end }}
---
{{- if .Values.inference.enabled }}
apiVersion: v1
kind: Service
metadata:
name: {{ .Release.Name }}-inference-headless
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: inference
spec:
clusterIP: None # Headless service for StatefulSet
selector:
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: inference
ports:
- port: {{ .Values.inference.service.port }}
name: api
{{- end }}
---
{{- if .Values.trainer.enabled }}
apiVersion: v1
kind: Service
metadata:
name: {{ .Release.Name }}-trainer-headless
namespace: {{ .Values.namespace }}
labels:
{{- include "prime-rl.labels" . | nindent 4 }}
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: trainer
spec:
clusterIP: None # Headless service for StatefulSet
selector:
{{- include "prime-rl.componentLabels" . | nindent 4 }}
role: trainer
ports:
- port: {{ .Values.trainer.service.port }}
name: api
- port: {{ .Values.trainer.service.ncclPort }}
name: nccl
{{- end }}
-156
View File
@@ -1,156 +0,0 @@
# Default values for prime-rl
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
# Global settings
namespace: default
# Docker image configuration
image:
repository: primeintellect/prime-rl
pullPolicy: IfNotPresent
tag: "main"
# Shared storage configuration
storage:
enabled: true
# PVC name will be automatically set to {{ .Release.Name }}-shared-data
storageClassName: nfs
accessModes:
- ReadWriteMany
size: 1Ti
mountPath: /data
# Orchestrator component
orchestrator:
enabled: true
replicas: 1
# Auto-start configuration (set to false to use sleep infinity for debugging)
autoStart: false
# Example command - use $INFERENCE_URL directly (the first inference server URL)
command: "" # e.g., 'uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL'
# $INFERENCE_URL is auto-set to 'http://<release>-inference-0...:8000/v1'. With more than one
# inference replica, put a router in front and point --client.base-url at it; admin operations
# (weight updates, health checks) fan out to every replica via
# --client.admin-base-url $ADMIN_INFERENCE_URLS (comma-separated list of all replica URLs).
resources:
requests:
memory: "2Gi"
cpu: "1"
service:
enabled: true
type: ClusterIP
port: 8000
ncclPort: 29501
env: []
# - name: CUSTOM_ENV
# value: "value"
nodeSelector: {}
# nvidia.com/gpu.present: "true" # Orchestrator doesn't need GPUs
# Inference component
inference:
enabled: true
replicas: 1
# Auto-start configuration (set to false to use sleep infinity for debugging)
autoStart: false
command: "" # e.g., "uv run inference @ /app/k8s/prime-rl/examples/reverse-text/infer.toml"
gpu:
enabled: true
count: 1
resources:
requests:
memory: "4Gi"
cpu: "1"
service:
enabled: true
type: ClusterIP
port: 8000
runtimeClassName: nvidia
# Health probes for inference server (/health for startup/readiness, /liveness for engine liveness)
probes:
enabled: false
# Startup probe: allows long model loading time (up to 45 min by default)
startup:
periodSeconds: 10
failureThreshold: 270 # 270 * 10s = 45 min max startup time
timeoutSeconds: 5
liveness:
periodSeconds: 10
failureThreshold: 3
timeoutSeconds: 10
readiness:
periodSeconds: 5
failureThreshold: 2
timeoutSeconds: 5
# Trainer component
trainer:
enabled: true
replicas: 1
# Auto-start configuration (set to false to use sleep infinity for debugging)
autoStart: false
command: "" # e.g., "uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml --output-dir /data/outputs"
# Helps reduce CUDA memory fragmentation with PyTorch allocator
pytorchCudaAllocConf: "expandable_segments:True"
gpu:
enabled: true
count: 1
resources:
requests:
memory: "4Gi"
cpu: "1"
service:
enabled: true
type: ClusterIP
port: 8000
ncclPort: 29501
env: []
runtimeClassName: nvidia
# Health probes for trainer (requires metrics_server config)
probes:
enabled: false
# Startup probe: allows time for model loading
startup:
periodSeconds: 10
failureThreshold: 60 # 60 * 10s = 10 min max startup time
timeoutSeconds: 30
liveness:
periodSeconds: 30
failureThreshold: 6 # 6 * 30s = 3 min before restart
timeoutSeconds: 30
readiness:
periodSeconds: 10
failureThreshold: 3
timeoutSeconds: 30
# Additional configuration
config:
# Example name (used for labeling)
example: "reverse-text"
# Secrets (optional)
secrets:
enabled: false
name: prime-rl-secrets
# wandbApiKey: ""
# hfToken: ""
@@ -21,7 +21,7 @@ class ServerConfig(BaseConfig):
"""Port to bind to."""
liveness_timeout_seconds: float = Field(30.0, gt=0)
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. With Kubernetes liveness probes, keep the probe ``timeoutSeconds`` at least this high."""
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. Health checks polling this endpoint should use a timeout at least this high."""
# Valid vLLM max_lora_rank values (`vllm.config.lora.MaxLoRARanks`), excluding 1 so
@@ -487,8 +487,8 @@ class CheckpointConfig(BaseConfig):
class ConcurrencyConfig(BaseConfig):
"""Adaptive in-flight concurrency control. The orchestrator sizes the
in-flight episode cap from engine KV capacity and learned per-env episode
costs; these fields only bound and seed it."""
in-flight episode cap from engine KV pressure; these fields only bound and
seed it."""
initial_inflight: int | None = Field(None, ge=1)
"""Optional initial in-flight episodes to start from. Set it when a good value is known to skip the initial ramp; otherwise auto-derive a pessimistic bound at runtime."""
@@ -270,14 +270,6 @@ class HeartbeatConfig(BaseConfig):
rate limit. Size it well under the monitor's period."""
class MetricsServerConfig(BaseConfig):
port: int = Field(8000, ge=1, le=65535)
"""Port to expose metrics and health endpoints on."""
host: str = "0.0.0.0"
"""Host to bind the server to."""
class BaseTransportConfig(BaseConfig):
pass
@@ -11,7 +11,6 @@ from prime_rl.configs.shared import (
EnvVars,
FileSystemWeightBroadcastConfig,
HeartbeatConfig,
MetricsServerConfig,
ResumeConfig,
TrainerLogConfig,
TransportConfig,
@@ -23,6 +22,7 @@ from prime_rl.utils.config import BaseConfig, default_output_dir
# -- Shared trainer configs (used by both SFT and RL trainers) --
AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]
DSABackend: TypeAlias = Literal["tilelang", "cudnn_flashmla"]
class GCConfig(BaseConfig):
@@ -326,6 +326,9 @@ class ModelConfig(BaseModelConfig):
quantization: QuantizationConfig | None = None
dsa_backend: DSABackend = "tilelang"
"""Kernels for the DSA sparse MLA attention (``glm_moe_dsa``, e.g. GLM-5). ``tilelang`` runs the TileLang forward and backward. ``cudnn_flashmla`` runs the FlashMLA sparse prefill forward with the cuDNN frontend CuTe-DSL backward; it needs the ``flash-mla`` extra and an SM90 GPU (SM100/SM103 are wired up but untested)."""
index_cache: IndexCacheConfig | None = None
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
@@ -683,9 +686,6 @@ class TrainerConfig(BaseConfig):
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
metrics_server: MetricsServerConfig | None = None
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
env_vars: EnvVars = {}
"""Extra environment variables for the trainer process(es). Merged on top of the launcher defaults."""
+9 -7
View File
@@ -11,7 +11,6 @@ dependencies = [
"datasets>=4.0.0",
"jaxtyping>=0.3.2",
"loguru>=0.7.3",
"pyarrow>=21.0.0",
"numpy>=2.2.6",
"transformers==5.6.2",
"wandb>=0.26.1",
@@ -32,8 +31,6 @@ dependencies = [
"verifiers[harbor]>=0.3.2.dev158",
"renderers[multimodal]>=0.1.12.dev2",
"pybase64>=1.4.2",
"orjson>=3.10",
"pandas>=2.0",
"msgspec>=0.18",
]
@@ -62,6 +59,8 @@ gpu = [
"torchtitan ; sys_platform == 'linux'",
"dion ; sys_platform == 'linux'",
"tilelang>=0.1.8 ; sys_platform == 'linux'",
# DSA sparse MLA backward kernel (CuTe DSL); >=1.29 matches the pinned CUTLASS DSL 4.7.
"nvidia-cudnn-frontend>=1.30.0 ; sys_platform == 'linux'",
"flash-linear-attention ; sys_platform == 'linux'",
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
@@ -91,13 +90,15 @@ disagg = [
"deep-ep ; sys_platform == 'linux'",
"deep-gemm ; sys_platform == 'linux'",
"nixl ; sys_platform == 'linux'",
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
"vllm-router ; sys_platform == 'linux'",
]
quack = [
"quack-kernels>=0.4.1 ; sys_platform == 'linux'",
]
sonic-moe = ["sonic-moe ; sys_platform == 'linux'"]
# FlashMLA sparse prefill forward for `model.dsa_backend = "cudnn_flashmla"` (sm_90a + sm_100f).
# FlashMLA is not on PyPI and only an x86_64 wheel is published.
flash-mla = ["flash-mla ; sys_platform == 'linux' and platform_machine == 'x86_64'"]
# Prebuilt `prime-kernels` wheels from a release (see the `kernels` skill). Compiled for
# sm_100a; on other GPUs the package installs fine and reports its kernels unavailable.
kernels = [
@@ -111,12 +112,10 @@ all = [
"prime-rl[sonic-moe]",
"prime-rl[flash-attn-3]",
"prime-rl[flash-attn-cute]",
"prime-rl[flash-mla]",
]
[dependency-groups]
mamba-ssm = [
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
]
dev = [
"ipykernel>=6.29.5",
"ipywidgets>=8.1.7",
@@ -253,6 +252,7 @@ deep-gemm = false
nixl-cu13 = false
torchao = false
prime-kernels = false
flash-mla = false
[tool.uv.sources]
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
@@ -293,6 +293,8 @@ prime-kernels = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
# FlashMLA nv_dev @ b7643bd built against torch 2.13.0+cu130 (see the release notes for the recipe).
flash-mla = { url = "https://github.com/NovaSky-AI/skyrl-wheels/releases/download/cu13torch2.13-flashmla-b7643bd/flash_mla-1.0.0%2Bcu.13.0.torch.2.13.b7643bd-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
mamba-ssm = { git = "https://github.com/state-spaces/mamba", rev = "f577286" }
flash_attn_3 = { index = "pytorch-cu130-test" }
+15 -2
View File
@@ -53,8 +53,8 @@ describe_tag() {
sed -E 's/-[0-9]+-g[0-9a-f]+$//' <<< "$1"
}
verifiers_git_version() {
local dir="$root/deps/verifiers"
standard_git_version() {
local dir="$1"
local desc tag distance
[ -d "$dir" ] || return 1
@@ -64,6 +64,14 @@ verifiers_git_version() {
next_patch_dev_version "$tag" "$distance"
}
verifiers_git_version() {
standard_git_version "$root/deps/verifiers"
}
pydantic_config_git_version() {
standard_git_version "$root/deps/pydantic-config"
}
renderers_git_version() {
local dir="$root/deps/renderers"
local desc tag distance version
@@ -111,22 +119,27 @@ resolve_version() {
verifiers_version="$(resolve_version verifiers VERIFIERS_PRETEND_VERSION verifiers_git_version)"
renderers_version="$(resolve_version renderers RENDERERS_PRETEND_VERSION renderers_git_version)"
pydantic_config_version="$(resolve_version prime-pydantic-config PYDANTIC_CONFIG_PRETEND_VERSION pydantic_config_git_version)"
printf 'Resolved verifiers pretend version: %s\n' "$verifiers_version" >&2
printf 'Resolved renderers pretend version: %s\n' "$renderers_version" >&2
printf 'Resolved pydantic-config pretend version: %s\n' "$pydantic_config_version" >&2
case "$mode" in
shell)
printf "export VERIFIERS_PRETEND_VERSION='%s'\n" "$verifiers_version"
printf "export RENDERERS_PRETEND_VERSION='%s'\n" "$renderers_version"
printf "export PYDANTIC_CONFIG_PRETEND_VERSION='%s'\n" "$pydantic_config_version"
;;
github-output)
printf 'verifiers=%s\n' "$verifiers_version"
printf 'renderers=%s\n' "$renderers_version"
printf 'pydantic_config=%s\n' "$pydantic_config_version"
;;
env)
printf 'VERIFIERS_PRETEND_VERSION=%s\n' "$verifiers_version"
printf 'RENDERERS_PRETEND_VERSION=%s\n' "$renderers_version"
printf 'PYDANTIC_CONFIG_PRETEND_VERSION=%s\n' "$pydantic_config_version"
;;
*)
printf 'Unknown output mode: %s\n' "$mode" >&2
+1 -2
View File
@@ -113,8 +113,7 @@ HEAVY_PINS_PY
echo "[prime-rl] syncing ${DEST} into /app/.venv"
( cd "$DEST" && uv sync --inexact --locked --no-dev --all-packages \
--extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 \
--extra flash-attn-cute --extra disagg --extra quack --extra kernels \
--group mamba-ssm )
--extra flash-attn-cute --extra disagg --extra quack --extra kernels )
# The chart's `uv run --no-sync <entrypoint>` commands resolve the
# project from the cwd; the venv itself stays /app/.venv via
# UV_PROJECT_ENVIRONMENT above.
+88
View File
@@ -0,0 +1,88 @@
import argparse
import os
import re
import shutil
import subprocess
import tomllib
from pathlib import Path
def editable_paths(root: Path) -> list[Path]:
lock = tomllib.loads((root / "uv.lock").read_text())
paths = set()
for package in lock["package"]:
source = package["source"]
if "directory" in source:
raise ValueError(f"Non-editable local package: {package['name']}")
if "editable" not in source:
continue
path = (root / source["editable"]).resolve()
if not path.is_relative_to(root):
raise ValueError(f"Editable package outside the application: {path}")
paths.add(path)
return sorted(paths)
def set_fallback_version(pyproject: Path, version: str) -> None:
if not re.fullmatch(r"[0-9][A-Za-z0-9.+-]*", version):
raise ValueError(f"Invalid package version: {version!r}")
content, count = re.subn(
r'(?m)^fallback-version = "[^"]*"$', f'fallback-version = "{version}"', pyproject.read_text()
)
if count != 1:
raise ValueError(f"Expected one fallback-version in {pyproject}")
pyproject.write_text(content)
def copy_installation_artifacts(venv: Path, baseline: set[Path], output: Path) -> None:
# The runtime supplies the interpreter and third-party environment.
for directory in (venv / "bin", venv / "lib/python3.12/site-packages"):
for path in directory.iterdir():
relative = path.relative_to(venv)
if relative in baseline:
continue
target = output / ".venv" / relative
target.parent.mkdir(parents=True, exist_ok=True)
if path.is_dir():
shutil.copytree(path, target, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
else:
shutil.copy2(path, target)
def application_layer(root: Path, output: Path) -> None:
if output.is_relative_to(root):
raise ValueError("The output directory must be outside the application")
if output.exists():
raise FileExistsError(output)
venv = root / ".venv"
if venv.exists() or venv.is_symlink():
raise FileExistsError(venv)
versions = {
"deps/verifiers": "VERIFIERS_PRETEND_VERSION",
"deps/renderers": "RENDERERS_PRETEND_VERSION",
"deps/pydantic-config": "PYDANTIC_CONFIG_PRETEND_VERSION",
}
for path, variable in versions.items():
set_fallback_version(root / path / "pyproject.toml", os.environ[variable])
subprocess.run(["uv", "venv", "--python", "/usr/bin/python3.12", str(venv)], check=True)
baseline = {path.relative_to(venv) for path in venv.rglob("*")}
command = ["uv", "pip", "install", "--python", str(venv / "bin/python"), "--no-deps"]
for path in editable_paths(root):
command.extend(["--editable", str(path)])
subprocess.run(command, check=True, cwd=root)
shutil.copytree(root, output, ignore=shutil.ignore_patterns(".venv", ".git", "__pycache__", "*.pyc"))
copy_installation_artifacts(venv, baseline, output)
def main() -> None:
parser = argparse.ArgumentParser(description="Build a source and editable-package Docker layer")
parser.add_argument("root", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
application_layer(args.root.resolve(), args.output.resolve())
if __name__ == "__main__":
main()
+80
View File
@@ -0,0 +1,80 @@
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
def dependency_fingerprint(root: Path) -> str:
inputs = [root / path for path in ("Dockerfile.cuda", ".dockerignore", "uv.lock", "scripts/docker_dependencies.py")]
for directory, children, files in os.walk(root):
children[:] = [name for name in children if name not in {".git", ".venv", "outputs"}]
if "pyproject.toml" in files:
inputs.append(Path(directory) / "pyproject.toml")
digest = hashlib.sha256()
for path in sorted(inputs):
name = path.relative_to(root).as_posix().encode()
content = path.read_bytes()
digest.update(len(name).to_bytes(8, "big"))
digest.update(name)
digest.update(len(content).to_bytes(8, "big"))
digest.update(content)
return digest.hexdigest()
def registry_digest(image: str) -> str | None:
registry, _, reference = image.partition("/")
if registry != "ghcr.io":
raise ValueError("Dependency images must use ghcr.io")
repository, separator, tag = reference.rpartition(":")
if not separator or not repository or not tag:
raise ValueError("Expected ghcr.io/<owner>/<image>:<tag>")
query = urlencode({"service": registry, "scope": f"repository:{repository}:pull"})
headers = {}
if token := os.environ.get("GH_TOKEN"):
credentials = f"{os.environ['GITHUB_ACTOR']}:{token}".encode()
headers["Authorization"] = f"Basic {base64.b64encode(credentials).decode()}"
request = Request(f"https://{registry}/token?{query}", headers=headers)
with urlopen(request, timeout=30) as response:
token = json.load(response)["token"]
request = Request(
f"https://{registry}/v2/{repository}/manifests/{tag}",
headers={
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json",
},
method="HEAD",
)
try:
with urlopen(request, timeout=30) as response:
digest = response.headers["Docker-Content-Digest"]
if not digest or not digest.startswith("sha256:"):
raise ValueError(f"Missing or invalid image digest for {image}")
return digest
except HTTPError as error:
if error.code != 404:
raise
return None
def main() -> None:
parser = argparse.ArgumentParser(description="Fingerprint and resolve Docker dependency images")
commands = parser.add_subparsers(dest="command", required=True)
fingerprint = commands.add_parser("fingerprint")
fingerprint.add_argument("root", type=Path)
resolve = commands.add_parser("resolve")
resolve.add_argument("image")
args = parser.parse_args()
if args.command == "fingerprint":
print(dependency_fingerprint(args.root.resolve()))
else:
print(registry_digest(args.image) or "")
if __name__ == "__main__":
main()
+2 -2
View File
@@ -4,7 +4,7 @@
const $ = (sel) => document.querySelector(sel);
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const api = async (path) => {
const res = await fetch(path);
const res = await fetch(path.replace(/^\//, ""));
if (!res.ok) throw new Error(`${path}: ${res.status} ${await res.text()}`);
return res.json();
};
@@ -6441,7 +6441,7 @@ function showViewToast(cmd) {
}
function connectViewEvents() {
const source = new EventSource("/api/view/events");
const source = new EventSource("api/view/events");
source.onmessage = (e) => {
let cmd;
try {
+6 -6
View File
@@ -5,14 +5,14 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>prime-rl dashboard</title>
<link rel="icon" href="/static/butterfly-white.svg">
<link rel="stylesheet" href="/static/vendor/uPlot.min.css">
<link rel="stylesheet" href="/static/style.css">
<link rel="icon" href="static/butterfly-white.svg">
<link rel="stylesheet" href="static/vendor/uPlot.min.css">
<link rel="stylesheet" href="static/style.css">
</head>
<body>
<header id="topbar">
<div class="brand">
<img src="/static/butterfly-white.svg" alt="Prime Intellect">
<img src="static/butterfly-white.svg" alt="Prime Intellect">
</div>
<select id="run-select" title="run"></select>
<div id="compare-wrap" class="dd-wrap">
@@ -295,7 +295,7 @@
</div>
</template>
<script src="/static/vendor/uPlot.iife.min.js"></script>
<script src="/static/app.js"></script>
<script src="static/vendor/uPlot.iife.min.js"></script>
<script src="static/app.js"></script>
</body>
</html>
-7
View File
@@ -34,10 +34,6 @@ from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.metrics import dispatch_failure_metrics
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
from prime_rl.orchestrator.utils import (
@@ -49,9 +45,6 @@ from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_config_dir
monkey_patch_oai_iterable_types()
monkey_patch_chat_completion_logprobs()
# How often ``run_epoch`` re-checks for a superseding checkpoint while it waits for episodes.
POLL_INTERVAL_S = 2.0
@@ -17,10 +17,6 @@ else:
class FileSystemWeightUpdateWorker(Worker):
"""vLLM worker extension for updating weights in-place using shared filesystem."""
def init_broadcaster(self) -> None:
"""Initialize the broadcaster."""
...
def liveness_probe(self) -> None:
"""No-op RPC used by the API server liveness endpoint."""
return None
@@ -55,7 +55,6 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
cls = ALGORITHM_CLASSES[config.type]
assert cls.action_loss_type == config.action_loss_type # config and runtime declare in two places
# The Algorithm is the runtime of the algorithm config's training signal
# (its sibling GenerationSource interprets the sampling half). Every algorithm is
# handed the live policy pool — opsd self-distills against it, others may
+3 -8
View File
@@ -2,11 +2,11 @@
from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from prime_rl.configs.algorithm import ActionLossType, AlgoConfig, FrozenModelConfig
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
@@ -50,9 +50,8 @@ class Algorithm:
annotated traces into transport samples only after admission.
"""
action_loss_type: ClassVar[ActionLossType] = "rl"
def __init__(self, config: AlgoConfig, clients: InferenceClient):
self.action_loss_type = config.action_loss_type
self.clients = clients
self.connected: InferenceClient | None = None
@@ -74,7 +73,3 @@ class Algorithm:
"""Run rollout-local scoring when the episode has trainable traces."""
if any(True for _ in iter_trainable_traces([episode])):
await self.score_episode(episode)
async def finalize_group(self, episodes: list[vf.Episode]) -> None:
"""Run group-relative scoring over the native episodes."""
await self.score_group(episodes)
-2
View File
@@ -24,8 +24,6 @@ class OPDAlgorithm(Algorithm):
credit is assigned — rollouts keep ``advantages=None`` and samples ship no
advantage stream; ``group_size`` only fans out sampling."""
action_loss_type = "ref_kl"
def __init__(self, config: OPDAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.teacher = config.teacher
-2
View File
@@ -31,8 +31,6 @@ class OPSDAlgorithm(Algorithm):
multimodal prompts and any number of turns. No scalar advantage is
assigned."""
action_loss_type = "ref_kl"
def __init__(self, config: OPSDAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.demo_key = config.demo_key
-2
View File
@@ -10,5 +10,3 @@ class SFTDistillAlgorithm(Algorithm):
Assigns no advantage — the ``ce`` loss ignores credit, and SFT trains on
every sampled token. A curriculum can reject results using reward or any
other finalized rollout data."""
action_loss_type = "ce"
+32
View File
@@ -5,8 +5,11 @@ from dataclasses import dataclass, field
from typing import Any
import numpy as np
from transformers import AutoConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.transports.batch.types import MicroBatch, MMImageRef, MMRefs, RoutedExperts, SamplingMask, TrainingSample
from prime_rl.utils.logger import get_logger
# Backfill value per component weight stream when a packed sample doesn't
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
@@ -858,3 +861,32 @@ def prepare_batch(
batches_per_gpu[worker_idx].extend(worker_batches)
return batches_per_gpu
class BatchPacker:
"""Bin-packs a step's training samples into one micro-batch list per trainer DP rank."""
def __init__(self, config: OrchestratorConfig):
self.seq_len = config.seq_len
self.num_train_workers = config.num_train_workers
self.pad_to_multiple_of = config.pad_to_multiple_of
try:
model_config = AutoConfig.from_pretrained(
config.model.name, trust_remote_code=config.tokenizer.trust_remote_code
)
except Exception as e:
get_logger().warning(
f"Could not load model config for {config.model.name} ({e}) - "
"packing balances by token count instead of estimated FLOPs"
)
model_config = None
self.bin_cost = build_bin_cost(model_config)
def pack(self, samples: list[TrainingSample]) -> list[list[MicroBatch]]:
return prepare_batch(
rollouts=samples,
seq_len=self.seq_len,
num_train_workers=self.num_train_workers,
bin_cost=self.bin_cost,
pad_to_multiple_of=self.pad_to_multiple_of,
)
+1 -1
View File
@@ -163,7 +163,7 @@ class ConcurrencyController:
# ── inbound hooks ────────────────────────────────────────────────────────
def record_episode(self, env_name: str, kind: str, tokens: int, duration: float) -> None:
def record_episode(self, tokens: int) -> None:
"""One completed unit (from the dispatcher). Advances the turnover
clock and, while the last poll was green, grows the cap — so growth
is paced by the pipeline itself at any concurrency scale."""
+3 -5
View File
@@ -143,7 +143,7 @@ class Dispatcher:
max_off_policy_steps: int,
run_id: str,
run_name: str | None,
on_episode_complete: Callable[[str, str, int, float], None] | None = None,
on_episode_complete: Callable[[int], None] | None = None,
) -> None:
self.policy = policy
self.progress = progress
@@ -157,7 +157,7 @@ class Dispatcher:
self.max_off_policy_steps = max_off_policy_steps
self.run_id = run_id
self.run_name = run_name
# ``(env_name, kind, total_tokens, duration_s)`` per completed episode
# Called with ``total_tokens`` per completed episode
self.on_episode_complete = on_episode_complete
# Starting value of the dynamic cap (the concurrency controller moves
@@ -694,9 +694,7 @@ class Dispatcher:
if not episode.ok and not episode.traces:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if self.on_episode_complete is not None and meta.started_at > 0:
self.on_episode_complete(
meta.env_name, meta.kind, episode.num_total_tokens, time.monotonic() - meta.started_at
)
self.on_episode_complete(episode.num_total_tokens)
await self.emit_episode(meta, group, episode)
def complete_group_member(self, meta: InflightEpisode, group: GroupState | None) -> int:
+3 -11
View File
@@ -38,6 +38,7 @@ from prime_rl import monitors
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.algo.routing import is_trainable
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.batch import BatchPacker
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient, setup_admin_plane
from prime_rl.orchestrator.concurrency import ConcurrencyController
@@ -47,11 +48,6 @@ from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.metrics import TrainEpisodes, dispatch_failure_metrics
from prime_rl.orchestrator.packing import BatchPacker
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.train_sink import TrainSink
from prime_rl.orchestrator.train_source import TrainSource
@@ -78,12 +74,8 @@ from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import get_broadcast_dir, get_config_dir
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
monkey_patch_oai_iterable_types()
monkey_patch_chat_completion_logprobs()
from prime_rl.utils.pathing import get_broadcast_dir, get_config_dir, resolve_latest_ckpt_step
from prime_rl.utils.utils import clean_exit
# Wall-clock budget for post-training cleanup; force-exit if graceful
# shutdown wedges (env-server ZMQ recv, vLLM admin aclose, etc)
-35
View File
@@ -1,35 +0,0 @@
from transformers import AutoConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.batch import build_bin_cost, prepare_batch
from prime_rl.transports.batch.types import MicroBatch, TrainingSample
from prime_rl.utils.logger import get_logger
class BatchPacker:
"""Bin-packs a step's training samples into one micro-batch list per trainer DP rank."""
def __init__(self, config: OrchestratorConfig):
self.seq_len = config.seq_len
self.num_train_workers = config.num_train_workers
self.pad_to_multiple_of = config.pad_to_multiple_of
try:
model_config = AutoConfig.from_pretrained(
config.model.name, trust_remote_code=config.tokenizer.trust_remote_code
)
except Exception as e:
get_logger().warning(
f"Could not load model config for {config.model.name} ({e}) - "
"packing balances by token count instead of estimated FLOPs"
)
model_config = None
self.bin_cost = build_bin_cost(model_config)
def pack(self, samples: list[TrainingSample]) -> list[list[MicroBatch]]:
return prepare_batch(
rollouts=samples,
seq_len=self.seq_len,
num_train_workers=self.num_train_workers,
bin_cost=self.bin_cost,
pad_to_multiple_of=self.pad_to_multiple_of,
)
-115
View File
@@ -1,115 +0,0 @@
from typing import Any, Optional, TypedDict, Union
import openai.types.chat
from openai.types.chat.chat_completion import ChatCompletion, Choice
from openai.types.chat.chat_completion_assistant_message_param import (
Audio,
ContentArrayOfContentPart,
)
from openai.types.chat.chat_completion_content_part_param import ChatCompletionContentPartParam
from openai.types.chat.chat_completion_content_part_text_param import ChatCompletionContentPartTextParam
from openai.types.chat.chat_completion_developer_message_param import ChatCompletionDeveloperMessageParam
from openai.types.chat.chat_completion_function_message_param import ChatCompletionFunctionMessageParam
from openai.types.chat.chat_completion_message import FunctionCall
from openai.types.chat.chat_completion_message_tool_call_union_param import ChatCompletionMessageToolCallUnionParam
from openai.types.chat.chat_completion_system_message_param import ChatCompletionSystemMessageParam
from openai.types.chat.chat_completion_user_message_param import ChatCompletionUserMessageParam
from typing_extensions import Literal, Required
def monkey_patch_oai_iterable_types():
"""
This monkey patch is necessary to avoid Pydantic validating fields using
typing.Iterable (e.g. in multimodal or tool call messages) lazily which
leads to tokenization errors, for more info see
https://github.com/PrimeIntellect-ai/prime-rl/pull/1249
"""
class ModdedChatCompletionDeveloperMessageParam(TypedDict, total=False):
"""Same as openai.types.chat.chat_completion_developer_message_param.ChatCompletionDeveloperMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
content: Required[Union[str, list[ChatCompletionContentPartTextParam]]]
role: Required[Literal["developer"]]
name: str
class ModdedChatCompletionSystemMessageParam(TypedDict, total=False):
"""Same as openai.types.chat.chat_completion_system_message_param.ChatCompletionSystemMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
content: Required[Union[str, list[ChatCompletionContentPartTextParam]]]
role: Required[Literal["system"]]
name: str
class ModdedChatCompletionUserMessageParam(TypedDict, total=False):
"""Same as openai.types.chat.chat_completion_user_message_param.ChatCompletionUserMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
content: Required[Union[str, list[ChatCompletionContentPartParam]]]
role: Required[Literal["user"]]
name: str
class ModdedChatCompletionAssistantMessageParam(TypedDict, total=False):
"""Same as openai.types.chat.chat_completion_assistant_message_param.ChatCompletionAssistantMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
role: Required[Literal["assistant"]]
audio: Optional[Audio]
content: Union[str, list[ContentArrayOfContentPart], None]
function_call: Optional[FunctionCall]
name: str
refusal: Optional[str]
tool_calls: list[ChatCompletionMessageToolCallUnionParam]
class ModdedChatCompletionToolMessageParam(TypedDict, total=False):
"""Same as openai.types.chat.chat_completion_tool_message_param.ChatCompletionToolMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
content: Required[Union[str, list[ChatCompletionContentPartTextParam]]]
role: Required[Literal["tool"]]
tool_call_id: Required[str]
# Patch OAI types
openai.types.chat.chat_completion_developer_message_param.ChatCompletionDeveloperMessageParam = (
ModdedChatCompletionDeveloperMessageParam
)
openai.types.chat.chat_completion_system_message_param.ChatCompletionSystemMessageParam = (
ModdedChatCompletionSystemMessageParam
)
openai.types.chat.chat_completion_user_message_param.ChatCompletionUserMessageParam = (
ModdedChatCompletionUserMessageParam
)
openai.types.chat.chat_completion_assistant_message_param.ChatCompletionAssistantMessageParam = (
ModdedChatCompletionAssistantMessageParam
)
openai.types.chat.chat_completion_tool_message_param.ChatCompletionToolMessageParam = (
ModdedChatCompletionToolMessageParam
)
openai.types.chat.chat_completion_message_param.ChatCompletionMessageParam = Union[
ChatCompletionDeveloperMessageParam,
ChatCompletionSystemMessageParam,
ChatCompletionUserMessageParam,
ModdedChatCompletionAssistantMessageParam,
ModdedChatCompletionToolMessageParam,
ChatCompletionFunctionMessageParam,
]
def monkey_patch_chat_completion_logprobs():
"""
At large batch sizes and context, constructing OAI's Pydantic model
ChatCompletion with logprobs is causing heavy CPU overhead (~200ms per
object at 32K context, which translates to >10min overhead at 4K batch
size). This function monkey-patches the OAI type and verifiers'
post-processing utils to avoid validating the complex logprobs field.
"""
class ChoiceAny(Choice):
"""Same as openai.types.chat.chat_completion.Choice, but without type validation for logprobs field."""
logprobs: Optional[Any] = None
class ModdedChatCompletion(ChatCompletion):
"""Same as openai.types.chat.chat_completion.ChatCompletion, but using ChoiceAny instead of Choice."""
choices: list[ChoiceAny] # type: ignore
# Patch OAI types
openai.types.chat.chat_completion.Choice = ChoiceAny
openai.types.chat.chat_completion.ChatCompletion = ModdedChatCompletion
+1 -1
View File
@@ -242,7 +242,7 @@ class TrainSink:
survivors = [trace for _, trace in iter_trainable_traces(group)]
if survivors:
await env.algorithm.finalize_group(group)
await env.algorithm.score_group(group)
admitted = self._admit(group) if group else False
if not survivors or not admitted:
self.pending_episodes.extend(group, admitted=admitted)
+1 -1
View File
@@ -27,7 +27,7 @@ from prime_rl.trainer.models.fusions import (
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path
from prime_rl.utils.pathing import get_all_ckpt_steps, get_ckpt_dir, get_step_path
@dataclass
+1
View File
@@ -365,6 +365,7 @@ def get_model(
subconfig = getattr(model_config, subconfig_key, None)
if subconfig is not None and hasattr(subconfig, "use_cache"):
subconfig.use_cache = False
model_config.dsa_backend = config.dsa_backend
if config.index_cache is not None:
model_config.use_index_cache = True
model_config.index_topk_freq = config.index_cache.topk_freq
@@ -23,7 +23,6 @@ from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import BaseModelOutputWithPast
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, auto_docstring
from transformers.utils.deprecation import deprecate_kwarg
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.glm4_moe.configuration_glm4_moe import Glm4MoeConfig
@@ -89,7 +88,6 @@ class Glm4MoeDecoderLayer(GradientCheckpointingLayer):
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
def forward(
self,
hidden_states: torch.Tensor,
@@ -10,7 +10,6 @@ from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import BaseModelOutputWithPast
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, auto_docstring
from transformers.utils.deprecation import deprecate_kwarg
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.glm_moe_dsa.configuration_glm_moe_dsa import GlmMoeDsaConfig, _index_cache_skip_topk
@@ -42,6 +41,7 @@ def _sparse_mla_attention_args(config: GlmMoeDsaConfig, layer_idx: int) -> Spars
index_topk=config.index_topk,
use_index_cache=getattr(config, "use_index_cache", False),
skip_topk=_index_cache_skip_topk(config, layer_idx),
dsa_backend=getattr(config, "dsa_backend", "tilelang"),
)
@@ -87,7 +87,6 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
def forward(
self,
hidden_states: torch.Tensor,
@@ -4,6 +4,7 @@ import torch
import torch.distributed as dist
from torch import nn
from prime_rl.configs.trainer import DSABackend
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
from prime_rl.trainer.models.layers.norms import LayerNorm, RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
@@ -30,6 +31,7 @@ class SparseMlaAttentionArgs:
index_n_heads: int
index_head_dim: int
index_topk: int
dsa_backend: DSABackend
use_index_cache: bool = False
skip_topk: bool = False
@@ -230,7 +232,7 @@ class GlmMoeDsaAttention(nn.Module):
position_embeddings_full=position_embeddings,
)
out, _ = sparse_mla(sparse_q, sparse_kv, indices, self.scaling)
out, _ = sparse_mla(sparse_q, sparse_kv, indices, self.args.dsa_backend, self.scaling)
out = torch.einsum("bshk,hdk->bshd", out, w_v)
batch_size, total_tokens = out.shape[:2]
out = out.reshape(batch_size, total_tokens, -1)
@@ -13,10 +13,14 @@ except Exception:
# This is expected on CPU-only machines
pass
import math
import tilelang
import torch
from tilelang import language as T
from prime_rl.configs.trainer import DSABackend
@tilelang.jit(out_idx=[-1])
def preprocess(
@@ -276,8 +280,32 @@ def bwd(
return sparse_mla_bwd_kernel
@torch.library.custom_op("prime_rl::sparse_mla_backward", mutates_args=())
def sparse_mla_backward(
_CUDNN_SM100_CAPABILITIES = ((10, 0), (10, 3))
def cudnn_backward_arch(q: torch.Tensor, kv: torch.Tensor) -> str | None:
"""The cuDNN DSA backward variant for this device ("sm90" / "sm100"), or None if unsupported."""
if kv.shape[2] != 1:
return None
capability = torch.cuda.get_device_capability(q.device)
if capability[0] == 9:
return "sm90"
if capability in _CUDNN_SM100_CAPABILITIES:
return "sm100"
return None
def flat_kv_indices(indices: torch.Tensor, S_kv: int) -> torch.Tensor:
"""Global indices into the batch-flattened KV, with sentinel / out-of-range indices as -1.
`indices` is [B, S, kv_group, topk]; valid entries live in [0, S_kv - 1) (see sparse_mla_fwd).
"""
B = indices.shape[0]
batch_offset = torch.arange(B, device=indices.device, dtype=indices.dtype).view(B, 1, 1, 1) * S_kv
return torch.where(indices <= S_kv - 2, indices + batch_offset, -1)
def tilelang_sparse_mla_backward(
q: torch.Tensor,
kv: torch.Tensor,
out: torch.Tensor,
@@ -286,20 +314,13 @@ def sparse_mla_backward(
lse: torch.Tensor,
sm_scale: float | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
assert q.is_contiguous()
assert kv.is_contiguous()
assert indices.is_contiguous()
assert lse.is_contiguous()
"""TileLang backward; takes a natural-log LSE."""
grad_out = grad_out.contiguous()
B, S, H, dim_plus_tail_dim = q.shape
_, S_kv, kv_group, _ = kv.shape
assert kv.shape[-1] == dim_plus_tail_dim
assert kv.shape[0] == B
H, dim_plus_tail_dim = q.shape[2:]
kv_group = kv.shape[2]
D = 512
D_tail = dim_plus_tail_dim - D
topk = indices.shape[-1]
assert indices.shape == (B, S, kv_group, topk)
assert lse.shape == (B, S, H)
preprocess_kernel = preprocess(H, D)
bwd_kernel = bwd(H, D, D_tail, topk, kv_group, sm_scale, True)
@@ -307,9 +328,82 @@ def sparse_mla_backward(
delta = preprocess_kernel(out, grad_out)
dkv = torch.zeros_like(kv, dtype=torch.float32)
dq = bwd_kernel(q, kv, grad_out, indices, lse, delta, dkv)
dq = bwd_kernel(q, kv, grad_out, indices, lse * math.log2(math.e), delta, dkv)
dkv = postprocess_kernel(dkv)
return dq, dkv
def cudnn_sparse_mla_backward(
q: torch.Tensor,
kv: torch.Tensor,
out: torch.Tensor,
grad_out: torch.Tensor,
indices: torch.Tensor,
lse: torch.Tensor,
sm_scale: float | None,
arch: str,
) -> tuple[torch.Tensor, torch.Tensor]:
"""cuDNN-frontend CuTe-DSL DSA backward (single KV head with K=V).
The cuDNN kernels take flat (tokens, ...) tensors with global indices, skip
negative indices (no KV load, no dKV atomics) and expect a natural-log LSE.
"""
B, S, H, D_qk = q.shape
S_kv = kv.shape[1]
topk = indices.shape[-1]
args = (
q.view(B * S, H, D_qk),
kv.view(B * S_kv, D_qk),
out.view(B * S, H, -1),
grad_out.contiguous().view(B * S, H, -1),
lse.view(B * S, H),
)
flat_indices = flat_kv_indices(indices, S_kv).view(B * S, topk)
if arch == "sm90":
from cudnn.deepseek_sparse_attention.sparse_attention_backward._interface_sm90 import flash_attn_bwd_sm90
dq, dkv = flash_attn_bwd_sm90(*args, softmax_scale=sm_scale, topk_idxs=flat_indices)
else:
# Untested: no SM100 hardware has run this path. A -inf sink leaves the softmax unchanged.
from cudnn.deepseek_sparse_attention.sparse_attention_backward._interface_sm100 import flash_attn_bwd_sm100
no_sink = torch.full((H,), float("-inf"), dtype=torch.float32, device=q.device)
dq, dkv, _ = flash_attn_bwd_sm100(*args, no_sink, flat_indices, softmax_scale=sm_scale)
return dq.view_as(q), dkv.view_as(kv)
@torch.library.custom_op(
"prime_rl::sparse_mla_backward",
mutates_args=(),
schema="(Tensor q, Tensor kv, Tensor out, Tensor grad_out, Tensor indices, Tensor lse, str backend, float? sm_scale=None) -> (Tensor, Tensor)",
)
def sparse_mla_backward(
q: torch.Tensor,
kv: torch.Tensor,
out: torch.Tensor,
grad_out: torch.Tensor,
indices: torch.Tensor,
lse: torch.Tensor,
backend: DSABackend,
sm_scale: float | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Sparse MLA backward for the `backend` route (see `sparse_mla`); `lse` is natural-log."""
assert q.is_contiguous()
assert kv.is_contiguous()
assert indices.is_contiguous()
assert lse.is_contiguous()
B, S, H, dim_plus_tail_dim = q.shape
_, S_kv, kv_group, _ = kv.shape
assert kv.shape[-1] == dim_plus_tail_dim
assert kv.shape[0] == B
topk = indices.shape[-1]
assert indices.shape == (B, S, kv_group, topk)
assert lse.shape == (B, S, H)
if backend == "cudnn_flashmla":
dq, dkv = cudnn_sparse_mla_backward(q, kv, out, grad_out, indices, lse, sm_scale, cudnn_backward_arch(q, kv))
else:
dq, dkv = tilelang_sparse_mla_backward(q, kv, out, grad_out, indices, lse, sm_scale)
return dq, dkv
@@ -321,6 +415,7 @@ def _sparse_mla_backward_fake(
grad_out: torch.Tensor,
indices: torch.Tensor,
lse: torch.Tensor,
backend: DSABackend,
sm_scale: float | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.empty_like(q), torch.empty_like(kv)
@@ -13,11 +13,17 @@ except Exception:
# This is expected on CPU-only machines
pass
import math
import tilelang
import torch
from tilelang import language as T
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_backward
from prime_rl.configs.trainer import DSABackend
from prime_rl.trainer.models.kernels.sparse_mla_bwd import (
flat_kv_indices,
sparse_mla_backward,
)
@tilelang.jit(
@@ -186,17 +192,52 @@ def sparse_mla_fwd(
return main
@torch.library.custom_op("prime_rl::sparse_mla", mutates_args=())
def flashmla_sparse_mla_forward(
q: torch.Tensor, kv: torch.Tensor, indices: torch.Tensor, sm_scale: float, d_v: int
) -> tuple[torch.Tensor, torch.Tensor]:
"""FlashMLA sparse prefill forward; returns a natural-log LSE."""
from flash_mla import flash_mla_sparse_fwd
B, S, H, D_qk = q.shape
S_kv, kv_group = kv.shape[1:3]
topk = indices.shape[-1]
# Shortest prefix holding every valid index, so the kernel skips the sentinel tail
# (the indexer sorts valid indices first); invalid entries inside it are -1.
positions = torch.arange(1, topk + 1, device=indices.device, dtype=torch.int32)
topk_length = torch.where(indices <= S_kv - 2, positions, 0).amax(-1).view(B * S)
out, _max_logits, lse = flash_mla_sparse_fwd(
q.view(B * S, H, D_qk),
kv.view(B * S_kv, kv_group, D_qk),
flat_kv_indices(indices, S_kv).view(B * S, kv_group, topk),
sm_scale,
d_v,
topk_length=topk_length,
)
return out.view(B, S, H, d_v), lse.view(B, S, H)
@torch.library.custom_op(
"prime_rl::sparse_mla",
mutates_args=(),
schema="(Tensor q, Tensor kv, Tensor indices, str backend, float? sm_scale=None, SymInt d_v=512, SymInt block_I=64, SymInt num_stages=2, SymInt threads=256) -> (Tensor, Tensor)",
)
def sparse_mla(
q: torch.Tensor,
kv: torch.Tensor,
indices: torch.Tensor,
backend: DSABackend,
sm_scale: float | None = None,
d_v: int = 512,
block_I: int = 64,
num_stages: int = 2,
threads: int = 256,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Sparse MLA attention over the top-k `indices`; returns the output and its natural-log LSE.
`backend` picks the kernels for the forward and (via autograd) the backward:
``tilelang`` is TileLang for both; ``cudnn_flashmla`` is FlashMLA forward + cuDNN backward
(SM90; SM100 / SM103 untested).
"""
assert q.is_contiguous() and kv.is_contiguous() and indices.is_contiguous()
batch, seq_len, heads, dim_plus_tail_dim = q.shape
_, seq_len_kv, kv_group, _ = kv.shape
@@ -209,19 +250,26 @@ def sparse_mla(
_, _, _, topk = indices.shape
assert indices.shape == (batch, seq_len, kv_group, topk)
kernel = sparse_mla_fwd(
heads,
dim,
tail_dim,
topk,
kv_group,
sm_scale,
True,
block_I=block_I,
num_stages=num_stages,
threads=threads,
)
out, lse = kernel(q, kv, indices)
if backend == "cudnn_flashmla":
if sm_scale is None:
sm_scale = dim_plus_tail_dim**-0.5
out, lse = flashmla_sparse_mla_forward(q, kv, indices, sm_scale, d_v)
else:
kernel = sparse_mla_fwd(
heads,
dim,
tail_dim,
topk,
kv_group,
sm_scale,
True,
block_I=block_I,
num_stages=num_stages,
threads=threads,
)
out, lse = kernel(q, kv, indices)
# The TileLang kernel returns a base-2 LSE.
lse = lse * math.log(2.0)
return out, lse
@@ -230,6 +278,7 @@ def _sparse_mla_fake(
q: torch.Tensor,
kv: torch.Tensor,
indices: torch.Tensor,
backend: DSABackend,
sm_scale: float | None = None,
d_v: int = 512,
block_I: int = 64,
@@ -240,10 +289,11 @@ def _sparse_mla_fake(
def _sparse_mla_setup_context(ctx, inputs, output) -> None:
q, kv, indices, sm_scale, _d_v, _block_I, _num_stages, _threads = inputs
q, kv, indices, backend, sm_scale, _d_v, _block_I, _num_stages, _threads = inputs
out, lse = output
ctx.save_for_backward(q, kv, out, indices, lse)
ctx.sm_scale = sm_scale
ctx.backend = backend
ctx.mark_non_differentiable(lse)
@@ -256,9 +306,10 @@ def _sparse_mla_autograd_backward(ctx, grad_out: torch.Tensor, _grad_lse: torch.
grad_out,
indices,
lse.detach(),
ctx.backend,
ctx.sm_scale,
)
return dq, dkv, None, None, None, None, None, None
return dq, dkv, None, None, None, None, None, None, None
sparse_mla.register_autograd(_sparse_mla_autograd_backward, setup_context=_sparse_mla_setup_context)
@@ -32,7 +32,6 @@ from transformers.modeling_outputs import (
from transformers.models.llama.configuration_llama import LlamaConfig
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
from transformers.utils.deprecation import deprecate_kwarg
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
@@ -71,7 +70,6 @@ class LlamaDecoderLayer(GradientCheckpointingLayer):
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
def forward(
self,
hidden_states: torch.Tensor,
+2 -35
View File
@@ -68,11 +68,11 @@ from prime_rl.trainer.world import get_world
from prime_rl.trainer.lora import get_lora_state
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.metrics_server import HealthServer, MetricsServer
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.utils import clean_exit, resolve_latest_ckpt_step
from prime_rl.utils.pathing import resolve_latest_ckpt_step
from prime_rl.utils.utils import clean_exit
@clean_exit
@@ -102,19 +102,6 @@ def train(config: TrainerConfig):
logger.info("Initializing heartbeat")
heart = Heartbeat(config.heartbeat)
# Setup metrics server (full on master, health-only on other nodes' local rank 0)
metrics_server = None
health_server = None
if config.metrics_server is not None and world.local_rank == 0:
if world.is_master:
logger.info(f"Initializing metrics server on port {config.metrics_server.port}")
metrics_server = MetricsServer(config.metrics_server)
metrics_server.start()
else:
logger.info(f"Initializing health server on port {config.metrics_server.port}")
health_server = HealthServer(config.metrics_server.port, config.metrics_server.host)
health_server.start()
# Set precision
setup_torch_distributed(
timeout=timedelta(seconds=config.dist_timeout_seconds),
@@ -721,20 +708,6 @@ def train(config: TrainerConfig):
disk_metrics["step"] = progress.step
asyncio.run(monitors.log(disk_metrics, step=progress.step))
# Update Prometheus metrics if configured
if metrics_server is not None:
metrics_server.update(
step=progress.step,
loss=tensor_stats["loss/mean"],
throughput=throughput,
grad_norm=grad_norm.item() if grad_norm is not None else None,
peak_memory_gib=peak_memory,
learning_rate=current_lr,
mfu=mfu,
entropy=tensor_stats.get("entropy/all/mean", 0.0),
mismatch_kl=tensor_stats.get("mismatch_kl/all/mean", 0.0),
)
# Send heartbeat if configured
if heart is not None:
heart.beat()
@@ -764,12 +737,6 @@ def train(config: TrainerConfig):
logger.success("RL trainer finished")
asyncio.run(monitors.finalize())
# Stop metrics/health server if configured
if metrics_server is not None:
metrics_server.stop()
if health_server is not None:
health_server.stop()
def main():
"""Main entry-point for RL trainer. Run using `uv run trainer`"""
-176
View File
@@ -1,176 +0,0 @@
"""Prometheus metrics server for trainer observability.
Exposes training metrics at /metrics in Prometheus format.
Also exposes /health endpoint for Kubernetes liveness probes.
Runs in a background thread to avoid blocking the training loop.
"""
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import TYPE_CHECKING
from loguru import logger
from prometheus_client import CONTENT_TYPE_LATEST, CollectorRegistry, Gauge, generate_latest
if TYPE_CHECKING:
from prime_rl.configs.shared import MetricsServerConfig
class HealthServer:
"""Lightweight HTTP server exposing /health for Kubernetes liveness probes.
Can be subclassed to add additional endpoints (e.g., MetricsServer).
"""
def __init__(self, port: int, host: str = "0.0.0.0"):
self.port = port
self.host = host
self._server: HTTPServer | None = None
self._thread: threading.Thread | None = None
self._started = False
def _make_handler(self) -> type[BaseHTTPRequestHandler]:
"""Create the request handler class. Override to add endpoints."""
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/health":
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"ok\n")
else:
self.send_response(404)
self.end_headers()
def log_message(self, format, *args):
pass
return Handler
def start(self) -> None:
"""Start the server in a background thread."""
if self._started:
logger.warning(f"{self.__class__.__name__} already started")
return
self._server = HTTPServer((self.host, self.port), self._make_handler())
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
self._thread.start()
self._started = True
logger.info(f"Health server started at http://{self.host}:{self.port}/health")
def stop(self) -> None:
"""Stop the server and release the port."""
if self._server is not None:
self._server.shutdown()
self._server.server_close()
if self._thread is not None:
self._thread.join(timeout=5.0)
self._server = None
self._thread = None
self._started = False
logger.info(f"{self.__class__.__name__} stopped")
class MetricsServer(HealthServer):
"""Prometheus metrics server extending HealthServer with /metrics endpoint.
Uses an isolated CollectorRegistry to avoid global state pollution.
Disabled by default - enable by setting `metrics_server` in trainer config.
"""
def __init__(self, config: "MetricsServerConfig"):
super().__init__(config.port, config.host)
self.config = config
self._registry = CollectorRegistry()
self._step = Gauge("trainer_step", "Current training step", registry=self._registry)
self._loss = Gauge("trainer_loss", "Current training loss", registry=self._registry)
self._throughput = Gauge(
"trainer_throughput_tokens_per_sec", "Training throughput in tokens/sec", registry=self._registry
)
self._last_step_ts = Gauge(
"trainer_last_step_timestamp_seconds", "Unix timestamp of last step", registry=self._registry
)
self._grad_norm = Gauge("trainer_grad_norm", "Gradient norm", registry=self._registry)
self._peak_mem = Gauge("trainer_peak_memory_gib", "Peak GPU memory in GiB", registry=self._registry)
self._lr = Gauge("trainer_learning_rate", "Current learning rate", registry=self._registry)
self._mfu = Gauge("trainer_mfu_percent", "Model FLOPS utilization %", registry=self._registry)
self._entropy = Gauge("trainer_entropy", "Mean entropy", registry=self._registry)
self._mismatch_kl = Gauge(
"trainer_mismatch_kl", "KL divergence between trainer and inference model", registry=self._registry
)
self._kl_ent_ratio = Gauge("trainer_kl_ent_ratio", "Ratio of mismatch KL to entropy", registry=self._registry)
def _make_handler(self) -> type[BaseHTTPRequestHandler]:
"""Create handler with /metrics and /health endpoints."""
registry = self._registry
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/metrics":
self._handle_metrics()
elif self.path == "/health":
self._handle_health()
else:
self.send_response(404)
self.end_headers()
def _handle_metrics(self):
self.send_response(200)
self.send_header("Content-Type", CONTENT_TYPE_LATEST)
self.end_headers()
self.wfile.write(generate_latest(registry))
def _handle_health(self):
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"ok\n")
def log_message(self, format, *args):
pass
return Handler
def start(self) -> None:
"""Start the metrics server in a background thread."""
if self._started:
logger.warning("Metrics server already started")
return
self._server = HTTPServer((self.host, self.port), self._make_handler())
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
self._thread.start()
self._started = True
logger.info(f"Metrics server started at http://{self.host}:{self.port}/metrics")
logger.info(f"Health endpoint available at http://{self.host}:{self.port}/health")
def update(
self,
step: int,
loss: float,
throughput: float,
grad_norm: float | None,
peak_memory_gib: float,
learning_rate: float,
mfu: float = 0.0,
entropy: float = 0.0,
mismatch_kl: float = 0.0,
) -> None:
"""Update metrics after a training step."""
self._step.set(step)
self._loss.set(loss)
self._throughput.set(throughput)
if grad_norm is not None:
self._grad_norm.set(grad_norm)
self._peak_mem.set(peak_memory_gib)
self._lr.set(learning_rate)
self._mfu.set(mfu)
self._entropy.set(entropy)
self._mismatch_kl.set(mismatch_kl)
if entropy > 0:
self._kl_ent_ratio.set(mismatch_kl / entropy)
self._last_step_ts.set(time.time())
-19
View File
@@ -2,33 +2,14 @@ import asyncio
import functools
import importlib
import math
import os
import sys
from collections import defaultdict
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Callable
import wandb
from prime_rl.utils.logger import get_logger
# TODO: Change all imports to use utils.pathing
# ruff: noqa: F401
from prime_rl.utils.pathing import (
get_all_ckpt_steps,
get_batch_dir,
get_broadcast_dir,
get_ckpt_dir,
get_eval_dir,
get_file_monitor_dir,
get_log_dir,
get_step_path,
resolve_latest_ckpt_step,
sync_wait_for_path,
wait_for_path,
)
def import_object(dotted_path: str) -> Any:
"""Import an object from a dotted path like 'my_module.submodule.MyClass'."""
@@ -1 +0,0 @@
+2 -5
View File
@@ -37,14 +37,11 @@ CONFIG_CLASSES = [
def get_config_files() -> list[Path]:
"""Any TOML file inside `configs/`, `examples/` or `k8s/`."""
"""Any TOML file inside `configs/` or `examples/`."""
config_files = list(Path("configs").rglob("*.toml"))
example_files = list(Path("examples").rglob("*.toml"))
# The k8s example configs are mounted into the chart's containers verbatim, so a
# stale key there breaks a deploy with nothing else to catch it.
k8s_files = list(Path("k8s").rglob("*.toml"))
return config_files + example_files + k8s_files
return config_files + example_files
def can_parse(config_cls: type, args: list[str]) -> bool:
-209
View File
@@ -1,209 +0,0 @@
"""Tests for the Prometheus metrics server."""
import socket
import time
import urllib.request
from contextlib import closing
import pytest
from prime_rl.configs.shared import MetricsServerConfig
from prime_rl.utils.metrics_server import HealthServer, MetricsServer
def find_free_port() -> int:
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("", 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return s.getsockname()[1]
def test_config_default_values():
config = MetricsServerConfig()
assert config.port == 8000
assert config.host == "0.0.0.0"
def test_config_custom_port():
config = MetricsServerConfig(port=9090)
assert config.port == 9090
def test_config_invalid_port_low():
with pytest.raises(ValueError):
MetricsServerConfig(port=0)
def test_config_invalid_port_high():
with pytest.raises(ValueError):
MetricsServerConfig(port=65536)
def test_server_start_stop():
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
assert server._started
time.sleep(0.1)
response = urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
assert response.status == 200
server.stop()
assert not server._started
def test_server_returns_404_on_unknown_path():
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
time.sleep(0.1)
try:
urllib.request.urlopen(f"http://localhost:{port}/unknown", timeout=2)
pytest.fail("Expected 404")
except urllib.error.HTTPError as e:
assert e.code == 404
finally:
server.stop()
def test_server_double_start_is_safe():
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
server.start() # Should not raise
server.stop()
def test_server_update_metrics():
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
time.sleep(0.1)
server.update(step=42, loss=0.5, throughput=1000.0, grad_norm=1.5, peak_memory_gib=10.0, learning_rate=1e-4)
response = urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
content = response.read().decode()
assert "trainer_step" in content
assert "trainer_loss" in content
assert "trainer_last_step_timestamp_seconds" in content
assert "trainer_mismatch_kl" in content
assert "trainer_kl_ent_ratio" in content
server.stop()
def test_server_metrics_values_are_correct():
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
time.sleep(0.1)
entropy = 1.5
mismatch_kl = 0.045
server.update(
step=100,
loss=0.123,
throughput=5000.0,
grad_norm=2.5,
peak_memory_gib=16.0,
learning_rate=3e-5,
entropy=entropy,
mismatch_kl=mismatch_kl,
)
response = urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
content = response.read().decode()
assert "trainer_step 100.0" in content
assert "trainer_loss 0.123" in content
assert "trainer_mismatch_kl 0.045" in content
assert f"trainer_kl_ent_ratio {mismatch_kl / entropy}" in content
server.stop()
def test_server_isolated_registry():
"""Each MetricsServer instance should have its own registry."""
port1 = find_free_port()
port2 = find_free_port()
server1 = MetricsServer(MetricsServerConfig(port=port1))
server2 = MetricsServer(MetricsServerConfig(port=port2))
server1.start()
server2.start()
time.sleep(0.1)
server1.update(step=999, loss=0.1, throughput=100, grad_norm=1, peak_memory_gib=1, learning_rate=1e-3)
resp1 = urllib.request.urlopen(f"http://localhost:{port1}/metrics", timeout=2).read().decode()
resp2 = urllib.request.urlopen(f"http://localhost:{port2}/metrics", timeout=2).read().decode()
assert "999.0" in resp1
assert "999.0" not in resp2
server1.stop()
server2.stop()
def test_server_port_conflict_raises():
port = find_free_port()
server1 = MetricsServer(MetricsServerConfig(port=port))
server1.start()
time.sleep(0.1)
server2 = MetricsServer(MetricsServerConfig(port=port))
with pytest.raises(OSError):
server2.start()
server1.stop()
def test_health_server_start_stop():
port = find_free_port()
server = HealthServer(port=port)
server.start()
assert server._started
time.sleep(0.1)
response = urllib.request.urlopen(f"http://localhost:{port}/health", timeout=2)
assert response.status == 200
assert response.read() == b"ok\n"
server.stop()
assert not server._started
def test_health_server_returns_404_on_metrics():
"""HealthServer should not expose /metrics endpoint."""
port = find_free_port()
server = HealthServer(port=port)
server.start()
time.sleep(0.1)
try:
urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
pytest.fail("Expected 404")
except urllib.error.HTTPError as e:
assert e.code == 404
finally:
server.stop()
def test_metrics_server_health_endpoint():
"""MetricsServer should also expose /health endpoint."""
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
time.sleep(0.1)
response = urllib.request.urlopen(f"http://localhost:{port}/health", timeout=2)
assert response.status == 200
assert response.read() == b"ok\n"
server.stop()
Generated
+41 -30
View File
@@ -17,26 +17,27 @@ exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for
exclude-newer-span = "P7D"
[options.exclude-newer-package]
verifiers = false
prime-pydantic-config = false
harbor = "2026-08-11T00:00:00Z"
prime-traces = false
vllm-router = false
deep-ep = false
deep-gemm = false
dion = false
fastokens = false
prime-runs = false
flash-attn-3 = false
prime-tunnel = false
deep-gemm = false
prime-evals = false
torchao = false
tokenspeed-mla = false
flash-mla = false
harbor = "2026-08-11T00:00:00Z"
nixl-cu13 = false
deep-ep = false
prime-sandboxes = false
renderers = false
prime-kernels = false
prime = false
prime-evals = false
prime-kernels = false
prime-pydantic-config = false
prime-runs = false
prime-sandboxes = false
prime-traces = false
prime-tunnel = false
renderers = false
tokenspeed-mla = false
torchao = false
verifiers = false
vllm-router = false
[manifest]
members = [
@@ -1860,6 +1861,14 @@ dependencies = [
{ name = "transformers" },
]
[[package]]
name = "flash-mla"
version = "1.0.0+cu.13.0.torch.2.13.b7643bd"
source = { url = "https://github.com/NovaSky-AI/skyrl-wheels/releases/download/cu13torch2.13-flashmla-b7643bd/flash_mla-1.0.0%2Bcu.13.0.torch.2.13.b7643bd-cp312-cp312-linux_x86_64.whl" }
wheels = [
{ url = "https://github.com/NovaSky-AI/skyrl-wheels/releases/download/cu13torch2.13-flashmla-b7643bd/flash_mla-1.0.0%2Bcu.13.0.torch.2.13.b7643bd-cp312-cp312-linux_x86_64.whl", hash = "sha256:0bdb32340979c739659b305537dbe0445ba9f3148a4ce2f97f4fd170887c01e4" },
]
[[package]]
name = "flashinfer-python"
version = "0.6.18.post1"
@@ -4045,11 +4054,15 @@ wheels = [
[[package]]
name = "nvidia-cudnn-frontend"
version = "1.25.0"
version = "1.30.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "apache-tvm-ffi" },
{ name = "nvidia-cutlass-dsl" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/28/0f/df39a194f2529093db737d43cc4cbf594c6a79712a09aa104b999e4d95d4/nvidia_cudnn_frontend-1.25.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:09e6e1bc48ce1235743f89d8ea699c52b3008fd6dae7f2ecadb744bebf272a2b", size = 3263306, upload-time = "2026-06-10T21:07:48.093Z" },
{ url = "https://files.pythonhosted.org/packages/03/65/3b45941d8a22128b971e910f2e9af6bf5ef453e92cc329c56b6eb53c53de/nvidia_cudnn_frontend-1.25.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9a94a72d736bd79eb35f451aaf26d9493778e02ecabccc92c05425508c9e7a83", size = 3414884, upload-time = "2026-06-10T21:08:08.603Z" },
{ url = "https://files.pythonhosted.org/packages/e4/53/07836d9f74f1416a8768530d428c155f67d7728f283bce3a9b3096b7e18f/nvidia_cudnn_frontend-1.30.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:279d227a226429288ae9e4e88db744ce144ae69605f63a286dc84ae180869a6e", size = 8631629, upload-time = "2026-09-23T03:44:15.265Z" },
{ url = "https://files.pythonhosted.org/packages/ee/95/c92076af7561e6e43da1ee3ac4155202dcd3876e5b999ff0dea5754eb3d2/nvidia_cudnn_frontend-1.30.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5dda72db38ea0c39f158ebffa9596eefab21ce7cc6a12824490ab8b6cb60e76d", size = 8797507, upload-time = "2026-09-23T03:44:35.051Z" },
]
[[package]]
@@ -4951,14 +4964,12 @@ dependencies = [
{ name = "numpy" },
{ name = "openai" },
{ name = "orjson" },
{ name = "pandas" },
{ name = "prime" },
{ name = "prime-pydantic-config" },
{ name = "prime-rl-configs" },
{ name = "prime-runs", extra = ["train"] },
{ name = "prometheus-client" },
{ name = "psutil" },
{ name = "pyarrow" },
{ name = "pybase64" },
{ name = "pyzmq" },
{ name = "pyzstd" },
@@ -4985,11 +4996,13 @@ all = [
{ name = "flash-attn-3", marker = "sys_platform == 'linux'" },
{ name = "flash-attn-4", marker = "sys_platform == 'linux'" },
{ name = "flash-linear-attention", marker = "sys_platform == 'linux'" },
{ name = "flash-mla", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "mamba-ssm", marker = "sys_platform == 'linux'" },
{ name = "modelexpress", marker = "sys_platform == 'linux'" },
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux'" },
{ name = "nixl", marker = "sys_platform == 'linux'" },
{ name = "nixl-cu13", marker = "sys_platform == 'linux'" },
{ name = "nvidia-cudnn-frontend", marker = "sys_platform == 'linux'" },
{ name = "nvidia-ml-py", marker = "sys_platform == 'linux'" },
{ name = "quack-kernels", marker = "sys_platform == 'linux'" },
{ name = "ring-flash-attn", marker = "sys_platform == 'linux'" },
@@ -5018,7 +5031,6 @@ 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_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ 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.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'" },
]
@@ -5035,6 +5047,9 @@ flash-attn-3 = [
flash-attn-cute = [
{ name = "flash-attn-4", marker = "sys_platform == 'linux'" },
]
flash-mla = [
{ name = "flash-mla", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
]
gpu = [
{ name = "dion", marker = "sys_platform == 'linux'" },
{ name = "flash-linear-attention", marker = "sys_platform == 'linux'" },
@@ -5042,6 +5057,7 @@ gpu = [
{ name = "modelexpress", marker = "sys_platform == 'linux'" },
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux'" },
{ name = "nixl-cu13", marker = "sys_platform == 'linux'" },
{ name = "nvidia-cudnn-frontend", marker = "sys_platform == 'linux'" },
{ name = "nvidia-ml-py", marker = "sys_platform == 'linux'" },
{ name = "ring-flash-attn", marker = "sys_platform == 'linux'" },
{ name = "tilelang" },
@@ -5077,9 +5093,6 @@ dev = [
{ name = "pytest-asyncio" },
{ name = "ruff" },
]
mamba-ssm = [
{ name = "mamba-ssm", marker = "sys_platform == 'linux'" },
]
[package.metadata]
requires-dist = [
@@ -5100,6 +5113,7 @@ requires-dist = [
{ name = "flash-attn-3", marker = "sys_platform == 'linux' and extra == 'flash-attn-3'", index = "https://download.pytorch.org/whl/test/cu130" },
{ name = "flash-attn-4", marker = "sys_platform == 'linux' and extra == 'flash-attn-cute'", git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=0251105" },
{ name = "flash-linear-attention", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/fla-org/flash-linear-attention" },
{ name = "flash-mla", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'flash-mla'", url = "https://github.com/NovaSky-AI/skyrl-wheels/releases/download/cu13torch2.13-flashmla-b7643bd/flash_mla-1.0.0%2Bcu.13.0.torch.2.13.b7643bd-cp312-cp312-linux_x86_64.whl" },
{ name = "jaxtyping", specifier = ">=0.3.2" },
{ name = "loguru", specifier = ">=0.7.3" },
{ name = "mamba-ssm", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/state-spaces/mamba?rev=f577286" },
@@ -5107,14 +5121,12 @@ requires-dist = [
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.3.10.post2" },
{ name = "msgspec", specifier = ">=0.18" },
{ name = "nixl", marker = "sys_platform == 'linux' and extra == 'disagg'" },
{ name = "nixl-cu13", marker = "sys_platform == 'linux' and extra == 'disagg'", specifier = "==0.10.1" },
{ name = "nixl-cu13", marker = "sys_platform == 'linux' and extra == 'gpu'", specifier = "==0.10.1" },
{ name = "numpy", specifier = ">=2.2.6" },
{ name = "nvidia-cudnn-frontend", marker = "sys_platform == 'linux' and extra == 'gpu'", specifier = ">=1.30.0" },
{ name = "nvidia-ml-py", marker = "sys_platform == 'linux' and extra == 'gpu'", specifier = ">=12.575.51" },
{ name = "openai", specifier = ">=1.106.1" },
{ name = "orjson", specifier = ">=3.10" },
{ name = "orjson", specifier = ">=3.11.0" },
{ name = "pandas", specifier = ">=2.0" },
{ name = "prime", specifier = ">=0.8.0" },
{ name = "prime-kernels", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'kernels'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl" },
{ name = "prime-kernels", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'kernels'" },
@@ -5124,6 +5136,7 @@ requires-dist = [
{ name = "prime-rl", extras = ["flash-attn"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["flash-attn-3"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["flash-attn-cute"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["flash-mla"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["gpu"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["sonic-moe"], marker = "extra == 'all'" },
@@ -5131,7 +5144,6 @@ requires-dist = [
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.3" },
{ name = "prometheus-client", specifier = ">=0.20.0" },
{ name = "psutil", specifier = ">=7.0.0" },
{ name = "pyarrow", specifier = ">=21.0.0" },
{ name = "pybase64", specifier = ">=1.4.2" },
{ name = "pyzmq", specifier = ">=27.1.0" },
{ name = "pyzstd", specifier = ">=0.16.2" },
@@ -5164,7 +5176,7 @@ requires-dist = [
{ name = "wandb", specifier = ">=0.26.1" },
{ name = "wandb-workspaces", specifier = ">=0.4.3" },
]
provides-extras = ["gpu", "dashboard", "dynamo", "flash-attn", "flash-attn-3", "flash-attn-cute", "disagg", "quack", "sonic-moe", "kernels", "all"]
provides-extras = ["gpu", "dashboard", "dynamo", "flash-attn", "flash-attn-3", "flash-attn-cute", "disagg", "quack", "sonic-moe", "flash-mla", "kernels", "all"]
[package.metadata.requires-dev]
dev = [
@@ -5176,7 +5188,6 @@ dev = [
{ name = "pytest-asyncio", specifier = ">=0.23" },
{ name = "ruff", specifier = ">=0.12.1" },
]
mamba-ssm = [{ name = "mamba-ssm", marker = "sys_platform == 'linux'", git = "https://github.com/state-spaces/mamba?rev=f577286" }]
[[package]]
name = "prime-rl-configs"