Compare commits

...
Author SHA1 Message Date
faresobeidandGitHub c8af127357 chore: remove legacy config options (#3770)
Removes legacy config options and their code paths. They have had no
changes of their own in 4+ months.

## Removed
- **SGD optimizer** (`optim.type = "sgd"`): `SGDConfig`, its union
member, and the `torch.optim.SGD` branch in `trainer/optim`. AdamW,
Muon, and SignSGD stay.
- **`ckpt.skip_progress`** (orchestrator and trainer ckpt configs):
resume now always restores progress. This affects the orchestrator ckpt
loading and SFT resume.
- **`Jackmin108/` model-name special case** in
`validate_shared_model_name`. Trainer and orchestrator model names now
must always match when no inference config is given.

## Kept
- **`orchestrator.collect_inference_metrics`** stays, unchanged from
main. Hosted training uses Grafana for inference metrics and sets it to
`false` to turn off W&B mirroring. The `/metrics` poll for the
concurrency controller always runs either way.

## Also included (#3774, merged into this branch)
- `RLConfig`: top-level shared fields (including `resume`) go through
`propagate_shared_fields` only. The old `validate_shared_*` helpers in
`validation.py` are replaced by inline cross-component checks in
`RLConfig.validate_shared_configs`.

## Breaking changes
TOMLs/CLI args that set any of these now fail validation:
- `trainer.optim.type = "sgd"` (and `optim.momentum`, `optim.nesterov`)
- `orchestrator.ckpt.skip_progress`, `trainer.ckpt.skip_progress` (SFT
`ckpt.skip_progress`)

No configs, examples, docs, or skills in the repo reference these
options.

## Validation
- `pytest tests/unit -m "not gpu"` (excluding
`tests/unit/train/test_cpu_adam.py`, which needs `ninja` to build a C++
extension on this machine): 651 passed
- `ruff check .` and `ruff format --check .` (only `docs/algorithms.md`
is flagged, same as on main)
- GPU/integration tests were not run (no GPU on this machine).

Rebased on main f42630873; resolved conflicts in `configs/rl.py` and
`utils/validation.py` (main's #3788 already removed
`validate_shared_weight_broadcast`; kept that and this PR's removal of
the other `validate_shared_*` helpers).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking config validation for old TOMLs/CLI flags and stricter
cross-component model/resume rules; resume behavior changes if anything
relied on skipping progress restore.
> 
> **Overview**
> Removes **legacy config knobs** that are no longer supported:
**`optim.type = "sgd"`** (config type + `torch.optim.SGD` factory), and
**`ckpt.skip_progress`** on trainer/orchestrator checkpoints. Resume now
**always** restores orchestrator progress/curriculum state and SFT
training progress (step counter always advances after load).
> 
> **RL config validation** is consolidated: shared-field helpers in
`validation.py` are deleted in favor of
**`RLConfig.validate_shared_configs`** using a generic `require_equal`
check (model name, chat template, `max_steps`, `resume`, ckpt/W&B
parity, seq_len bound). Top-level **`resume`** is propagated via
**`propagate_shared_fields`** instead of a separate `auto_setup_resume`
validator; the **`Jackmin108/`** trainer/orchestrator model-name
exemption is gone.
> 
> CI slim-install smoke test imports **`propagate_shared_fields`** only.
Unit tests drop SGD from full-offload optimizer coverage.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1df3854c75fc652e2b0a5dbd7d019555e73736ba. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-05 11:53:03 +01:00
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
35 changed files with 675 additions and 385 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:
+1 -1
View File
@@ -75,7 +75,7 @@ jobs:
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
from prime_rl.utils.validation import validate_shared_ckpt_config
from prime_rl.utils.validation import propagate_shared_fields
# `verifiers` (+ its `datasets` dep) is a declared slim dep: the v1 config types
# (EnvConfig, Task, ...) extend verifiers.v1, which is pure-pydantic and pulls no
+51 -76
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,50 +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 --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 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 --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")]'
--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);
@@ -184,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
@@ -262,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
@@ -282,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"
@@ -303,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
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
@@ -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
+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
@@ -481,9 +481,6 @@ class CheckpointConfig(BaseConfig):
keep_interval: int | None = Field(None, ge=1)
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
skip_progress: bool = False
"""Skip loading the progress from checkpoint."""
class ConcurrencyConfig(BaseConfig):
"""Adaptive in-flight concurrency control. The orchestrator sizes the
@@ -25,15 +25,7 @@ from prime_rl.configs.trainer import (
TrainerConfig,
)
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
from prime_rl.utils.validation import (
propagate_shared_fields,
validate_shared_ckpt_config,
validate_shared_max_steps,
validate_shared_model_name,
validate_shared_seq_len,
validate_shared_tokenizer,
validate_shared_wandb_config,
)
from prime_rl.utils.validation import propagate_shared_fields
class SharedLogConfig(BaseConfig):
@@ -333,15 +325,6 @@ class RLConfig(BaseConfig):
sub.output_dir = run_dir
return self
@model_validator(mode="after")
def auto_setup_resume(self):
"""Propagate the top-level resume onto the sub-configs."""
if self.resume is None:
return self
self.trainer.resume = self.resume.model_copy()
self.orchestrator.resume = self.resume.model_copy()
return self
@model_validator(mode="after")
def auto_setup_run_identity(self):
"""Default the W&B and Prime platform run names to ``run.name``.
@@ -365,13 +348,70 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def validate_shared_configs(self):
"""Validate consistency of shared configs across trainer, orchestrator, and inference."""
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
validate_shared_tokenizer(self.trainer, self.orchestrator, self.inference)
validate_shared_max_steps(self.trainer, self.orchestrator)
validate_shared_seq_len(self.trainer, self.orchestrator)
validate_shared_ckpt_config(self.trainer, self.orchestrator)
validate_shared_wandb_config(self.trainer, self.orchestrator)
"""Cross-component constraints for values set per sub-config rather than through the
shared fields (``propagate_shared_fields`` already rejects shared vs sub-config conflicts)."""
trainer, orchestrator, inference = self.trainer, self.orchestrator, self.inference
def require_equal(name: str, values: dict[str, Any]) -> None:
if len({repr(v) for v in values.values()}) > 1:
found = ", ".join(f"{path}={value!r}" for path, value in values.items())
raise ValueError(f"{name} must match across components ({found}). Set the shared [{name}] instead.")
# The orchestrator queries the inference server it is paired with; without one, it
# must match the trainer whose weights the external server receives.
if inference is not None:
require_equal(
"model.name",
{"inference.vllm.model": inference.vllm.model, "orchestrator.model.name": orchestrator.model.name},
)
else:
require_equal(
"model.name",
{"trainer.model.name": trainer.model.name, "orchestrator.model.name": orchestrator.model.name},
)
# ``tokenizer.name`` / ``trust_remote_code`` may differ (e.g. FP8-quantized inference variants).
chat_templates = {
"trainer.tokenizer.chat_template": trainer.tokenizer.chat_template,
"orchestrator.tokenizer.chat_template": orchestrator.tokenizer.chat_template,
}
if inference is not None:
chat_templates["inference.vllm.chat_template"] = inference.vllm.chat_template
require_equal("tokenizer.chat_template", chat_templates)
require_equal(
"max_steps", {"trainer.max_steps": trainer.max_steps, "orchestrator.max_steps": orchestrator.max_steps}
)
require_equal("resume", {"trainer.resume": trainer.resume, "orchestrator.resume": orchestrator.resume})
if trainer.model.seq_len < orchestrator.seq_len:
raise ValueError(
f"trainer.model.seq_len ({trainer.model.seq_len}) must be >= orchestrator.seq_len "
f"({orchestrator.seq_len}) so the trainer can handle every sequence the orchestrator produces."
)
if (trainer.ckpt is None) != (orchestrator.ckpt is None):
raise ValueError(
"Checkpointing must be configured on both trainer and orchestrator. Use the shared [ckpt]."
)
if trainer.ckpt and orchestrator.ckpt:
require_equal(
"ckpt.interval",
{
"trainer.ckpt.interval": trainer.ckpt.interval,
"orchestrator.ckpt.interval": orchestrator.ckpt.interval,
},
)
trainer_wandb, orchestrator_wandb = trainer.monitors.wandb, orchestrator.monitors.wandb
if (trainer_wandb is None) != (orchestrator_wandb is None):
raise ValueError(
"W&B must be configured on both trainer and orchestrator, otherwise only one side's "
"metrics are logged. Use the shared [monitors.wandb]."
)
if trainer_wandb and orchestrator_wandb:
require_equal(
"monitors.wandb.project",
{
"trainer.monitors.wandb.project": trainer_wandb.project,
"orchestrator.monitors.wandb.project": orchestrator_wandb.project,
},
)
return self
@model_validator(mode="after")
@@ -22,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):
@@ -325,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."""
@@ -462,16 +466,6 @@ class BaseOptimizerConfig(BaseConfig):
"""Maximum gradient norm to clip to. If None, gradient clipping is disabled."""
class SGDConfig(BaseOptimizerConfig):
type: Literal["sgd"] = "sgd"
nesterov: bool = True
"""Use Nesterov momentum."""
momentum: float = 0.9
"""SGD momentum factor."""
class AdamWConfig(BaseOptimizerConfig):
type: Literal["adamw"] = "adamw"
@@ -499,9 +493,7 @@ class SignSGDConfig(BaseOptimizerConfig):
type: Literal["sign_sgd"] = "sign_sgd"
OptimizerConfig: TypeAlias = Annotated[
SGDConfig | AdamWConfig | MuonConfig | SignSGDConfig, Field(discriminator="type")
]
OptimizerConfig: TypeAlias = Annotated[AdamWConfig | MuonConfig | SignSGDConfig, Field(discriminator="type")]
class CheckpointConfig(BaseConfig):
@@ -517,9 +509,6 @@ class CheckpointConfig(BaseConfig):
keep_interval: int | None = Field(None, ge=1)
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
skip_progress: bool = False
"""Skip loading the progress from checkpoint."""
skip_scheduler: bool = False
"""Skip loading the scheduler from checkpoint."""
@@ -1,10 +1,6 @@
from __future__ import annotations
from typing import Any, Optional
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.trainer import TrainerConfig
from typing import Any
def propagate_shared_fields(data: Any) -> Any:
@@ -128,6 +124,8 @@ def propagate_shared_fields(data: Any) -> Any:
"inference.vllm.chat_template",
)
propagate("resume", "trainer.resume", "orchestrator.resume")
# [rollout_transport] → both sub-configs (host is launcher-injected for zmq multi-node).
propagate("rollout_transport", "trainer.rollout_transport", "orchestrator.rollout_transport")
@@ -147,7 +145,7 @@ def propagate_shared_fields(data: Any) -> Any:
# - shared ``[tokenizer] chat_template`` (already filled all three above,
# this re-fill is a no-op via fill-if-absent), and
# - ``[trainer.tokenizer] chat_template`` set directly without shared
# (only path that reaches inference; ``validate_shared_tokenizer``
# (only path that reaches inference; ``RLConfig.validate_shared_configs``
# would otherwise complain about the missing inference value).
trainer_chat_template = get("trainer.tokenizer.chat_template")
if trainer_chat_template is not None:
@@ -190,115 +188,3 @@ def propagate_shared_fields(data: Any) -> Any:
raise ValueError("\n".join(lines))
return data
def validate_shared_ckpt_config(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.ckpt and not orchestrator.ckpt:
raise ValueError(
"Trainer checkpoint config is specified, but orchestrator checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
)
if orchestrator.ckpt and not trainer.ckpt:
raise ValueError(
"Orchestrator checkpoint config is specified, but trainer checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
)
if trainer.ckpt and orchestrator.ckpt and trainer.ckpt.interval != orchestrator.ckpt.interval:
raise ValueError(
f"Trainer checkpoint interval ({trainer.ckpt.interval}) and orchestrator checkpoint interval ({orchestrator.ckpt.interval}) are not the same. Please specify the same checkpoint interval for both."
)
if trainer.resume != orchestrator.resume:
raise ValueError(
f"Trainer resume ({trainer.resume}) and orchestrator resume ({orchestrator.resume}) are not the same. Please specify the same resume config for both."
)
def validate_shared_model_name(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
# Orchestrator must match inference (it queries the inference server)
if inference is not None:
if inference.vllm.model != orchestrator.model.name:
raise ValueError(
f"Inference model name ({inference.vllm.model}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
"The orchestrator queries the inference server and must use the same model name."
)
return
if trainer.model.name.startswith("Jackmin108/"): # The TT MoE models will have a different name on the orchestrator
return
if trainer.model.name != orchestrator.model.name:
raise ValueError(
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
)
def validate_shared_wandb_config(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.monitors.wandb and not orchestrator.monitors.wandb:
raise ValueError(
"Trainer W&B config is specified, but orchestrator W&B config is not. "
"This means only trainer metrics will be logged. Please specify [orchestrator.monitors.wandb] to log orchestrator metrics as well, "
"or use [monitors.wandb] to configure both at once."
)
if orchestrator.monitors.wandb and not trainer.monitors.wandb:
raise ValueError(
"Orchestrator W&B config is specified, but trainer W&B config is not. "
"This means only orchestrator metrics will be logged. Please specify [trainer.monitors.wandb] to log trainer metrics as well, "
"or use [monitors.wandb] to configure both at once."
)
if trainer.monitors.wandb and orchestrator.monitors.wandb:
if trainer.monitors.wandb.project != orchestrator.monitors.wandb.project:
raise ValueError(
f"Trainer W&B project ({trainer.monitors.wandb.project}) and orchestrator W&B project ({orchestrator.monitors.wandb.project}) are not the same. Please specify the same W&B project for both."
)
def validate_shared_max_steps(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.max_steps != orchestrator.max_steps:
raise ValueError(
f"Trainer max steps ({trainer.max_steps}) and orchestrator max steps ({orchestrator.max_steps}) are not the same. Please specify the same max steps for both."
)
def validate_shared_seq_len(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.model.seq_len < orchestrator.seq_len:
raise ValueError(
f"Trainer model seq_len ({trainer.model.seq_len}) must be >= orchestrator seq_len ({orchestrator.seq_len}). "
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
)
def validate_shared_tokenizer(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
# Validate chat_template is consistent across all components.
# We only check chat_template (not name/trust_remote_code) because those
# are auto-derived from model names which may legitimately differ (e.g.
# when inference uses an FP8 quantized variant of the same model).
if trainer.tokenizer.chat_template != orchestrator.tokenizer.chat_template:
raise ValueError(
f"Trainer chat_template ({trainer.tokenizer.chat_template!r}) and orchestrator "
f"chat_template ({orchestrator.tokenizer.chat_template!r}) do not match. "
f"Use the shared [tokenizer] config to set chat_template for both."
)
if inference is not None:
if trainer.tokenizer.chat_template != inference.vllm.chat_template:
raise ValueError(
f"Inference chat_template ({inference.vllm.chat_template!r}) does not match "
f"the shared tokenizer chat_template ({trainer.tokenizer.chat_template!r}). "
f"Use the shared [tokenizer] config to set chat_template for all components."
)
+9
View File
@@ -59,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'",
@@ -94,6 +96,9 @@ 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 = [
@@ -107,6 +112,7 @@ all = [
"prime-rl[sonic-moe]",
"prime-rl[flash-attn-3]",
"prime-rl[flash-attn-cute]",
"prime-rl[flash-mla]",
]
[dependency-groups]
@@ -246,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 }
@@ -286,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
+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()
@@ -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,
)
+10 -13
View File
@@ -55,19 +55,16 @@ class CheckpointManager:
raise FileNotFoundError(f"Orchestrator checkpoint not found at {state_file}")
get_logger().debug(f"Loading checkpoint from {state_file}")
start = time.perf_counter()
if self.config.skip_progress:
get_logger().info("Skipping progress and train source loading from checkpoint")
else:
with open(state_file, "rb") as f:
state = torch.load(f, weights_only=False)
saved: Progress = state["progress"]
for key, value in asdict(saved).items():
if hasattr(progress, key):
setattr(progress, key, value)
train_source.load_state_dict(state["train_source"])
for name in state["train_source"]["envs"]:
if name in train_source.curricula:
get_logger().info(f"Resumed curriculum state for env {name}")
with open(state_file, "rb") as f:
state = torch.load(f, weights_only=False)
saved: Progress = state["progress"]
for key, value in asdict(saved).items():
if hasattr(progress, key):
setattr(progress, key, value)
train_source.load_state_dict(state["train_source"])
for name in state["train_source"]["envs"]:
if name in train_source.curricula:
get_logger().info(f"Resumed curriculum state for env {name}")
get_logger().debug(f"Orchestrator checkpoint loaded in {format_time(time.perf_counter() - start)}")
+2 -3
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,7 +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.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.train_sink import TrainSink
from prime_rl.orchestrator.train_source import TrainSource
@@ -242,8 +242,7 @@ class Orchestrator:
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
# trainer even when ``ckpt.skip_progress`` leaves the counter unrestored. The curricula
# themselves are restored below, once the envs are loaded.
# trainer. The curricula themselves are restored below, once the envs are loaded.
if self.resume_step is not None:
self.progress.step = self.resume_step + 1
get_logger().info(f"Resuming from step {self.resume_step}")
-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,
)
+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
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
@@ -41,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"),
)
@@ -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)
+1 -9
View File
@@ -3,7 +3,7 @@ import torch.distributed as dist
from dion import Muon
from torch import nn
from torch.distributed.device_mesh import DeviceMesh
from torch.optim import SGD, AdamW, Optimizer
from torch.optim import AdamW, Optimizer
from prime_rl.configs.trainer import OptimizerConfig, OptimizerInBackwardOffloadConfig
from prime_rl.trainer.models.fusions import get_model_packed_parameters
@@ -117,14 +117,6 @@ def _create_optimizer(
# param at load time, mismatching the saved state). Muon filters internally below.
trainable_params = [p for _, p in named_params if p.requires_grad]
match config.type:
case "sgd":
return SGD(
params=trainable_params,
lr=lr,
weight_decay=config.weight_decay,
momentum=config.momentum,
nesterov=config.nesterov,
)
case "adamw":
return AdamW(
params=trainable_params,
+2 -3
View File
@@ -210,13 +210,12 @@ def train(config: SFTConfig):
model,
[optimizer],
scheduler if not skip.skip_scheduler else None,
progress if not skip.skip_progress else None,
progress,
dataloader=dataloader if not skip.skip_dataloader else None,
path=resume_dir / "trainer" if resume_dir is not None else None,
)
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
if not skip.skip_progress:
progress.step += 1
progress.step += 1
# This redundant setup is necessary because loading the optimizer's state has side effects on the scheduler state dict
if skip.skip_scheduler:
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
+2 -3
View File
@@ -354,13 +354,12 @@ def test_full_optimizer_offload_disables_gradient_clipping(config_cls):
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
@pytest.mark.parametrize("optimizer_type", ["sgd", "muon"])
def test_full_optimizer_offload_requires_supported_optimizer(config_cls, optimizer_type):
def test_full_optimizer_offload_requires_supported_optimizer(config_cls):
with pytest.raises(ValidationError, match="Full optimizer offload only supports AdamW and SignSGD"):
config_cls.model_validate(
{
"model": {"optim_cpu_offload": False, "full_offload": True},
"optim": {"type": optimizer_type, "max_norm": None},
"optim": {"type": "muon", "max_norm": None},
}
)
Generated
+41 -19
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]]
@@ -4983,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'" },
@@ -5032,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'" },
@@ -5039,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" },
@@ -5094,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" },
@@ -5103,6 +5123,7 @@ requires-dist = [
{ name = "nixl", marker = "sys_platform == 'linux' and extra == 'disagg'" },
{ 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.11.0" },
@@ -5115,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'" },
@@ -5154,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 = [