Compare commits

..
569 changed files with 31754 additions and 58965 deletions
-1
View File
@@ -1 +0,0 @@
../skills
-11
View File
@@ -1,11 +0,0 @@
# .git stays: docker-editable-pretend-versions.sh reads .git/modules via the bind mount.
outputs
**/.venv
**/__pycache__
**/*.py[cod]
**/.pytest_cache
**/.ruff_cache
**/.mypy_cache
.claude
.vscode
*.ipynb
+5 -5
View File
@@ -146,7 +146,7 @@ jobs:
id: artifact
run: echo "name=benchmark-${{ matrix.runner }}-$(echo '${{ matrix.model }}' | sed 's/\//--/')-${{ matrix.type }}-${{ matrix.lora_rank || 'full' }}-${{ matrix.num_gpus }}gpu-${{ matrix.ac }}-${{ matrix.attention }}-${{ matrix.seq_len }}-cp${{ matrix.cp }}-ep${{ matrix.ep }}" >> "$GITHUB_OUTPUT"
- name: Upload benchmark result
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v5
if: always()
with:
name: ${{ steps.artifact.outputs.name }}
@@ -163,16 +163,16 @@ jobs:
pull-requests: write
steps:
- name: Checkout repository # We can't use the image because then no git
uses: actions/checkout@v7
uses: actions/checkout@v5
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras
run: uv sync
- name: Download all benchmark artifacts
uses: actions/download-artifact@v8
uses: actions/download-artifact@v6
with:
path: /tmp/benchmark_artifacts
pattern: benchmark-*
+27 -73
View File
@@ -1,6 +1,8 @@
name: Build Image (ghcr)
on:
release:
types: [published]
workflow_dispatch:
inputs:
ref:
@@ -25,51 +27,17 @@ on:
env:
REGISTRY: ghcr.io
IMAGE_NAME: primeintellect-ai/prime-rl
BUILD_REF: ${{ inputs.ref || github.ref_name }}
BUILD_TAG: ${{ inputs.tag || '' }}
BUILD_REF: ${{ github.event.release.tag_name || inputs.ref || github.ref_name }}
BUILD_TAG: ${{ github.event.release.tag_name || inputs.tag || '' }}
BUILD_PLATFORMS: ${{ inputs.platforms || 'both' }}
concurrency:
group: build-image-${{ inputs.tag || inputs.ref || github.ref_name }}
group: build-image-${{ github.event.release.tag_name || inputs.tag || inputs.ref || github.ref_name }}
cancel-in-progress: false
jobs:
authorize:
name: Authorize dispatcher
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Require maintain or admin
# Gate MANUAL dispatches only; other events (e.g. release) are
# already privileged and pass through. Guard the step, not the job —
# a skipped job would skip `prepare` via `needs: authorize`.
if: github.event_name == 'workflow_dispatch'
env:
GH_TOKEN: ${{ github.token }}
ACTOR: ${{ github.triggering_actor }}
REPO: ${{ github.repository }}
run: |
# Restricted to repo members with maintain or admin. Automated
# in-repo dispatches (devx_tag dev-image builds, the release build)
# run as github-actions[bot] via GITHUB_TOKEN — allow those through.
if [ "$ACTOR" = "github-actions[bot]" ]; then
echo "Dispatcher is repo automation ($ACTOR); allowed."
exit 0
fi
role=$(gh api "repos/${REPO}/collaborators/${ACTOR}/permission" --jq '.role_name' 2>/dev/null || true)
echo "Dispatcher $ACTOR has repo role: ${role:-<none>}"
case "$role" in
admin|maintain)
echo "Authorized." ;;
*)
echo "::error::$ACTOR (role: ${role:-none}) is not allowed to trigger image builds; requires maintain or admin." >&2
exit 1 ;;
esac
prepare:
name: Prepare build
needs: authorize
runs-on: ubuntu-latest
permissions:
contents: read
@@ -103,7 +71,7 @@ jobs:
esac
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v5
with:
ref: ${{ env.BUILD_REF }}
fetch-depth: 0
@@ -115,30 +83,27 @@ jobs:
INPUT_TAG: ${{ env.BUILD_TAG }}
PLATFORMS: ${{ env.BUILD_PLATFORMS }}
run: |
case "$INPUT_REF" in
main|v[0-9]*|*.dev[0-9]*) ;;
*)
echo "ref '${INPUT_REF}' not allowed for ghcr publish (must be main, v*, or *.dev*)" >&2
exit 1
;;
esac
if [ -n "$INPUT_TAG" ] && [ "$INPUT_TAG" != "$INPUT_REF" ] && [ "$INPUT_REF" != "main" ]; then
echo "custom 'tag' that differs from 'ref' is only allowed when ref=main; got ref='${INPUT_REF}' tag='${INPUT_TAG}'" >&2
exit 1
fi
sanitize() {
echo "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//' | cut -c1-50
}
# A ref that is exactly a git tag builds under that tag verbatim;
# any other ref (branch / arbitrary commit) is prefixed with
# `git describe` so the tag carries the nearest release, commit
# distance and short sha (e.g. v0.7.0-42-g1a2b3c4d5-fix-my-branch)
# and can't collide with a clean release tag.
if [ -n "$INPUT_TAG" ]; then
tag=$(sanitize "$INPUT_TAG")
elif tag=$(git describe --tags --exact-match 2>/dev/null); then
:
else
tag="$(git describe --tags --always)-$(sanitize "$INPUT_REF")"
raw_tag="$INPUT_TAG"
if [ -z "$raw_tag" ]; then
raw_tag="$INPUT_REF"
fi
tag=$(echo "$raw_tag" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | cut -c1-50 | sed 's/^-//;s/-$//')
if [ -z "$tag" ]; then
echo "Could not derive a valid image tag from ref='${INPUT_REF}' tag='${INPUT_TAG}'." >&2
echo "Could not derive a valid image tag from '${raw_tag}'." >&2
exit 1
fi
@@ -161,16 +126,10 @@ jobs:
steps:
- name: Remove unnecessary packages
run: |
# Deleting the preinstalled toolchains costs ~70s; skip unless disk is tight.
avail_gb=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
if [ "${avail_gb:-0}" -lt 80 ]; then
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
else
echo "Skipping cleanup: ${avail_gb}G available on /"
fi
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v5
with:
ref: ${{ needs.prepare.outputs.ref }}
fetch-depth: 0
@@ -180,7 +139,7 @@ jobs:
run: |
if [ -f .gitmodules ]; then
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/pydantic-config deps/verifiers deps/renderers deps/prime-envs
git submodule update --init --recursive -- deps/pydantic-config deps/verifiers deps/renderers deps/research-environments
fi
- name: Log in to GitHub Container Registry
@@ -198,16 +157,11 @@ jobs:
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.
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
# This experiment tag derives from the immutable current-main arm64
# image and only bakes the pinned NVFP4 runtime. Main still uses
# Dockerfile.cuda; this workflow change exists solely on the tag.
file: ./Dockerfile.nvfp4-e2e-overlay
push: true
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
+6 -6
View File
@@ -12,20 +12,20 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v5
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
run: uv sync --extra flash-attn --all-packages --locked
- name: Run tests
env:
USERNAME_CI: CI_RUNNER
@@ -48,9 +48,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v5
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Create next .dev tag from latest release
uses: actions/github-script@v9
uses: actions/github-script@v8
with:
script: |
const { owner, repo } = context.repo;
+9 -17
View File
@@ -26,15 +26,15 @@ jobs:
apt-get install -y git
git config --global --add safe.directory "$GITHUB_WORKSPACE"
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v5
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
uses: astral-sh/setup-uv@v7
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run unit tests
@@ -84,12 +84,12 @@ jobs:
- test: reverse_text_moe
runner: vm
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: reverse_text_multi_run
runner: 4xa6000
pytest_args: "tests/integration/test_reverse_text_multi_run.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py"
- test: gsm8k_eval
runner: vm
pytest_args: "tests/integration/test_gsm8k_eval.py"
steps:
- name: Install Git
run: |
@@ -97,15 +97,15 @@ jobs:
apt-get install -y git
git config --global --add safe.directory "$GITHUB_WORKSPACE"
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v5
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
uses: astral-sh/setup-uv@v7
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run integration tests
@@ -121,11 +121,3 @@ jobs:
PYTEST_OUTPUT_DIR: /tmp/outputs
VLLM_WORKER_MULTIPROC_METHOD: spawn
run: uv run pytest -vvs ${{ matrix.pytest_args }}
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: ${{ matrix.test }}-logs
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
-197
View File
@@ -1,197 +0,0 @@
name: Nightly FFT
on:
# Allow to manually trigger the workflow
workflow_dispatch:
inputs:
config_file:
description: "Full-FT config to dispatch (e.g. configs/ci/nightly-fft/wordle.toml). Leave empty to run all."
required: false
default: ""
image_tag:
description: "prime-rl image tag to pin (e.g. v0.7.1.dev58). Leave empty to auto-resolve the newest v*.dev* with a published manifest."
required: false
default: ""
# Scheduled run at 3AM PST (11AM UTC)
schedule:
- cron: "0 11 * * *"
permissions:
contents: read
packages: read
jobs:
discover-configs:
name: Discover configs
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.build-matrix.outputs.matrix }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
submodules: false
- name: Build matrix from nightly FFT configs
id: build-matrix
run: |
# Find all nightly full-finetune configs
files=$(ls configs/ci/nightly-fft/*.toml)
# Filter to specific config if provided in workflow_dispatch
if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ -n "${{ github.event.inputs.config_file }}" ]; then
filtered=$(echo "$files" | grep -F "${{ github.event.inputs.config_file }}" || true)
if [ -z "$filtered" ]; then
echo "Error: Config file '${{ github.event.inputs.config_file }}' not found"
exit 1
fi
files="$filtered"
fi
echo "Discovered nightly FFT configs:"
echo "$files"
# Build JSON of the form: { "config_file": ["configs/ci/nightly-fft/foo.toml", ...] }
json=$(printf '%s\n' "$files" | jq -R . | jq -sc '{config_file: .}')
echo "matrix=$json" >> "$GITHUB_OUTPUT"
dispatch-run:
name: Dispatch hosted FFT run
needs: discover-configs
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.discover-configs.outputs.matrix) }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
submodules: false
- name: Resolve prime-rl image tag
id: image
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Pass the dispatch input through env so a malicious value
# cannot break out of shell context via $(...) or embedded
# quotes — the GitHub expression is substituted before Bash
# parses the script.
REQUESTED_IMAGE_TAG: ${{ github.event.inputs.image_tag }}
run: |
# If workflow_dispatch passed an explicit image_tag, validate
# it as a Docker/OCI tag, verify its manifest is pullable,
# and use it as-is (skip resolution).
requested="$REQUESTED_IMAGE_TAG"
if [ -n "$requested" ]; then
# OCI/Docker tag charset: [A-Za-z0-9._-], max 128, no
# leading '.' or '-'. Reject anything else before it
# reaches curl or GITHUB_OUTPUT.
if ! printf '%s' "$requested" | grep -Eq '^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$'; then
echo "Invalid image_tag: only [A-Za-z0-9._-] allowed, max 128 chars, no leading '.' or '-'." >&2
exit 1
fi
registry_token=$(curl -fsSL \
"https://ghcr.io/token?scope=repository:primeintellect-ai/prime-rl:pull" \
| jq -r .token)
code=$(curl -sS -o /dev/null -w '%{http_code}' \
-H "Authorization: Bearer $registry_token" \
-H 'Accept: application/vnd.oci.image.index.v1+json' \
-H 'Accept: application/vnd.docker.distribution.manifest.list.v2+json' \
"https://ghcr.io/v2/primeintellect-ai/prime-rl/manifests/$requested")
if [ "$code" != "200" ]; then
echo "Requested image_tag '$requested' has no published manifest (HTTP $code)." >&2
exit 1
fi
echo "Using pinned prime-rl image tag: $requested"
echo "tag=$requested" >> "$GITHUB_OUTPUT"
exit 0
fi
# No dispatch input: auto-resolve the newest v*.dev* tag on
# GHCR (the point of a nightly is to catch regressions on
# tip-of-main). The GHCR versions API can list a tag before
# its manifest is actually pullable (build in-flight, or
# manifest step didn't finish), so pull the top N candidates
# and verify each with a manifest HEAD via the anonymous
# registry token flow; take the newest one that resolves.
# Disable pipefail locally: `grep` may exit 1 on no matches
# (empty tag list) and `head` may SIGPIPE `sort` after
# reading its 10 lines. Both would abort the step before the
# explicit no-candidates guard below runs.
set +o pipefail
candidates=$(gh api --paginate \
"/orgs/primeintellect-ai/packages/container/prime-rl/versions" \
--jq '.[].metadata.container.tags[]' \
| grep -E '^v[0-9]+\.[0-9]+\.[0-9]+\.dev[0-9]+$' \
| sort -Vru | head -n 10)
set -o pipefail
if [ -z "$candidates" ]; then
echo "No v*.dev* tag listed on GHCR." >&2
exit 1
fi
registry_token=$(curl -fsSL \
"https://ghcr.io/token?scope=repository:primeintellect-ai/prime-rl:pull" \
| jq -r .token)
tag=""
for cand in $candidates; do
code=$(curl -sS -o /dev/null -w '%{http_code}' \
-H "Authorization: Bearer $registry_token" \
-H 'Accept: application/vnd.oci.image.index.v1+json' \
-H 'Accept: application/vnd.docker.distribution.manifest.list.v2+json' \
"https://ghcr.io/v2/primeintellect-ai/prime-rl/manifests/$cand")
if [ "$code" = "200" ]; then
tag="$cand"
break
fi
echo "Skip $cand — manifest HEAD returned $code"
done
if [ -z "$tag" ]; then
echo "None of the top v*.dev* tags have a published manifest." >&2
exit 1
fi
echo "Latest published prime-rl image tag on GHCR: $tag"
echo "tag=$tag" >> "$GITHUB_OUTPUT"
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
- name: Install prime CLI (latest)
run: uv tool install prime
- name: Dispatch run
env:
PRIME_API_KEY: ${{ secrets.PRIME_FFT_API_KEY }}
PRIME_TEAM_ID: ${{ secrets.PRIME_FFT_TEAM_ID }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
HF_TOKEN: ${{ secrets.HF_TOKEN }}
run: |
echo "Dispatching config: ${{ matrix.config_file }}"
echo "Image tag: ${{ steps.image.outputs.tag }}"
# Tag the RFTRun so it's identifiable on the platform as
# coming from this workflow. Injected here rather than in
# the checked-in toml because a top-level `name` field
# breaks tests/unit/test_configs.py::test_load_configs
# (RLConfig has no top-level name).
config_base=$(basename "${{ matrix.config_file }}" .toml)
run_name="nightly-${config_base}-$(date -u +%Y-%m-%d)-${{ github.run_id }}"
dispatch_cfg=$(mktemp --suffix=.toml)
printf 'name = "%s"\n\n' "$run_name" > "$dispatch_cfg"
cat "${{ matrix.config_file }}" >> "$dispatch_cfg"
echo "Dispatched run name: $run_name"
# Forward WANDB_API_KEY / HF_TOKEN into the hosted payload:
# the full-FT dispatch path (`prime train`) only picks up
# secrets that were explicitly collected via `-e` / `--env-file`,
# not ambient env, so the workflow env: block alone is not
# enough to reach the hosted trainer/orchestrator pods.
prime train "$dispatch_cfg" \
--image-tag "${{ steps.image.outputs.tag }}" \
-e WANDB_API_KEY \
-e HF_TOKEN \
--yes --output json
+4 -4
View File
@@ -23,7 +23,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v5
with:
submodules: false
@@ -73,15 +73,15 @@ jobs:
apt-get install -y git
git config --global --add safe.directory "$GITHUB_WORKSPACE"
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v5
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
uses: astral-sh/setup-uv@v7
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
+3 -3
View File
@@ -15,17 +15,17 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v5
# Submodules are excluded from ruff via pyproject.toml; no need to fetch them.
with:
submodules: false
- name: Run ruff
uses: astral-sh/ruff-action@v4.1.0
with:
version: "0.15.14"
version: "0.13.0"
args: "check --config=pyproject.toml"
- name: Run ruff format (check)
uses: astral-sh/ruff-action@v4.1.0
with:
version: "0.15.14"
version: "0.13.0"
args: "format --check --config=pyproject.toml"
+6 -4
View File
@@ -1,16 +1,18 @@
name: Sync Docs to Public Docs
on:
release:
types:
- published
push:
branches:
- main
paths:
- 'docs/**'
workflow_dispatch:
jobs:
trigger-docs-sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v5
- name: Validate mint.json pages exist
run: |
+7 -39
View File
@@ -29,7 +29,7 @@ jobs:
version: ${{ steps.tag.outputs.version }}
steps:
- name: Checkout main
uses: actions/checkout@v7
uses: actions/checkout@v5
with:
fetch-depth: 0
@@ -119,8 +119,6 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
steps:
- name: Publish draft release
env:
@@ -129,32 +127,22 @@ jobs:
run: |
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
# Publishing runs as GITHUB_TOKEN, whose events don't retrigger
# workflows, so dispatch the image build explicitly.
- name: Trigger image build for the release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.auto-tag-on-main.outputs.tag }}
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
resolve-release:
tag-and-release:
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
outputs:
tag: ${{ steps.release.outputs.tag }}
version: ${{ steps.release.outputs.version }}
permissions:
contents: write
steps:
- name: Checkout tagged release (dispatch)
if: github.event_name == 'workflow_dispatch'
uses: actions/checkout@v7
uses: actions/checkout@v5
with:
fetch-depth: 0
ref: refs/tags/${{ inputs.tag }}
- name: Checkout tagged release (push)
if: github.event_name != 'workflow_dispatch'
uses: actions/checkout@v7
uses: actions/checkout@v5
with:
fetch-depth: 0
@@ -206,19 +194,10 @@ jobs:
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
publish-release:
needs: resolve-release
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
steps:
- name: Publish draft release
id: publish
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.resolve-release.outputs.tag }}
TAG: ${{ steps.release.outputs.tag }}
run: |
STATE=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft --jq '.isDraft' 2>/dev/null || echo "missing")
if [ "$STATE" = "missing" ]; then
@@ -228,17 +207,6 @@ jobs:
fi
if [ "$STATE" = "false" ]; then
echo "Release $TAG is already published; nothing to do."
echo "published=false" >> "$GITHUB_OUTPUT"
exit 0
fi
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
echo "published=true" >> "$GITHUB_OUTPUT"
# Skipped when the release was already published (no rebuild needed).
- name: Trigger image build for the release
if: steps.publish.outputs.published == 'true'
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.resolve-release.outputs.tag }}
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
+18 -3
View File
@@ -1,13 +1,26 @@
.vscode/*
.claude/scheduled_tasks.lock
.claude/worktrees/
.codex/
*.ipynb
*.jsonl
configs/endpoints.py
# Run artifacts
outputs/
# Artifacts
**/slurm
!src/prime_rl/slurm
!examples/slurm
!docs/slurm.md
**/torchrun
**/weights
**/checkpoints
**/broadcasts
**/rollouts
**/logs
**/wandb
**/evals
**/run_*/
!configs/**/evals
final_summary.json
.pydantic_config
.chroma_db
deps/nixl_*
@@ -188,4 +201,6 @@ cython_debug/
debug_I2_zero_band
.idea
outputs/
third_party/
+3 -6
View File
@@ -4,12 +4,9 @@
[submodule "renderers"]
path = deps/renderers
url = git@github.com:PrimeIntellect-ai/renderers.git
[submodule "prime-envs"]
path = deps/prime-envs
url = git@github.com:PrimeIntellect-ai/prime-envs.git
[submodule "research-environments"]
path = deps/research-environments
url = git@github.com:PrimeIntellect-ai/research-environments.git
[submodule "pydantic-config"]
path = deps/pydantic-config
url = https://github.com/PrimeIntellect-ai/pydantic-config
[submodule "prime-kernels"]
path = deps/prime-kernels
url = https://github.com/PrimeIntellect-ai/prime-kernels
+2 -4
View File
@@ -5,7 +5,6 @@
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
- **Don't touch `optimization_dtype` / `reduce_dtype`**: never change these model config fields (or their defaults in `trainer.py`) unless the user explicitly asks. They're load-bearing numerical knobs — flipping bfloat16/float32 silently changes training dynamics.
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
- **Context parallelism**: a module that needs CP state holds a `CPContext` (`models/base.py`) as `self.cp_context`, defaulting to `CPContext()`, which is the non-CP case; `PreTrainedModelPrimeRL` supplies that default. `setup_context_parallel` in `utils/cp.py` builds one `CPContext` and assigns it to every module that has the field, so each module holds the same frozen object.
- **Zen of Python**: remember the Zen of Python when writing code.
```
Beautiful is better than ugly.
@@ -32,7 +31,6 @@ Namespaces are one honking great idea -- let's do more of those!
## Running code
- **Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
- **Tools vs entrypoints**: standalone scripts in `tools/` use plain argparse with positional args; `[project.scripts]` entrypoints use pydantic-config (`@ file.toml` + dotted CLI overrides).
- **Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
@@ -43,9 +41,9 @@ Namespaces are one honking great idea -- let's do more of those!
## Skills
Skills live in `skills/` and are symlinked to `.claude/skills/` (Claude Code) and `.agents/skills/` (Codex). They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs).
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs). When you make changes to the codebase, check if any skills need to be updated to stay accurate.
If a repository skill could benefit from an update, suggest the specific change, explain why it would help, and ask the user for approval before making it. Wait for approval before creating, modifying, renaming, or deleting skills, including their supporting files and symlinks. If the user has already explicitly requested or approved the skill change, proceed without asking again. Requests to change code, fix workflows, update documentation, or open a PR do not implicitly authorize skill changes. You may read and follow skills without changing them.
You are responsible for maintaining the skills folder. When a workflow fails and you fix it – whether with help from the user or through trial and error – you must update the skills to make implicit knowledge explicit. You are also responsible for keeping the skills up to date whenever you or anyone else modifies the code.
## Testing
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+44 -111
View File
@@ -1,21 +1,7 @@
# 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
# 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
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:12.8.1-cudnn-devel-ubuntu24.04 AS builder
LABEL maintainer="prime intellect"
LABEL repository="prime-rl"
@@ -86,24 +72,11 @@ ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
# the runtime stage's `COPY /app`
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
# Install Python dependencies
# Install Python dependencies (The gradual copies help with caching)
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).
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
@@ -115,13 +88,14 @@ 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
COPY scripts/patch-vllm-nvfp4-writable-scales.py /app/scripts/patch-vllm-nvfp4-writable-scales.py
# 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 \
RUN --mount=type=cache,target=/app/.cache/uv \
--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 \
&& \
@@ -133,44 +107,35 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
&& \
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 \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --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")]'
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]' \
&& \
/app/.venv/bin/python /app/scripts/patch-vllm-nvfp4-writable-scales.py
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
# ships its own UCX which segfaults on prefill→decode KV transfer (#2883);
# rebuilding against our UCX is the documented fix. The rename is required: an
# unrenamed source build is `nixl_cu12`, and the `nixl` shim imports nixl_cu13
# (the PyPI wheel) first, so the fix would silently not apply. Libraries carry
# RUNPATH=/opt/ucx/lib, so no LD_LIBRARY_PATH is needed at runtime.
# Opt out via `--build-arg INCLUDE_NIXL_FROM_SOURCE=0`.
#
# NIXL's [build-system] requires are unpinned, so pip's build isolation picks up
# new backends as they are released. meson-python 0.22.0 stopped keeping Meson's
# build RPATH in wheel libraries, which dropped RUNPATH=/opt/ucx/lib and failed
# the linkage check below on every build. Pin the validated backend.
ARG INCLUDE_NIXL_FROM_SOURCE=1
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
# (#2883); rebuilding against our UCX is the documented fix. Only needed for
# the disaggregated P/D path — default off so training-only / single-node
# inference builds are unaffected. Enable via `--build-arg INCLUDE_NIXL_FROM_SOURCE=1`.
ARG INCLUDE_NIXL_FROM_SOURCE=0
ARG NIXL_VERSION=0.10.1
RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
VIRTUAL_ENV=/app/.venv uv pip install pip \
&& git clone --depth 1 --branch ${NIXL_VERSION} https://github.com/ai-dynamo/nixl.git /tmp/nixl \
&& cd /tmp/nixl \
&& uv run --no-project --with tomlkit python contrib/tomlutil.py --wheel-name nixl-cu13 pyproject.toml \
&& printf 'meson-python==0.21.1\n' > /tmp/nixl-build-constraints.txt \
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/tmp/nixl-whl \
--build-constraint /tmp/nixl-build-constraints.txt \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /tmp/nixl-whl/nixl_cu13-*.whl \
&& PLUGIN=/app/.venv/lib/python3.12/site-packages/.nixl_cu13.mesonpy.libs/plugins/libplugin_UCX.so \
&& if ! ldd "$PLUGIN" | grep -q /opt/ucx/lib/libucp.so; then \
echo "ERROR: $PLUGIN does not link /opt/ucx/lib. RUNPATH and ldd output:" >&2; \
readelf -d "$PLUGIN" | grep -E 'RUNPATH|RPATH' >&2 || true; \
ldd "$PLUGIN" >&2; \
exit 1; \
fi \
&& rm -rf /tmp/nixl /tmp/nixl-whl /tmp/nixl-build-constraints.txt; \
LD_LIBRARY_PATH=/opt/ucx/lib:/opt/ucx/lib/ucx \
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/app/deps \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu12-*.whl \
&& rm -rf /tmp/nixl /app/deps/nixl_cu12-*.whl; \
fi
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
ARG TARGETARCH
COPY scripts/docker-arm64-post-install.sh /app/scripts/docker-arm64-post-install.sh
RUN if [ "$TARGETARCH" = "arm64" ]; then /app/scripts/docker-arm64-post-install.sh; fi
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
# COPY ships only the trimmed result (~1.5 GB) instead of the full ~6.6 GB. Drops the math
# runtime libs (cublas/cusparse/cufft/cusolver/curand/npp/nvjpeg) and big static .a
@@ -178,14 +143,19 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
# (uses pinned nvidia-* wheels) needs them. Keeps nvcc/nvvm/ptxas + headers +
# libcudart/libnvrtc/libcudadevrt for JIT compile+link.
FROM builder AS cuda-trim
RUN find /usr/local/cuda-13.0/targets/*/lib \
RUN find /usr/local/cuda-12.8/targets/*/lib \
\( -name 'libcublas*' -o -name 'libcusparse*' -o -name 'libcufft*' \
-o -name 'libcusolver*' -o -name 'libcurand*' -o -name 'libnpp*' \
-o -name 'libnvjpeg*' -o -name 'libnvblas*' \) -delete \
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
&& find /usr/local/cuda-12.8 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
# CUDA 13 runtime libs source
FROM nvidia/cuda:13.0.1-runtime-ubuntu24.04 AS cuda13
RUN mkdir -p /cu13 && cp -d $(find /usr/local \
-name 'libcudart.so.13*' -o -name 'libnvrtc.so.13*' -o -name 'libnvrtc-builtins.so.13*') /cu13/
# Runtime image
FROM nvidia/cuda:13.0.1-base-ubuntu24.04
FROM nvidia/cuda:12.8.1-base-ubuntu24.04
ENV DEBIAN_FRONTEND=noninteractive
@@ -215,43 +185,24 @@ RUN apt-get update && apt-get install -y \
libibverbs1 \
ibverbs-providers \
librdmacm1 \
libhwloc15 \
&& ln -sf /usr/bin/python3.12 /usr/local/bin/python \
&& apt-get clean autoclean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# AWS EFA userspace stack: libfabric + the aws-ofi-nccl NCCL net plugin,
# installed as one version-matched unit via AWS's official installer rather
# than picking versions by hand. Do not substitute a host-mounted copy of
# these libraries instead of building them in -- symbol-version mismatches
# between a host's rdma-core and a container's can silently break the NCCL
# plugin. Run directly in this stage (not a separate one COPY'd in after):
# the installer's own apt-get/dpkg step upgrades system rdma-core packages
# (libibverbs, ibverbs-providers, librdmacm) in place to versions libfabric
# actually links against -- copying only /opt/amazon out of an isolated
# stage leaves that system-wide upgrade behind, so libfabric ends up paired
# with whatever older rdma-core this image's own apt install pulled in and
# fails to load (symbol version mismatch on libefa.so.1). --skip-kmod:
# containers share the host kernel and must never build/load a kernel
# module themselves; the EFA driver is expected to already be present on
# the host. --skip-limit-conf: ulimits config doesn't apply inside a build.
ARG EFA_INSTALLER_VERSION=1.47.0
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates tar gzip \
&& curl -fsSL "https://efa-installer.amazonaws.com/aws-efa-installer-${EFA_INSTALLER_VERSION}.tar.gz" \
-o /tmp/aws-efa-installer.tar.gz \
&& tar -xzf /tmp/aws-efa-installer.tar.gz -C /tmp \
&& cd /tmp/aws-efa-installer \
&& ./efa_installer.sh -y --skip-kmod --skip-limit-conf \
&& cd / && rm -rf /tmp/aws-efa-installer.tar.gz /tmp/aws-efa-installer \
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/*
# CUDA 13.0 toolkit (TileLang's runtime nvcc JIT)
COPY --from=cuda-trim /usr/local/cuda-13.0 /usr/local/cuda-13.0
RUN ln -sfn /usr/local/cuda-13.0 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
# CUDA 12.8 toolkit (TileLang's runtime nvcc JIT)
COPY --from=cuda-trim /usr/local/cuda-12.8 /usr/local/cuda-12.8
RUN ln -sfn /usr/local/cuda-12.8 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
ENV CUDA_HOME=/usr/local/cuda
ENV PATH="/usr/local/cuda/bin:${PATH}"
# CUDA 13 runtime libs for deep-gemm
COPY --from=cuda13 /cu13/ /opt/cuda13/lib64/
RUN echo /opt/cuda13/lib64 > /etc/ld.so.conf.d/cuda13.conf \
&& ldconfig \
&& ldconfig -p | grep -q libcudart.so.13 \
&& ldconfig -p | grep -q libnvrtc.so.13
ARG USER_ID=1000
ARG GROUP_ID=1000
@@ -269,32 +220,14 @@ RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.
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.
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
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn /app/.venv/lib/python3.12/site-packages/flash_attn
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 the application from the builder
COPY --from=builder --chown=appuser:appuser /app /app
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
# Place executables in the environment at the front of the path
ENV PATH="/app/.venv/bin:$PATH"
ENV UCX_HOME=/opt/ucx
+21
View File
@@ -0,0 +1,21 @@
ARG BASE_IMAGE=ghcr.io/primeintellect-ai/prime-rl@sha256:a86004b9b44d43c8018633283ec0267c3339c0dac0e35a9957f48f0a6b56153c
FROM ${BASE_IMAGE}
USER root
COPY pyproject.toml /app/pyproject.toml
COPY uv.lock /app/uv.lock
COPY scripts/patch-vllm-nvfp4-writable-scales.py /app/scripts/patch-vllm-nvfp4-writable-scales.py
COPY k8s/experiments/run_nvfp4_inference.sh /app/k8s/experiments/run_nvfp4_inference.sh
RUN uv --no-config pip install \
--python /app/.venv/bin/python \
--upgrade \
--no-deps \
'https://wheels.vllm.ai/910cc8543a6907c9cc87c417f8f2420969278bf5/vllm-0.23.1rc1.dev1392%2Bg910cc8543-cp38-abi3-manylinux_2_28_aarch64.whl' \
'https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_python-0.6.15.post1-py3-none-any.whl' \
'https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_cubin-0.6.15.post1-py3-none-any.whl' \
&& /app/.venv/bin/python /app/scripts/patch-vllm-nvfp4-writable-scales.py \
&& /app/.venv/bin/python -c 'from importlib.metadata import version; expected={"vllm":"0.23.1rc1.dev1392+g910cc8543","flashinfer-python":"0.6.15.post1","flashinfer-cubin":"0.6.15.post1"}; actual={name:version(name) for name in expected}; assert actual == expected, (actual, expected)'
USER appuser
+19
View File
@@ -0,0 +1,19 @@
ARG BASE_IMAGE=ghcr.io/primeintellect-ai/prime-rl@sha256:823eea93b07b5adbaaafddacdc00a7d0f7384c65696b952b92ff28b5790af6b7
FROM ${BASE_IMAGE}
USER root
# Keep Prime main and the pinned NVFP4 runtime from the immutable dev2 image.
# This layer only adapts Prime to vLLM's scale-out package move and fixes the
# persistent-cache wrapper; it does not install or compile anything.
COPY --chown=appuser:appuser \
src/prime_rl/inference/vllm/serving_tokens.py \
/app/src/prime_rl/inference/vllm/serving_tokens.py
COPY --chown=appuser:appuser \
src/prime_rl/utils/client.py \
/app/src/prime_rl/utils/client.py
COPY --chown=appuser:appuser \
k8s/experiments/run_nvfp4_inference.sh \
/app/k8s/experiments/run_nvfp4_inference.sh
USER appuser
+40 -12
View File
@@ -38,7 +38,7 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
5. Multi-node deployment with Slurm and Kubernetes support.
6. Multimodal support for VLMs such as Qwen3-VL.
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/).
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.2/).
## Models support
@@ -53,13 +53,15 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | yes | ✅ | ✅ |
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ❌ |
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
| GLM-4 · GLM-4.5 MoE · INTELLECT-3 (`glm4_moe`) | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5-Air`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | yes | ✅ | ✅ |
| GPT-OSS (`gpt_oss`) | `unsloth/gpt-oss-20b-BF16`, … | yes | ✅ | ✅ |
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ✅ | ✅ |
| Other HF causal LMs | Qwen3 dense, Mistral, … (`impl = "hf"`) | varies | ❌ | ✅ |
## Setup
@@ -93,7 +95,7 @@ cd prime-rl
2. Initialize submodules
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
```
3. Install [uv](https://docs.astral.sh/uv/)
@@ -111,6 +113,24 @@ uv sync --all-extras
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
4.1. On aarch64 hosts: build flash-attn from source for your GPU
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`.
```bash
bash scripts/docker-arm64-post-install.sh
```
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`
```bash
uv pip install "flash-attn-3 @ git+https://github.com/Dao-AILab/flash-attention.git@main#subdirectory=hopper" --no-build-isolation
```
</details>
<details>
@@ -137,16 +157,22 @@ uv run python -c "import flash_attn"
uv run sft @ configs/debug/fake/sft.toml
```
4. Check that you can run the inference server (*this requires 1 GPU*)
4. Check that you can run the RL trainer (*this requires 1 GPU*)
```bash
uv run inference --vllm.model Qwen/Qwen3-0.6B
uv run trainer @ configs/debug/fake/rl.toml
```
5. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
5. Check that you can run the inference server (*this requires 1 GPU*)
```bash
uv run rl @ examples/basic/reverse-text/rl.toml
uv run inference --model.name Qwen/Qwen3-0.6B
```
6. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
```bash
uv run rl @ configs/basic/reverse-text/rl.toml
```
</details>
@@ -187,7 +213,10 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
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.
3. [**GLM-5**](examples/advanced/glm-5.3/): Large-scale `GLM-5`/`GLM-5.3` training with P/D disaggregation, the `llm-d` router, and FP8.
3. [**Nemotron-3-Super**](examples/advanced/nemotron-3-super/): Train the `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
4. [**MiniMax-M2.5 SWE**](examples/advanced/minimax-m2.5/): Train `MiniMax-M2.5` on agentic SWE tasks.
5. [**INTELLECT-3.1**](examples/advanced/intellect-3.1/): Reproduce our `INTELLECT-3.1` training run.
6. [**High-throughput GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation, the `llm-d` router, and FP8.
## Docs
@@ -195,11 +224,10 @@ Check out the [docs](docs) directory for in-depth guides on how to use prime-rl.
- [**Overview**](docs/overview.md) - Architecture, install, and a copy-pasteable end-to-end RL run
- [**Configuration**](docs/configuration.md) - TOML composition, CLI overrides, env vars, validation
- [**Training**](docs/training.md) - RL, SFT, checkpointing, observability, rules of thumb
- [**Eval**](docs/eval.md) - Standalone evals against any inference server, online evals, resume, platform upload
- [**Training**](docs/training.md) - RL, SFT, evals, checkpointing, observability, rules of thumb
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA, multi-tenant training
- [**Development**](docs/development.md) - Test suite, pre-commit hooks, adding a new model
## Contributing
@@ -6,46 +6,43 @@
"lora_rank": null,
"seq_len": 65536,
"ac": "Recompute",
"selective_targets": null,
"attention": "flash_attention_2",
"output": "benchmarks/baselines/benchmark-1xa6000-Qwen--Qwen3-0.6B-rl-full-1gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
"output": "benchmark_result.json",
"dry_run": false,
"timeout": 600,
"max_steps": 4,
"timeout": 1500,
"micro_batches": 2,
"ep": 1,
"cp": 1,
"fused_lm_head_token_chunk_size": 1024,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "7007d2ef",
"timestamp": "2026-08-29T02:35:31.543870+00:00",
"commit_sha": "c88d08fdf",
"timestamp": "2026-06-24T22:50:40+00:00",
"success": true,
"error_reason": null,
"time_taken": 295.5118532651104
"time_taken": 276.12556480802596
},
"metrics": {
"mfu": {
"mean": 16.701924322664684,
"std": 0.0999595293790186,
"min": 16.586575698092034,
"max": 16.763194274056005
"mean": 20.802552047875178,
"std": 0.16199364988631793,
"min": 20.664358307416567,
"max": 20.98082222151257
},
"throughput": {
"mean": 1994.6806480062144,
"std": 11.937986005933869,
"min": 1980.9047701633856,
"max": 2001.998007610024
"mean": 2484.411208996455,
"std": 19.346608946709658,
"min": 2467.9069802355616,
"max": 2505.7016937694384
},
"step_time": {
"mean": 65.74198961785685,
"std": 0.3962098986964774,
"min": 65.49867434287444,
"max": 66.19917749473825
"mean": 52.79691480938345,
"std": 0.4071756223542672,
"min": 52.35017399210483,
"max": 53.14720633160323
},
"peak_memory": {
"gib": 11.591145833333334,
"pct": 24.45296844104
"gib": 11.728515625,
"pct": 24.742767157118376
}
}
}
}
@@ -6,46 +6,43 @@
"lora_rank": null,
"seq_len": 65536,
"ac": "Recompute",
"selective_targets": null,
"attention": "flash_attention_2",
"output": "benchmarks/baselines/benchmark-4xa6000-Qwen--Qwen3-0.6B-rl-full-4gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
"output": "benchmark_result.json",
"dry_run": false,
"timeout": 600,
"max_steps": 4,
"timeout": 1500,
"micro_batches": 2,
"ep": 1,
"cp": 1,
"fused_lm_head_token_chunk_size": 1024,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "7007d2ef",
"timestamp": "2026-08-29T02:28:40.728120+00:00",
"commit_sha": "c88d08fdf",
"timestamp": "2026-06-24T22:55:54+00:00",
"success": true,
"error_reason": null,
"time_taken": 317.33935201819986
"time_taken": 291.91085167229176
},
"metrics": {
"mfu": {
"mean": 15.880248465863398,
"std": 0.005915779562921215,
"min": 15.873443653590638,
"max": 15.884167926432548
"mean": 17.217465998339005,
"std": 0.02905058130694137,
"min": 17.19503698271855,
"max": 17.250282374540514
},
"throughput": {
"mean": 7586.197539502296,
"std": 2.826043462792163,
"min": 7582.946793757898,
"max": 7588.069915881657
"mean": 8225.003435798719,
"std": 13.877833769765575,
"min": 8214.288808538377,
"max": 8240.68023789224
},
"step_time": {
"mean": 69.21047159920757,
"std": 0.022114607283211834,
"min": 69.19065106380731,
"max": 69.234325167723
"mean": 63.90305413212627,
"std": 0.11015530079183487,
"min": 63.77801387012005,
"max": 63.985770548693836
},
"peak_memory": {
"gib": 8.55078125,
"pct": 18.038939985655993
"gib": 6.298828125,
"pct": 13.288163877053583
}
}
}
}
@@ -0,0 +1,507 @@
#!/usr/bin/env python3
"""Exercise Prime's layerwise reload path with vLLM online NVFP4 weights."""
from __future__ import annotations
import argparse
import hashlib
import importlib.metadata
import json
import math
import os
import time
from functools import partial
from pathlib import Path
from typing import Any, Iterable
DEFAULT_MODEL = "Qwen/Qwen3-30B-A3B-Instruct-2507"
EXPERT_WEIGHT_SUFFIXES = (
".gate_proj.weight",
".up_proj.weight",
".down_proj.weight",
)
KERNEL_WEIGHT_NAMES = {"w13_weight", "w2_weight"}
KERNEL_DERIVED_NAMES = {
"g1_scale_c",
"gemm1_alpha",
"gemm1_beta",
"gemm1_clamp_limit",
}
def _package_version(name: str) -> str:
try:
return importlib.metadata.version(name)
except importlib.metadata.PackageNotFoundError:
return "not-installed"
def environment_probe() -> dict[str, Any]:
import torch
import vllm
from vllm._custom_ops import scaled_fp4_quant
from vllm.model_executor.layers.quantization.online.nvfp4 import (
Nvfp4OnlineMoEMethod,
)
from vllm.utils.flashinfer import has_flashinfer_trtllm_fused_moe
from prime_rl.inference.vllm.worker.weight_transfer import (
load_weights_checkpoint_layerwise,
)
if not torch.cuda.is_available():
raise RuntimeError("CUDA is unavailable")
capability = torch.cuda.get_device_capability()
if capability[0] != 10:
raise RuntimeError(f"online NVFP4 requires SM100, found SM{capability[0]}{capability[1]}")
if not has_flashinfer_trtllm_fused_moe():
raise RuntimeError("FlashInfer TRTLLM fused MoE is unavailable")
source = torch.arange(256, device="cuda", dtype=torch.bfloat16).reshape(16, 16)
scale = torch.ones((), device="cuda", dtype=torch.float32)
packed, block_scales = scaled_fp4_quant(
source,
scale,
is_sf_swizzled_layout=False,
)
torch.cuda.synchronize()
return {
"torch": _package_version("torch"),
"torch_cuda": torch.version.cuda,
"vllm": _package_version("vllm"),
"vllm_module": str(Path(vllm.__file__).resolve()),
"flashinfer_python": _package_version("flashinfer-python"),
"flashinfer_cubin": _package_version("flashinfer-cubin"),
"gpu": torch.cuda.get_device_name(),
"compute_capability": list(capability),
"nvfp4_method": f"{Nvfp4OnlineMoEMethod.__module__}.{Nvfp4OnlineMoEMethod.__name__}",
"prime_reload_helper": (
f"{load_weights_checkpoint_layerwise.__module__}.{load_weights_checkpoint_layerwise.__name__}"
),
"scaled_fp4_quant": {
"packed_shape": list(packed.shape),
"packed_dtype": str(packed.dtype),
"block_scale_shape": list(block_scales.shape),
"block_scale_dtype": str(block_scales.dtype),
},
"persistent_cache": {
"hit": os.environ.get("NVFP4_CACHE_HIT") == "1",
"key": os.environ.get("NVFP4_CACHE_KEY"),
"marker": os.environ.get("NVFP4_CACHE_READY_MARKER"),
},
}
def _mark_persistent_cache_ready() -> None:
"""Mark the versioned JIT cache reusable after engine warmup succeeds."""
marker_value = os.environ.get("NVFP4_CACHE_READY_MARKER")
cache_key = os.environ.get("NVFP4_CACHE_KEY")
if not marker_value or not cache_key:
return
marker = Path(marker_value)
marker.parent.mkdir(parents=True, exist_ok=True)
temporary = marker.with_name(f".{marker.name}.{os.getpid()}.tmp")
temporary.write_text(cache_key + "\n")
os.replace(temporary, marker)
def _get_worker_model(worker: Any):
model_runner = worker.model_runner
get_model = getattr(model_runner, "get_model", None)
model = get_model() if callable(get_model) else model_runner.model
return getattr(model, "runnable", model)
def _is_expert_weight(name: str, layer_index: int) -> bool:
marker = f"model.layers.{layer_index}.mlp.experts."
return name.startswith(marker) and name.endswith(EXPERT_WEIGHT_SUFFIXES)
def _reload_checkpoint(
worker: Any,
*,
model_path: str,
mutation_layer: int | None,
) -> dict[str, Any]:
"""Worker-side reload through Prime's production checkpoint-format helper."""
import torch
from torch.nn import Module
from vllm.model_executor.model_loader import DefaultModelLoader, get_model_loader
from prime_rl.inference.vllm.worker.weight_transfer import (
load_weights_checkpoint_layerwise,
)
model = _get_worker_model(worker)
if not isinstance(model, Module):
raise TypeError(f"expected torch Module, got {type(model)!r}")
model_loader = get_model_loader(worker.load_config)
if not isinstance(model_loader, DefaultModelLoader):
raise TypeError(f"expected DefaultModelLoader, got {type(model_loader)!r}")
source = DefaultModelLoader.Source(
model_path,
revision=None,
prefix="",
fall_back_to_pt=getattr(model, "fall_back_to_pt_during_load", True),
allow_patterns_overrides=getattr(model, "allow_patterns_overrides", None),
)
source_iterator = model_loader._get_weights_iterator(source)
stats: dict[str, Any] = {
"mutated_tensors": 0,
"mutated_numel": 0,
"mutated_names": [],
}
def transformed_weights() -> Iterable[tuple[str, torch.Tensor]]:
for name, tensor in source_iterator:
if mutation_layer is not None and _is_expert_weight(name, mutation_layer):
stats["mutated_tensors"] += 1
stats["mutated_numel"] += tensor.numel()
if len(stats["mutated_names"]) < 12:
stats["mutated_names"].append(name)
# Negation changes every non-zero packed FP4 value without
# creating the degenerate all-zero activation path. That
# keeps this test focused on reload/restore correctness.
yield name, tensor.neg()
else:
yield name, tensor
started = time.perf_counter()
load_weights_checkpoint_layerwise(
model,
transformed_weights(),
worker.model_runner.model_config,
worker.vllm_config,
)
torch.cuda.synchronize()
stats["elapsed_seconds"] = time.perf_counter() - started
if mutation_layer is not None:
num_experts = int(worker.model_runner.model_config.hf_text_config.num_experts)
expected_tensors = num_experts * len(EXPERT_WEIGHT_SUFFIXES)
if stats["mutated_tensors"] != expected_tensors:
raise RuntimeError(f"mutated {stats['mutated_tensors']} expert tensors, expected {expected_tensors}")
return stats
def _sample_tensor(tensor: Any, sample_size: int = 8192) -> dict[str, Any]:
import torch
value = tensor.detach()
if not value.is_contiguous():
value = value.contiguous()
raw = value.view(torch.uint8).reshape(-1)
count = min(sample_size, raw.numel())
if count:
indices = torch.linspace(
0,
raw.numel() - 1,
steps=count,
device=raw.device,
dtype=torch.float64,
).to(torch.long)
sample = raw[indices].to(device="cpu", dtype=torch.uint8)
payload = bytes(sample.tolist())
else:
payload = b""
return {
"shape": list(tensor.shape),
"dtype": str(tensor.dtype),
"device": str(tensor.device),
"nbytes": tensor.numel() * tensor.element_size(),
"data_ptr": tensor.data_ptr(),
"sample_bytes": len(payload),
"sample_nonzero": sum(byte != 0 for byte in payload),
"sample_sha256": hashlib.sha256(payload).hexdigest(),
"sample_prefix": list(payload[:16]),
}
def _probe_model(model: Any, *, layer_index: int) -> dict[str, Any]:
import torch
model = getattr(model, "runnable", model)
marker = f"model.layers.{layer_index}.mlp.experts"
tensors: dict[str, Any] = {}
for name, tensor in model.named_parameters():
leaf = name.rsplit(".", 1)[-1]
if marker in name and (
leaf.startswith(("w13_", "w2_")) or leaf in KERNEL_DERIVED_NAMES
):
tensors[name] = tensor
for name, tensor in model.named_buffers():
leaf = name.rsplit(".", 1)[-1]
if marker in name and (
leaf.startswith(("w13_", "w2_")) or leaf in KERNEL_DERIVED_NAMES
):
tensors.setdefault(name, tensor)
if not tensors:
nearby = [name for name, _ in model.named_parameters() if marker in name]
raise RuntimeError(f"found no NVFP4 kernel tensors under {marker}; nearby={nearby[:20]}")
quant_methods: dict[str, str] = {}
kernel_references: dict[str, Any] = {}
for name, module in model.named_modules():
if marker not in name:
continue
method = getattr(module, "_quant_method", None)
if method is None:
method = getattr(module, "quant_method", None)
if method is not None:
quant_methods[name] = f"{type(method).__module__}.{type(method).__name__}"
quant_config = getattr(method, "moe_quant_config", None)
for attr in (
"g1_alphas",
"g2_alphas",
"a1_gscale",
"a2_gscale",
"w1_scale",
"w2_scale",
):
value = getattr(quant_config, attr, None)
if isinstance(value, torch.Tensor):
kernel_references[f"{name}.moe_quant_config.{attr}"] = _sample_tensor(value)
moe_kernel = getattr(method, "moe_kernel", None)
fused_experts = getattr(moe_kernel, "fused_experts", None)
for attr in KERNEL_DERIVED_NAMES:
value = getattr(fused_experts, attr, None)
if isinstance(value, torch.Tensor):
kernel_references[f"{name}.moe_kernel.fused_experts.{attr}"] = _sample_tensor(value)
if not any(value.endswith(".Nvfp4OnlineMoEMethod") for value in quant_methods.values()):
raise RuntimeError(f"layer {layer_index} is not using Nvfp4OnlineMoEMethod: {quant_methods}")
return {
"quant_methods": quant_methods,
"tensors": {name: _sample_tensor(tensor) for name, tensor in sorted(tensors.items())},
"kernel_references": dict(sorted(kernel_references.items())),
"cuda_memory": {
"allocated": torch.cuda.memory_allocated(),
"reserved": torch.cuda.memory_reserved(),
"max_allocated": torch.cuda.max_memory_allocated(),
"max_reserved": torch.cuda.max_memory_reserved(),
},
}
def _generation_signature(llm: Any, prompt: str) -> dict[str, Any]:
from vllm import SamplingParams
params = SamplingParams(
temperature=0.0,
max_tokens=4,
logprobs=5,
seed=0,
)
request = llm.generate([prompt], params, use_tqdm=False)[0]
sequence = request.outputs[0]
chosen_logprobs: list[float | None] = []
for token_id, candidates in zip(sequence.token_ids, sequence.logprobs or []):
candidate = candidates.get(token_id)
chosen_logprobs.append(None if candidate is None else float(candidate.logprob))
return {
"token_ids": list(sequence.token_ids),
"text": sequence.text,
"cumulative_logprob": (None if sequence.cumulative_logprob is None else float(sequence.cumulative_logprob)),
"chosen_logprobs": chosen_logprobs,
}
def _kernel_leaf(name: str) -> str:
return name.rsplit(".", 1)[-1]
def _compare_phases(
baseline: dict[str, Any],
mutated: dict[str, Any],
restored: dict[str, Any],
baseline_generation: dict[str, Any],
mutated_generation: dict[str, Any],
restored_generation: dict[str, Any],
) -> dict[str, Any]:
baseline_tensors = baseline["tensors"]
mutated_tensors = mutated["tensors"]
restored_tensors = restored["tensors"]
if baseline_tensors.keys() != mutated_tensors.keys() or baseline_tensors.keys() != restored_tensors.keys():
raise RuntimeError("kernel tensor names changed across reload phases")
pointer_mismatches = [
name
for name in baseline_tensors
if not (
baseline_tensors[name]["data_ptr"]
== mutated_tensors[name]["data_ptr"]
== restored_tensors[name]["data_ptr"]
)
]
restore_hash_mismatches = [
name
for name in baseline_tensors
if baseline_tensors[name]["sample_sha256"] != restored_tensors[name]["sample_sha256"]
]
changed_kernel_weights = [
name
for name in baseline_tensors
if _kernel_leaf(name) in KERNEL_WEIGHT_NAMES
and baseline_tensors[name]["sample_sha256"] != mutated_tensors[name]["sample_sha256"]
]
kernel_weights = [name for name in baseline_tensors if _kernel_leaf(name) in KERNEL_WEIGHT_NAMES]
baseline_logprob = baseline_generation["cumulative_logprob"]
mutated_logprob = mutated_generation["cumulative_logprob"]
restored_logprob = restored_generation["cumulative_logprob"]
mutation_changed_output = baseline_generation["token_ids"] != mutated_generation["token_ids"] or (
baseline_logprob is not None
and mutated_logprob is not None
and not math.isclose(baseline_logprob, mutated_logprob, abs_tol=1e-5)
)
restored_output_matches = baseline_generation["token_ids"] == restored_generation["token_ids"]
if baseline_logprob is not None and restored_logprob is not None:
restored_output_matches = restored_output_matches and math.isclose(
baseline_logprob,
restored_logprob,
abs_tol=1e-5,
)
checks = {
"kernel_tensor_names_stable": True,
"kernel_storage_pointers_preserved": not pointer_mismatches,
"mutated_kernel_weights_changed": bool(kernel_weights) and len(changed_kernel_weights) == len(kernel_weights),
"restored_kernel_fingerprints_match": not restore_hash_mismatches,
"mutation_changed_generation": mutation_changed_output,
"restored_generation_matches": restored_output_matches,
}
return {
"passed": all(checks.values()),
"checks": checks,
"pointer_mismatches": pointer_mismatches,
"restore_hash_mismatches": restore_hash_mismatches,
"changed_kernel_weights": changed_kernel_weights,
}
def run_experiment(args: argparse.Namespace) -> dict[str, Any]:
from vllm import LLM
probe = environment_probe()
started = time.perf_counter()
llm = LLM(
model=args.model,
quantization="nvfp4_per_token",
dtype="bfloat16",
tensor_parallel_size=1,
enforce_eager=args.enforce_eager,
enable_prefix_caching=False,
max_model_len=args.max_model_len,
max_num_seqs=1,
gpu_memory_utilization=args.gpu_memory_utilization,
trust_remote_code=False,
disable_log_stats=True,
)
load_seconds = time.perf_counter() - started
_mark_persistent_cache_ready()
try:
baseline = llm.apply_model(partial(_probe_model, layer_index=args.layer))[0]
baseline_generation = _generation_signature(llm, args.prompt)
mutated_reload = llm.collective_rpc(
_reload_checkpoint,
timeout=args.reload_timeout,
kwargs={"model_path": args.model, "mutation_layer": args.layer},
)[0]
mutated = llm.apply_model(partial(_probe_model, layer_index=args.layer))[0]
mutated_generation = _generation_signature(llm, args.prompt)
restored_reload = llm.collective_rpc(
_reload_checkpoint,
timeout=args.reload_timeout,
kwargs={"model_path": args.model, "mutation_layer": None},
)[0]
restored = llm.apply_model(partial(_probe_model, layer_index=args.layer))[0]
restored_generation = _generation_signature(llm, args.prompt)
comparison = _compare_phases(
baseline,
mutated,
restored,
baseline_generation,
mutated_generation,
restored_generation,
)
return {
"status": "passed" if comparison["passed"] else "failed",
"environment": probe,
"configuration": {
"model": args.model,
"layer": args.layer,
"quantization": "nvfp4_per_token",
"enforce_eager": args.enforce_eager,
"max_model_len": args.max_model_len,
"gpu_memory_utilization": args.gpu_memory_utilization,
},
"initial_load_seconds": load_seconds,
"reloads": {
"mutated": mutated_reload,
"restored": restored_reload,
},
"generations": {
"baseline": baseline_generation,
"mutated": mutated_generation,
"restored": restored_generation,
},
"kernel_probes": {
"baseline": baseline,
"mutated": mutated,
"restored": restored,
},
"comparison": comparison,
}
finally:
shutdown = getattr(llm, "shutdown", None)
if callable(shutdown):
shutdown()
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", default=DEFAULT_MODEL)
parser.add_argument("--layer", type=int, default=0)
parser.add_argument("--prompt", default="The capital of France is")
parser.add_argument("--max-model-len", type=int, default=256)
parser.add_argument("--gpu-memory-utilization", type=float, default=0.5)
parser.add_argument("--reload-timeout", type=float, default=1800)
parser.add_argument("--enforce-eager", action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--environment-only", action="store_true")
parser.add_argument("--output", type=Path)
return parser.parse_args()
def main() -> None:
os.environ.setdefault("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
args = parse_args()
if args.environment_only:
result: dict[str, Any] = {"status": "passed", "environment": environment_probe()}
else:
result = run_experiment(args)
rendered = json.dumps(result, indent=2, sort_keys=True)
print(rendered, flush=True)
if args.output is not None:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(rendered + "\n")
if result["status"] != "passed":
raise RuntimeError("NVFP4 layerwise reload verification failed")
if __name__ == "__main__":
main()
+18 -73
View File
@@ -2,18 +2,15 @@
"""
Run a single benchmark configuration and output JSON results.
This script runs a normal short training (--max-steps) with the file monitor
enabled and aggregates throughput / MFU / step time / peak memory from the
run's metrics.jsonl.
This script wraps the prime-rl training with --bench.output-json to get
metrics directly without parsing console output.
"""
from __future__ import annotations
import json
import statistics
import subprocess
import sys
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
@@ -23,7 +20,6 @@ import torch
from pydantic import Field
from prime_rl.utils.config import BaseConfig, cli
from prime_rl.utils.pathing import get_file_monitor_dir
MAX_LORAS = 4
@@ -71,6 +67,11 @@ class BenchmarkConfig(BaseConfig):
Field(description="Activation checkpointing type"),
] = "Recompute"
selective_targets: Annotated[
list[str] | None,
Field(description="Selective activation checkpoint targets when ac=Selective"),
] = None
attention: Annotated[
Literal["sdpa", "flash_attention_2", "flash_attention_3", "flash_attention_4"],
Field(description="Attention implementation"),
@@ -82,8 +83,6 @@ class BenchmarkConfig(BaseConfig):
timeout: Annotated[int, Field(description="Timeout in seconds")] = 3600
max_steps: Annotated[int, Field(ge=2, description="Training steps to run. The first step is warmup.")] = 4
micro_batches: Annotated[int, Field(ge=1, description="Number of micro batches")] = 2
ep: Annotated[int, Field(ge=1, description="Expert parallelism size (1 = no EP)")] = 1
@@ -116,7 +115,7 @@ class BenchmarkConfig(BaseConfig):
] = None
def build_command(config: BenchmarkConfig, output_dir: Path) -> list[str]:
def build_command(config: BenchmarkConfig) -> list[str]:
"""Build the benchmark command from config."""
# Determine training script
if config.type == "rl":
@@ -138,24 +137,20 @@ def build_command(config: BenchmarkConfig, output_dir: Path) -> list[str]:
str(config.seq_len),
"--model.attn",
config.attention,
"--max-steps",
str(config.max_steps),
"--output-dir",
str(output_dir),
"--monitors.file.path",
"metrics.jsonl",
"--bench.output-json",
str(config.output),
"--model.compile",
"--dist-timeout-seconds",
str(config.timeout),
]
if config.type == "sft":
cmd.extend(["--run.name", "bench"])
# Add activation checkpointing if enabled
if config.ac == "Recompute":
cmd.append("--model.ac")
elif config.ac == "Selective":
cmd.extend(["--model.ac", "--model.ac.mode", "selective"])
if config.selective_targets:
cmd.extend(["--model.ac.targets", json.dumps(config.selective_targets)])
elif config.ac == "Offload":
cmd.append("--model.ac-offloading")
@@ -203,65 +198,14 @@ def dummy_metrics() -> dict:
}
def aggregate_metrics(metrics_path: Path) -> dict:
"""Aggregate per-step metrics from a run's metrics.jsonl.
Each metrics.jsonl line is one monitor.log call (``{"step": N, ...}``);
merge the lines per step, drop the first (warmup) step, and compute
mean/std/min/max per metric like the old --bench JSON export did. Rows
keyed by wall time rather than step (``step: null``) are not per-step and
are skipped.
"""
per_step: dict[int, dict] = {}
with open(metrics_path) as f:
for line in f:
row = json.loads(line)
if row.get("step") is not None:
per_step.setdefault(row["step"], {}).update(row)
steps = sorted(per_step)[1:] # Exclude first warmup step
columns = {
"perf/mfu": "mfu",
"perf/throughput": "throughput",
"time/step": "step_time",
"perf/peak_memory": "peak_memory",
}
series = {name: [per_step[step][key] for step in steps] for key, name in columns.items()}
def stats(values: list[float]) -> dict:
return {
"mean": statistics.mean(values),
"std": statistics.stdev(values) if len(values) > 1 else 0.0,
"min": min(values),
"max": max(values),
}
total_memory_gib = torch.cuda.mem_get_info()[1] / 1024**3
peak_memory_gib = statistics.mean(series["peak_memory"])
return {
"mfu": stats(series["mfu"]),
"throughput": stats(series["throughput"]),
"step_time": stats(series["step_time"]),
"peak_memory": {
"gib": peak_memory_gib,
"pct": peak_memory_gib / total_memory_gib * 100,
},
}
def run_benchmark(config: BenchmarkConfig) -> None:
"""Run a single benchmark and write results to output path."""
output_dir = Path(tempfile.mkdtemp(prefix="benchmark-run-"))
cmd = build_command(config, output_dir)
cmd = build_command(config)
print(f"Running: {' '.join(cmd)}")
if config.dry_run:
return
# The SFT entrypoint writes to output_dir/<run.name>, the RL trainer to output_dir directly
run_dir = output_dir / "bench" if config.type == "sft" else output_dir
metrics_path = get_file_monitor_dir(run_dir) / "metrics.jsonl"
start_time = time.perf_counter()
try:
config.output.parent.mkdir(parents=True, exist_ok=True)
@@ -277,13 +221,14 @@ def run_benchmark(config: BenchmarkConfig) -> None:
config.success = False
config.error_reason = extract_oom_error_reason(output) or f"Non-zero exit code: {result.returncode}"
print(f"Process exited with code {result.returncode}: {output}")
if not metrics_path.exists():
if not config.output.exists():
config.success = False
config.error_reason = config.error_reason or extract_oom_error_reason(output) or "No metrics.jsonl written"
config.error_reason = config.error_reason or extract_oom_error_reason(output) or "No JSON output written"
print(f"Process exited with code {result.returncode}: {output}")
print("Benchmark completed but no metrics.jsonl was written")
print("Benchmark completed but no JSON output was written")
else:
metrics = aggregate_metrics(metrics_path)
with open(config.output) as f:
metrics = json.load(f)
lines = output.splitlines()
print("\n".join(lines))
except subprocess.TimeoutExpired:
+8 -11
View File
@@ -2,19 +2,16 @@
Configurations for running prime-rl.
- **[`advanced/`](advanced)** — frontier-model training configs without launch walkthroughs:
`minimax-m2.5` (swe), `nemotron-3-super` (swe), `deepseek-v4-flash` (sft + a standalone
vLLM serving pre-flight). For the tutorialized equivalents, see
[`examples/advanced/`](../examples/advanced).
- **[`basic/`](basic)** — small, 2-GPU (1 trainer + 1 inference) configs for the core
environments, sized to run on a single dev machine. Each mirrors the matching
[`examples/basic/`](../examples/basic) tutorial and is smoke-tested for one step.
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
- **`ci/`** — integration and nightly configs used by CI.
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and
`eval/` (`uv run eval` smokes against Prime Inference, one per shape: `single-turn`
(gsm8k), `multi-turn` (terminal-bench-2 fix-git in sandboxes against a local vLLM deployment with the adaptive band), `resume`, `multi-env`).
Not guaranteed functional or up to date.
(per-algorithm smokes) and `fake/` (fake-data trainer/SFT smokes). Not guaranteed
functional or up to date.
```bash
uv run rl @ configs/debug/algo/<algo>.toml
uv run sft @ configs/debug/fake/sft.toml
uv run eval @ configs/debug/eval/<shape>.toml
uv run rl @ configs/basic/<env>/rl.toml
uv run sft @ configs/basic/<env>/sft.toml # where present
```
@@ -1,35 +0,0 @@
# Standalone vLLM serving pre-flight: does this cluster's vLLM serve the real DeepSeek V4 Flash
# checkpoint at all, independent of the trainer? Uses vLLM's own native DeepSeek V4 support, not
# this repo's trainer port. Run directly on one allocated 8xH200 node (no [slurm] block):
#
# uv run inference @ examples/advanced/deepseek-v4-flash/inference.toml
#
# Then check /health and a /v1/chat/completions request from another shell on the same node, and
# confirm a coherent response before trusting the model for a real run.
#
# Reference: https://recipes.vllm.ai/deepseek-ai/DeepSeek-V4-Flash
# Mandatory for the fp8 checkpoint, not an optimization: without it the UE8M0-scaled fp8 weights
# route to a CUTLASS kernel that crashes on boot. That crash was observed during SM120 bring-up and
# has not been re-tested on Hopper, but the vLLM recipe sets the flag on every NVIDIA configuration.
# The mHC pre-norm GEMM does not need it on H200: measured there, the TileLang fallback matches the
# reference to 1.3e-06 relative at every token count, including the >= 1024 block-M kernel.
use_deep_gemm = true
[server]
port = 8000
[vllm]
model = "deepseek-ai/DeepSeek-V4-Flash-0731"
tensor_parallel_size = 8
enable_expert_parallel = true
gpu_memory_utilization = 0.85
max_model_len = 8192
# Required, not a tuning choice. Every DeepSeek V4 attention class sets
# `use_fp8_ds_mla_layout = True`, and the sparse-MLA layout then asserts
# "DeepseekV4 fp8_ds_mla layout only supports fp8 kv-cache" against the `auto` default. The vLLM
# recipe sets it on every vendor and every architecture.
kv_cache_dtype = "fp8"
# Recipe-derived rather than measured here: every NVIDIA configuration in the vLLM recipe pairs
# the fp8 KV cache with this block size.
block_size = 256
@@ -1,62 +0,0 @@
# Real-data SFT for deepseek-ai/DeepSeek-V4-Flash-0731 at full depth (all 43 layers, no
# `debug.num_layers` truncation) on 4 train nodes. Trainer only: no online eval, no inference
# node, and so no weight broadcast. Tested on 8xH200.
#
# uv run sft @ examples/advanced/deepseek-v4-flash/sft.toml --run.name ds-v4-sft-torch-4node
#
# Note: on 4 8xH200 nodes, this config is near the memory limit, using ~94%+ GPU memory.
#
# `dist_timeout_seconds = 14400` is needed on any run that has to build the HF -> prime-rl
# conversion cache, which takes far longer than the 3600s default.
#
# To buy memory back for quicker testing on fewer nodes, set `full_offload = true` under `[model]`,
# which keeps the fp32 masters, moments and gradients in CPU RAM and needs `optim_cpu_offload =
# false` and `optim.max_norm = "None"` set alongside it; the lighter `optim_cpu_offload = true` is
# already the default here.
#
# There is no `[ckpt]` block. The trainer saves unconditionally at the last step, and a 43-layer
# checkpoint (fp32 master weights plus two fp32 AdamW moments) is ~3 TiB. Add one with
# `ckpt.output_dir` pointed at a volume that can hold it if you need the trained weights.
dist_timeout_seconds = 14400
max_steps = 20
[model]
name = "deepseek-ai/DeepSeek-V4-Flash-0731"
impl = "custom"
ep = 8
# Torch all-to-all, not DeepEP. At full depth DeepEP dies on the first backward with
# "RuntimeError: Autograd not support dtype: Byte", raised from `Tensor.float()` in
# `DeepEPTokenDispatcher.combine` while the activation-checkpoint recompute replays through a
# `__torch_dispatch__` mode that hands back a uint8 tensor. Reproduced deterministically on 4
# nodes against the same weights and conversion cache this config trains on.
[model.moe.dispatch]
type = "torch"
[model.ac]
freq = 1
[model.ac_offloading]
max_inflight_activations = 5
[data]
name = "PrimeIntellect/Reverse-Text-SFT"
seq_len = 2048
batch_size = 32
[optim]
lr = 1e-5
[monitors.wandb]
project = "deepseek-v4-flash"
name = "deepseek-v4-flash-sft"
# `num_infer_nodes` defaults to 0, so this allocates 4 nodes and runs only the trainer.
[deployment]
type = "multi_node"
num_train_nodes = 4
[slurm]
job_name = "ds-v4-sft"
partition = "all"
+8
View File
@@ -0,0 +1,8 @@
# alphabet-sort (2 GPU)
Multi-turn task driven by a colocated user simulator, LoRA on `Qwen3-4B`. Dev mirror of
[`examples/basic/alphabet-sort`](../../../examples/basic/alphabet-sort).
```bash
uv run rl @ configs/basic/alphabet-sort/rl.toml
```
+42
View File
@@ -0,0 +1,42 @@
# Alphabet-sort on 2 GPUs (1 trainer + 1 inference) — a multi-turn task driven by a colocated
# user simulator, trained with LoRA on Qwen3-4B. Dev-sized mirror of examples/basic/alphabet-sort.
max_steps = 200
seq_len = 2048
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
project = "alphabet-sort"
name = "alphabet-sort"
[trainer.model.ac]
freq = 1
[trainer.model.lora]
rank = 32
alpha = 64
[trainer.optim]
lr = 1e-5
[orchestrator]
batch_size = 128
group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 768
[[orchestrator.train.env]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[ckpt] # Checkpoint at the end of training
[inference]
+9
View File
@@ -0,0 +1,9 @@
# hendrycks-sanity (2 GPU)
Single-turn math sanity run (reward climbs slowly, meant to run long),
`DeepSeek-R1-Distill-Qwen-1.5B`. Dev mirror of
[`examples/basic/hendrycks-sanity`](../../../examples/basic/hendrycks-sanity).
```bash
uv run rl @ configs/basic/hendrycks-sanity/rl.toml
```
+36
View File
@@ -0,0 +1,36 @@
# Hendrycks-math sanity on 2 GPUs (1 trainer + 1 inference) — a single-turn math env meant to
# run long (reward climbs slowly). Dev-sized mirror of examples/basic/hendrycks-sanity.
max_steps = 5000
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
[orchestrator]
batch_size = 128
group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.model]
seq_len = 16384
[inference.model]
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+9
View File
@@ -0,0 +1,9 @@
# reverse-text (2 GPU)
Smallest end-to-end RL loop — single-turn, `Qwen3-0.6B`. Dev mirror of
[`examples/basic/reverse-text`](../../../examples/basic/reverse-text).
```bash
uv run sft @ configs/basic/reverse-text/sft.toml # optional warmup
uv run rl @ configs/basic/reverse-text/rl.toml
```
+40
View File
@@ -0,0 +1,40 @@
# Reverse-text on 2 GPUs (1 trainer + 1 inference) — the smallest end-to-end RL loop
# (single-turn, 0.6B). Dev-sized mirror of examples/basic/reverse-text.
max_steps = 20
seq_len = 2048
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text"
name = "reverse-text"
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
[ckpt] # Checkpoint at the end of training
[inference]
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[orchestrator.renderer]
name = "prime-qwen3"
+19
View File
@@ -0,0 +1,19 @@
# SFT warmup for reverse-text on 2 GPUs. Dev-sized mirror of examples/basic/reverse-text/sft.toml.
max_steps = 100
[deployment]
num_gpus = 2
[ckpt] # Checkpoint at the end of training
[model]
name = "PrimeIntellect/Qwen3-0.6B"
[data]
name = "willcb/R1-reverse-wikipedia-paragraphs-v1-1000"
seq_len = 4096
batch_size = 32
[optim]
lr = 2e-5
+8
View File
@@ -0,0 +1,8 @@
# wiki-search (2 GPU)
Multi-turn tool calling (search a wiki corpus via native V1 tools), LoRA on `Qwen3-4B`. Dev mirror
of [`examples/basic/wiki-search`](../../../examples/basic/wiki-search).
```bash
uv run rl @ configs/basic/wiki-search/rl.toml
```
+51
View File
@@ -0,0 +1,51 @@
# Wiki-search on 2 GPUs (1 trainer + 1 inference) — a multi-turn tool-calling task (the model
# searches a wiki corpus via MCP tools), trained with LoRA on Qwen3-4B. Dev-sized mirror of
# examples/basic/wiki-search.
max_steps = 200
seq_len = 4096
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
project = "wiki-search"
name = "wiki-search"
[trainer.optim]
lr = 1e-5
weight_decay = 0.0
[trainer.model.lora]
rank = 8
dropout = 0.0
target_modules = [
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
]
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.env]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[ckpt] # Checkpoint at the end of training
[inference.model]
tool_call_parser = "hermes"
+9
View File
@@ -0,0 +1,9 @@
# wordle (2 GPU)
Multi-turn Wordle (~6-turn games), `Qwen3-1.7B-Wordle-SFT`. Dev mirror of
[`examples/basic/wordle`](../../../examples/basic/wordle).
```bash
uv run sft @ configs/basic/wordle/sft.toml # optional warmup
uv run rl @ configs/basic/wordle/rl.toml
```
+38
View File
@@ -0,0 +1,38 @@
# Wordle on 2 GPUs (1 trainer + 1 inference). The Wordle-SFT model plays a
# full ~6-turn game per rollout.
max_steps = 200
seq_len = 8192
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[wandb]
project = "wordle"
name = "wordle"
[ckpt] # Checkpoint at the end of training
[model]
name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 128
group_size = 8
[[orchestrator.train.env]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer] # Default trainer config
[inference] # single inference GPU (no data parallelism)
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
[orchestrator.renderer]
name = "prime-qwen3"
+20
View File
@@ -0,0 +1,20 @@
# SFT warmup for wordle on 2 GPUs. Dev-sized mirror of examples/basic/wordle/sft.toml.
max_steps = 20
[deployment]
num_gpus = 2
[ckpt] # Checkpoint at the end of training
[model]
name = "PrimeIntellect/Qwen3-1.7B"
[data]
name = "willcb/V3-wordle"
seq_len = 1024
batch_size = 64
micro_batch_size = 1
[optim]
lr = 1e-5
+3 -15
View File
@@ -17,27 +17,15 @@ lr = 1e-5
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 384
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "alphabet-sort"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 2
env.taskset.max_turns = 2
env.taskset.min_names_per_turn = 1
env.taskset.max_names_per_turn = 3
env.taskset.task.similarity_power = 4
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "alphabet-sort-v1", min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, task = { similarity_power = 4, power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
-14
View File
@@ -1,14 +0,0 @@
# CI eval smoke: gsm8k with the null harness in a local subprocess runtime against
# Prime Inference — the eval path end to end without a GPU or sandbox.
dashboard = false
[select]
limit = 4
[sampling]
max_completion_tokens = 8192
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
@@ -2,9 +2,7 @@ max_steps = 20
seq_len = 2048
[ckpt]
[resume]
step = 15
resume_step = 15
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -15,33 +13,29 @@ lr = 5e-5
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[inference.vllm]
enable_lora = true
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "prime-qwen3"
@@ -12,33 +12,29 @@ lr = 5e-5
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[inference.vllm]
enable_lora = true
gpu_memory_utilization = 0.7
[orchestrator.renderer]
name = "prime-qwen3"
@@ -20,26 +20,22 @@ impl = "custom"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
[inference.vllm]
max_model_len = 2048
gpu_memory_utilization = 0.7
[inference.model]
max_model_len = 2048
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -0,0 +1,13 @@
# Inference config for multi-run RL integration test
enable_lora = true
max_lora_rank = 8
max_loras = 4
gpu_memory_utilization = 0.7
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
max_model_len = 2048
[weight_broadcast]
type = "filesystem"
@@ -0,0 +1,32 @@
# Orchestrator config for multi-run RL integration test
# model.lora.name and output_dir are set via CLI
batch_size = 128
group_size = 16
seq_len = 2048
max_steps = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[optim]
lr = 3e-5
[train.sampling]
max_completion_tokens = 128
[[train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[ckpt]
interval = 10
resume_step = -1
[weight_broadcast]
type = "filesystem"
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
# suffix misses the MODEL_RENDERER_MAP exact match).
[renderer]
name = "prime-qwen3"
@@ -0,0 +1,21 @@
# Trainer config for multi-run RL integration test
max_concurrent_runs = 2
enable_token_export = true
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
seq_len = 65536
fused_lm_head_token_chunk_size = 8192
optim_cpu_offload = false
[model.lora]
rank = 8
[model.ac]
freq = 1
[model.compile]
fullgraph = false
[weight_broadcast]
type = "filesystem"
@@ -16,25 +16,20 @@ type = "filesystem"
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
[wandb]
project = "reverse-text-ci"
name = "ci-rl-opd"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.algo]
[orchestrator.algo]
type = "opd"
[orchestrator.train.algo.teacher]
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
base_url = ["http://localhost:8001/v1"]
[orchestrator.renderer]
name = "prime-qwen3"
@@ -42,31 +37,25 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
[orchestrator.eval.select]
limit = 16
num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.4
@@ -16,26 +16,21 @@ type = "filesystem"
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
[wandb]
project = "reverse-text-ci"
name = "ci-rl-sft"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.algo]
[orchestrator.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.train.algo.sampling.source]
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
base_url = ["http://localhost:8001/v1"]
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -48,31 +43,25 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
[orchestrator.eval.select]
limit = 16
num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.4
@@ -1,9 +1,10 @@
max_steps = 10
[ckpt]
resume_step = 5
[resume]
step = 5
[ckpt.weights]
save_adapter_separately = true
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -2,6 +2,9 @@ max_steps = 5
[ckpt]
[ckpt.weights]
save_adapter_separately = true
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -1,21 +0,0 @@
max_steps = 6
[ckpt]
skip_optimizer = true
skip_scheduler = true
[resume]
step = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
optim_cpu_offload = false
full_offload = true
[optim]
lr = 0.0
[data]
name = "PrimeIntellect/Reverse-Text-SFT"
batch_size = 4
seq_len = 1024
@@ -1,9 +1,7 @@
max_steps = 10
[ckpt]
[resume]
step = 5
resume_step = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -8,9 +8,7 @@ seq_len = 2048
type = "filesystem"
[ckpt]
[resume]
step = 15
resume_step = 15
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -20,21 +18,15 @@ lr = 3e-6
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
@@ -17,21 +17,15 @@ lr = 3e-6
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
-41
View File
@@ -1,41 +0,0 @@
max_steps = 200
seq_len = 2048
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[monitors.wandb]
project = "alphabet-sort"
name = "alphabet-sort"
[ckpt]
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[[orchestrator.train.source]]
name = "alphabet-sort"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 768
[trainer]
[inference.vllm]
data_parallel_size = 4
@@ -1,55 +0,0 @@
max_steps = 5000
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[monitors.wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
[ckpt]
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
seq_len = 8192
[orchestrator.train]
group_size = 8
[orchestrator.concurrency]
max_inflight = 128
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset.id = "math-env"
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
env.taskset.dataset_subset = "default"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 50
[[orchestrator.eval.source]]
name = "aime2024"
group_size = 32
env.taskset.id = "aime24"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer]
[trainer.model]
seq_len = 16384
attn = "flash_attention_2"
[inference.vllm]
max_model_len = 8192
data_parallel_size = 4
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-40
View File
@@ -1,40 +0,0 @@
max_steps = 20
seq_len = 2048
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
[ckpt]
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[[orchestrator.train.source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 128
[trainer]
[inference]
[orchestrator.renderer]
name = "prime-qwen3"
-40
View File
@@ -1,40 +0,0 @@
max_steps = 200
seq_len = 4096
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[monitors.wandb]
project = "wiki-search"
name = "wiki-search"
[ckpt]
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
initial_inflight = 128
max_inflight = 128
[[orchestrator.train.source]]
name = "wiki-search"
env.taskset.id = "wiki-search"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
[trainer]
[inference.vllm]
tool_call_parser = "hermes"
data_parallel_size = 4
-40
View File
@@ -1,40 +0,0 @@
max_steps = 200
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[monitors.wandb]
project = "wordle"
name = "wordle"
[ckpt]
[model]
name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 512
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[[orchestrator.train.source]]
name = "wordle"
env.taskset.id = "wordle"
env.player.harness.id = "null"
env.player.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer]
[inference.vllm]
data_parallel_size = 6
[orchestrator.renderer]
name = "prime-qwen3"
@@ -15,22 +15,15 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "color-codeword"
env.taskset.id = "color-codeword"
env.taskset.images_per_turn = 1
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "color-codeword-v1", images_per_turn = 1 }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer]
+5 -5
View File
@@ -16,7 +16,7 @@ Minimal end-to-end configs for the algorithms against bundled verifiers envs, us
The policy inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local frozen model (used by `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed_grpo_opd.toml`) is **not** auto-launched — start it manually on GPU 1.
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.train.algo.teacher]` for `opd`, `[orchestrator.train.algo.sampling.source]` for `sft` — with `name` + `base_url`. `opsd` declares none (it self-distills against the live policy). prime-rl never hosts them; only the trainable policy's server is managed by the `rl` entrypoint.
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for `opd`, `[orchestrator.algo.sampling.source]` for `sft` — with `name` + `base_url`. `opsd` declares none (it self-distills against the live policy). prime-rl never hosts them; only the trainable policy's server is managed by the `rl` entrypoint.
## Start the local frozen model
@@ -24,15 +24,15 @@ Needed for `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--server.port 8001 \
--vllm.gpu-memory-utilization 0.5 \
--vllm.enforce-eager
--gpu-memory-utilization 0.5 \
--model.enforce-eager
```
## Run the debug configs
Every config writes to the default `outputs/` directory, so running two back-to-back — or re-running one — fails with `FileExistsError`. Pass a distinct `--output-dir outputs/<algo>` per config (recommended for a sweep) or `--clean` to wipe and restart.
Every config writes to the default `outputs/` directory, so running two back-to-back — or re-running one — fails with `FileExistsError`. Pass a distinct `--output-dir outputs/<algo>` per config (recommended for a sweep) or `--clean-output-dir` to wipe and restart.
```bash
# GRPO (no frozen model)
+12 -14
View File
@@ -8,36 +8,36 @@ seq_len = 4096
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
[wandb]
project = "algorithms-debug"
name = "debug-echo"
[orchestrator]
batch_size = 32
[orchestrator.train]
group_size = 4
# alphabet-sort's feedback arrives as user messages, so train the user role
# instead of echo's tool default.
[orchestrator.train.algo]
[orchestrator.algo]
type = "echo"
[orchestrator.train.algo.roles.user]
[orchestrator.algo.roles.user]
alpha = 0.1
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "alphabet-sort"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.sampling]
max_completion_tokens = 512
# ECHO learns from observation tokens even when the GRPO advantage collapses
# to zero — keep zero-advantage rollouts in the batch.
[[orchestrator.post_batch_filters]]
type = "zero_advantage"
enforce = false
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
[orchestrator.renderer]
name = "prime-qwen3"
@@ -46,6 +46,4 @@ name = "prime-qwen3"
lr = 1e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+9 -17
View File
@@ -4,17 +4,15 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
[wandb]
project = "algorithms-debug"
name = "debug-rl"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
[orchestrator.algo]
type = "grpo"
[orchestrator.renderer]
@@ -23,26 +21,22 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
[orchestrator.eval.select]
limit = 128
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
@@ -50,6 +44,4 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+9 -17
View File
@@ -4,17 +4,15 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
[wandb]
project = "algorithms-debug"
name = "debug-max-rl"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
[orchestrator.algo]
type = "max_rl"
[orchestrator.renderer]
@@ -23,26 +21,22 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
[orchestrator.eval.select]
limit = 128
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
@@ -50,6 +44,4 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+21 -26
View File
@@ -3,8 +3,8 @@
# ref_logprobs, GRPO samples don't, and both pack into the same micro batches.
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/mixed_grpo_opd.toml
@@ -14,17 +14,15 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
[wandb]
project = "algorithms-debug"
name = "debug-mixed-grpo-opd"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
[orchestrator.algo]
type = "grpo"
[orchestrator.renderer]
@@ -33,40 +31,37 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text-grpo"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text-opd"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
algo.type = "opd"
algo.teacher.name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
algo.teacher.base_url = "http://localhost:8001/v1"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.env.algo]
type = "opd"
[orchestrator.train.env.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
[orchestrator.eval]
interval = 5
[orchestrator.eval.select]
limit = 128
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+13 -21
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/opd.toml
@@ -11,22 +11,20 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
[wandb]
project = "algorithms-debug"
name = "debug-opd"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
[orchestrator.algo]
type = "opd"
[orchestrator.train.algo.teacher]
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
base_url = ["http://localhost:8001/v1"]
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
@@ -35,26 +33,22 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
[orchestrator.eval.select]
limit = 128
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
@@ -62,6 +56,4 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+16 -21
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/opd_lora.toml
@@ -11,22 +11,20 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
[wandb]
project = "algorithms-debug"
name = "debug-opd-lora"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
[orchestrator.algo]
type = "opd"
[orchestrator.train.algo.teacher]
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
base_url = ["http://localhost:8001/v1"]
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
@@ -35,26 +33,22 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
[orchestrator.eval.select]
limit = 128
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 1e-4
@@ -62,9 +56,10 @@ lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
-59
View File
@@ -1,59 +0,0 @@
max_steps = 20
seq_len = 4096
[model]
name = "Qwen/Qwen3-0.6B"
[monitors.wandb]
project = "algorithms-debug"
name = "debug-rae"
[orchestrator]
batch_size = 32
[orchestrator.train]
group_size = 1
[orchestrator.train.algo]
type = "rae"
[orchestrator.renderer]
name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 512
[[orchestrator.train.source]]
name = "kuhn-poker"
env.taskset.id = "kuhn-poker"
env.player0.harness.id = "null"
env.player0.runtime.type = "subprocess"
env.player1.harness.id = "null"
env.player1.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
[orchestrator.eval.select]
limit = 16
[orchestrator.eval.sampling]
max_completion_tokens = 512
[[orchestrator.eval.source]]
name = "kuhn-poker"
env.taskset.id = "kuhn-poker"
env.player0.harness.id = "null"
env.player0.runtime.type = "subprocess"
env.player1.harness.id = "null"
env.player1.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+9 -17
View File
@@ -10,18 +10,16 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
[wandb]
project = "algorithms-debug"
name = "debug-self-distill"
[orchestrator]
batch_size = 32
[orchestrator.train]
group_size = 1
# reverse-text's demo lives in the "answer" column.
[orchestrator.train.algo]
[orchestrator.algo]
type = "opsd"
demo_key = "answer"
@@ -31,31 +29,25 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
[orchestrator.eval.select]
limit = 128
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+13 -21
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/sft_distill.toml
@@ -11,23 +11,21 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
[wandb]
project = "algorithms-debug"
name = "debug-sft"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 4
[orchestrator.train.algo]
[orchestrator.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.train.algo.sampling.source]
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
base_url = ["http://localhost:8001/v1"]
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -40,26 +38,22 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
[orchestrator.eval.select]
limit = 128
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 3e-6
@@ -67,6 +61,4 @@ lr = 3e-6
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
+16 -21
View File
@@ -1,7 +1,7 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/algo/sft_distill_lora.toml
@@ -11,23 +11,21 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[monitors.wandb]
[wandb]
project = "algorithms-debug"
name = "debug-sft-lora"
[orchestrator]
batch_size = 128
[orchestrator.train]
group_size = 4
[orchestrator.train.algo]
[orchestrator.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.train.algo.sampling.source]
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
base_url = ["http://localhost:8001/v1"]
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
@@ -40,26 +38,22 @@ name = "prime-qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 1
[orchestrator.eval.select]
limit = 128
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[trainer.optim]
lr = 1e-4
@@ -67,9 +61,10 @@ lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
[inference.vllm]
gpu_memory_utilization = 0.5
-16
View File
@@ -1,16 +0,0 @@
# AIME 2026 at avg@16: every problem 16 times with the null harness (one chat
# completion per rollout) against Prime Inference. The math tasksets forbid the
# agent any network, and only the sandboxed runtimes enforce that policy, so the
# rollouts run in prime sandboxes (PRIME_API_KEY) rather than as subprocesses.
# Competition math needs room to reason, so the completion budget is generous.
#
# uv run eval @ configs/debug/eval/aime2026.toml
group_size = 16
[sampling]
max_completion_tokens = 32768
[[source]]
env.taskset.id = "aime26"
env.agent.harness.id = "null"
-21
View File
@@ -1,21 +0,0 @@
# Multi env: 16 terminal-bench-2 tasks under two harnesses, bash and rlm, in prime
# sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout each with
# a ten-minute budget, against Prime Inference on the default model. One env server
# per source; the sources share the taskset, so each carries its own name.
#
# uv run eval @ configs/debug/eval/multi-env.toml
[select]
limit = 16
[[source]]
name = "tb2-bash"
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 600
[[source]]
name = "tb2-rlm"
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "rlm"
env.agent.timeout.rollout = 600
-13
View File
@@ -1,13 +0,0 @@
# Single env, multi turn: 16 terminal-bench-2 tasks with the bash harness in
# prime sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout
# each, against Prime Inference on the default model.
#
# uv run eval @ configs/debug/eval/multi-turn.toml
[select]
limit = 16
[[source]]
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
-25
View File
@@ -1,25 +0,0 @@
# Single env, resume: gsm8k with a low pinned concurrency so the run can be
# interrupted partway. Relaunch with the same --run.name and --resume: the landed
# episodes are restored from the trace stream and only the owed rollouts run.
# Resuming a finished run restores everything and exits.
#
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug
# <Ctrl-C partway>
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug --resume
group_size = 2
[select]
limit = 8
[concurrency]
min_inflight = 2
max_inflight = 2
[sampling]
max_completion_tokens = 8192
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
-17
View File
@@ -1,17 +0,0 @@
# Single env, single turn: gsm8k with the null harness (one chat completion per
# task, no sandbox) against Prime Inference.
#
# uv run eval @ configs/debug/eval/single-turn.toml
group_size = 2
[select]
limit = 8
[sampling]
max_completion_tokens = 8192
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
-15
View File
@@ -1,15 +0,0 @@
# Terminal-Bench 2 at avg@4: every task 4 times with the bash harness in prime
# sandboxes (PRIME_API_KEY authenticates sandbox creation) against Prime Inference.
#
# uv run eval @ configs/debug/eval/tb2.toml
group_size = 4
[[source]]
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
env.agent.retries.rules = [
{type = "ProviderError", max_retries = 2},
{type = "SandboxError", max_retries = 2},
]
-1
Submodule deps/prime-envs deleted from d4fb80a56f
Submodule deps/prime-kernels deleted from 6f481769ca
+1 -1
Vendored Submodule
+1
+1 -1
+27 -95
View File
@@ -1,17 +1,17 @@
# Advanced
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, multi-tenant training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
## Table of Contents
- [Custom Modeling](#custom-modeling)
- [Expert Parallelism Backends](#expert-parallelism-backends)
- [Runtime Fusions](#runtime-fusions)
- [Multimodal Training](#multimodal-training)
- [Supported Families](#supported-families)
- [Enabling VLM Mode](#enabling-vlm-mode)
- [Limitations](#limitations)
- [LoRA Training](#lora-training)
- [Multi-Tenant Training](#multi-tenant-training)
- [Disaggregated Prefill/Decode Inference](#disaggregated-prefilldecode-inference)
## Custom Modeling
@@ -28,121 +28,42 @@ impl = "custom" # or "hf" to force the HF path
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ❌ |
| Laguna | `poolside/Laguna-XS.2` | ✅ | ✅ |
| MiniMax M2 | `MiniMax/MiniMax-M2` | ✅ | ✅ |
| Nemotron H | `nvidia/Nemotron-3-Nano-30B-A3B`, … | ✅ | ❌ |
| Trinity (AFMoE) | `arcee-ai/Trinity-Mini`, … | ✅ | ✅ |
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
| GPT-OSS | `unsloth/gpt-oss-20b-BF16`, … | ✅ | ✅ |
| DeepSeek V4 | `deepseek-ai/DeepSeek-V4-Flash-0731` | ✅ | ✅ |
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
Selective activation checkpointing works with either implementation. The custom path additionally enables EP, CP, low-precision training, and grouped MoE kernels. Forcing `impl = "hf"` is mostly useful when debugging and disables those model-specific runtime features.
GPT-OSS uses FlashAttention 4 with learned attention sinks. Training requires SM90 or SM100/SM110 GPUs
and a BF16 checkpoint such as `unsloth/gpt-oss-20b-BF16`; the original MXFP4 checkpoints are not supported.
The custom path enables you to set EP, CP, selective activation checkpointing, low-precision training (`[trainer.model.quantization]`), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
### Low-precision training
Dense linear precision and routed-expert precision are configured independently. `[trainer.model.quantization]` applies only to dense `Linear` modules:
Set `[trainer.model.quantization]` to train dense linears and MoE expert GEMMs in low precision. Two backends are available via the `type` discriminator:
- `type = "fp8"` — DeepGEMM FP8 blockwise linears (requires SM90+).
- `type = "mxfp8"` — torchao MXFP8 linears (requires SM100). `recipe` is `mxfp8_rceil` or `mxfp8_rceil_wgrad_with_hp`.
`[trainer.model.moe.compute]` selects routed-expert compute independently:
- `type = "bf16"` (default), with `backend = "torch"` (default) or `"sonicmoe"`.
- `type = "deepgemm_fp8"` (requires DeepGEMM and SM90+)
- `type = "mxfp8"` (requires `prime-kernels`, torchao, and SM100)
SonicMoE uses the upstream `sonic-moe` package (`uv sync --extra sonic-moe`) for fused BF16 expert computation. The supported model is Qwen3 MoE with the `gate_up` model fusion enabled. Backend selection requires fused gate/up weights, standard SwiGLU, and bias-free experts; incompatible expert structures raise an error during setup. It uses the same router and local, torch EP, or DeepEP dispatch as other compute backends:
```toml
[trainer.model]
name = "Qwen/Qwen3-30B-A3B"
ep = 2
[trainer.model.fusions]
enabled = ["gate_up"]
[trainer.model.moe.compute]
type = "bf16"
backend = "sonicmoe"
[trainer.model.moe.dispatch]
type = "torch"
```
- `type = "fp8"` — DeepGEMM FP8 blockwise (requires SM90+ / Hopper). Options: `enable_grouped_gemm` (FP8 MoE expert GEMM). Both default on.
- `type = "mxfp8"` — torchao MXFP8 microscaling (requires SM100+ / Blackwell). Options: `enable_grouped_gemm`, `enable_a2a` (MXFP8 expert-parallel all-to-all), and `recipe` (`mxfp8_rceil` default or `mxfp8_rceil_wgrad_with_hp`).
```toml
[trainer.model.quantization]
type = "mxfp8"
recipe = "mxfp8_rceil"
[trainer.model.moe.compute]
type = "mxfp8"
recipe = "mxfp8_rceil"
[trainer.model.moe.dispatch]
type = "torch"
transport = "mxfp8"
enable_a2a = true
```
All MoE compute backends accept `apply_to`:
- `"all"` (default) applies the backend to all expert groups.
- `"85%"` applies it to the first 85% of model layers, rounded down. For a 48-layer model, this selects layers 0–39.
- `[0, 1, 2, 3]` selects explicit zero-based model layer indices; `[]` selects none.
Percentages must be between 0% and 100%; explicit indices must be within the model's layer count. Non-MoE blocks in hybrid models count toward layer indices and percentages. Each selected layer uses the backend for all its routed experts. Other expert groups use BF16 compute and BF16 token transport while retaining the configured dispatch backend and expert parallelism. Dense linear quantization is configured separately.
For example, this selects routed experts in Qwen3's first four model layers:
```toml
[trainer.model.moe.compute]
type = "mxfp8"
apply_to = [0, 1, 2, 3]
```
Backend shape checks and token alignment apply only to the selected compute path.
In RL runs, configure the same precision selection for rollouts. Inference module names can differ from the trainer's names, and inference precision is configured explicitly, not inferred from `apply_to`. Check the selected modules on both sides before comparing trainer and rollout logprobs.
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
### Expert Parallelism Backends
`[trainer.model.moe.dispatch]` selects how routed tokens are dispatched and combined:
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
- **`torch`** (default): torch all-to-all with `transport = "bf16"` or, when MXFP8 expert compute is selected, `transport = "mxfp8"` on SM100.
- **`deepep`**: DeepEP custom dispatch/combine kernels. Set `num_sms` and optional `token_chunk_size` in the same table. Pre-built H100/H200 binaries use CUDA 13.0 and are installed by `uv sync --all-extras`.
```toml
[trainer.model.moe.dispatch]
type = "deepep"
num_sms = 20
token_chunk_size = 4096
```
- **`torch`** (default): TorchTitan's all-to-all collective. Works everywhere, no extra install.
- **`deepep`**: Utilizes DeepEP's custom all-to-all collectives. This provides better performance if EP dimension spans multiple nodes. We provide pre-built binaries for H100/H200 with cuda runtime 12.9 installed, you can install them by running `uv sync --all-extras`.
DeepEP requires some careful tuning to achieve optimal performance, tuning parameters are `deepep_num_sms` and `deepep_token_chunk_size`.
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
### Runtime Fusions
`model.fusions` packs parameters that are always computed together into one tensor, turning several GEMMs into one. Both fusions are on by default:
- `gate_up` — each gated MoE expert's `gate_proj` and `up_proj` become one `[num_experts, 2 * intermediate_size, hidden_size]` weight, halving the routed-expert grouped GEMMs.
- `qkv` — an attention layer's `q_proj`, `k_proj` and `v_proj` (and their biases) become one linear layer.
```toml
[trainer.model.fusions]
enabled = ["gate_up", "qkv"] # [] disables
```
Fusions are runtime-only. Checkpoints keep the canonical parameter names and shapes, so a run can turn a fusion on or off at any point and still load its own checkpoints, and exported weights are unaffected. Only modules that support a fusion are packed; a requested fusion that no module supports logs a warning and is skipped. Fusions are skipped when LoRA is enabled.
Muon receives the packed layout as matrix partitions and orthogonalizes each logical matrix on its own, so a packed parameter trains exactly as the parameters it replaces would — including per-projection learning-rate scaling for grouped-query attention — while keeping a single momentum tensor.
The experimental `shard_fused_on_dim1 = true` shards fused 2-D weights along dim 1 under FSDP, which makes weight loading and checkpointing zero-copy: fused weights and their optimizer state are read and written in place rather than assembled into a full copy on each rank first. It requires `hidden_size` to be divisible by the FSDP shard mesh size.
## Multimodal Training
### Supported Families
@@ -195,7 +116,18 @@ dropout = 0.0
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. To save the raw adapter alongside the merged HF weights:
```toml
[ckpt.weights]
save_adapter_separately = true
```
LoRA pairs naturally with [multi-tenant training](#multi-tenant-training) — each tenant gets its own adapter and the backbone is shared across all of them in trainer memory.
## Multi-Tenant Training
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/src/prime_rl/trainer/runs.py).
## Disaggregated Prefill/Decode Inference
@@ -206,7 +138,7 @@ For large MoE serving, splitting prefill and decode onto separate vLLM groups ca
| Agentic (SWE, Lean) | 3:1 | Long growing contexts → prefill-heavy |
| Non-agentic (math, chat) | 1:2 | Short prompts, long generations → decode-heavy |
Example config: [`examples/advanced/glm-5.3/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.3/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.3/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3/infer).
Example config: [`examples/advanced/glm-5.2/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.2/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.2/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2/infer).
Monitor live queue depths to detect imbalance:
@@ -221,7 +153,7 @@ If prefill queues and decode is idle, add prefill nodes (and vice versa).
```bash
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
uv pip install --reinstall --no-deps deps/nixl_cu13-*.whl
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
```
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
+96 -215
View File
@@ -1,6 +1,6 @@
# Algorithms
This page covers the math and the configurable algorithmic components: the algorithm abstraction and its algorithms, how off-policy training works, the loss components and advantage functions, curricula, and how multi-turn rollouts get merged into training samples.
This page covers the math and the configurable algorithmic components: the algorithm abstraction and its algorithms, how off-policy training works, the loss components and advantage functions, how to plug in your own, the filters applied between rollout and training, and how multi-turn rollouts get merged into training samples.
## Table of Contents
@@ -13,15 +13,13 @@ This page covers the math and the configurable algorithmic components: the algor
- [Async / Off-Policy Training](#async--off-policy-training)
- [Loss](#loss)
- [Loss Components](#loss-components)
- [IPO Loss](#ipo-loss)
- [Default RL Loss](#default-rl-loss)
- [Custom Loss](#custom-loss)
- [Advantage](#advantage)
- [Default Advantage](#default-advantage)
- [Hierarchical GRPO](#hierarchical-grpo)
- [Self-Play Advantage (RAE)](#self-play-advantage-rae)
- [Authoring an Algorithm](#authoring-an-algorithm)
- [Reference Scoring](#reference-scoring)
- [Curricula](#curricula)
- [Filters](#filters)
- [Multi-Turn Trajectories](#multi-turn-trajectories)
- [Extension Property](#extension-property)
- [Best-Effort Interleaving](#best-effort-interleaving)
@@ -30,29 +28,29 @@ This page covers the math and the configurable algorithmic components: the algor
## The Algorithm Abstraction
A training algorithm in `prime-rl` is configured under `[orchestrator.train.algo]`, where **`type` names the algorithm** (`grpo`, `opd`, `sft`, …) and the class defaults are its vetted setting. It has two parts:
A training algorithm in `prime-rl` is configured under `[orchestrator.algo]`, where **`type` names the algorithm** (`grpo`, `opd`, `sft`, …) and the class defaults are its vetted setting. It has two parts:
1. **Sampling** (`algo.sampling`) — how train rollouts are produced: which model generates them. `source` is a [model reference](#model-references): `"policy"` (the live policy, the default) or an inline frozen hosted model. Group sizing stays on the env config (`group_size`).
2. **The per-token training signal** — credit assignment and loss routing, fused; the algorithm's own parameters sit directly on `algo`. One mapping from a finalized rollout to per-token *(loss component, weight)* pairs — the credit a token gets and the loss that consumes it are two coordinates of the same output. Group-relative algorithms compute credit on the orchestrator and ship per-token advantage streams; reference-KL algorithms query a reference model at batch-ship time (bounded concurrency) and ship its prefill logprobs for the trainer to evaluate against the live policy. The `type` determines which loss component consumes the action tokens (`rl` / `ce` / `ref_kl`) and what happens to env-provided observation tokens in multi-turn rollouts (masked out by default; `echo` trains on them with weighted CE).
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, batch packing, or trainer hot path.
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, packer, or trainer hot path.
### Model References
`prime-rl` hosts exactly one model: the trainable policy (`[orchestrator.model]`). Every other model an algorithm uses is an external OpenAI-compatible endpoint, declared *inline on the component that uses it*. A model reference is either the string `"policy"` (the live policy) or a frozen hosted model (`name` + `base_url`):
```toml
[orchestrator.train.algo]
[orchestrator.algo]
type = "opd"
[orchestrator.train.algo.teacher] # opd's teacher: the frozen model it scores against
[orchestrator.algo.teacher] # opd's teacher: the frozen model it scores against
name = "Qwen/Qwen3-32B"
base_url = "http://localhost:8001/v1"
base_url = ["http://localhost:8001/v1"]
```
Model *roles* are algorithm-local vocabulary — each algorithm names its reference on the field where the model is actually used, and there is no shared `teacher` slot. `opd` declares a `teacher` field (the frozen model whose reverse KL the policy distills toward); `sft`'s teacher *is* its `sampling.source` (the frozen model it imitates); `opsd` self-distills against the live policy and names no model at all. No role exists outside the algorithm that declares it: the dispatcher, sink, and trainer branch on liveness alone, never on what an algorithm calls a model.
So for `opd` set `[orchestrator.train.algo.teacher]`; for `sft` set `[orchestrator.train.algo.sampling.source]`; `opsd` needs neither. `opd`'s teacher must be a frozen endpoint — it is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero); `opsd`'s teacher *is* the live policy by definition (self-distillation conditioned on a demonstration), so it exposes no reference to configure.
So for `opd` set `[orchestrator.algo.teacher]`; for `sft` set `[orchestrator.algo.sampling.source]`; `opsd` needs neither. `opd`'s teacher must be a frozen endpoint — it is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero); `opsd`'s teacher *is* the live policy by definition (self-distillation conditioned on a demonstration), so it exposes no reference to configure.
Liveness is a property of the reference, not of any role: rollouts sampled from `"policy"` get version-salted prefix caches, carry sampling logprobs for importance ratios, and age off-policy as weights update; rollouts and scores from frozen models get a stable prefix cache and never go stale. Frozen models are externally hosted (`base_url` is required) — `prime-rl` never launches or updates them, and each env's algorithm builds its own client pool to the endpoints it declares.
@@ -61,7 +59,7 @@ Liveness is a property of the reference, not of any role: rollouts sampled from
The `algo.type` names the algorithm, and each type's class defaults are its vetted setting — picking a type with no other keys IS the algorithm:
```toml
[orchestrator.train.algo]
[orchestrator.algo]
type = "grpo" # the default
```
@@ -69,8 +67,6 @@ type = "grpo" # the default
|---|---|---|---|
| `grpo` | policy | `rl` on actions | Standard group-relative RL. |
| `max_rl` | policy | `rl` on actions | MaxRL ([arXiv:2602.02710](https://arxiv.org/abs/2602.02710)): GRPO's centered reward normalized by the group **mean** instead of the standard deviation — the gradient is unbiased for the order-`group_size` truncation of the maximum-likelihood objective, upweighting hard examples like `1/p`. |
| `rae` | policy | `rl` on actions | RAE (SPIRAL, [arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): reward minus a per-agent EMA baseline of that agent's own rewards — the estimator for multi-agent self-play envs, where the group mean would mix the agents' opposite reward scales. See [Self-Play Advantage](#self-play-advantage-rae). |
| `hierarchical_grpo` | policy | `rl` on actions | GRPO for proposer-solver envs. Solvers are compared only with attempts on the same proposed problem; proposers are compared with the other proposals in the group. See [Hierarchical GRPO](#hierarchical-grpo). |
| `opd` | policy | `ref_kl` on actions | On-policy distillation ([Thinking Machines](https://thinkingmachines.ai/blog/on-policy-distillation/)): the policy samples, per-token reverse KL against a reference model as the gradient signal. Needs a `teacher`. |
| `sft` | *(the teacher)* | `ce` on actions | Hard distillation: a frozen model generates rollouts, the policy trains with CE on its tokens. Needs a frozen `sampling.source` (the teacher it samples from). |
| `opsd` | policy | `ref_kl` on actions | SDFT ([arXiv:2601.19897](https://arxiv.org/abs/2601.19897)): the model is its own reference, conditioned on an expert demonstration. The teacher *is* the live policy (the paper's setting, no extra deployment) — no model to configure. |
@@ -83,13 +79,13 @@ Every key beyond `type` is visibly your own assembly — there is no preset laye
```toml
# echo on tool AND user feedback tokens, each at its own weight.
# Setting any role replaces the whole table.
[orchestrator.train.algo]
[orchestrator.algo]
type = "echo"
[orchestrator.train.algo.roles.tool]
[orchestrator.algo.roles.tool]
alpha = 0.25
[orchestrator.train.algo.roles.user]
[orchestrator.algo.roles.user]
alpha = 0.05
```
@@ -98,11 +94,9 @@ A new algorithm is a named class in code, not a config that points at an import
Echo also takes an optional user-supplied token filter that narrows the role selection per rollout — e.g. dropping warning lines from tool output, or tokens the sampler found unlikely:
```toml
[orchestrator.train.algo.filter]
[orchestrator.algo.filter]
import_path = "my_module.drop_warnings"
[orchestrator.train.algo.filter.kwargs]
patterns = ["WARNING"]
kwargs = { patterns = ["WARNING"] }
```
```python
@@ -112,54 +106,50 @@ patterns = ["WARNING"]
def drop_warnings(rollout, *, patterns: list[str]) -> list[list[bool]]: ...
```
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and skips it), not at config time.
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and aborts after repeated zero-trainable batches), not at config time.
### Per-Env Algorithms
Both components resolve per environment. Each env inherits `[orchestrator.train.algo]` like any other group default: an env that sets only some params keeps the group's algorithm with those params changed, and an env that sets a different `type` runs its own algorithm. So a single run can mix algorithms across envs — e.g. GRPO on math, ECHO on a terminal env:
Both components resolve per environment. Each env inherits `[orchestrator.algo]` unless it sets its own, so a single run can mix algorithms across envs — e.g. GRPO on math, ECHO on a terminal env:
```toml
[orchestrator.train.algo]
[orchestrator.algo]
type = "grpo"
[[orchestrator.train.source]]
name = "math" # inherits the group's grpo
env.taskset.id = "math"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.env]]
name = "math"
taskset = { id = "math-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
# inherits the top-level grpo
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "terminal"
env.taskset.id = "terminal"
env.agent.harness.id = "bash"
env.agent.runtime.type = "subprocess"
# this env runs its own algorithm
algo.type = "echo"
taskset = { id = "terminal-v1" }
harness = { id = "bash", runtime = { type = "subprocess" } }
algo = { type = "echo" } # this env runs its own algorithm
```
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_rl.orchestrator.sampler`) from the `sampling` component — the pool rollouts are generated from, and the home of future sampling strategies like replay buffers or branching — and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
| `grpo` | `GRPOAlgorithm` | `score_group`: group-norm credit (optional length penalty) |
| `echo` | `EchoAlgorithm` | `score_episode`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
| `echo` | `EchoAlgorithm` | `score_rollout`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
| `max_rl` | `MaxRLAlgorithm` | `score_group`: mean-normalized group credit |
| `rae` | `RAEAlgorithm` | `score_group`: per-agent EMA-baseline credit |
| `hierarchical_grpo` | `HierarchicalGRPOAlgorithm` | `score_group`: GRPO baseline per episode for solvers, per group for the proposer |
| `opd` | `OPDAlgorithm` | `score_episode`: own-context prefill under the teacher |
| `opsd` | `OPSDAlgorithm` | `score_episode`: demo-conditioned prefill under the live policy |
| `sft` | `SFTDistillAlgorithm` | no credit assignment; CE on sampled tokens |
| `opd` | `OPDAlgorithm` | `score_rollout`: own-context prefill under the teacher |
| `opsd` | `OPSDAlgorithm` | `score_rollout`: demo-conditioned prefill under the live policy |
| `sft` | `SFTDistillAlgorithm` | `score_group`: group-norm credit (feeds filters) |
Algorithms operate on native verifier artifacts and annotate their message graphs directly:
Each class owns its hooks outright — reading one top to bottom reads the algorithm, and everything on the class is an override point. The two hooks are one scope-and-timing ladder — the wider scope is unlocked by a later barrier, so the two axes coincide. Each is handed the `Rollout` directly — the env's typed trace (`reward`, `nodes`, `num_turns`, ...) with `samples` attached, plus `assign_advantages` to write credit:
- `async score_episode(episode)` — rollout-local scoring as one episode arrives.
- `async score_group(episodes)` — group-relative scoring after the cohort completes.
- `async score_rollout(rollout)` — one rollout, **on arrival** (as it's tokenized, before its group is complete): rollout-local credit (`rollout.assign_advantages(...)`, scalar broadcast or per-token), observation ce weights, **or** model I/O — query a reference pool (e.g. `self.teacher_pool`, connected in `setup()` via `self.connect(...)`, or the live `self.policy_pool` for opsd) and attach per-token results (e.g. teacher logprobs) with bounded concurrency. No siblings. `echo` weights observation tokens here, identifying env-provided observation nodes by their non-sampled status and source step role attribution, applying the optional user filter, and writing the `ce_weights` stream. Model I/O runs *before* the pre-batch filters, so it pays compute on rollouts that may then be filtered out.
- `score_group(group)` — the cohort, **before filtering** (filters read the streams), synchronous: group-relative credit (GRPO/MaxRL baselines). `group` is a list of `Rollout`.
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 drives the hooks through two non-virtual methods it never looks inside: `algorithm.finalize_rollout(rollout)` per arrival (rollout-local scoring + reference I/O) and `algorithm.finalize_group(rollouts)` per group (scoring + wire stamping; after this the records are frozen — groups die at stamping). Sample construction (interleaving) is pure pipeline — observation-token provenance is available through structural attribution (`node.sampled`, `node.is_content`) for any algorithm that trains on env-provided tokens.
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`.
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 pool (`self.policy_pool`). 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.algo.advantage`.
## Async / Off-Policy Training
@@ -184,61 +174,47 @@ $$
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
$$
- `rl` — the configured RL loss (`[trainer.loss]`): IPO by default, or optionally [IcePop](#icepop-loss) or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the group-relative algorithms (`grpo`, `max_rl`, and `echo`'s action tokens).
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens, so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
### IPO Loss
### Default RL Loss
The default RL loss is Importance Policy Optimization (IPO). It is an importance-weighted policy-gradient term. A symmetric trust region removes tokens whose absolute probability change exceeds $\epsilon$:
The default RL loss is a DPPO policy-gradient term combined with a KL regularizer similar to Kimi-K2.5. For each prompt $x_j$ we sample a group of $G$ rollouts $\{y_i\}_{i=1}^G$, score them to get $s_i$, then optimize:
$$
\mathcal{L}(\theta) = -\frac{1}{N}\sum_t
\mathbb{1}\!\left(\left|\pi(y_t)-\mu(y_t)\right| \le \epsilon\right)
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}.
\mathcal{L}(\theta) = -\,\mathcal{J}_{\text{PG}}(\theta) \;+\; \tau_{KL}\,\mathcal{L}_{KL}(\theta)
$$
$\mu$ is the policy that generated the rollout. $\pi$ is the current trainer policy. $\hat{A}_t$ is the token-level advantage. The trust region uses the sampled token probabilities, not their ratio.
where the policy-gradient term is
The knobs under `[trainer.loss]` are:
$$
\mathcal{J}_{\text{PG}}(\theta)
= \frac{1}{\sum_{j,i} |y_i^{(j)}|}
\sum_{j,i,t}
\min\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}, \delta\right) \hat{A}^{(j)}_{i,t}
$$
and the KL regularizer penalizes drift between trainer and inference policies via the squared log importance ratio:
$$
\mathcal{L}_{KL}(\theta) = \frac{1}{\sum_{j,i} |y_i^{(j)}|}
\sum_{j,i,t} \log^2\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}\right).
$$
$\mu$ is the policy that generated the rollout (inference), $\pi$ is the current policy (trainer), $\hat{A}_{i,t}$ is the token-level advantage, $\delta$ is the importance-sampling clipping ratio, and $\tau_{KL}$ is the KL temperature. The `min` clamps the importance ratio from above so a stale rollout assigning very low probability to a high-reward token doesn't produce a runaway gradient.
The knobs (under `[trainer.loss]` with `type = "default"`):
| Knob | Default | What it does |
|---|---|---|
| `eps` | 0.3 | Maximum absolute probability change before a token is masked. |
| `adv_tau` | 1.0 | Temperature on the advantage term. |
| `dppo_mask_low` / `dppo_mask_high` | 0.2 / 0.2 | Lower / upper thresholds for DPPO-style token-level masking. |
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
### IcePop Loss
IcePop is an opt-in RL loss that drops tokens whose trainer-to-inference
importance ratio falls outside a fixed acceptance band, introduced to stabilize
MoE RL in [Every Step Evolves: Scaling Reinforcement Learning for Trillion-Scale
Mixture-of-Experts Reasoning Models](https://arxiv.org/abs/2510.18855). Accepted
tokens retain the importance-weighted policy-gradient term:
$$
\mathcal{L}(\theta) = -\frac{1}{N}\sum_t
\mathbb{1}\!\left(\alpha \le \frac{\pi(y_t)}{\mu(y_t)} \le \beta\right)
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}.
$$
Enable it explicitly:
```toml
[trainer.loss]
type = "icepop"
ratio_low = 0.2
ratio_high = 5.0
```
| Knob | Default | What it does |
|---|---|---|
| `ratio_low` | 0.2 | Lower accepted trainer-to-inference probability ratio. |
| `ratio_high` | 5.0 | Upper accepted trainer-to-inference probability ratio. |
| `adv_tau` | 1.0 | Temperature on the advantage term. |
Set `[trainer.loss] type = "default"` and configure via the knobs above. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
### Custom Loss
@@ -269,9 +245,7 @@ Wire it up:
[trainer.loss]
type = "custom"
import_path = "my_module.ppo_clip_loss"
[trainer.loss.kwargs]
clip_eps = 0.2
kwargs = { clip_eps = 0.2 }
```
The dataclasses:
@@ -302,11 +276,9 @@ The per-token training signal is set by `algo.type` and the [algorithm](#the-alg
|---|---|---|
| `grpo` | `rl` | Group-norm: reward minus per-group baseline, optional length penalty. |
| `max_rl` | `rl` | Mean-normalized group credit (maximum-likelihood RL). |
| `rae` | `rl` | Reward minus a per-agent EMA baseline (SPIRAL's role-conditioned advantage estimation) — for multi-agent self-play envs. |
| `hierarchical_grpo` | `rl` | GRPO for proposer-solver envs: solvers are compared within one proposed problem, while proposers are compared across proposals. |
| `echo` | `rl` + `ce` | Group-norm on action tokens, plus weighted CE on env-provided tokens selected by message role (each role's `alpha` is its ECHO λ), optionally narrowed by a user filter. |
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` and ship no advantage stream; `group_size` only fans out sampling. |
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` and ship no advantage stream. |
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream; `group_size` only fans out sampling. |
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream. |
| `sft` | `ce` | Cross-entropy on the sampled tokens. Assigns no advantage — trains on every sampled token. |
### Default Advantage
@@ -318,167 +290,78 @@ This is intentionally simple — it does the right thing for most envs. Write a
A **length penalty** (`length_penalty` on the `grpo`-family algorithms) can be layered on top to discourage rambling. The `linear` penalty subtracts a single `pass_rate`-scaled penalty from each reward before the GRPO baseline, combining output tokens (`num_output_tokens_weight`), input / context tokens (`num_input_tokens_weight`), and turns (`num_turns_weight`) — each normalized by the group's own max for that quantity, with `num_input_tokens_weight` and `num_turns_weight` defaulting to `0.1`.
```toml
[orchestrator.train.algo]
[orchestrator.algo]
type = "grpo"
[orchestrator.train.algo.length_penalty]
[orchestrator.algo.length_penalty]
type = "linear"
```
### Hierarchical GRPO
GRPO gives each rollout its reward minus the average reward of comparable rollouts. In an ordinary single-agent group, every rollout answers the same task, so one group average is enough.
A proposer-solver env is different. Starting from one source task, it produces several proposed problems, then runs several solver attempts on each problem:
```text
one source task
├── proposed problem A
│ ├── proposer trace
│ ├── solver attempt 1
│ └── solver attempt 2
└── proposed problem B
├── proposer trace
├── solver attempt 1
└── solver attempt 2
```
The solver attempts for A should not be compared with the solver attempts for B: the two problems may have very different difficulty. Proposer and solver rewards should not be compared either: they measure different jobs.
`hierarchical_grpo` therefore chooses the average separately for each role:
| Trace | Compared with | Why |
|---|---|---|
| Solver | Other solver attempts on the same proposed problem | They attempted the same problem. |
| Proposer | Other proposer traces in the group | They started from the same source task and proposed alternatives. |
For example, if three solvers receive rewards `[1, 1, 0]` on one proposed problem, their average is `2/3` and their advantages are `[1/3, 1/3, -2/3]`. Solver rewards from other proposed problems do not affect those values. The proposers are scored separately according to how useful their problems were for the solvers, then compared with the other proposers in the group.
Configure which roles are compared within a single proposed problem with `episode_agents`. For `proposer-solver`, that role is `solver`:
```toml
[orchestrator.train.algo]
type = "hierarchical_grpo"
episode_agents = ["solver"]
[[orchestrator.train.source]]
name = "proposer-solver"
group_size = 4 # proposed problems per source task
env.n = 4 # solver attempts per proposed problem
env.taskset.id = "proposer-solver"
env.proposer.harness.id = "null"
env.proposer.runtime.type = "subprocess"
env.solver.harness.id = "null"
env.solver.runtime.type = "subprocess"
```
`group_size` controls how many problems are proposed from each source task. `env.n` controls how many solvers attempt each proposed problem. If a comparison contains only one trace—for example, a solver when `env.n = 1`—its advantage is zero.
This algorithm is accepted only for proposer-solver envs. Use the env's `train_proposer` and `train_solver` settings if you want to train only one role.
### Self-Play Advantage (RAE)
Group-relative baselines assume the group is exchangeable attempts by one agent. A multi-agent self-play env breaks that: one episode yields one trace per agent, all trainable, and in a zero-sum game the rewards sum to ~0 whatever the policy does — the group mean carries no information, and centering against it converts any structural asymmetry (a first-mover edge) into permanent credit for one agent.
`rae` implements SPIRAL's role-conditioned advantage estimation ([arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): each agent keeps an exponential-moving-average baseline of its own rewards, and every trace's advantage is its reward minus its agent's baseline — measured against the *pre-update* baseline (the unbiased order), then folded in at `decay` (SPIRAL's α, default 0.95). The algorithm instance is per-env, so baselines are keyed per (env, agent) — the paper's per (game, role). Advantages are not normalized, and `group_size` is free (RAE needs no sibling rollouts; `group_size = 1` is fine). Baselines live in orchestrator memory and re-warm from 0 over ~`1/(1 − decay)` traces per agent after a restart.
```toml
[orchestrator.train.algo]
type = "rae"
decay = 0.95
[[orchestrator.train.source]]
name = "kuhn-poker"
env.taskset.id = "kuhn-poker"
env.player0.harness.id = "null"
env.player0.runtime.type = "subprocess"
env.player1.harness.id = "null"
env.player1.runtime.type = "subprocess"
```
Both of `kuhn-poker`'s agents late-bind to the run's own model — shared-policy self-play against a continuously improving opponent. Pin one agent to a frozen endpoint (`env.player1.model = ...`) for asymmetric play; its traces are marked untrainable by the env and never reach the advantage computation. A single-agent env under `rae` degrades to REINFORCE with an EMA baseline.
### Authoring an Algorithm
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class:
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class. The hook receives the group's `Rollout`s (each the env's typed `verifiers.Trace` — turns, tool calls, metadata in `info` — with `samples` attached) and writes credit via `assign_advantages`:
```python
# src/prime_rl/orchestrator/algo/my_algo.py
import torch
from prime_rl.orchestrator.train.algo.base import Algorithm
from prime_rl.orchestrator.train.algo.routing import assign_advantages
from prime_rl.orchestrator.algo.base import Algorithm
class MyAlgorithm(Algorithm):
async def score_group(self, episodes):
traces = [trace for episode in episodes for trace in episode.traces]
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
advantages = ... # one value per trace
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
assign_advantages(trace, advantage)
async def score_group(self, group):
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
advantages = ... # one value per rollout
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
rollout.assign_advantages(advantage)
```
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick `score_episode` for rollout-local work or model calls, and `score_group` for group-relative credit. `assign_advantages` takes a scalar or a list aligned to the trace graph's sampled tokens.
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick the hook by *when* your signal is ready: `score_rollout` for per-arrival credit or credit that needs a model call (it's `async`), `score_group` for group-relative credit (GRPO/MaxRL). `assign_advantages` takes a scalar (broadcast over the rollout's trainable tokens — the common case) or a full-length per-token list aligned to the concatenated sample token_ids (process rewards, step-level credit; `0.0` off-mask).
Curriculum admission and metrics can inspect the resulting graph-native streams after group scoring.
Each per-token list must match the rollout's completion-token count exactly — validated loudly when the view writes it. Advantage-based filters and metrics derive from the streams (the zero-advantage filter checks for all-zero streams; logged distributions use per-rollout means). Signals that depend on the live policy's weights (like OPD's reverse KL) cannot be precomputed here; those are reference-scoring algorithms, evaluated in the trainer.
### Reference Scoring
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_episode`: as each episode arrives they query a reference and attach sampled-token reference logprobs to its graph nodes:
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_rollout`: as each rollout arrives they query a reference (the sample's own context for `opd`, the demo-conditioned context for `opsd`) and attach per-token reference logprobs to each sample. Rollouts are consumed serially by the orchestrator's main loop and each carries only a handful of samples, so the in-flight request count is naturally bounded — no explicit concurrency cap:
- `opd` — score each sample's own context under the `teacher` (a frozen [model reference](#model-references)) via prefill; fills `ref_logprobs` for the `ref_kl` loss component (on-policy distillation). The `teacher` is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero).
- `opsd` — SDFT: prepend an expert demonstration as a leading system message (`template`, with a `{demonstration}` placeholder) and score the sample under that demo-conditioned context. The sample is scored verbatim (`hint_block + token_ids`, slicing the hint's logprobs back off), so the join is BPE-clean and it's robust to tool/multimodal prompts and any number of turns. The scoring reference *is* the live policy — self-distillation names no teacher. opsd builds its own renderer to tokenize the hint block: the tokenizer is always the live policy's (not configurable — there is no separate model), and only the `renderer` family is settable (defaults to `"auto"`, resolved from the policy tokenizer; set it to match a non-auto policy renderer). The demonstration is read from the example's `info[demo_key]`, falling back to a top-level rollout field of the same name (e.g. `answer`).
```toml
[orchestrator.train.algo]
[orchestrator.algo]
type = "opsd"
demo_key = "demonstration"
```
Scoring runs before curriculum admission, so a rollout that is later rejected still costs its reference compute.
Scoring runs at arrival, *before* the pre-batch filters, so a rollout that is later filtered still cost its reference compute — accepted for the simpler one-rollout-at-a-time shape (advantage-based filters never fire for opd/opsd anyway, since neither assigns an advantage).
The orchestrator filters samples with no training signal. This includes samples with zero advantage on all RL tokens. Samples that still carry CE or reference-KL components are retained. Filtering an RL token also removes its trainer/inference mismatch-KL contribution.
## Filters
`orchestrator.constant_trainer_batch_size` defaults to `true`. The orchestrator filters samples before they count toward the batch target. It collects replacements, so rollout-based batches contain `orchestrator.batch_size` training traces. Set the option to `false` to filter after collection without replacement. This setting can improve orchestrator throughput, but it produces smaller trainer batches.
Filters drop rollouts between scoring and training. Built-ins (composable):
## Curricula
| Filter | Effect |
|---|---|
| `gibberish` | Drops rollouts whose mean log-prob fall below a threshold — usually a sign of degenerate output. |
| `repetition` | Drops rollouts with high n-gram repetition. |
| `zero_advantage` | Drops rollouts whose advantage is zero, so the trainer doesn't waste tokens on them. |
Each training source has a `Curriculum` composed from one `TaskSampler` and any number of named `AdmissionGate`s. The sampler chooses tasks and observes every finalized `list[vf.Episode]`; each gate inspects the same native episodes. The group trains only if every gate admits it. Rejected groups remain observable while the orchestrator samples again to fill the batch.
Samplers and gates can be stateful. Their `state_dict`, `load_state_dict`, and `metrics` methods are included in orchestrator checkpoints and logged under `curriculum/<env>/`.
Three small implementations are included:
- `StandardSampler` is the default: it advances the task iterator and cycles finite tasksets in source order.
- `DifficultyPoolSampler` samples finite tasksets with replacement and tracks each task's latest valid mean group reward. Each named pool has an inclusive reward threshold and a relative per-task sampling weight; weight `0` disables sampling from that pool. Unseen tasks use neutral weight `1.0`, so pool observations affect sampling immediately without waiting for a full taskset pass.
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in token filter, it can reject a configurable advantage range. Groups without an advantage stream are admitted.
The default `[orchestrator]` config registers all three in both filter slots: `post_batch_filters` enforce by default (flagged rollouts are recorded but not shipped to the trainer), while `pre_batch_filters` run in monitor mode (`enforce = false`); flip `enforce = true` there to drop matching rollouts before they consume a slot in the batch. Setting a slot replaces its defaults wholesale:
```toml
[orchestrator.train.source.curriculum.sampler]
type = "difficulty_pool"
[[orchestrator.post_batch_filters]]
type = "zero_advantage"
[orchestrator.train.source.curriculum.sampler.pools.hard]
threshold = 0.25
weight = 0.2
[orchestrator.train.source.curriculum.sampler.pools.normal]
threshold = 0.75
weight = 1.0
[orchestrator.train.source.curriculum.sampler.pools.easy]
threshold = 1.0
weight = 0.2
[orchestrator.train.source.curriculum.gates.low_signal]
type = "advantage_range"
reject_min = -0.05
reject_max = 0.05
[[orchestrator.post_batch_filters]]
type = "repetition"
threshold = 0.4
```
Filtered rollouts still appear in W&B distributions, just not in the trainer batch — useful for spotting whether filtering is doing its job.
## Multi-Turn Trajectories
For multi-turn rollouts (tool use, browser environments, long conversations), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
Multi-turn rollouts (tool use, browser environments, long conversations) used to be stitched into a single fake "single-turn" sample, which silently corrupted the importance ratio when chat templates didn't roundtrip. Since [`verifiers` v0.1.8](https://github.com/PrimeIntellect-ai/verifiers/releases/tag/v0.1.8), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
### Extension Property
@@ -544,8 +427,6 @@ Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `glm-5`, `glm-4.5`
name = "auto" # detect from tokenizer; pass an explicit name for fine-tunes
```
A renderer outside the `renderers` package loads as a custom renderer: `name = "custom"` with `import_path = "my_module.Class"` (or `path/to/file.py:Class`), see [Custom renderers](training.md#dataset-format).
For the full design rationale (failure modes ruled out, empirical token-identity comparison against `apply_chat_template`, when to write a hand-coded renderer), see [the renderers writeup on the Prime Intellect blog](https://www.primeintellect.ai/blog/renderers) — the canonical reference.
### Discontinuous Trajectories
+36 -75
View File
@@ -2,7 +2,7 @@
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions) that aren't surfaced here.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
## Table of Contents
@@ -17,7 +17,7 @@ Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeInt
- [Optional Sub-Configs](#optional-sub-configs)
- [None](#none)
- [Discriminated Unions](#discriminated-unions)
- [Environments](#environments)
- [Environments](#environments-orchestratortrainenv)
- [Environment Variables](#environment-variables)
- [Examples](#examples)
@@ -50,18 +50,18 @@ CLI flags mirror the TOML tree using dots:
--max-steps 50 # top-level
--model.name Qwen/Qwen3-4B # nested
--trainer.optim.lr 1e-5 # double-nested
--inference.vllm.tensor-parallel-size 4
--inference.parallel.tp 4
```
> Field names are snake_case in TOML (`max_model_len`) and kebab-case on the CLI (`--max-model-len`).
> A renamed field keeps no alias for its old name: the old spelling fails as an unknown key rather than being silently translated.
> Renamed fields keep their old name as a validation alias — e.g. `rollouts_per_example` is still accepted in TOML and CLI after being renamed to `group_size`. Mixing the two names across sources is safe.
## Inspecting and Validating
```bash
uv run rl --help # full schema
uv run rl @ rl.toml --dry-run --output-dir /tmp --run.name check # write resolved configs (JSON) to /tmp/check/configs
uv run rl @ rl.toml --dry-run --output-dir /tmp/check # write resolved configs
```
## Syntax
@@ -71,12 +71,12 @@ uv run rl @ rl.toml --dry-run --output-dir /tmp --run.name check # write resolv
CLI uses paired flags: bare `--flag` sets `True`, `--no-flag` sets `False`. TOML must be explicit:
```bash
uv run rl @ rl.toml --clean # True
uv run rl @ rl.toml --no-clean # False
uv run rl @ rl.toml --clean-output-dir # True
uv run rl @ rl.toml --no-clean-output-dir # False
```
```toml
clean = true
clean_output_dir = true
```
### Lists
@@ -93,21 +93,20 @@ uv run rl @ rl.toml --trainer.model.lora.target-modules '["q_proj", "k_proj", "v
target_modules = ["q_proj", "k_proj", "v_proj"]
```
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables, see [Environments](#environments).
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables (e.g. environments), see [Environments](#environments-orchestratortrainenv).
### Dicts
CLI takes a JSON literal. TOML uses a table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
CLI takes a JSON literal. TOML uses a table or inline-table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
```bash
uv run rl @ rl.toml --orchestrator.train.source.0.args \
uv run rl @ rl.toml --orchestrator.train.env.0.args \
'{"dataset_name": "openai/gsm8k", "dataset_subset": "main"}'
```
```toml
[[orchestrator.train.source]]
args.dataset_name = "openai/gsm8k"
args.dataset_subset = "main"
[[orchestrator.train.env]]
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
```
### Optional Sub-Configs
@@ -124,11 +123,11 @@ To **disable** a sub-config that's on by default, use `--no-<name>` on the CLI o
TOML has no `null`. Use the string `"None"`, which the loader coerces:
```toml
[inference.vllm]
[inference.model]
max_model_len = "None"
```
On the CLI: `--inference.vllm.max-model-len None`.
On the CLI: `--inference.model.max-model-len None`.
### Discriminated Unions
@@ -143,61 +142,30 @@ mu = 0.95
Omit `type` to keep the default variant.
### Environments
### Environments (`[[orchestrator.train.env]]`)
Training and evaluation sources are arrays of tables. Set one source per environment; training sources can optionally carry sampling weights:
Training environments are an array of tables — set one per env, optionally with sampling weights:
```toml
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "gsm8k"
env.taskset = { id = "gsm8k-v1", split = "train" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
ratio = 3 # 75% of batches
env.taskset.id = "gsm8k"
env.taskset.split = "train"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
ratio = 1 # default — 25% of batches
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "gsm8k-eval"
env.taskset.id = "gsm8k"
env.taskset.split = "test"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
env.taskset = { id = "gsm8k-v1", split = "test" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
```
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — holds defaults for its sources. Every field that a group and its sources both have is a default: `env`, `sampling`, `select` and `group_size`, plus `algo` on the train group and `interval` on the eval groups of a training run. Each source inherits the fields that its group sets. One rule applies to all of them: nested blocks merge key by key, a source's own values win, and a block whose `type` (e.g. of `algo`) differs from the group's is the source's alone.
```toml
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
type = "grpo"
[[orchestrator.train.source]]
env.taskset.id = "math"
group_size = 32 # this source's own value wins over the group's 16
[orchestrator.eval.env]
retries.rules = [
{type = "ProviderError", max_retries = 3},
{type = "SandboxError", max_retries = 3},
]
timeout.episode = 7200
[orchestrator.eval.select] # evaluate 128 tasks of each taskset
limit = 128
```
The group `env` block holds only the knobs that every env and taskset has: `retries`, `timeout`, `max_concurrent_agents`, `interception`, and `taskset.task` and `taskset.system_prompt`. Ids and agents stay on each source. `select` picks which tasks of a source's taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit`, in that order.
`ratio` is a training-source field: it defaults to `1` (equal weight per env), and values are relative weights normalized to probabilities across envs. Eval sources of a training run carry `interval` instead, the step interval at which they fire; a standalone eval has neither.
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
Everything environment lives under the `env` block (verifiers' `[env]` shape): `env.taskset` configures the v1 taskset, and each agent is a field on the env — `env.agent.harness` selects how the single-agent env's tasks are run, and per-run caps are per-agent (`env.agent.max_turns`, `env.agent.timeout`, `env.agent.max_output_tokens`). A multi-agent env declares its own seats (`env.<role>.*`).
@@ -224,7 +192,7 @@ PYTORCH_CUDA_ALLOC_CONF = "expandable_segments:False"
VLLM_USE_DEEP_GEMM = "1"
[orchestrator.env_vars]
PRIME_LOG_LEVEL = "debug"
PI_USAGE_BASE_URL = "https://..."
```
The `rl` launcher applies these the same way in both single-node and multi-node (SLURM) runs. Precedence, low to high:
@@ -251,11 +219,11 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
**Advanced** (32–2048 GPUs, SLURM):
- [**Qwen3-30B-A3B**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-30b-a3b) — `Qwen3-30B-A3B` on math, SWE, and tool use.
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal; includes a variant that trains the 100B+ MoE on only two nodes.
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal.
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale `GLM-5`/`GLM-5.3` inference with P/D disaggregation and FP8.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation and FP8.
### Worked Example: Compose, Override, Dry-Run
@@ -263,24 +231,17 @@ Start from a shipped base config, override two fields on the CLI, and dry-run:
```bash
uv run rl @ examples/basic/reverse-text/rl.toml \
--monitors.wandb.name my-experiment \
--wandb.name my-experiment \
--trainer.optim.lr 5e-6 \
--output-dir /tmp/reverse-dry \
--run.name check \
--dry-run
```
Then inspect the resolved config:
```bash
ls /tmp/reverse-dry/check/configs/latest/resolved/
# rl.json trainer.json orchestrator.json inference.json
ls /tmp/reverse-dry/configs/
# rl.toml trainer.toml orchestrator.toml inference.toml
```
Each per-process JSON contains the final, validated configuration that the run
uses. This is also what each standalone process reads. For example, the trainer
reads `configs/latest/resolved/trainer.json`.
`configs/latest/command.txt` records the shell-safe launch command and its CLI
overrides. Each launch also remains under `configs/attempt_<n>/`. To compare
configs, dry-run a known-good base and your overlay. Then diff the two attempts.
Each per-process TOML reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/configs/trainer.toml`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
+4 -17
View File
@@ -14,7 +14,6 @@ This page covers workflows for developing on `prime-rl` itself — running the t
- [Implement the Modeling Code](#implement-the-modeling-code)
- [Register a Mini Preset](#register-a-mini-preset)
- [Run the Smoke Test](#run-the-smoke-test)
- [Adding a Custom VLM Implementation](#adding-a-custom-vlm-implementation)
## Test Suite
@@ -42,7 +41,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
| Workflow | Trigger | What runs | Where |
|---|---|---|---|
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_multi_run`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
@@ -109,7 +108,7 @@ uv run sft \
--data.name PrimeIntellect/Reverse-Text-SFT \
--max_steps 200 \
--optim.lr 1e-4 \
--ckpt
--ckpt.weights
```
Then run the full RL stack on reverse-text:
@@ -118,8 +117,8 @@ Then run the full RL stack on reverse-text:
uv run rl @ configs/ci/integration/reverse-text-moe/start.toml \
--model.name samsja/mini-glm-moe \
--trainer.model.impl custom \
--inference.vllm.gpu-memory-utilization 0.7 \
--inference.vllm.max-model-len 2048
--inference.gpu-memory-utilization 0.7 \
--inference.model.max-model-len 2048
```
What to look for:
@@ -138,15 +137,3 @@ Before merging a new model, you need to ensure the following:
- The small smoke test passes.
In the PR that adds the new model, you also need to provide a table covering the KL mismatch across 20 steps on `math` environment with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not met, the PR will not be merged (unless reasonable justification is provided). This is to ensure all our models are consistent and their implementations match the implementations in the inference framework.
## Adding a Custom VLM Implementation
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body. The unified dense/MoE Qwen3.5 implementation in `models/qwen3_5/` is the reference. The pieces, in dependency order:
1. **Custom text model first.** The VLM body wraps a custom `*ForCausalLM` (see [Adding a New Model](#adding-a-new-model)), so the text side — including its state-dict conversion and KL-mismatch table — comes first.
2. **Composite VLM body.** A `*VLMModel` that holds the vision encoder and custom text model, embeds tokens, runs vision, scatters image embeddings over placeholder tokens, and builds MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
6. **Context parallelism (optional).** CP-capable VLMs hold a `CPContext` on all modules which need to be CP-aware and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
7. **Validation.** Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the `color-codeword` environment is the reference task).
-127
View File
@@ -1,127 +0,0 @@
# Eval
This page covers `uv run eval` — evaluating a model in one or more environments. For the online evals of a training run, see [Training](training.md#online-evals).
> **AI agents working in this repo:** the equivalent runbook is at [`skills/eval/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/eval/SKILL.md).
## Table of Contents
- [Launch](#launch)
- [Configuration](#configuration)
- [Resume](#resume)
- [Monitors](#monitors)
- [File](#file)
- [Prime](#prime)
- [Metrics](#metrics)
`uv run eval` runs one epoch of every configured source and exits. It reuses the orchestrator's eval pipeline: env servers are spawned per source, episodes are admitted under the concurrency controller, and every episode streams into the run's trace stream and metrics.
## Launch
By default the model is served by Prime Inference; authenticate with `PRIME_API_KEY` or `prime login`:
```bash
uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Inference
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
```
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
```bash
uv run inference --vllm.model Qwen/Qwen3-4B
uv run eval gsm8k -n 32 -r 4 -m Qwen/Qwen3-4B --client.base_url http://localhost:8000/v1
```
Single-source shorthands: `<taskset-id>` names the run's only source, `--env.<field> <value>` sets a field of that source's env block (`--env.agent.harness.id bash`, `--env.taskset.tasks '["fix-git"]'`), `-n`/`-s`/`-r` set `select.limit`/`select.shuffle`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). `<taskset-id>` cannot be combined with a TOML that defines `[[source]]` blocks; next to one, `--env.<field>` sets the shared [env block](#configuration) instead. `uv run eval -h` lists them.
Against a local vLLM deployment, set `min_inflight < max_inflight` in `[concurrency]` to dynamically adjust the number of concurrent episodes for maximum throughput. An external API exposes no vLLM `/metrics` to adapt to, so pin the concurrency there (`-c N`, i.e. `min_inflight = max_inflight`).
## Configuration
Multi-source runs use a TOML (`EvalConfig` in `packages/prime-rl-configs/src/prime_rl/configs/eval.py`). The eval block is flattened to the top level — `[[source]]`, `[client]`, `[concurrency]`, `[sampling]`, `[select]`, `group_size` — and each source takes the same `env` block as `[[orchestrator.eval.source]]`:
```toml
model = "Qwen/Qwen3-4B"
group_size = 4
[select] # every source inherits these
limit = 32
[client]
base_url = "http://localhost:8000/v1"
[concurrency] # adaptive against a local vLLM deployment
min_inflight = 8
max_inflight = 256
[sampling]
max_completion_tokens = 2048
[env] # every source inherits these
timeout.episode = 7200
retries.max_retries = 3
[[source]]
env.taskset.id = "gsm8k"
env.agent.harness.id = "bash"
[[source]]
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
select.include.idx = ["0:30"]
```
Per-source `group_size` and `sampling` override the top-level defaults. The top-level `[env]` block holds the env knobs that every source inherits (see [Environments](configuration.md#environments)); a source's own `env` values win.
Each field a source sets in its `select` overrides the same field of the top-level `[select]`. `select` picks which tasks of the taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit` (see verifiers' [Selecting tasks](../deps/verifiers/docs/v1/tasksets.md#selecting-tasks)). Train sources take the same `select`.
Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
## Resume
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: the episodes that landed rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch) and only the rollouts still owed run. Errored episodes and the ones the interruption cut off run again.
```bash
uv run eval @ eval.toml --run.name my-eval
# <interrupted>
uv run eval @ eval.toml --run.name my-eval --resume
```
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
A landed episode counts toward the task with its `task.key`, so `select` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
## Monitors
Monitors receive the run's metrics and episodes through one abstraction. The file monitor is on by default; `--monitors.wandb` logs the run to Weights & Biases; `--monitors.prime` streams it to the Prime platform.
### File
The file monitor writes the run's metrics and trace stream under `output_dir / run.name / monitors/file/` and feeds the local [dashboard](training.md#dashboard). Env servers stream every rollout to the eval process as it happens: the trace's header when it is minted, then one delta per committed turn (the new messages and the model call behind them), per phase change (boot, setup, agent, finalize, scoring), and a preview of each model request's uncommitted messages, so a tool result shows the moment the model is asked about it rather than with the reply. The file monitor appends those deltas to `monitors/file/traces/live/<trace_id>.jsonl` and deletes the file when the episode lands in the finished trace stream, so that directory is exactly the live set and finished traces stay where they always were. The dashboard's traces tab shows live rollouts in the episode table itself: a pulsing dot in the `#` cell marks the row, a phase badge says where the rollout is (boot, setup, running, finalize, scoring), the `dispatched → arrived` column shows the dispatch time with the elapsed time in brackets, and the turn, token and branch counts grow as deltas land. The status filter toggles live and completed rows, and a live row opens in the trace viewer, which follows the rollout turn by turn (the transcript stays pinned to the newest turn until you scroll up; folded entries stay folded; the pending messages of the request in flight render dimmed with an `awaiting model` chip). The table and an open live trace poll once a second and transfer nothing while the rollout is unchanged. The progress line in `eval.log` counts the live rollouts by phase (`2 inflight episodes ... - boot 1 · running 1`). Read a live trace from a shell with `uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`. The same stream exists for RL runs, covering train and online-eval rollouts alike.
The dashboard's overview tab reads the trace stream directly. It shows one env at a time; the filter menu picks the env and whether errored episodes join the distributions. A block bar has one cell per expected episode: landed episodes (errored ones in red; click one to open it), live rollouts as pulsing outlines (click one to follow it), and the rest empty, with the percentage beside it. The expected count is what the eval runner wrote to `monitors/file/plan.json` when it counted the epoch's tasks. Below the bar, a summary row gives the headline numbers: avg@k and pass@k, the error and truncation rates (yellow past 10%, red past 50%), mean turns and branches in one tile, mean episode time and tokens, and the total cost when the run has costs; hover a tile for its distribution. The env's own rewards and metrics follow, a beeswarm pane each, resizable like the training charts. The usage section is one pane splitting each episode's tokens into input and output, and the timing section is the same pane over the phases of a rollout (boot, setup, model, harness, finalize, scoring, and `other` for wall time no phase accounts for): an icicle bar shows the mean split, one strip per episode below shows the split per rollout, and a legend sits above. Hovering a phase highlights it across the pane; the strips show 40 episodes by default and all of them on `show all`. A metric every episode shares appears as a chip instead of a pane, and a metric with only a few distinct values, such as a binary reward, as a counted dot plot with the count and share of each value. Every dot is an episode (or a task): hover it for its value and click it to open the trace; hover the pane's background for the summary (min, p10, median, p90, max), with a faint boxplot behind the dots. Errored episodes stay out of the distributions until the filter includes them, where they read red. The metrics tab charts every key of the run's `metrics.jsonl`: the epoch's `eval/<env>/…` summaries and the time-keyed `inference/` and `concurrency/` rows the runner samples while the epoch is in flight.
### Prime
`--monitors.prime` streams each source's epoch as an evaluation on the Prime platform:
```bash
uv run eval gsm8k -n 32 -r 4 -c 8 --monitors.prime
```
The monitor opens one platform evaluation per env when its epoch starts, streams every episode to it as it lands, and closes it with the epoch's aggregates. The run leaves its platform identity in `monitors/prime/run.json` (the training run's id and URL, or one entry per eval epoch), and the dashboard's top bar shows a `view on platform` link from the moment the evaluation opens: a direct link for a training run or a single evaluation, a menu when a run has several.
## Metrics
Eval metrics mirror the training rollout hierarchy under the `eval/<env>` scope:
| Metric | Reading |
|---|---|
| `eval/<env>/all/<agent>/reward/mean` | mean reward over the epoch |
| `eval/<env>/all/<agent>/is_truncated/mean` | share of rollouts cut by the length limit |
| `eval/<env>/all/<agent>/is_timeout/mean` | share of rollouts stopped by a stage deadline (`<stage>_timeout`) |
| `eval/<env>/all/<agent>/has_error/mean` | share of rollouts that raised |
| `eval/<env>/all/seq_len/mean` | mean episode length in tokens |
Task-specific env metrics (e.g. `correct_answer`, `format`) appear under the same prefix. The console summary line per source (`Evaluated <env> ... Reward 0.8125`) reports the epoch mean.
+50 -84
View File
@@ -12,7 +12,6 @@ This page covers the inference configuration and the supported features/deployme
- [P/D Disaggregation](#pd-disaggregation)
- [Router](#router)
- [Routing policies](#routing-policies)
- [Adaptive Concurrency](#adaptive-concurrency)
- [Advanced Configuration](#advanced-configuration)
- [KV Cache Offload](#kv-cache-offload)
- [Optimized P/D disaggregation deployment](#optimized-pd-disaggregation-deployment)
@@ -31,9 +30,7 @@ We support 3 distinct deployment shapes:
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
Every deployment shape has the same client-facing layout: a single global router listens on `inference.server.port` and fronts all vLLM engines, which listen on `inference.backend_port` (+ rank offset). Clients always talk to one URL, regardless of how many engines run behind it.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape and topology knobs such as `num_nodes` and `num_replicas`.
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `backend_port`, and a `[...deployment.router]` block, etc.
```toml
[inference.deployment]
@@ -43,7 +40,7 @@ type = "single_node" # or "multi_node" or "disaggregated"
To configure the inference server, you can use the `InferenceConfig` field. This is a config-field that allows you to set the inference server-specific knobs. Most of these are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
```toml
[inference.vllm]
[inference]
model = "PrimeIntellect/INTELLECT-3"
...
```
@@ -59,23 +56,23 @@ The single-node deployment is the default deployment shape. It runs the inferenc
type = "single_node"
```
The launcher starts a `vllm-router` on `inference.server.port` (default `8000`) fronting the vLLM engine on `inference.backend_port` (default `8100`). Clients connect to the router URL; admin operations (weight updates, health checks) bypass the router and hit the engine port directly — the RL entrypoint wires `orchestrator.model.client.admin_base_url` accordingly.
This deployment shape runs the inference server on a single node, if configured with NVLink enabled, it allows you more freedom in terms of parallelism configurations.
```toml
[inference.vllm]
[inference]
enable_expert_parallel = true # defaults to False
tensor_parallel_size = 2
data_parallel_size = 4
[inference.parallel]
tp = 2
dp = 4
[inference.deployment]
type = "single_node"
```
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required concurrency (see [Adaptive Concurrency](#adaptive-concurrency)). Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required `orchestrator.max_inflight_requests`. Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.vllm.enable_expert_parallel` or `inference.vllm.tensor_parallel_size` to maximize the available GPU memory.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.enable_expert_parallel` or `inference.parallel.tp` to maximize the available GPU memory.
You can also increase the available KV cache memory by enabling `inference.kv_cache_offload`. More details in the [Advanced Configuration](#advanced-configuration) section.
@@ -85,7 +82,7 @@ You can also increase the available KV cache memory by enabling `inference.kv_ca
This deployment shape branches into 2 sub-shapes:
- [Multi-replica](#multi-replica) - Runs the inference server on multiple nodes, but each node runs an independent vLLM replica. You can think of this as a for-loop over single-node deployments.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.vllm.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
- [Wide-EP](#wide-ep) - This option is gated behind `inference.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
### Multi-replica
@@ -97,31 +94,35 @@ Parallelism configuration is the same as the single-node deployment. The shape i
type = "multi_node"
num_nodes = 2
[inference.vllm]
[inference]
model = "PrimeIntellect/INTELLECT-3"
tensor_parallel_size = 2
data_parallel_size = 4
[inference.parallel]
tp = 2
dp = 4
```
This configuration will run 2 independent vLLM replicas, each with `tensor_parallel_size=2` and `data_parallel_size=4`. Routing is handled by a single global router running on the first inference node, fronting the per-rank endpoints of all replicas — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[inference.router]` block. You can read more about the supported routing options in the [router](#router) section.
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a router instance running on the same node as the 1st replica — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[...deployment.router]` block. You can read more about the supported routing options in the [router](#router) section.
### Wide-EP
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.vllm.enable_expert_parallel = true`.
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.enable_expert_parallel = true`.
```toml
[inference.deployment]
type = "multi_node"
num_nodes = 2
[inference.vllm]
[inference]
model = "PrimeIntellect/INTELLECT-3"
enable_expert_parallel = true
tensor_parallel_size = 2
data_parallel_size = 8
[inference.parallel]
tp = 2
dp = 8
```
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tensor_parallel_size = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tp = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
## P/D Disaggregation
@@ -159,57 +160,45 @@ num_train_nodes = 4
num_infer_replicas = 3
```
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes, fronted by the single global router.
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes and start 3 separate router instances.
## Router
Every deployment fronts its vLLM engines with a single global router — it listens on `inference.server.port` and is the one URL clients connect to. The backend is configured via a discriminated `[inference.router]` block (`type = "vllm-router" | "llm-d"`):
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
```toml
[inference.router] # or [router] for the standalone inference entrypoint
[inference.deployment.router] # or [deployment.router] for the standalone inference entrypoint
type = "llm-d" # "vllm-router" (default) or "llm-d"
non_cached_tokens = 16 # llm-d only: below this many non-cached prompt tokens, skip remote prefill (P/D)
# llm-d only: base scorer weights, applied to every profile
[inference.router.scorers]
"prefix-cache-scorer" = 3.0
"active-request-scorer" = 2.0
# llm-d only: merged onto the P/D prefill profile (decode_scorer_overrides for decode)
[inference.router.prefill_scorer_overrides]
"queue-scorer" = 2.0
"kv-cache-utilization-scorer" = 2.0
# llm-d-only knobs (all optional):
scorers = { "prefix-cache-scorer" = 3.0, "active-request-scorer" = 2.0 } # base, applied to every profile
prefill_scorer_overrides = { "queue-scorer" = 2.0, "kv-cache-utilization-scorer" = 2.0 } # merged onto the P/D prefill profile
decode_scorer_overrides = {} # merged onto the P/D decode profile
non_cached_tokens = 16 # below this many non-cached prompt tokens, skip remote prefill (P/D)
```
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`. The only backend supported for single-node (local) deployments.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy (multi-node / disaggregated SLURM deployments only). Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`.
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy. Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
Both backends support the 2 most important things:
- Request routing - KV cache re-use and balanced routing
- P/D disaggregation - handling the prefill and decode stages separately
### Routing policies
The policies you might want to configure are:
- `sticky_least_loaded` - the default policy. A new `X-Session-ID` is assigned to the least-loaded replica, then every later turn in that rollout remains on the same replica for KV cache reuse. The orchestrator releases sessions when rollouts complete, fail, or are cancelled, including traces discarded during retries. Failed release requests are logged without disabling future cleanup.
The 2 policies you might want to configure are:
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - this works by hashing a request header to determine where to route the request to. You can configure what to hash by setting
`orchestrator.model.client.extra_headers_from_state` to the header the `router` expects to be set.
- `consistent_hash` - hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica, preserving KV cache reuse without considering current load.
We set it to a sensible default, that works with all verifiers environments.
```toml
[orchestrator.model.client.extra_headers_from_state]
X-Session-ID = "trajectory_id" # this is the default - each rollout has a unique trajectory_id and router expects X-Session-ID
```
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
## Adaptive Concurrency
The orchestrator continuously sizes how many episodes run against the inference engines at once. A static cap cannot be right: too low starves the engines, too high crosses into KV thrash — the engines evict prefix cache, re-prefill the evicted work, and throughput collapses. The optimal value depends on the model, the deployment, and the workload's episode lengths, and it moves as training changes the policy.
The controller's idea is to treat the engines as ground truth and probe, instead of modeling episode cost: while the engines show headroom, admit a little more; when they show pressure, back off. Three behaviors, in increasing severity:
- **Grow**: while the engines look healthy and the current cap is fully used, raise it multiplicatively. Growth is clocked by the pipeline itself — the cap rises by a fixed factor each time the in-flight pool has turned over once — so a fast single-turn workload ramps in seconds while a slow agentic workload ramps at its own pace, with no tuning per workload.
- **Trim**: episodes grow their context *while running*, so a pool that fit comfortably an hour ago can outgrow memory without a single new admission. When KV usage nears the ceiling, the controller first lowers the cap and lets completions drain the pool naturally (soft — no work lost); only if usage keeps climbing despite the closed gate does it also cancel the youngest episodes (hard — least work lost).
- **Cut**: when the engines are demonstrably overloaded — requests being preempted, or piling up in the waiting queue — cut the pool hard, cancel the excess, and hold further cuts until the system settles.
The cap starts from a safe bound derived from the engines (KV capacity divided by the maximum context length), or from `initial_inflight` when a good value is known, and always stays within `[min_inflight, max_inflight]`.
## Advanced Configuration
### KV Cache Offload
@@ -262,57 +251,34 @@ For configuring various knobs with environment variables, we enable you to confi
[inference.deployment]
type = "disaggregated"
[inference.deployment.prefill_env_vars]
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
"VLLM_DEEP_GEMM_WARMUP" = "skip"
[inference.deployment.decode_env_vars]
"VLLM_DEEP_GEMM_WARMUP" = "skip"
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip"}
```
These are role-specific and layer on top of [`env_vars`](configuration.md#environment-variables) shared by all inference processes regardless of role.
### Other vLLM features
The `[inference.vllm]` section is a pass-through: every key is forwarded to the vLLM server under vLLM's own argument name, whether prime-rl types it or not. Anything `vllm serve` accepts can be set here.
We support various other vLLM features. Some of those, such as `enable_dbo`, `enable_eplb` are exposed as a top-level config fields. For those that are not, you can configure them by setting `inference.vllm_extra` to the desired value.
```toml
[inference.vllm]
[inference.vllm_extra]
headless = true
max_num_seqs = 256
```
On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (or `--vllm.max-num-seqs 256` for the standalone inference entrypoint); dict-valued arguments take a JSON string, e.g. `--vllm.compilation-config '{"cudagraph_mode": "NONE"}'`.
### Router Replay
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Standard deployments use the V2 model runner. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
To enable router replay, you can set `inference.enable_return_routed_experts = true`.
```toml
[trainer]
enable_router_replay = true # this will also auto-set inference.vllm.enable_return_routed_experts = true
enable_router_replay = true # this will also auto-set the inference.enable_return_routed_experts = true
[inference.vllm]
[inference]
enable_return_routed_experts = true
```
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend increasing `orchestrator.*.env.num_workers` to allow for more parallelization on the verifiers side.
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
### Sampling Replay
Truncated sampling (`top_p < 1`, `top_k`) renormalizes the sampling distribution over a sampling mask of surviving token ids. The rollout logprobs reflect that (`logprobs_mode = "processed_logprobs"`), so the trainer must renormalize over the same mask — otherwise every importance ratio is biased and training collapses (DeepSeek V3.2's "Keep Sampling Mask", [arXiv:2512.02556](https://arxiv.org/abs/2512.02556) §3.1; Cognition's [SWE-1.7 post](https://cognition.com/blog/swe-1-7)). prime-rl handles this automatically: vLLM records the sampling mask at sampling time (`--return-sampling-mask`, native since vLLM 0.28) and the trainer renormalizes its logprobs over it.
```toml
[orchestrator.train.sampling]
top_p = 0.95
top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling mask)
```
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`; Gemma-family (softcapped) lm_heads fail loudly. Frozen-source envs are exempt.
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
-1
View File
@@ -7,7 +7,6 @@
"overview",
"configuration",
"training",
"eval",
"inference",
"scaling",
"algorithms",
+5 -5
View File
@@ -10,9 +10,9 @@ A `prime-rl` RL run is three cooperating processes:
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/inference/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). We are trying to stay up-to-date with the latest vLLM features, you can read more about the supported features and deployment options in the dedicated [inference documentation](inference.md).
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, and LoRA. You can read more in the dedicated [training documentation](training.md).
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses ZMQ, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap the rollout link to the local filesystem (`rollout_transport.type = "filesystem"`) if you want rollouts persisted to disk. See [Scaling](scaling.md) for the deployment options.
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
## Installation
@@ -20,7 +20,7 @@ The three processes communicate through configurable transports — by default t
curl -sSL https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/main/scripts/install.sh | bash
```
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`prime-envs`](https://github.com/PrimeIntellect-ai/prime-envs) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`research-environments`](https://github.com/PrimeIntellect-ai/research-environments) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
You need at least one NVIDIA GPU (RTX 3090/4090/5090, A100, H100, H200, or B200). Single-GPU runs are supported for debugging; production RL is typically 1× inference node + 1+ trainer nodes.
@@ -32,7 +32,7 @@ Train an SFT-warmed `Qwen3-0.6B` on the `reverse-text` task — the env is bundl
uv run rl @ examples/basic/reverse-text/rl.toml
```
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into the run directory at `outputs/<run_name>/logs/{trainer,orchestrator,inference}.log` (`run.name` auto-generates as `<envs>--<model>--<short-id>`; pass `--run.name <name>` for a predictable path). Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes with a final DCP checkpoint at `outputs/<run_name>/checkpoints/step_20`.
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into `outputs/logs/{trainer,orchestrator,inference}.log`. Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes and final HF-compatible weights land at `outputs/weights/step_20`.
## Documentation
@@ -41,5 +41,5 @@ The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into
- **[Inference](inference.md)** — vLLM-backed server (or fleet) holding the current policy.
- **[Scaling](scaling.md)** — Single-GPU through multi-node clusters via FSDP / EP / CP and SLURM.
- **[Algorithms](algorithms.md)** — Async semantics, loss / advantage / filter plugins, trajectory merging.
- **[Advanced](advanced.md)** — Custom modeling, multimodal, LoRA, P/D inference.
- **[Advanced](advanced.md)** — Custom modeling, multimodal, LoRA, multi-tenant, P/D inference.
- **[Development](development.md)** — Test suite, pre-commit hooks, adding a new model.
+46 -61
View File
@@ -38,25 +38,24 @@ The `rl`, `sft`, and `inference` entrypoints all accept a `[deployment]` block (
uv run rl @ rl.toml \
--deployment.num-infer-gpus 6 \
--deployment.num-train-gpus 2 \
--inference.vllm.data-parallel-size 6
--inference.parallel.dp 6
```
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
For quick A/B ablations on the same node, run two RL instances side-by-side in separate shells, each pinned to half the GPUs and a separate inference port, and track both in one dashboard:
For quick A/B ablations on the same node, run two RL instances side-by-side in separate tmux sessions, each pinned to half the GPUs and a separate inference port:
```bash
# shell 1, GPUs 0–1, default port 8000
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --run.name exp1
# session 1, GPUs 0–1, default port 8000
bash scripts/tmux.sh -s exp1 -o outputs/exp1
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --output-dir outputs/exp1
# shell 2, GPUs 2–3, port 8001
# session 2, GPUs 2–3, port 8001
bash scripts/tmux.sh -s exp2 -o outputs/exp2
CUDA_VISIBLE_DEVICES=2,3 uv run rl @ rl.toml \
--inference.server.port 8001 \
--orchestrator.model.client.base-url http://localhost:8001/v1 \
--run.name exp2
# watch both side by side
uv run dashboard outputs
--output-dir outputs/exp2
```
#### SFT and Torchrun
@@ -70,7 +69,7 @@ uv run torchrun \
src/prime_rl/trainer/sft/train.py @ sft.toml
```
`--local-ranks-filter 0` keeps console output to rank 0 only; per-rank stdout/stderr is still captured in `<run_dir>/logs/latest/trainer/torchrun/`.
`--local-ranks-filter 0` keeps console output to rank 0 only; per-rank stdout/stderr is still captured in `<output_dir>/logs/trainer/torchrun/`.
### Multi-Node
@@ -87,37 +86,33 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
| `trainer.model.dp_replicate` | Number of dimensions to **replicate** instead of shard. Set to 2 to run 2-way DP replication × FSDP sharding within each replica — useful for very large clusters where pure FSDP communication dominates. |
| `trainer.model.reshard_after_forward` | If `true` (default), parameters are resharded after the forward pass to free memory; the backward pass re-gathers. Set `false` to keep params resident — faster but more memory. |
| `trainer.model.fsdp_cpu_offload` | Offload params + grads + optimizer state to CPU. Big memory win, large throughput hit. |
| `trainer.model.optim_cpu_offload` | Offload optimizer state to CPU between steps. Enabled by default. |
| `trainer.model.full_offload` | Offload gradients, FP32 masters, and optimizer state and run the optimizer (AdamW or SignSGD) on CPU during backward. Disabled by default. |
| `trainer.model.optim_cpu_offload` | Offload only optimizer state. Mid-ground — small throughput cost, decent memory savings, especially at low GPU count. |
### Expert Parallelism
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is at most 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is <= 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
```toml
[trainer.model]
impl = "custom"
ep = 8 # explicit EP degree; must divide num_experts
[trainer.model.moe.dispatch]
type = "torch"
transport = "bf16"
ep = 8 # explicit EP degree; must divide num_experts
ep_comm_backend = "torch" # or "deepep"
```
For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_size` in the same dispatch table. Routed-expert precision is selected separately with `[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, or `mxfp8`).
`ep_comm_backend = "deepep"` uses DeepEP's custom dispatch/combine kernels for speed, with two extra knobs (`deepep_num_sms`, `deepep_token_chunk_size`) — tune on your hardware.
### Context Parallelism
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Prefer `ulysses`: it gets the most throughput and is the only style that works for hybrid linear-attention/Mamba models (Qwen3.5, NemotronH) and for VLMs. Each model class declares its supported styles in `cp_support`; an unsupported `cp_style`, or a model with no CP support at all, is rejected at setup.
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Nemotron-H redistributes its Mamba activations between sequence- and head-parallel layouts in the model-owned Mamba path; the CP degree must divide `mamba_num_heads` and `n_groups`.
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Hybrid Mamba layers head-shard independently (`cp_mamba`), which requires the CP degree to divide `mamba_num_heads` and `n_groups`.
```toml
[trainer.model]
impl = "custom"
attn = "auto" # auto = FA3 on Hopper, FA4 on datacenter Blackwell, FA2 otherwise; or flash_attention_2/3/4
attn = "auto" # auto = FA3 on Hopper, FA4 on Blackwell; or flash_attention_2/3/4
cp = 2 # CP degree
cp_style = "ulysses" # "ring"
```
@@ -130,22 +125,26 @@ cp_style = "ulysses" # "ring"
| `trainer.model.ac.mode = "selective"` | medium | small |
| `trainer.model.ac_offloading` | extra | a bit more |
AC and AC offloading are enabled by default (full mode). Both AC modes retain stateful MoE routing updates and DeepEP communication that cannot safely replay. Selective AC uses the same transformer-block boundaries and additionally retains distributed communication, expensive matrix multiplications, grouped GEMMs, and supported attention kernels:
AC and AC offloading are enabled by default (full mode). For the best memory/throughput tradeoff, switch to selective AC (custom impl only):
```toml
[trainer.model.ac]
mode = "selective"
targets = ["norm", "attn_proj"] # see Reference for the full list per architecture
```
Set `targets` to operator names (for example, `"aten::mm"`) or namespaces (for example, `"prime_rl_collectives"`) to replace the default selective targets. Correctness-required operations remain retained.
Activation offloading still applies to tensors saved by autograd, but tensors retained by the checkpoint policy remain on the accelerator.
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only losing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
### Optimizer Offloading
State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`. For full offload, set `model.optim_cpu_offload = false` and `model.full_offload = true`; this keeps BF16 compute weights on GPU and runs CPU optimizer chunks as gradients become ready during backward. Full offload only supports AdamW and SignSGD (`optim.type = "sign_sgd"`) and disables gradient clipping. SignSGD is stateless, so it halves the host RAM footprint versus AdamW (8 instead of 16 bytes per parameter: FP32 master + FP32 accumulated gradient, no moments).
Offloading optimizer states to CPU is enabled by default (`optim_cpu_offload = true`) — a near-free memory win at low GPU counts:
```toml
[trainer.model]
optim_cpu_offload = true # already the default
```
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training) — set `optim_cpu_offload = false` for multi-run. Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
### LM Head Chunking
@@ -200,11 +199,9 @@ Launch:
```bash
uv run rl @ base_rl.toml @ my_slurm.toml # submits via sbatch
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes launcher/rl.sbatch + resolved config, exits
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script + resolved config, exits
```
Every SLURM entrypoint stores its generated scripts and coordination files under `<run_dir>/launcher/`. SLURM stdout and stderr go to `launcher/logs/`. Local launches do not create `launcher/`.
### `[deployment]` Block
`[deployment]` is a discriminated union picked by `type` — `single_node` or `multi_node` for RL/SFT, with an extra disaggregated variant for inference. RL multi-node:
@@ -223,8 +220,7 @@ SFT multi-node:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 1 # required only for online evals
num_nodes = 2
gpus_per_node = 8
```
@@ -232,29 +228,10 @@ gpus_per_node = 8
Full multi-node configs ship under [`examples/advanced/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced):
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/configs/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`glm-5.3/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale and P/D-disaggregated inference across the GLM-5 family.
- [`glm-4.5-air/swe-2-node.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-4.5-air/swe-2-node.toml) — train a 100B+ MoE on only two nodes: a single-node sign-SGD trainer (full optimizer offload) paired with one inference replica at batch size 64. An overlay on the shared `swe-budget.toml` base — launch with `uv run rl @ swe-budget.toml @ swe-2-node.toml`.
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
### NIXL weight broadcast
Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transfer. Before the first SLURM run, install the NIXL/UCX build and the ModelExpress service binaries on the shared filesystem:
```bash
bash scripts/install_nixl_from_source.sh
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
bash scripts/install_modelexpress.sh
```
The generated job starts a job-scoped ModelExpress server and Redis backend on the trainer head node and passes that address to every component. To use an existing service, set `slurm.launch_modelexpress = false` and configure `weight_broadcast.host` and `weight_broadcast.port`.
The launcher requires the CUDA and InfiniBand transports from `third_party/ucx`. Each NIXL process selects the active InfiniBand port nearest its GPU; an explicitly configured `UCX_NET_DEVICES` takes precedence. Inference ranks start their pulls at different trainer ranks so concurrent workers distribute traffic across all available source rails.
ModelExpress exchanges peer metadata during startup. Weight updates reuse prepared NIXL requests, post every trainer-rank read in a transfer group concurrently, and use versioned NIXL notifications for source readiness and buffer credits.
By default, the trainer and inference worker each allocate one transfer arena. Set `weight_broadcast.overlap_transfer_and_replay = true` to allocate two arenas on both sides and replay one weight group while receiving the next. The additional arena is the size of the largest transfer group per GPU; allocation errors are reported instead of silently disabling overlap.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), and the launcher prints one URL per node. Front the URLs with a router or point clients at any of them.
### Custom Templates
@@ -268,14 +245,22 @@ The default templates live under [`src/prime_rl/templates/`](https://github.com/
## Benchmarking
To benchmark a parallelism config before committing a multi-day run, run a short training with fake data and a step cap, and read throughput / MFU / step time / peak memory from the logs:
Every entrypoint supports a `--bench` flag that runs a few warm-up + measurement steps with fake data and prints a rich-formatted throughput / MFU table:
```bash
# SFT trainer alone
uv run sft @ sft.toml --data.type fake --max-steps 4
uv run sft @ sft.toml --bench
uv run sft ... --data.type fake --data.length variable --bench # variable-length fake data
# RL trainer alone (no inference involved) -- launch it under torchrun, like the `rl` launcher does
uv run torchrun --nproc-per-node=8 src/prime_rl/trainer/rl/train.py @ train.toml --data.fake --max-steps 4
# RL trainer alone (no inference involved)
uv run trainer @ train.toml --data.fake --bench
# Inference alone — start the server normally, then bench the orchestrator
uv run inference @ infer.toml
uv run orchestrator @ orch.toml --bench
# Full RL stack (trainer with fake data, inference with real data from orchestrator)
uv run rl @ rl.toml --bench
```
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `monitors/file/metrics.jsonl` under the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
Persist results with `--bench.output-json`. Use this to compare parallelism configs before committing a multi-day run.
+76 -165
View File
@@ -1,6 +1,6 @@
# Training
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md). For standalone evals, see [Eval](eval.md).
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md).
> **AI agents working in this repo:** the equivalent runbooks are at [`skills/training/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/skills/training) — top-level routing in [`skills/training/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/SKILL.md), launch details in [`skills/training/start-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/start-run/SKILL.md), and check-in / restart procedures in [`skills/training/monitor-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/monitor-run/SKILL.md).
@@ -35,9 +35,8 @@ This page covers everything you need to launch, observe, checkpoint, and recover
| `uv run rl` | Wraps the trainer, orchestrator, and inference server in one launch from a merged TOML. | The default for any RL run. Runs locally for single-node experiments; submits to SLURM for single- or multi-node when `[slurm]` is set (see [Scaling § SLURM](scaling.md#slurm)). |
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
| `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 trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer + inference. |
## RL Trainer
@@ -58,12 +57,11 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| Knob | What it does |
|---|---|
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.constant_trainer_batch_size` | Keep trainer batches constant when samples have no training signal, such as zero advantage on all tokens. Enabled by default. Disable it for faster collection with variable trainer batch sizes. |
| `orchestrator.train.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.train.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
| `orchestrator.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | How many distinct policies may have contributed to one rollout before it's discarded (default 8). The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `errored_rollouts` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.env]]` | Training environments. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Environments](configuration.md#environments-orchestratortrainenv). |
| `[[orchestrator.eval.env]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
**Monitoring:**
@@ -71,29 +69,26 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|---|---|
| `log.level` | Process log level for trainer + orchestrator (`info` default; falls back to `$PRIME_LOG_LEVEL`). Set per-process via `trainer.log.level` / `orchestrator.log.level`, or globally on the `rl` entrypoint to propagate to both. |
| `orchestrator.log.vf_level` | Env-worker / [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) log level (`info` default; `debug` is noisy but useful for env debugging). |
| `--monitors.wandb` (+ `--monitors.wandb.project`, `--monitors.wandb.name`) | Enable Weights & Biases logging. See [Weights & Biases](#weights--biases). |
| `--monitors.prime` | Stream metrics and episodes to the Prime Intellect platform (Prime Lab). See [Platform monitoring](#platform-monitoring). |
| `--wandb` (+ `--wandb.project`, `--wandb.name`) | Enable Weights & Biases logging. See [Weights & Biases](#weights--biases). |
| `--orchestrator.prime-monitor` | Stream metrics to the Prime Intellect platform (Prime Lab). See [Platform monitoring](#platform-monitoring). |
**Run management:**
| Knob | What it does |
|---|---|
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). Defaults to `$PRL_OUTPUT_DIR` if set, else `outputs`. |
| `--run.name <name>` | Run name, also the run directory name under `<output_dir>` (override the directory separately via `--run.dir`). Auto-generated as `<envs>--<model>--<short-id>` when unset, so every launch gets a fresh, readable run directory. Set an explicit name for a predictable path — required to resume the run later. |
| `--clean` | Wipe the run directory before starting. Useful when re-running a named run during iteration. |
| `--clean-output-dir` | Wipe `<output_dir>` before starting. Useful when re-running an experiment with the same name during iteration. |
| `--output-dir outputs/<name>` | Per-run output directory. Always set this when running more than one experiment in parallel. |
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/latest/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
| `--dry-run` | Resolve + validate the full config, write per-process TOMLs to `<output_dir>/configs/`, and exit without launching. The fastest way to debug a misbehaving config. |
### Algorithms
The RL entrypoint supports several training algorithms, switched via `[orchestrator.train.algo]`'s `type` (see [Algorithms](algorithms.md#the-algorithm-abstraction) for the full reference, model references, and per-algorithm customization):
The RL entrypoint supports several training algorithms, switched via `[orchestrator.algo]`'s `type` (see [Algorithms](algorithms.md#the-algorithm-abstraction) for the full reference, model references, and per-algorithm customization):
| `algo.type` | Frozen model | Use case |
|---|---|---|
| `grpo` (default) | None | Standard group-relative RL |
| `max_rl` | None | [MaxRL](https://arxiv.org/abs/2602.02710): GRPO with mean-normalized advantages (maximum-likelihood RL) |
| `rae` | None | [SPIRAL](https://arxiv.org/abs/2506.24119)'s role-conditioned advantage estimation: reward minus a per-agent EMA baseline, for multi-agent self-play envs (e.g. `kuhn-poker`) |
| `hierarchical_grpo` | None | GRPO for proposer-solver envs: compare solvers only with attempts on the same proposed problem, and compare proposers with the other proposals in the group |
| `opd` | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): the policy generates rollouts, the trainer minimizes per-token reverse KL to a reference model |
| `sft` | Required, any OpenAI-compatible endpoint | Hard-distill: a frozen model generates rollouts, the policy trains on its tokens |
| `opsd` | None — the live policy is its own reference (no deployment) | [SDFT](https://arxiv.org/abs/2601.19897): the model is its own reference conditioned on expert demonstrations |
@@ -101,11 +96,11 @@ The RL entrypoint supports several training algorithms, switched via `[orchestra
A new algorithm is a named class in code, not a config — see [Algorithms § Authoring an Algorithm](algorithms.md#authoring-an-algorithm).
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.train.algo.teacher]` for `opd` (the frozen model scored against), `[orchestrator.train.algo.sampling.source]` for `sft` (the model it samples from) — each with `name` + `base_url`. `opsd` declares no frozen model: it self-distills against the live policy. The `rl` entrypoint only manages policy inference — start frozen-model servers yourself and point `base_url` at them:
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for `opd` (the frozen model scored against), `[orchestrator.algo.sampling.source]` for `sft` (the model it samples from) — each with `name` + `base_url`. `opsd` declares no frozen model: it self-distills against the live policy. The `rl` entrypoint only manages policy inference — start frozen-model servers yourself and point `base_url` at them:
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--vllm.model <frozen-model> --server.port 8001
--model.name <frozen-model> --server.port 8001
```
The standalone `uv run sft` entrypoint is the more traditional SFT path — pure dataset-based, no orchestrator. Use the `sft` algorithm only when you want a frozen model to generate the supervision on the fly.
@@ -118,7 +113,6 @@ Pulled from the console logs and mirrored to W&B.
- `reward/{all,env}/mean` — main signal. Should trend upward over hundreds of steps.
- `seq_len/{all,env}/mean` and `is_truncated/{all,env}/mean` — rollout length and truncation rate.
- `is_timeout/{all,env}/mean` — share of rollouts stopped by a stage deadline (`setup`/`agent`/`finalize`/`scoring` `_timeout`). Training counts a timed-out rollout as an error, so it stays out of the batch; eval scores it.
- `num_turns/{all,env}/mean` — for multi-turn envs.
- `empty_rollouts/{all,env}`, `errored_rollouts/{all,env}` — non-zero is fine in small numbers; sustained > 5% is a smell.
- `eval/{env}/{avg@k,pass@k}` — eval scores when `[orchestrator.eval]` is set.
@@ -127,7 +121,7 @@ Pulled from the console logs and mirrored to W&B.
- `mismatch_kl/{all,env}/{mean,std,max}` — KL between trainer's current policy and the (older) inference policy that generated the rollouts. A sustained, growing mean is the early-warning sign for off-policy collapse.
- `entropy/{all,env}/mean` — too low means mode-collapse; too high means the model isn't committing.
- `is_masked/mean` — fraction of tokens masked by the IPO trust region.
- `masked_advantage_{positive,negative}/mean` — fraction of DPPO-masked tokens, split by sign.
- `optim/grad_norm` — spikes precede divergence; check the loss config or lower the LR.
**Performance** (trainer + orchestrator step independently):
@@ -135,9 +129,7 @@ Pulled from the console logs and mirrored to W&B.
| Source | Metric | Reading |
|---|---|---|
| trainer | `time/wait_for_batch` | **high → orchestrator bottleneck** |
| orchestrator | `time/wait_for_policy` | **high → trainer bottleneck** |
The trainer warns when batch wait time exceeds active trainer time. Add inference nodes when this warning persists. The orchestrator warns when policy wait time exceeds active orchestrator time. Add trainer nodes when this warning persists. The orchestrator also warns when it discards more than half of an episode window. This warning reports stale, errored, and no-signal counts.
| orchestrator | `time/wait_for_ckpt` | **high → trainer bottleneck** |
## SFT Trainer
@@ -150,15 +142,9 @@ Two accepted layouts:
- **Prompt-completion**: a HF dataset with `prompt` and `completion` columns ([TRL format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion)). The trainer masks out the prompt and computes loss only over the completion.
- **Messages**: a HF dataset with a single `messages` column containing a list of chat turns. The trainer interprets the whole conversation as one sample, applies role-based loss masking, and trains over all assistant turns.
If both columns are present, `messages` takes precedence. A dataset that stores these under other names maps them in `[data.columns]`; the trainer renames the columns at load time:
If both columns are present, `messages` takes precedence.
```toml
[data.columns]
messages = "conversation"
tools = "schemas"
```
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column in OpenAI function-calling format. Each row's value can be either a list of dicts or a JSON-encoded string of a list.
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column (OpenAI function-calling format) or `tool_defs` ([`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) rollout format). Each row's value can be either a list of dicts or a JSON-encoded string of a list — both are accepted, and `tool_defs` rows are auto-converted to OAI shape before being passed into the renderer.
Renderer-backed SFT reads template controls from the typed `[renderer]` config in the SFT TOML. For example:
@@ -168,27 +154,8 @@ name = "qwen3"
enable_thinking = false
```
Dataset columns can set renderer template controls per row, on top of the `[renderer]` config. `[data.columns.renderer]` maps renderer fields to columns and defaults to `reasoning_effort = "reasoning_effort"`, so a `reasoning_effort` column sets that field on renderers that have it (for example `gpt-oss`, `qwen3.8`, `deepseek-v4`). Rows with a null value use the configured renderer unchanged. This lets one run mix reasoning efforts, with the `[renderer]` value as the default for rows that do not set one:
```toml
# The renderer field is reasoning_effort; this dataset stores it in an effort column.
[data.columns.renderer]
reasoning_effort = "effort"
```
If a model needs another template control, add it to that model's renderer config in `renderers` (for example a new field on the relevant `*RendererConfig`) and consume it in the renderer implementation.
**Custom renderers.** A renderer can also live outside the `renderers` package. Set `name = "custom"` and point `import_path` at the class, as `my_module.Class` or `path/to/file.py:Class`; relative file paths resolve against the launch directory. The class sets `config_class` to its own `BaseRendererConfig` subclass, which validates the remaining `[renderer]` keys and declares its template controls:
```toml
[renderer]
name = "custom"
import_path = "my_renderers.glm53_no_thinking.NoThinkingGLM53Renderer"
clear_thinking = true
```
The same config selects the renderer for RL under `[orchestrator.renderer]`. The [`renderers` README](https://github.com/PrimeIntellect-ai/renderers#custom-renderers) shows the class behind this example.
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5.
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) requires `model.impl = "custom"` and only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
@@ -200,58 +167,11 @@ See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectorie
The minimal SFT run trains `Qwen3-0.6B` on the `reverse-text` SFT dataset:
```bash
uv run sft @ examples/basic/reverse-text/sft.toml --monitors.wandb
uv run sft @ examples/basic/reverse-text/sft.toml --wandb
```
Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manages this for you — see [Scaling § SFT and Torchrun](scaling.md#sft-and-torchrun) for non-default layouts; multi-node SFT goes through [SLURM](scaling.md#slurm)).
`--monitors.prime` streams the run to the Prime Intellect platform — see [Platform Monitoring](#platform-monitoring).
### Online Evals
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `select` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
```toml
[eval]
interval = 25
[eval.select]
limit = 32
[[eval.source]]
name = "reverse-text"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
[deployment]
num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an online-eval process next to the trainer (it logs to `logs/attempt_<n>/eval.log`). NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the online-eval process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
#### Multi-Node Trainer and Inference Pool
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and online-eval process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2 # trainer nodes
num_infer_nodes = 1 # inference pool + online evals
[inference.vllm]
tensor_parallel_size = 8
[slurm]
job_name = "my-run"
```
The shared script passes the trainer rank-0 hostname directly to the online-eval process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, online-eval never sees a final broadcast, so the job remains active until walltime. Trainer and online-eval log to one shared W&B run. The trainer creates it, and online-eval finalizes it.
### SFT-Specific Knobs
| Knob | What it controls |
@@ -261,7 +181,6 @@ The shared script passes the trainer rank-0 hostname directly to the online-eval
| `data.seq_len` | Per-sample sequence length |
| `loss_mask.*` | Which roles contribute to loss (system / user / assistant / tool). |
| `val.interval` | Run validation every N steps; `val.data` mirrors `data` |
| `eval.interval` | Run online evals every N steps; see [Online Evals](#online-evals) |
### Important Metrics
@@ -269,17 +188,16 @@ Pulled from the console log and mirrored to W&B.
**Progress and loss:**
- `loss/mean`, `loss/perplexity` — main signal. Should decrease through the run.
- `val/loss`, `val/perplexity` — validation metrics when `[val]` is set, logged every `val.interval` steps.
- `eval/{env}/...` — online eval metrics when `[eval]` is set, logged at each evaluated checkpoint step.
- `loss/mean` — main signal. Should decrease through the run.
- `val/loss` — validation loss when `[val]` is set, logged every `val.interval` steps.
- `progress/epoch`, `progress/num_samples`, `progress/num_tokens` — dataset progress.
- `progress/<subset>/ratio_{samples,tokens}` — when training on multiple HF subsets/splits, the realized mixing ratio.
**Stability and optimization:**
- `optim/grad_norm` — spikes precede divergence.
- `optim/lr` — LR schedule.
- For MoE: `max_vio/mean`, `max_vio/max` — mean and max over the step's microsteps of the largest load-balancing violation across layers and EP groups, computed from expert token counts summed across each EP group. `routing_confidence/mean` — mean routing confidence.
- `optim/lr`, `optim/zero_grad_ratio` — LR schedule and the fraction of params that received zero gradients (high → dead path or wrong loss masking).
- For MoE: `max_vio/mean` (load-balancing violation), `routing_confidence/mean` — both are logged when non-zero.
**Performance:**
@@ -296,9 +214,10 @@ Checkpointing is split across processes because the orchestrator and trainer can
| Process | What's saved | Where |
|---|---|---|
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_{n}/trainer/` |
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_{n}/orchestrator/` |
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<output_dir>/checkpoints/step_N/trainer/` |
| Orchestrator | Step counter, total tokens / samples / problems | `<output_dir>/checkpoints/step_N/orchestrator/` |
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
| Trainer (HF weights) | HF-compatible weight snapshot for serving | `<output_dir>/weights/step_N/` |
### Enabling Checkpoints
@@ -313,121 +232,113 @@ uv run rl @ rl.toml --ckpt.interval 25 --ckpt.keep-interval 100 # …plus perma
### Resuming a Run
Re-run the same launch command and pass `--resume` (latest checkpoint) or `--resume.step <N>`. Resuming reuses the run directory, so the run needs a name you can point back at — launch with `--run.name` (or pass the first run's auto-generated name). Make sure `--max-steps` is at least the target final step, not the remaining delta:
Re-run the same launch command and pass `--ckpt.resume-step <N>` (or `-1` for "latest"). Make sure `--max-steps` is at least the target final step, not the remaining delta:
```bash
# First run: steps 1–10
uv run rl @ rl.toml --max-steps 10 --ckpt --run.name my-run
uv run rl @ rl.toml --max-steps 10 --ckpt
# Resume from the latest checkpoint: continue to step 20
uv run rl @ rl.toml --max-steps 20 --ckpt --resume --run.name my-run
# ...or from a specific step
uv run rl @ rl.toml --max-steps 20 --ckpt --resume.step 10 --run.name my-run
# ...or fork another run's checkpoint into a fresh run
uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
--resume.dir outputs/my-run/checkpoints/step_10
# Resume: continue to step 20
uv run rl @ rl.toml --max-steps 20 --ckpt.resume-step 10
```
### Exporting Checkpoints
### Serving Checkpoints
Trainer checkpoints are DCP-sharded; export them to HF-format safetensors with `tools/convert_dcp_to_bf16.py`. The script reads the model config from the run's resolved config and writes sharded safetensors plus config/tokenizer assets to `<ckpt_dir>/weights` (or a second positional arg). It exports full fine-tunes only — LoRA checkpoints are rejected.
HF-compatible weight snapshots are written under `<output_dir>/weights/step_N/` whenever a full checkpoint runs (or you can write weights-only via `--ckpt.weights-only` for cheaper snapshots). Upload directly:
```bash
# single process (1 GPU)
uv run python tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
# multi-rank for faster gathers and models that don't fit one GPU
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
uv run hf upload <user>/<model>-RL outputs/weights/step_100
```
The exported directory loads directly into `uv run inference --vllm.model <dir>` or any HF consumer. Quantize it to blockwise FP8 (DeepSeek/GLM format, loads natively in vLLM) with `tools/convert_bf16_to_fp8.py <dir>`, or go straight from the checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (each rank quantizes its gathered slice, writes only `<ckpt_dir>/weights-FP8` — no intermediate bf16 export); dequantize an fp8-only release (e.g. GLM-5-FP8) for training with `tools/convert_fp8_to_bf16.py <dir>`.
For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write the raw adapter alongside the merged weights — useful when serving the adapter through a separate `/load_lora_adapter` call.
## Observability
### Config Files
Each launch writes its command, input TOML, and resolved JSON files to
`<run_dir>/configs/attempt_<n>/`. Resumed runs keep the earlier configs.
`command.txt` uses shell-safe quoting.
`configs/latest` points to the current attempt.
### Log Files
The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>/` — every launch (fresh or resumed) gets its own numbered attempt directory, and `logs/latest` symlinks to the current one. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The full layout (single-node runs skip the `node_*.log` and `router_*.log` files):
```
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
<output_dir>/logs/
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
├── orchestrator.log # single instance, single file
├── eval.log # `uv run eval` process, or the SFT online-eval process
├── inference.log # symlink → inference/node_0.log on multi-node
├── trainer/
│ ├── node_*.log # per-node trainer stdout (multi-node only)
│ └── torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log # per-rank
├── inference/
│ ├── node_*.log # per-node inference stdout (multi-node only)
│ └── router.log # the single global router (multi-node only)
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
│ └── router_*.log # vllm-router per replica (multi-node only)
└── envs/{train,eval}/<env_name>/
├── env_server.log
└── env_worker_<id>.log
```
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/latest/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Env worker logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
```bash
tail -F <run_dir>/logs/latest/{trainer,orchestrator,eval,inference}.log
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
tail -F <output_dir>/logs/{trainer,orchestrator,inference}.log
tail -F <output_dir>/logs/trainer/node_*.log # multi-node only
tail -F <output_dir>/logs/inference/router_*.log # multi-node only
```
### Dashboard
### Console Output
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with six views per run: an overview (the W&B overview sections, read from the file monitor's `metrics.jsonl`), metrics (every key in that file, one pane each, with a regex filter), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
`scripts/tmux.sh` opens a 4-pane tmux session that follows `trainer.log`, `orchestrator.log`, `inference.log`, and the union of env worker logs. Start it before launching:
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
```bash
bash scripts/tmux.sh
# then in the Launcher window:
uv run rl @ ... --output-dir outputs/my-run
```
Pass `-s <session>` and `-o <output_dir>` to run multiple parallel experiments side-by-side in different sessions. The helper also works on a SLURM head node — `bash scripts/tmux.sh my-rl-job /shared/outputs/my-rl-job`.
### Weights & Biases
W&B is off by default (the file monitor, which writes the metrics and the trace stream under the run's `monitors/file/` directory, is on by default):
W&B is off by default. Enable with `--wandb`:
```bash
uv run rl @ rl.toml --monitors.wandb # default project, random name
uv run rl @ rl.toml --monitors.wandb.project my-proj --monitors.wandb.name run-42
uv run rl @ rl.toml --no-monitors.file # disable the local metric/trace files
uv run rl @ rl.toml --wandb # default project, random name
uv run rl @ rl.toml --wandb.project my-proj --wandb.name run-42
uv run rl @ rl.toml --no-wandb # force-disable even if the TOML enables it
```
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `monitors.wandb.offline = true`.
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `wandb.offline = true`.
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, every training run (RL and SFT) gets an **auto-created `overview` saved view** curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
By default, every 10 steps each process also logs a sample of prompts/completions (with rewards and advantages) and reward/advantage/entropy distributions as W&B tables. Tune via `--wandb.log-extras.interval` and `--wandb.log-extras.sample-ratio`, or disable subsets:
```bash
uv run rl @ rl.toml --wandb \
--orchestrator.wandb.log-extras.interval 50 \
--no-trainer.wandb.log-extras.distributions
```
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, W&B mode **auto-creates an `overview` saved view** on the first run into a project — curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
### Platform Monitoring
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics and episodes to the platform dashboard. Bare flag uses defaults:
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics, samples, and distributions to the platform dashboard. Bare flag uses defaults:
```bash
uv run rl @ rl.toml --monitors.prime
uv run sft @ sft.toml --monitors.prime # same flag on the SFT trainer
uv run rl @ rl.toml --orchestrator.prime-monitor
```
Or set it in TOML:
```toml
[monitors.prime]
name = "my-experiment"
[orchestrator.prime_monitor]
run_name = "my-experiment"
```
The monitor is a thin layer over the [`prime-runs`](https://github.com/PrimeIntellect-ai/prime/tree/main/packages/prime-runs) SDK (installed as `prime-runs[train]`): it registers the run, streams per-step metrics, uploads every 10th step's episodes (full conversations with rewards and advantages) to the run's sample viewer, and closes the run out. Finalization is best-effort SDK delivery: a process that exits without finishing is reported crashed when the SDK's atexit hook runs, but an abrupt kill (SIGKILL, OOM, node loss) skips the report and a lost finalize is not retried — the platform owns the terminal state of attached (`RUN_ID`) and managed runs. Uploaded episodes are keyed to the platform run by the SDK; the orchestrator's own run id (the launcher's `PRL_RUN_ID`) stays on W&B and in the local records.
On `sft` the monitor registers the run with the dataset-batched training fields (`max_steps`, `batch_size`, `seq_len`) and streams the trainer's per-step metrics and validation losses; SFT has no rollouts, so no episodes are uploaded.
Requires `PRIME_API_KEY` (`prime login` or the env var) and a team (`PRIME_TEAM_ID`, or the team selected with `prime login`) enabled for external runs. A configured monitor must work: a missing key or a team outside the allowlist fails the launch. `PRIME_RUNS_MODE=disabled` keeps the monitor configured but opens no platform run; `RUN_ID=<id>` attaches to an external run a launcher already created instead of registering a new one. Currently internal-only.
Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted team. Currently internal-only.
## Rules of Thumb
- **Start small.** Run `examples/basic/reverse-text/rl.toml` end-to-end on 2 GPUs before scaling. If the smoke run finishes cleanly, your install is good.
- **Batch size ≥ 64.** Smaller batches give noisy gradient estimates and the trainer's overhead-per-step dominates throughput. 64 is the practical floor; 128–512 is the range for quick ablations; production RL often runs at 1024+.
- **Group size ≥ 8.** Bigger groups (`orchestrator.train.group_size`) make it more likely that a task produces a mix of high- and low-reward rollouts, which is what gives the trainer a usable signal — if all rollouts in a group succeed or all fail, the within-group advantage collapses to zero and the trainer learns nothing from that task. Bigger groups also tighten advantage normalization. 8 is the floor; 16–32 is common.
- **Runs never share a directory.** Every launch writes to its own run directory `<output_dir>/<run_name>`, auto-named `<envs>--<model>--<short-id>` by default. Name runs you want to find again or resume with `--run.name <name>`; re-using a name blocks unless you resume or pass `--clean`.
- **Group size ≥ 8.** Bigger groups (`orchestrator.group_size`) make it more likely that a task produces a mix of high- and low-reward rollouts, which is what gives the trainer a usable signal — if all rollouts in a group succeed or all fail, the within-group advantage collapses to zero and the trainer learns nothing from that task. Bigger groups also tighten advantage normalization. 8 is the floor; 16–32 is common.
- **Pin `output_dir` per run.** Sharing a directory across runs will mix rollouts and break resumes. `--output-dir outputs/<unique-name>` is the simplest discipline.
- **Use `--dry-run` before SLURM.** Validators (e.g. CP needs flash-attention) fail fast in dry-run and slow in queue.
+12 -32
View File
@@ -2,36 +2,16 @@
End-to-end usage examples for prime-rl, referenced from the top-level [README](../README.md).
New here? Follow [`basic/reverse-text/`](basic/reverse-text/README.md) first — it trains a small model end-to-end on 2 GPUs and introduces the launch → dashboard → checkpoint flow the advanced examples reuse.
- **[`basic/`](basic)** — walk-throughs for the core environments on 1–8 GPUs (baseline eval →
optional SFT warmup → RL → eval), each with its own README:
- `reverse-text` — smallest end-to-end loop (single-turn, 0.6B)
- `alphabet-sort` — multi-turn, user simulator, LoRA
- `wiki-search` — multi-turn tool calling, LoRA
- `wordle` — multi-turn (~6-turn games)
- `hendrycks-sanity` — single-turn math, long-running
- **[`advanced/`](advanced)** — larger, mostly multi-node runs on frontier models, one folder
per model: `qwen3-30b-a3b` (math/swe/tool), `glm-4.5-air` (search/swe/terminal), `glm-5.2`
(large-scale + PD-disaggregated inference), `minimax-m2.5` (swe), `nemotron-3-super` (swe),
`intellect-3.1` (swe).
## advanced/ — frontier models, multi-node
Larger runs on frontier models, one folder per model, each with a launch README covering requirements, credentials, launch, monitoring, and resume:
- [`qwen3-30b-a3b/`](advanced/qwen3-30b-a3b/README.md) — `Qwen3-30B-A3B` RL on math (`i3_math`), SWE (`r2e-gym`), and agentic tool use (general-agent on Modal). 2 train + 2 infer nodes; the SWE config runs at 131k context with `ep = 8` + `cp = 2`.
- [`glm-4.5-air/`](advanced/glm-4.5-air/README.md) — `GLM-4.5-Air` (100B MoE) RL across search, SWE, and terminal domains at 131k context, with agents in sandboxes. 2 train + 4 infer nodes (SWE: 1 + 3).
- [`glm-5.3/`](advanced/glm-5.3/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
- `intellect-3.1/` — reproduce the `INTELLECT-3.1` run: 4 train + 12 infer nodes on SWE.
All advanced configs submit through SLURM (the `rl` entrypoint writes the sbatch job when the config has a `[slurm]` table) and are monitored with `uv run dashboard`. See the per-model README for the full walkthrough.
## basic/ — 1 to 8 GPUs
Walk-throughs for the core environments (baseline eval → optional SFT warmup → RL → eval), each with its own README:
- [`reverse-text/`](basic/reverse-text/README.md) — smallest end-to-end loop (single-turn, 0.6B): `eval.toml` → `sft.toml` → `rl.toml`
- [`alphabet-sort/`](basic/alphabet-sort/README.md) — multi-turn, user simulator, LoRA
- [`wiki-search/`](basic/wiki-search/README.md) — multi-turn tool calling, LoRA
- [`wordle/`](basic/wordle/README.md) — multi-turn (~6-turn games)
- [`hendrycks-sanity/`](basic/hendrycks-sanity/README.md) — single-turn math, long-running
## extra/ — beyond the core loop
Examples that don't follow the basic eval → SFT → RL walk-through pattern:
- [`dynamo/`](extra/dynamo/README.md) — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
- [`vlm/`](extra/vlm/README.md) — multimodal (VLM) SFT, dense + MoE LoRA configs
## Related config folders
- Frontier-model configs without launch walkthroughs (`minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`) live in [`configs/advanced/`](../configs/advanced).
Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
-103
View File
@@ -1,103 +0,0 @@
# GLM-4.5-Air
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0). The SWE configs also ship budget variants: `swe-4-node.toml` (1 train + 3 infer) and `swe-2-node.toml` — train a 100B+ MoE on only two nodes. Both are thin overlays on a shared `swe-budget.toml` base: the base holds the recipe, the overlay the topology, batch size, and per-run identity.
| Config | Trains on | Evals on | Topology |
|---|---|---|---|
| [`search.toml`](search.toml) | `openseeker` + `redsearcher` (search QA, `rlm` harness + `search` skill) | `browsecomp` (500 examples) | 2 train + 4 infer nodes |
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 2 train + 4 infer nodes |
| [`swe-budget.toml`](swe-budget.toml) + [`swe-4-node.toml`](swe-4-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
| [`swe-budget.toml`](swe-budget.toml) + [`swe-2-node.toml`](swe-2-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 1 infer node |
| [`terminal.toml`](terminal.toml) | `tmax` (per-task Docker image, `rlm` ipython harness) | `swebench-verified` + `terminal-bench-2` (avg@4) | 2 train + 4 infer nodes |
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8` (plus expert parallelism on `swe.toml`). `search.toml`, `swe.toml`, and `terminal.toml` train with Muon on 2 trainer nodes. The budget variants instead fit the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer; `swe-2-node.toml` cuts the batch size to 64 (4 groups of 16) to match the throughput of its single inference replica. They don't parse standalone: compose them left-to-right over `swe-budget.toml` (`uv run rl @ swe-budget.toml @ swe-2-node.toml`). Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
## Requirements
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. Install the `prime` CLI separately and log in. Each config's `slurm.pre_run_command` then cleans up the run's orphaned sandboxes by label before launch:
```bash
uv tool install prime
prime login # or: prime config set-api-key <your-key>
```
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend) and drop the `slurm.pre_run_command` cleanup line.
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
- `HF_TOKEN` — `zai-org/GLM-4.5-Air` is a gated model.
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
- `SERPER_API_KEY` — search envs only; forwarded into the agent sandbox for the `search` skill (`harness.forward_env`).
## Setup
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
uv sync --all-extras --all-packages
```
## Tweak before launching
- `[slurm] partition` is set to `all` — override with `--slurm.partition <your-partition>`, or edit the config.
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
## Start the run
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
```bash
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
--output-dir /shared/outputs/glm45air \
--run.name glm45air-swe
```
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. For SWE on a smaller budget, compose a budget variant over its base: `uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml` trains the 100B+ MoE on only two nodes. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
## Monitor with the dashboard
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
```bash
uv run dashboard /shared/outputs/glm45air # serves http://localhost:7788
```
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
```bash
ssh -L 7788:localhost:7788 <head-node>
```
Pick the run (`<run_name>` from the launch) and you get five views:
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
## Checkpoint, resume, export
Checkpoints land in `<run_dir>/checkpoints/step_<N>` every 50 steps (`keep_last = 1`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
```bash
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
--output-dir /shared/outputs/glm45air \
--run.name glm45air-swe \
--resume --max-steps 1000
```
Trainer checkpoints are DCP-sharded; export HF-format weights with:
```bash
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/glm45air/glm45air-swe/checkpoints/step_100
```
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
+42 -48
View File
@@ -21,7 +21,7 @@ num_train_nodes = 2
num_infer_nodes = 1
num_infer_replicas = 4
[monitors.wandb]
[wandb]
project = "search-ablations"
name = "glm45air-search"
@@ -32,8 +32,7 @@ timeout = 3600
[ckpt]
interval = 50
keep_last = 1
[resume]
resume_step = -1
[model]
name = "zai-org/GLM-4.5-Air"
@@ -47,9 +46,10 @@ enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp = 8
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
[trainer.model.ac]
@@ -59,6 +59,7 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
@@ -68,43 +69,38 @@ type = "muon"
[orchestrator]
batch_size = 256
max_off_policy_steps = 32
[orchestrator.train]
group_size = 16
[orchestrator.concurrency]
initial_inflight = 256
max_inflight = 512
max_off_policy_steps = 32
max_inflight_rollouts = 512
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
[orchestrator.train.algo]
[orchestrator.algo]
type = "grpo"
[orchestrator.train.algo.length_penalty]
[orchestrator.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.0
[orchestrator.prime_monitor]
# --- Train: the search envs with usable training data (rlm `search` skill, prime sandbox) ---
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
# entry wholesale (keep `name`/`question_field`/`choices` in sync with the taskset defaults —
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "openseeker"
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.taskset.id = "openseeker"
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
[[orchestrator.train.source.env.taskset.task.judges]]
[orchestrator.train.env.env.taskset]
id = "openseeker-v1"
[[orchestrator.train.env.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
@@ -112,23 +108,21 @@ question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.source.env.taskset.task.judges]]
# [[orchestrator.train.env.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/prime-envs/rubrics/rlm.toml"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
[[orchestrator.train.source]]
[[orchestrator.train.env]]
name = "redsearcher"
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.taskset.id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
[[orchestrator.train.source.env.taskset.task.judges]]
[orchestrator.train.env.env.taskset]
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
[[orchestrator.train.env.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
@@ -136,10 +130,10 @@ question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.source.env.taskset.task.judges]]
# [[orchestrator.train.env.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/prime-envs/rubrics/rlm.toml"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
@@ -148,36 +142,36 @@ choices = ["A", "B"]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
[[orchestrator.eval.env]]
name = "browsecomp"
select.limit = 500 # full set is 1266; cap eval at 500
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.agent.timeout.rollout = 3600
env.taskset.id = "browsecomp"
env.taskset.task.judge.model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
num_examples = 500 # full set is 1266; cap eval at 500
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
env.agent.timeout = { rollout = 3600 }
[orchestrator.eval.env.env.taskset]
id = "browsecomp-v1"
task = { judge = { model = "Qwen/Qwen3-235B-A22B-Instruct-2507" } }
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.eval.source.env.taskset.task.judges]]
# [[orchestrator.eval.env.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/prime-envs/rubrics/rlm.toml"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
[inference.model]
max_model_len = 131072
tensor_parallel_size = 8
enable_return_routed_experts = true
[inference.parallel]
tp = 8
@@ -1,41 +0,0 @@
# Budget variant of swe.toml: train a 100B+ MoE on only two nodes (1 train + 1 infer replica) with
# the single-node sign-SGD trainer. Overlay for swe-budget.toml — this file only carries the
# deltas, so compose the two (left-to-right merge, see docs/configuration.md "TOML Composition"):
#
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml
#
# The batch size is 64 (4 groups of 16), matching the rollout throughput of the single inference
# replica. The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the
# budget variants can run side by side.
[slurm]
job_name = "glm45air-swe-2-node"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe-2-node" -y || true'
[deployment]
num_infer_replicas = 1
[monitors.wandb]
name = "glm45air-scaleswe-2-node"
[orchestrator]
batch_size = 64
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-2-node"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-2-node"]
env.agent.timeout.rollout = 3600
@@ -1,42 +0,0 @@
# Budget variant of swe.toml: the same recipe on four nodes (1 train + 3 infer replicas, the
# topology swe.toml used before the Muon switch) with the single-node sign-SGD trainer. Overlay for
# swe-budget.toml — this file only carries the deltas, so compose the two (left-to-right merge, see
# docs/configuration.md "TOML Composition"):
#
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-4-node.toml
#
# Batch size 256 (16 groups of 16) matches the rollout throughput of the three inference replicas.
# The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the budget
# variants can run side by side.
[slurm]
job_name = "glm45air-swe-4-node"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe-4-node" -y || true'
[deployment]
num_infer_replicas = 3
[monitors.wandb]
name = "glm45air-scaleswe-4-node"
[orchestrator]
batch_size = 256
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-4-node"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe-4-node"]
env.agent.timeout.rollout = 3600
@@ -1,116 +0,0 @@
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Shared base of the budget variants of swe.toml
# (`swe-4-node.toml`, `swe-2-node.toml`): the pre-Muon recipe with the single-node sign-SGD
# trainer, composed as `uv run rl @ swe-budget.toml @ <variant>.toml`. Router replay is enabled
# (trainer.enable_router_replay replays the routed-expert decisions returned by inference via
# enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe model, which supports routed_experts.
#
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
#
# Inference serves the bf16 checkpoint as-is (no quantization). The trainer fits on one node via
# cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus the
# memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
# skip-gather / skip-optimizer checkpointing. Concurrency is fully default: the controller derives
# its start from the measured KV budget and adapts from there.
#
# The variant overlays on top of this base set the inference replica count and batch size, the
# per-variant SLURM job name / sandbox cleanup label / W&B run name, and the train/eval sources
# with their matching runtime labels.
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
partition = "all"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[monitors.wandb]
project = "swe-ablations"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
[resume]
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
optim_cpu_offload = false
full_offload = true
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "sign_sgd"
# --- Orchestrator ---
[orchestrator]
max_off_policy_steps = 32
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
type = "grpo"
[orchestrator.train.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
# --- Inference ---
[inference]
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
enable_return_routed_experts = true

Some files were not shown because too many files have changed in this diff Show More