Compare commits
69
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e466d233e9 | ||
|
|
9ea9fb193e | ||
|
|
91c86b7383 | ||
|
|
d4b30bf3ae | ||
|
|
d5ce4ce84d | ||
|
|
04d067145f | ||
|
|
632ef2b318 | ||
|
|
c8759c370a | ||
|
|
0695f9caa5 | ||
|
|
e0f8a35c78 | ||
|
|
54012df504 | ||
|
|
53b22b55c8 | ||
|
|
c2a5fa466c | ||
|
|
90b074492e | ||
|
|
766e36f000 | ||
|
|
209f76eb52 | ||
|
|
e5c9169566 | ||
|
|
65914f924f | ||
|
|
b67fd12fe6 | ||
|
|
e6998a6f41 | ||
|
|
7f6ca61ecc | ||
|
|
434c9c0a42 | ||
|
|
3979894bae | ||
|
|
63af82343d | ||
|
|
5b5f234053 | ||
|
|
f619e36b63 | ||
|
|
563b37a9c7 | ||
|
|
e7517948f2 | ||
|
|
43f6261454 | ||
|
|
bf7eab0640 | ||
|
|
8d88f5e302 | ||
|
|
c13409e2c1 | ||
|
|
c613ec5631 | ||
|
|
3ce918920f | ||
|
|
517ee5c486 | ||
|
|
b243184d19 | ||
|
|
f3ad435508 | ||
|
|
da9a92a79c | ||
|
|
9589c04de3 | ||
|
|
f6563ff0ee | ||
|
|
543e37eb3a | ||
|
|
618de8a511 | ||
|
|
eead822cb3 | ||
|
|
aeaf4c44f1 | ||
|
|
241d8e931e | ||
|
|
f510ef62cb | ||
|
|
26cdf2ee1d | ||
|
|
ae748fd69d | ||
|
|
083127fe32 | ||
|
|
b90aca4221 | ||
|
|
d3727060cb | ||
|
|
1891771201 | ||
|
|
10bc02c6dc | ||
|
|
dbe4d1f351 | ||
|
|
4ecb92b534 | ||
|
|
6d17559422 | ||
|
|
c1f6fbdd3b | ||
|
|
b8a2205389 | ||
|
|
3f5ee350f6 | ||
|
|
a73fa39f2f | ||
|
|
0057f3bb91 | ||
|
|
e792f9cf88 | ||
|
|
a36151c951 | ||
|
|
c5559033bd | ||
|
|
25d4b1dcc8 | ||
|
|
3b386a4489 | ||
|
|
38303f82d4 | ||
|
|
f5e8113420 | ||
|
|
ef773f1cee |
@@ -15,3 +15,5 @@ Config files live in:
|
||||
- `src/prime_rl/configs/`
|
||||
|
||||
If breaking changes are detected without a corresponding `CHANGELOG.md` update, request that the author add an entry.
|
||||
|
||||
Any PR that introduces a new custom model must also provide a table showing mean KL mismatch across 20 steps on math environment on this new model with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not present, request the author to add such a table.
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
name: Build Image (ghcr)
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
ref:
|
||||
description: "Branch, tag, or commit to build"
|
||||
required: false
|
||||
default: "main"
|
||||
type: string
|
||||
tag:
|
||||
description: "Image tag (defaults to sanitized ref)"
|
||||
required: false
|
||||
type: string
|
||||
platforms:
|
||||
description: "Target platforms to build"
|
||||
required: false
|
||||
default: "both"
|
||||
type: choice
|
||||
options:
|
||||
- amd64-only
|
||||
- arm64-only
|
||||
- both
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: primeintellect-ai/prime-rl
|
||||
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-${{ github.event.release.tag_name || inputs.tag || inputs.ref || github.ref_name }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
name: Prepare build
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
outputs:
|
||||
matrix: ${{ steps.matrix.outputs.matrix }}
|
||||
ref: ${{ steps.vars.outputs.ref }}
|
||||
tag: ${{ steps.vars.outputs.tag }}
|
||||
sha: ${{ steps.vars.outputs.sha }}
|
||||
full_sha: ${{ steps.vars.outputs.full_sha }}
|
||||
platforms: ${{ steps.vars.outputs.platforms }}
|
||||
steps:
|
||||
- name: Set build matrix
|
||||
id: matrix
|
||||
env:
|
||||
PLATFORMS: ${{ env.BUILD_PLATFORMS }}
|
||||
run: |
|
||||
case "$PLATFORMS" in
|
||||
arm64-only)
|
||||
echo 'matrix={"include":[{"runner":"image-builder-arm-2204","platform":"linux/arm64","suffix":"arm64"}]}' >> "$GITHUB_OUTPUT"
|
||||
;;
|
||||
both)
|
||||
echo 'matrix={"include":[{"runner":"image-builder","platform":"linux/amd64","suffix":"amd64"},{"runner":"image-builder-arm-2204","platform":"linux/arm64","suffix":"arm64"}]}' >> "$GITHUB_OUTPUT"
|
||||
;;
|
||||
amd64-only)
|
||||
echo 'matrix={"include":[{"runner":"image-builder","platform":"linux/amd64","suffix":"amd64"}]}' >> "$GITHUB_OUTPUT"
|
||||
;;
|
||||
*)
|
||||
echo "Unsupported platforms value: ${PLATFORMS}" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ env.BUILD_REF }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Resolve image vars
|
||||
id: vars
|
||||
env:
|
||||
INPUT_REF: ${{ env.BUILD_REF }}
|
||||
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
|
||||
|
||||
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 '${raw_tag}'." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "ref=${INPUT_REF}" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=${tag}" >> "$GITHUB_OUTPUT"
|
||||
echo "sha=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT"
|
||||
echo "full_sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
echo "platforms=${PLATFORMS}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
build:
|
||||
name: Build and push (${{ matrix.suffix }})
|
||||
needs: prepare
|
||||
environment: ghcr-publish
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix: ${{ fromJson(needs.prepare.outputs.matrix) }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Remove unnecessary packages
|
||||
run: |
|
||||
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.prepare.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
submodules: false
|
||||
|
||||
- name: Init public submodules
|
||||
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/research-environments
|
||||
fi
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build and push
|
||||
id: build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.cuda
|
||||
push: true
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:commit-${{ needs.prepare.outputs.sha }}-${{ matrix.suffix }}
|
||||
labels: |
|
||||
org.opencontainers.image.revision=${{ needs.prepare.outputs.full_sha }}
|
||||
org.opencontainers.image.version=${{ needs.prepare.outputs.tag }}
|
||||
org.opencontainers.image.source=https://github.com/${{ github.repository }}
|
||||
|
||||
- name: Summary
|
||||
env:
|
||||
INPUT_REF: ${{ needs.prepare.outputs.ref }}
|
||||
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
|
||||
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
|
||||
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
|
||||
PLATFORM: ${{ matrix.platform }}
|
||||
SUFFIX: ${{ matrix.suffix }}
|
||||
run: |
|
||||
{
|
||||
echo "## Build Summary (${SUFFIX})"
|
||||
echo ""
|
||||
echo "| Property | Value |"
|
||||
echo "|----------|-------|"
|
||||
echo "| **Ref** | \`${INPUT_REF}\` |"
|
||||
echo "| **Platform** | \`${PLATFORM}\` |"
|
||||
echo "| **Image** | \`${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}-${SUFFIX}\` |"
|
||||
echo "| **Commit** | \`${IMAGE_SHA}\` |"
|
||||
echo "| **Digest** | \`${IMAGE_DIGEST}\` |"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
manifest:
|
||||
name: Create multi-arch manifest
|
||||
needs: [prepare, build]
|
||||
if: needs.prepare.outputs.platforms == 'both'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
packages: write
|
||||
steps:
|
||||
- name: Log in to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Create and push manifests
|
||||
env:
|
||||
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
|
||||
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
|
||||
IMAGE_FULL_SHA: ${{ needs.prepare.outputs.full_sha }}
|
||||
PLATFORMS: ${{ needs.prepare.outputs.platforms }}
|
||||
SOURCE_URL: https://github.com/${{ github.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
image="${REGISTRY}/${IMAGE_NAME}"
|
||||
tag_sources=()
|
||||
sha_sources=()
|
||||
|
||||
if [ "$PLATFORMS" != "arm64-only" ]; then
|
||||
tag_sources+=("${image}:${IMAGE_TAG}-amd64")
|
||||
sha_sources+=("${image}:commit-${IMAGE_SHA}-amd64")
|
||||
fi
|
||||
|
||||
if [ "$PLATFORMS" != "amd64-only" ]; then
|
||||
tag_sources+=("${image}:${IMAGE_TAG}-arm64")
|
||||
sha_sources+=("${image}:commit-${IMAGE_SHA}-arm64")
|
||||
fi
|
||||
|
||||
docker buildx imagetools create \
|
||||
--annotation "index:org.opencontainers.image.revision=${IMAGE_FULL_SHA}" \
|
||||
--annotation "index:org.opencontainers.image.version=${IMAGE_TAG}" \
|
||||
--annotation "index:org.opencontainers.image.source=${SOURCE_URL}" \
|
||||
-t "${image}:${IMAGE_TAG}" \
|
||||
"${tag_sources[@]}"
|
||||
|
||||
docker buildx imagetools create \
|
||||
--annotation "index:org.opencontainers.image.revision=${IMAGE_FULL_SHA}" \
|
||||
--annotation "index:org.opencontainers.image.version=${IMAGE_TAG}" \
|
||||
--annotation "index:org.opencontainers.image.source=${SOURCE_URL}" \
|
||||
-t "${image}:commit-${IMAGE_SHA}" \
|
||||
"${sha_sources[@]}"
|
||||
|
||||
- name: Summary
|
||||
env:
|
||||
INPUT_REF: ${{ needs.prepare.outputs.ref }}
|
||||
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
|
||||
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
|
||||
PLATFORMS: ${{ needs.prepare.outputs.platforms }}
|
||||
run: |
|
||||
{
|
||||
echo "## Manifest Summary"
|
||||
echo ""
|
||||
echo "| Property | Value |"
|
||||
echo "|----------|-------|"
|
||||
echo "| **Ref** | \`${INPUT_REF}\` |"
|
||||
echo "| **Platforms** | \`${PLATFORMS}\` |"
|
||||
echo "| **Image** | \`${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}\` |"
|
||||
echo "| **Commit Image** | \`${REGISTRY}/${IMAGE_NAME}:commit-${IMAGE_SHA}\` |"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -7,6 +7,7 @@ on:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
actions: write
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
@@ -81,7 +82,6 @@ jobs:
|
||||
sha,
|
||||
});
|
||||
core.notice(`Created tag ${tag} at ${sha}`);
|
||||
return;
|
||||
} catch (error) {
|
||||
if (error.status === 422) {
|
||||
core.warning(`Tag ${tag} already exists, retrying...`);
|
||||
@@ -89,6 +89,20 @@ jobs:
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.actions.createWorkflowDispatch({
|
||||
owner,
|
||||
repo,
|
||||
workflow_id: "build_image.yaml",
|
||||
ref: "main",
|
||||
inputs: { ref: tag, tag, platforms: "both" },
|
||||
});
|
||||
core.notice(`Dispatched build_image.yaml for ${tag}`);
|
||||
} catch (error) {
|
||||
core.setFailed(`Failed to dispatch build_image.yaml: ${error.message}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
core.setFailed("Could not create a unique .dev tag after retries.");
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
.vscode/*
|
||||
.claude/scheduled_tasks.lock
|
||||
.claude/worktrees/
|
||||
*.ipynb
|
||||
*.jsonl
|
||||
configs/endpoints.py
|
||||
|
||||
@@ -7,9 +7,6 @@
|
||||
[submodule "research-environments"]
|
||||
path = deps/research-environments
|
||||
url = git@github.com:PrimeIntellect-ai/research-environments.git
|
||||
[submodule "configs/private"]
|
||||
path = configs/private
|
||||
url = git@github.com:PrimeIntellect-ai/research-configs.git
|
||||
[submodule "pydantic-config"]
|
||||
path = deps/pydantic-config
|
||||
url = https://github.com/PrimeIntellect-ai/pydantic-config
|
||||
|
||||
@@ -35,6 +35,10 @@ Namespaces are one honking great idea -- let's do more of those!
|
||||
- **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.
|
||||
|
||||
## Docs
|
||||
|
||||
- **Docs reflect `main`, not history**: `docs/` describes the current state of the codebase only. Don't mention removed/legacy fields, migration paths, or "this used to be X" anecdotes.
|
||||
|
||||
## Skills
|
||||
|
||||
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.
|
||||
@@ -50,11 +54,10 @@ Write tests as plain functions with pytest fixtures. Don't use class-based tests
|
||||
|
||||
## Git
|
||||
|
||||
- **Branch prefixes**: use the following prefixes for branches: `feat/`, `fix/`, `chore/`
|
||||
- **Branch prefixes**: use `feat/`, `fix/`, `chore/`; use `exp/` for experiment branches (configs, run summaries, pins, notes).
|
||||
|
||||
## GitHub
|
||||
|
||||
- **Draft PRs**: always create PRs as drafts (`gh pr create --draft`) to avoid triggering CI unnecessarily.
|
||||
- **Pull requests**: do not include a "test plan" section in PR descriptions unless you actually ran tests to verify the changes or the user explicitly asked for one.
|
||||
- **Keep PR descriptions in sync**: every time you push commits to a PR, also update the PR description (`gh pr edit <num> --body-file ...`) so it reflects the current state of the branch — not just what was true when the PR was opened. Preserve any auto-generated blocks (e.g. `<!-- CURSOR_SUMMARY -->`).
|
||||
|
||||
|
||||
@@ -2,6 +2,20 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
|
||||
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
|
||||
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
|
||||
- **`orchestrator.eval.eval_base_model` → `orchestrator.eval.skip_first_step`** (semantics inverted): `eval_base_model = true` becomes `skip_first_step = false` (the default — run the step-0 eval before any train rollouts). No alias; configs setting `eval_base_model` must rename.
|
||||
- **`orchestrator.eval.skip_eval_on_resume` (and its alias `skip_eval_on_restart`) removed**: folded into `skip_first_step`. Resume no longer re-fires an already-completed eval (deduped via per-env last-eval-step tracking in the checkpointed progress).
|
||||
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval` removed**: the drain-switch overlap (stop scheduling new train, let in-flight train drain while eval queues) is now the only eval transition mode.
|
||||
- **`ckpt.skip_buffer` removed**: there is no buffer to skip.
|
||||
- **`[orchestrator.buffer]` removed** (difficulty pools): the whole block and every key (`seed`, `easy_threshold`, `hard_threshold`, `easy_fraction`, `hard_fraction`, `online_difficulty_filtering`, `hash_keys`) are gone, with no alias — `extra="forbid"` rejects the block, so existing configs must delete it. To preserve `online_difficulty_filtering = true`, enforce the zero-advantage pre-batch filter: `[[orchestrator.pre_batch_filters]]\ntype = "zero_advantage"\nenforce = true`.
|
||||
- **`orchestrator.filters` → `orchestrator.post_batch_filters`** (renamed, no alias): existing configs setting `[[orchestrator.filters]]` must rename to `[[orchestrator.post_batch_filters]]` (`extra="forbid"` rejects the old key). A new `pre_batch_filters` list is also available. Filters are **train-only** now — eval rollouts are no longer filtered.
|
||||
- **`orchestrator.max_off_policy_steps` now also applies to eval** (behavior change, field unchanged): eval rollouts that fall more than `max_off_policy_steps` versions behind the policy are cancelled, same as train. (2026-05-29)
|
||||
- **`sampling.min_tokens`, `sampling.repetition_penalty`, `sampling.seed` removed**: Dropped from both `TrainSamplingConfig` and `EvalSamplingConfig` (group-level `[orchestrator.train.sampling]` / `[orchestrator.eval.sampling]` and per-env `[[orchestrator.train.env.sampling]]` / `[[orchestrator.eval.env.sampling]]`). `min_tokens` suppressed natural EOS, `repetition_penalty` distorts the on-policy sampling distribution, and `seed` wasn't pulling its weight — none belonged on the supported config surface. Existing configs setting any of these must delete the field. Hard-deprecation, no migration window. (2026-05-27)
|
||||
- **`wandb.shared` removed**: The deprecation shim that popped `wandb.shared` from input dicts with a `FutureWarning` (introduced in #2649) is gone. The `rl` entrypoint always uses shared W&B mode now, and existing configs that still set `wandb.shared = true` (or `false`) will fail validation. Drop the field from your config. (2026-05-27)
|
||||
- **`max_async_level` and `strict_async_level` removed**: The async-execution semantics between trainer and orchestrator are now design invariants, not config knobs. The trainer always runs exactly one step ahead of inference, and the orchestrator always adopts the freshest checkpoint that doesn't violate the one-step barrier. The shared top-level `max_async_level`, the per-sub-config `trainer.max_async_level` / `orchestrator.max_async_level`, and `orchestrator.strict_async_level` have all been removed. Existing configs setting any of these must drop the field; the previous defaults (`max_async_level = 1`, `strict_async_level = false`) match the new hardcoded behavior. Bench mode no longer bypasses the weight-ckpt wait (the `int(1e9)` workaround is gone) and `multimodal/rl_color_codeword_feat_renderer.toml`'s prior `max_async_level = 0` (fully synchronous on-policy) is no longer expressible. (2026-05-25)
|
||||
- **`teacher_inference` removed from RL entrypoint**: The `[teacher_inference]` config block and the `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` fields have been removed. The `rl` entrypoint now only manages the student-policy inference server. External teachers (used by OPD and local-vLLM SFT) must be started manually (e.g. `CUDA_VISIBLE_DEVICES=1 uv run inference --model.name <teacher> --server.port 8001 ...`) and pointed at via `[orchestrator.teacher.client]`. Existing configs using `[teacher_inference]` or `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` must drop those fields and bring up the teacher out-of-band. (2026-05-25)
|
||||
- **`rollouts_per_example` → `group_size`**: The orchestrator-level field, the group-level `[orchestrator.eval]` field, and the per-env `[[orchestrator.eval.env]]` field have all been renamed. The old name still parses as a validation alias (in both TOML and CLI), so existing configs keep working without changes; new configs should prefer `group_size`. (2026-05-22)
|
||||
- **`AdvantageInputs` / `AdvantageOutputs` are now per-group, and `AdvantageOutputs.advantages` is a plain `list[float]`** (second breaking change to this API in three weeks). `AdvantageInputs.rollouts` is now `list[vf.RolloutOutput]` (a single group) instead of `list[list[vf.RolloutOutput]]`, and `AdvantageOutputs.advantages` is now `list[float]` instead of a 2D `Float[Tensor, "num_examples rollouts_per_example"]`. `compute_advantages` calls `advantage_fn` once per group, which lets partial-group training (groups smaller than `rollouts_per_example` after rollout errors) round-trip without the previous bucket-by-size workaround. Custom advantage functions must drop the outer list dimension and return a list of floats — e.g. `AdvantageOutputs(advantages=(rewards - rewards.mean(dim=1, keepdim=True)).tolist())` becomes `AdvantageOutputs(advantages=[r - mean for r in rewards])` (or `.tolist()` if you keep torch internally). (2026-05-22)
|
||||
- **`[model.vlm]` requires `orchestrator.use_renderer = true`**: VLMs must go through the renderer path; the `vlm_requires_renderer` validator rejects `use_renderer = false` when `[model.vlm]` is set. The renderer owns the HF processor per-slot and ships generic `mm_kwargs` keyed by the model's forward signature. Since `use_renderer` already defaults to `true`, most VLM configs need no change. (2026-05-19)
|
||||
|
||||
+39
-2
@@ -1,7 +1,7 @@
|
||||
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
|
||||
|
||||
# Build stage - multi-arch base (supports amd64 + arm64)
|
||||
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu22.04 AS builder
|
||||
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 AS builder
|
||||
LABEL maintainer="prime intellect"
|
||||
LABEL repository="prime-rl"
|
||||
|
||||
@@ -18,12 +18,42 @@ ENV DEBIAN_FRONTEND=noninteractive
|
||||
ENV TZ=Etc/UTC
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
|
||||
build-essential \
|
||||
autoconf \
|
||||
automake \
|
||||
libtool \
|
||||
pkg-config \
|
||||
ca-certificates \
|
||||
curl \
|
||||
sudo \
|
||||
git \
|
||||
ninja-build \
|
||||
libnuma-dev \
|
||||
libnl-3-dev \
|
||||
libnl-route-3-dev \
|
||||
libibverbs-dev \
|
||||
librdmacm-dev \
|
||||
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
|
||||
ARG UCX_VERSION=1.19.1
|
||||
RUN git clone --depth 1 --branch v${UCX_VERSION} https://github.com/openucx/ucx.git /tmp/ucx \
|
||||
&& cd /tmp/ucx \
|
||||
&& ./autogen.sh \
|
||||
&& ./configure \
|
||||
--prefix=/opt/ucx \
|
||||
--enable-shared \
|
||||
--disable-static \
|
||||
--disable-doxygen-doc \
|
||||
--enable-optimizations \
|
||||
--enable-cma \
|
||||
--enable-devel-headers \
|
||||
--enable-mt \
|
||||
--with-verbs \
|
||||
--with-cuda=/usr/local/cuda \
|
||||
--with-ze=no \
|
||||
&& make -j"$(nproc)" \
|
||||
&& make install \
|
||||
&& rm -rf /tmp/ucx
|
||||
|
||||
# Download the latest installer
|
||||
ADD https://astral.sh/uv/install.sh /uv-installer.sh
|
||||
|
||||
@@ -49,7 +79,7 @@ COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
|
||||
RUN --mount=type=cache,target=/app/.cache/uv \
|
||||
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --group mamba-ssm --locked --no-dev
|
||||
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress --group mamba-ssm --locked --no-dev
|
||||
|
||||
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
|
||||
ARG TARGETARCH
|
||||
@@ -74,8 +104,12 @@ RUN apt-get update && apt-get install -y \
|
||||
net-tools \
|
||||
curl \
|
||||
vim \
|
||||
libnuma1 \
|
||||
libnl-3-200 \
|
||||
libnl-route-3-200 \
|
||||
libibverbs1 \
|
||||
ibverbs-providers \
|
||||
librdmacm1 \
|
||||
&& apt-get clean autoclean \
|
||||
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
|
||||
@@ -96,6 +130,7 @@ ENV PATH="/usr/local/bin:$PATH"
|
||||
WORKDIR /app
|
||||
# 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
|
||||
@@ -107,6 +142,8 @@ RUN rm /app/.venv/bin/python3.12 && ln -s /usr/local/bin/python /app/.venv/bin/p
|
||||
|
||||
# Place executables in the environment at the front of the path
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
ENV UCX_HOME=/opt/ucx
|
||||
ENV LD_LIBRARY_PATH="/opt/ucx/lib:/opt/ucx/lib/ucx${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"
|
||||
|
||||
# HuggingFace Hub timeouts (defaults are 10s which causes issues on slow networks)
|
||||
ENV HF_HUB_ETAG_TIMEOUT=500
|
||||
|
||||
@@ -52,13 +52,13 @@ 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 | [multimodal.md](docs/multimodal.md) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
|
||||
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#vision-language-models) (`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 | ✅ | ❌ |
|
||||
| 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 (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ❌ | ✅ |
|
||||
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ✅ | ✅ |
|
||||
| Other HF causal LMs | Qwen3 dense, Mistral, … (`impl = "hf"`) | varies | ❌ | ✅ |
|
||||
|
||||
|
||||
@@ -110,6 +110,15 @@ source $HOME/.local/bin/env
|
||||
uv sync --all-extras
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -217,17 +226,13 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
|
||||
|
||||
Check out the [docs](docs) directory for in-depth guides on how to use PRIME-RL.
|
||||
|
||||
- [**Entrypoints**](docs/entrypoints.md) - Overview of the main components (orchestrator, trainer, inference) and how to run SFT, RL, and evals
|
||||
- [**Configs**](docs/configs.md) - Configuration system using TOML files, CLI arguments, and environment variables
|
||||
- [**Environments**](docs/environments.md) - Installing and using verifiers environments from the Environments Hub
|
||||
- [**Async Training**](docs/async.md) - Understanding asynchronous off-policy training and step semantics
|
||||
- [**Logging**](docs/logging.md) - Logging with loguru, torchrun, and Weights & Biases
|
||||
- [**Checkpointing**](docs/checkpointing.md) - Saving and resuming training from checkpoints
|
||||
- [**Benchmarking**](docs/benchmarking.md) - Performance benchmarking and throughput measurement
|
||||
- [**Deployment**](docs/deployment.md) - Training deployment on single-GPU, multi-GPU, and multi-node clusters
|
||||
- [**Memory Usage**](docs/memory_usage.md) - Techniques for reducing memory usage (activation checkpointing, offloading, EP, CP, LoRA, etc.)
|
||||
- [**Troubleshooting**](docs/troubleshooting.md) - Common issues and their solutions
|
||||
- [**Multimodal**](docs/multimodal.md) - Training VLMs like Qwen3-VL
|
||||
- [**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, 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, multi-tenant training
|
||||
- [**Development**](docs/development.md) - Test suite, pre-commit hooks, adding a new model
|
||||
|
||||
## Contributing
|
||||
|
||||
@@ -249,28 +254,11 @@ uv run pre-commit install
|
||||
|
||||
### Tests
|
||||
|
||||
Run the full test suite
|
||||
|
||||
```bash
|
||||
uv run pytest -v
|
||||
```
|
||||
|
||||
To run unit tests, run
|
||||
|
||||
```bash
|
||||
uv run pytest tests/unit -v
|
||||
```
|
||||
|
||||
To run integration tests, run
|
||||
|
||||
```bash
|
||||
uv run pytest tests/integration -v
|
||||
```
|
||||
|
||||
To run CPU-only tests, use the inverse of the `gpu` marker:
|
||||
|
||||
```bash
|
||||
uv run pytest -v -m "not gpu"
|
||||
uv run pytest -v # everything
|
||||
uv run pytest tests/unit -v # unit only
|
||||
uv run pytest tests/integration -v # integration only
|
||||
uv run pytest -v -m "not gpu" # CPU-only (inverse of the gpu marker)
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
max_steps = 5
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
@@ -26,4 +26,5 @@ args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_tur
|
||||
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
|
||||
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
|
||||
[orchestrator.renderer]
|
||||
name = "auto"
|
||||
preserve_all_thinking = true
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
# Trainer config for multi-run RL integration test
|
||||
max_concurrent_runs = 2
|
||||
max_async_level = 5
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
max_steps = 3000
|
||||
seq_len = 8192
|
||||
seq_len = 4096
|
||||
|
||||
[wandb]
|
||||
project = "hendrycks-math-debug"
|
||||
@@ -9,7 +9,8 @@ name = "hendrycks-math-sanity"
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
batch_size = 256
|
||||
max_inflight_rollouts = 512
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
@@ -30,7 +31,7 @@ group_size = 16
|
||||
[trainer.model.compile]
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 8192
|
||||
max_model_len = 4096
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
@@ -0,0 +1,52 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-multi-env"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "rl"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
# -- multi train envs --
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
name = "reverse-text-train-1"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
name = "reverse-text-train-2"
|
||||
|
||||
# -- multi eval envs --
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
num_examples = 16
|
||||
group_size = 4
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
name = "reverse-text-eval-1"
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
name = "reverse-text-eval-2"
|
||||
interval = 5
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 128
|
||||
@@ -0,0 +1,75 @@
|
||||
# 2-GPU debug RL run for the multimodal (renderer) path: Qwen3-VL-4B on
|
||||
# color-codeword. Sized to actually learn (reward should trend up) while
|
||||
# staying 2-GPU friendly. Exercises RendererClient + Qwen3VLRenderer end-to-end.
|
||||
|
||||
max_steps = 15
|
||||
seq_len = 4096
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-VL-4B-Instruct"
|
||||
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
gpus_per_node = 2
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
# Image processor is CPU-bound and dominates for VLMs; returns diminish past 4.
|
||||
pool_size = 4
|
||||
|
||||
# Step 0 on Qwen3-VL-4B vs color-codeword can be uniform (all-correct or
|
||||
# all-wrong), so don't enforce zero-advantage dropping or training would crash
|
||||
# before any progress.
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "gibberish"
|
||||
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "repetition"
|
||||
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
enforce = false
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
|
||||
|
||||
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
|
||||
# MODEL_RENDERER_MAP to Qwen3VLRenderer at runtime; no explicit name needed.
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.model]
|
||||
# Workaround for vLLM 0.20.1 Qwen3-VL deepstack buffer bug: when num_scheduled_tokens
|
||||
# (188) gets padded up to the next cudagraph_capture_size (192), the model's
|
||||
# _set_deepstack_input_embeds sizes the buffer to 188 but forward() runs with 192,
|
||||
# triggering "Requested more deepstack tokens than available in buffer". Eager mode
|
||||
# skips the padding so num_input_tokens == num_scheduled_tokens.
|
||||
enforce_eager = true
|
||||
|
||||
[inference.parallel]
|
||||
dp = 1
|
||||
tp = 1
|
||||
|
||||
[wandb]
|
||||
project = "debug"
|
||||
name = "multimodal"
|
||||
tags = ["qwen3vl-4b", "color-codeword", "renderer"]
|
||||
@@ -1,5 +1,4 @@
|
||||
max_steps = 5
|
||||
max_async_level = 5
|
||||
batch_size = 16
|
||||
|
||||
[train.sampling]
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text-v1"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
args = { v1 = true }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
@@ -1,5 +1,4 @@
|
||||
max_steps = 5
|
||||
max_async_level = 5
|
||||
|
||||
[data.fake]
|
||||
batch_size = 2
|
||||
|
||||
@@ -44,4 +44,4 @@ uv run rl @ configs/debug/training_modes/sft_lora.toml
|
||||
uv run rl @ configs/debug/training_modes/sft_external.toml
|
||||
```
|
||||
|
||||
See [docs/training_modes.md](../../docs/training_modes.md) for what each mode does.
|
||||
See [docs/training.md](../../docs/training.md#training-modes-rl--opd--sft-via-orchestrator) for what each mode does.
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
max_steps = 5
|
||||
seq_len = 8192
|
||||
|
||||
[wandb]
|
||||
project = "general-agent-debug"
|
||||
name = "qwen3-0p6b-rlm"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 16
|
||||
rollouts_per_example = 4
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 4096
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "general-agent-solver-rlm"
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 8192
|
||||
|
||||
[inference.parallel]
|
||||
dp = 1
|
||||
@@ -0,0 +1,52 @@
|
||||
max_steps = 400
|
||||
seq_len = 32768
|
||||
|
||||
[slurm]
|
||||
job_name = "general-agent-qwen3-30b-a3b-rlm"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
[wandb]
|
||||
project = "general-agent-debug"
|
||||
name = "qwen3-30b-a3b-rlm"
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
cp = 2
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "general-agent-solver-rlm"
|
||||
|
||||
[orchestrator.train.env.args]
|
||||
min_tier = 1
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 32768
|
||||
|
||||
[inference.parallel]
|
||||
dp = 2
|
||||
tp = 4
|
||||
@@ -0,0 +1,44 @@
|
||||
max_steps = 200
|
||||
seq_len = 32768
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[wandb]
|
||||
project = "general-agent-debug"
|
||||
name = "qwen3-4b-rlm"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
keep_last = 1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
cp = 2
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "general-agent-solver-rlm"
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 32768
|
||||
|
||||
[inference.parallel]
|
||||
dp = 4
|
||||
@@ -27,4 +27,5 @@ args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max
|
||||
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
|
||||
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
|
||||
[orchestrator.renderer]
|
||||
name = "auto"
|
||||
preserve_all_thinking = true
|
||||
|
||||
@@ -20,10 +20,6 @@ id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
|
||||
|
||||
@@ -23,10 +23,6 @@ name = "acereason-math"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
|
||||
ratio = 0.5
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
# -- train envs --
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
name = "reverse-text-1"
|
||||
|
||||
[orchestrator.train.env.sampling]
|
||||
max_completion_tokens = 127
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
name = "reverse-text-2"
|
||||
|
||||
# -- eval envs --
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
name = "eval-default"
|
||||
num_examples = 32
|
||||
group_size = 4
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
name = "eval-custom"
|
||||
num_examples = 16
|
||||
group_size = 2
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.env.sampling]
|
||||
max_completion_tokens = 256
|
||||
temperature = 0.5
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference] # Default inference config
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
@@ -1,34 +0,0 @@
|
||||
max_steps = 15
|
||||
seq_len = 4096
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-VL-4B-Instruct"
|
||||
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 1
|
||||
@@ -1,99 +0,0 @@
|
||||
# 20-step Qwen3-VL-4B RL run on color-codeword using the renderer multimodal path.
|
||||
#
|
||||
# Pair with rl_color_codeword_main_mito.toml for an A/B comparison: same env,
|
||||
# same hyperparameters, same step count — only difference is the inference
|
||||
# client. The feat-branch run uses the new RendererClient + Qwen3VLRenderer
|
||||
# (renderers package with multimodal support); the main-branch baseline uses
|
||||
# the existing TITO chat-completions path through the inference server.
|
||||
#
|
||||
# Compare in W&B project ``multimodal-renderer``:
|
||||
# - ``kl/sampler_vs_trainer`` should be ~0 on this branch (the renderer
|
||||
# produces byte-identical tokens to what the trainer re-tokenizes) and
|
||||
# can spike on main when BPE drifts mid-rollout.
|
||||
# - ``reward`` and ``loss`` should track within noise — same model, same
|
||||
# env, same hyperparameters.
|
||||
# - ``bridge_break_rate`` is renderer-only; surfaces multi-turn extension
|
||||
# failures.
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 4096
|
||||
output_dir = "outputs/rl_color_codeword_feat_renderer"
|
||||
clean_output_dir = true
|
||||
# Pure on-policy: inference can't run ahead of training, so every rollout
|
||||
# is generated from the latest policy weights. Removes async/off-policy
|
||||
# drift as a confound for the sampler-vs-trainer KL.
|
||||
max_async_level = 0
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-VL-4B-Instruct"
|
||||
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
gpus_per_node = 2
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 16
|
||||
group_size = 8
|
||||
use_renderer = true
|
||||
|
||||
# Track zero-advantage groups but don't drop them — we're validating the
|
||||
# multimodal renderer path on 20 steps, not optimizing training efficiency.
|
||||
# Step 0 on Qwen3-VL-4B vs color-codeword is likely uniform (all-correct or
|
||||
# all-wrong) so enforce=True would crash before any training happens.
|
||||
[[orchestrator.filters]]
|
||||
type = "gibberish"
|
||||
|
||||
[[orchestrator.filters]]
|
||||
type = "repetition"
|
||||
|
||||
[[orchestrator.filters]]
|
||||
type = "zero_advantage"
|
||||
enforce = false
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 2, max_turns = 2, num_examples = 100, seed = 42 }
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "auto"
|
||||
# 64 concurrent rollouts (batch_size=16 × group_size=4) want
|
||||
# more than one tokenizer slot to avoid serialization queueing. The
|
||||
# image processor (CPU-bound) dominates for VLMs so returns diminish
|
||||
# past 4; bump to 4 as the default for multimodal runs.
|
||||
pool_size = 4
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.model]
|
||||
# Workaround for vLLM 0.20.1 Qwen3-VL deepstack buffer bug: when num_scheduled_tokens
|
||||
# (188) gets padded up to the next cudagraph_capture_size (192), the model's
|
||||
# _set_deepstack_input_embeds sizes the buffer to 188 but forward() runs with 192,
|
||||
# triggering "Requested more deepstack tokens than available in buffer". Eager mode
|
||||
# skips the padding so num_input_tokens == num_scheduled_tokens.
|
||||
enforce_eager = true
|
||||
|
||||
[inference.parallel]
|
||||
dp = 1
|
||||
tp = 1
|
||||
|
||||
[wandb]
|
||||
project = "multimodal-renderer"
|
||||
name = "feat-renderer-20step-r8-i2-t2-onpolicy"
|
||||
tags = ["qwen3vl-4b", "color-codeword", "renderer", "feat-branch", "mm-kwargs-generic", "on-policy"]
|
||||
@@ -1,35 +0,0 @@
|
||||
max_steps = 3
|
||||
seq_len = 2048
|
||||
output_dir = "outputs/rl_color_codeword_test"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-VL-4B-Instruct"
|
||||
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 16
|
||||
group_size = 2
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 32
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 2, num_examples = 100, seed = 42 }
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 1
|
||||
@@ -18,7 +18,6 @@ level = "debug"
|
||||
[wandb]
|
||||
project = "sami_debug_nemotron"
|
||||
name = "nemotron-120b-math"
|
||||
shared = true
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
@@ -56,10 +55,6 @@ id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ level = "debug"
|
||||
[wandb]
|
||||
project = "nemotron_sami_debug"
|
||||
name = "nemotron-120b-math"
|
||||
shared = true
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
@@ -55,10 +54,6 @@ id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
|
||||
|
||||
Submodule configs/private deleted from 894caa0047
@@ -0,0 +1,99 @@
|
||||
output_dir = "/beegfs/mika/rlm-swe-qwen35-4b"
|
||||
max_steps = 400
|
||||
seq_len = 65536
|
||||
|
||||
[slurm]
|
||||
job_name = "rlm-swe-qwen35-4b"
|
||||
project_dir = "."
|
||||
pre_run_command = "prime sandbox delete --label rlm-swe-qwen35-4b -y --plain || true"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 2
|
||||
|
||||
[wandb]
|
||||
project = "rlm-swe-debug"
|
||||
name = "qwen35-4b"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3.5-4B"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 8
|
||||
max_inflight_rollouts = 512
|
||||
max_off_policy_steps = 16
|
||||
|
||||
# Thinking enabled for the Qwen3.5 renderer.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3.5"
|
||||
enable_thinking = true
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 1.0
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "rlm_swe"
|
||||
name = "rlm-swe-r2e"
|
||||
num_workers = 4
|
||||
|
||||
[orchestrator.train.env.args]
|
||||
labels = ["rlm-swe-qwen35-4b"]
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "rlm_swe"
|
||||
name = "rlm-swe-swebench-verified-quick"
|
||||
num_workers = 4
|
||||
timeout = 3600
|
||||
|
||||
[orchestrator.eval.env.args]
|
||||
task_type = "swebench"
|
||||
dataset_name = "PrimeIntellect/SWE-Bench-Verified-Quick"
|
||||
labels = ["rlm-swe-qwen35-4b"]
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
enable_prefix_caching = true
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 65536
|
||||
|
||||
[inference.parallel]
|
||||
dp = 8
|
||||
|
||||
# Qwen3.5-4B is a VL model; skip the vision tower for text-only SWE.
|
||||
# `language_model_only` is a vLLM MultiModalConfig arg (no prime-rl field) → pass via vllm_extra.
|
||||
[inference.vllm_extra]
|
||||
language_model_only = true
|
||||
@@ -33,9 +33,6 @@ oversampling_factor = 2.0
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[orchestrator.buffer]
|
||||
online_difficulty_filtering = true
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "wiki-search"
|
||||
|
||||
|
||||
Vendored
+1
-1
Submodule deps/renderers updated: 3ae276c446...e6dba5ad6c
Vendored
+1
-1
Submodule deps/research-environments updated: d141472268...4c08260f07
Vendored
+1
-1
Submodule deps/verifiers updated: 04651bec3e...0ad8b4d523
@@ -0,0 +1,145 @@
|
||||
# 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, 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)
|
||||
- [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
|
||||
|
||||
`prime-rl` ships custom optimized model implementations for several MoE families. With `model.impl = "auto"` (default) the trainer picks the custom path when the HF config type is registered, falling back to plain HF otherwise. To force one:
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom" # or "hf" to force the HF path
|
||||
```
|
||||
|
||||
| Family | HF config types | EP | CP |
|
||||
|---|---|---|---|
|
||||
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-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 | ✅ |
|
||||
| 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 (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
|
||||
|
||||
The custom path enables you to set EP, CP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), 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.
|
||||
|
||||
### Expert Parallelism Backends
|
||||
|
||||
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
|
||||
|
||||
- **`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.)
|
||||
|
||||
## Multimodal Training
|
||||
|
||||
### Supported Families
|
||||
|
||||
The built-in VLM registry covers:
|
||||
|
||||
| Family | `model_type` | Vision attr | LM attr |
|
||||
|---|---|---|---|
|
||||
| Qwen3-VL | `qwen3_vl` | `model.visual` | `model.language_model` |
|
||||
| Qwen3-VL MoE | `qwen3_vl_moe` | `model.visual` | `model.language_model` |
|
||||
| Qwen3.5 | `qwen3_5` | `model.visual` | `model.language_model` |
|
||||
| Qwen3.5-MoE | `qwen3_5_moe` | `model.visual` | `model.language_model` |
|
||||
|
||||
For a model not in the table, look up the attribute paths on the loaded HF model with `model.named_children()` and set them under `[model.vlm]` directly.
|
||||
|
||||
### Enabling VLM Mode
|
||||
|
||||
Add `[model.vlm]` and bfloat16 dtypes:
|
||||
|
||||
```toml
|
||||
[model]
|
||||
name = "Qwen/Qwen3-VL-4B-Instruct"
|
||||
optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
# freeze_vision_encoder = true # default; set false to fine-tune the encoder
|
||||
```
|
||||
|
||||
The weight-broadcast key prefix is derived as `{language_model_attr}.layers.` automatically.
|
||||
|
||||
To add a new model family permanently, append an entry to `VLM_REGISTRY` in `src/prime_rl/utils/vlm.py`.
|
||||
|
||||
### Limitations
|
||||
|
||||
- **Vision encoder frozen by default.** Set `freeze_vision_encoder = false` to fine-tune it; in that case it's FSDP-sharded per block. The combination `freeze_vision_encoder = false` + LoRA is rejected by a config validator — LoRA freezes everything non-adapter, so unfreezing the encoder under LoRA would be a silent no-op.
|
||||
- **No multimodal-safe truncation.** Token sequences are truncated to `seq_len`, but `pixel_values` and `image_grid_thw` pass through unchanged. If a sample's tokens overflow, image tokens may get dropped while image tensors still describe the full image set. Set `seq_len` to cover your longest sample.
|
||||
- **bfloat16 mandatory.** The trainer config validator refuses any other `optimization_dtype` / `reduce_dtype` for VLMs — vLLM serves VLMs in bfloat16 and a mismatch breaks the importance ratio.
|
||||
- **Higher KL mismatch with multi-image inputs.** Expect noisier `mismatch_kl` than text-only; this is from minor numerical differences between the trainer's and vLLM's image processing.
|
||||
- **Images aren't logged to monitors.** Sample logging captures the prompt text but not the actual images.
|
||||
|
||||
## LoRA Training
|
||||
|
||||
LoRA is enabled by adding `[model.lora]`:
|
||||
|
||||
```toml
|
||||
[model.lora]
|
||||
rank = 16
|
||||
alpha = 32
|
||||
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. For RL, `weight_broadcast.type = "nccl"` is **not** supported with LoRA — use the default filesystem transport. 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
|
||||
|
||||
For large MoE serving, splitting prefill and decode onto separate vLLM groups can substantially improve throughput. Pick the prefill:decode ratio based on workload shape:
|
||||
|
||||
| Workload | P:D ratio | Why |
|
||||
|---|---|---|
|
||||
| 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/glm5_pd_disag/rl.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/glm5_pd_disag/rl.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast (see the [README](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/glm5_pd_disag) for the launch story).
|
||||
|
||||
Monitor live queue depths to detect imbalance:
|
||||
|
||||
```bash
|
||||
curl -s http://<prefill_node>:8100/metrics | grep num_requests_waiting
|
||||
curl -s http://<decode_node>:8200/metrics | grep num_requests_waiting
|
||||
```
|
||||
|
||||
If prefill queues and decode is idle, add prefill nodes (and vice versa).
|
||||
|
||||
**UCX 1.19 requirement.** NVSHMEM needs UCX ≥ 1.19 for multi-GPU CUDA. If your cluster doesn't ship with UCX >=1.19, you can build it from source with the following command:
|
||||
```bash
|
||||
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,320 @@
|
||||
# Algorithms
|
||||
|
||||
This page covers the math and the configurable algorithmic components: how off-policy training works, the default loss 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
|
||||
|
||||
- [Async / Off-Policy Training](#async--off-policy-training)
|
||||
- [Loss](#loss)
|
||||
- [Default Loss](#default-loss)
|
||||
- [Custom Loss](#custom-loss)
|
||||
- [Advantage](#advantage)
|
||||
- [Default Advantage](#default-advantage)
|
||||
- [Custom Advantage](#custom-advantage)
|
||||
- [Filters](#filters)
|
||||
- [Difficulty Pools](#difficulty-pools)
|
||||
- [Online Difficulty Filtering](#online-difficulty-filtering)
|
||||
- [Multi-Turn Trajectories](#multi-turn-trajectories)
|
||||
- [Extension Property](#extension-property)
|
||||
- [Best-Effort Interleaving](#best-effort-interleaving)
|
||||
- [Renderers](#renderers)
|
||||
- [Discontinuous Trajectories](#discontinuous-trajectories)
|
||||
|
||||
## Async / Off-Policy Training
|
||||
|
||||
`prime-rl` is asynchronous by default. The trainer and inference always run one step overlapped: while the trainer is producing $\pi_n$ from rollouts at step $n$, inference is already generating the rollouts for step $n+1$ using $\pi_{n-1}$. With matched trainer and inference step times this produces fully-overlapped pipeline parallelism — neither side ever idles.
|
||||
|
||||

|
||||
|
||||
At step $n = 1, 2, 3, \dots$:
|
||||
|
||||
- **Trainer** produces policy $\pi_n$ with weights $\theta_n$ from rollouts $(x_n, y_n)$.
|
||||
- **Inference** produces rollouts $(x_n, y_n)$ from policy $\pi_{\max(0,\,n-1)}$.
|
||||
|
||||
Step indices are 0-indexed so the gap holds at startup — inference is exactly one step behind the trainer.
|
||||
|
||||
## Loss
|
||||
|
||||
### Default Loss
|
||||
|
||||
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) = -\,\mathcal{J}_{\text{PG}}(\theta) \;+\; \tau_{KL}\,\mathcal{L}_{KL}(\theta)
|
||||
$$
|
||||
|
||||
where the policy-gradient term is
|
||||
|
||||
$$
|
||||
\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 |
|
||||
|---|---|---|
|
||||
| `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 for pure distillation (no RL signal). |
|
||||
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
|
||||
|
||||
The trainer dispatches automatically based on the batch's training mode (set by the orchestrator via `orchestrator.training_mode`):
|
||||
|
||||
- `rl` mode → DPPO + KL with the advantage signal.
|
||||
- `opd` mode → KL distillation against the teacher's per-token logprobs. The teacher must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
|
||||
- `sft` mode → standard token-level NLL on teacher-generated rollouts.
|
||||
|
||||
Set `[trainer.loss] type = "default"` and configure via the knobs above. SFT and OPD modes ignore the policy-gradient–specific fields.
|
||||
|
||||
### Custom Loss
|
||||
|
||||
The loss is computed **per sequence**: you write a function that takes one sequence's tensors and returns a scalar loss. The trainer iterates and aggregates.
|
||||
|
||||
```python
|
||||
# my_module.py
|
||||
import torch
|
||||
from prime_rl.trainer.rl.loss import LossInputs, LossOutputs
|
||||
|
||||
def ppo_clip_loss(inputs: LossInputs, clip_eps: float = 0.2) -> LossOutputs:
|
||||
ratio = torch.exp(inputs.trainer_logprobs - inputs.inference_logprobs)
|
||||
clipped = torch.clamp(ratio, 1 - clip_eps, 1 + clip_eps)
|
||||
surr1 = ratio * inputs.advantages
|
||||
surr2 = clipped * inputs.advantages
|
||||
loss = -torch.min(surr1, surr2)[inputs.loss_mask].sum()
|
||||
return LossOutputs(
|
||||
loss=loss,
|
||||
metrics={
|
||||
"clip_frac": (ratio != clipped)[inputs.loss_mask].float().mean(),
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
Wire it up:
|
||||
|
||||
```toml
|
||||
[trainer.loss]
|
||||
type = "custom"
|
||||
import_path = "my_module.ppo_clip_loss"
|
||||
kwargs = { clip_eps = 0.2 }
|
||||
```
|
||||
|
||||
The dataclasses:
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class LossInputs:
|
||||
trainer_logprobs: Float[Tensor, "seq"] # current policy
|
||||
inference_logprobs: Float[Tensor, "seq"] # rollout-time policy
|
||||
teacher_logprobs: Float[Tensor, "seq"] | None # only set in OPD mode
|
||||
advantages: Float[Tensor, "seq"]
|
||||
loss_mask: Bool[Tensor, "seq"]
|
||||
|
||||
@dataclass
|
||||
class LossOutputs:
|
||||
loss: Float[Tensor, ""]
|
||||
metrics: dict[str, Tensor]
|
||||
```
|
||||
|
||||
Anything you put in `metrics` is averaged across sequences and logged with the other trainer metrics.
|
||||
|
||||
## Advantage
|
||||
|
||||
### Default Advantage
|
||||
|
||||
The default advantage is per-group reward minus per-group baseline (DR-GRPO without std normalization). For each prompt's group of `group_size` rollouts, every token in rollout $i$ receives advantage $s_i - \bar{s}$ where $\bar{s}$ is the group mean.
|
||||
|
||||
This is intentionally simple — it does the right thing for most envs. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
|
||||
|
||||
Two built-in **length penalties** can be layered on top of any advantage to discourage rambling:
|
||||
|
||||
- `[orchestrator.length_penalty] type = "tokens"` — penalizes long completions in tokens, with configurable target and slope.
|
||||
- `[orchestrator.length_penalty] type = "turns"` — penalizes long multi-turn rollouts by turn count.
|
||||
|
||||
|
||||
### Custom Advantage
|
||||
|
||||
Advantages are computed **per group**. You write a function that takes one group of rollouts and returns one advantage scalar per rollout. The orchestrator handles groups of varying size automatically — partial-group training kicks in when some rollouts in a group errored.
|
||||
|
||||
```python
|
||||
# my_module.py
|
||||
import statistics
|
||||
from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
|
||||
|
||||
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
|
||||
rewards = [r["reward"] for r in inputs.rollouts]
|
||||
mean = statistics.fmean(rewards)
|
||||
std = statistics.pstdev(rewards) if len(rewards) > 1 else 0.0
|
||||
return AdvantageOutputs(advantages=[(r - mean) / (std + eps) for r in rewards])
|
||||
```
|
||||
|
||||
```toml
|
||||
[orchestrator.advantage]
|
||||
type = "custom"
|
||||
import_path = "my_module.normalized_advantage"
|
||||
kwargs = { eps = 1e-8 }
|
||||
```
|
||||
|
||||
`AdvantageInputs.rollouts` is a list of `verifiers.RolloutOutput`, so you have access to the full rollout (turns, tool calls, custom metadata) — not just the reward. Use this for anything reward-shaping-like that needs trajectory context.
|
||||
|
||||
### Per-Env Advantage
|
||||
|
||||
`advantage` can be set per training environment. Each env inherits the top-level `[orchestrator.advantage]` when it doesn't set its own, so mixed-env runs can give each env its own advantage computation:
|
||||
|
||||
```toml
|
||||
[orchestrator.advantage]
|
||||
type = "default" # the default every env inherits unless it overrides
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env" # inherits the default above
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "agent-env"
|
||||
advantage = { type = "custom", import_path = "my_module.normalized_advantage" }
|
||||
```
|
||||
|
||||
## Filters
|
||||
|
||||
Filters drop rollouts between scoring and training. Built-ins (composable):
|
||||
|
||||
| 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. |
|
||||
|
||||
The default `[orchestrator]` config already includes all three filters with their defaults. To override, set `filters` explicitly — the list replaces the defaults wholesale:
|
||||
|
||||
```toml
|
||||
[[orchestrator.filters]]
|
||||
type = "zero_advantage"
|
||||
|
||||
[[orchestrator.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.
|
||||
|
||||
## Difficulty Pools
|
||||
|
||||
Difficulty pools gradually retire problems the model has solved or never solves. After each rollout, the average reward across a problem's group is compared to two thresholds:
|
||||
|
||||
- `buffer.easy_threshold` — at or above this, the problem moves into the `easy` pool and is no longer sampled.
|
||||
- `buffer.hard_threshold` — at or below this, the problem moves into the `hard` pool and is no longer sampled.
|
||||
- Otherwise the problem stays in `normal` and remains in the sampling rotation.
|
||||
|
||||
Pool assignments persist across checkpoints (`easy_examples.jsonl` / `hard_examples.jsonl` under each step's orchestrator checkpoint). When you resume — or want to broaden the curriculum mid-run — `buffer.easy_fraction` / `buffer.hard_fraction` randomly lift that fraction of pooled problems back into `normal` so they re-enter sampling.
|
||||
|
||||
```toml
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 0.95
|
||||
hard_threshold = 0.05
|
||||
easy_fraction = 0.0 # default; bump on resume to bring some easy problems back
|
||||
hard_fraction = 0.0 # default; bump on resume to bring some hard problems back
|
||||
```
|
||||
|
||||
Watch `pool/{env}/{easy,normal,hard}` (current pool ratios) and `evicted_examples/{env}/{easy,hard}` (per-step eviction rate).
|
||||
|
||||
## Online Difficulty Filtering
|
||||
|
||||
Online difficulty filtering (ODF) drops collapsed-advantage groups on the way *into* the buffer. Set `buffer.online_difficulty_filtering = true` (default `false`) to enable:
|
||||
|
||||
- Average reward across the group is **0.0** (every rollout failed) → drop the group, count under `filtered_rollouts/{env}/hard`.
|
||||
- Average reward **1.0** (every rollout succeeded) → drop, count under `filtered_rollouts/{env}/easy`.
|
||||
- Otherwise → into the buffer.
|
||||
|
||||
These are exactly the groups whose within-group advantage collapses to zero — DR-GRPO produces no gradient signal for them, so the trainer would burn step time on tokens it can't learn from.
|
||||
|
||||
```toml
|
||||
[orchestrator.buffer]
|
||||
online_difficulty_filtering = true
|
||||
```
|
||||
|
||||
**Tradeoff: trainer stability vs. inference speed.** With ODF on, every rollout that reaches the trainer carries non-zero advantage — each trainer step's effective batch is predictable and the gradient signal is denser. The cost is paid on the inference side: rollouts get produced and then thrown away, so the orchestrator has to oversample to keep the trainer fed. If the orchestrator is your bottleneck (`time/wait_for_batch` high on the trainer), ODF can starve the loop. Bump `orchestrator.oversampling_factor` so inference produces enough groups per step to absorb the drops.
|
||||
|
||||
ODF is orthogonal to the [pools](#difficulty-pools): ODF reacts to the *current* group's reward distribution, the pools track the *running* per-problem average. Many configs use both — ODF for per-step density, pools for long-horizon curriculum cleanup.
|
||||
|
||||
## Multi-Turn Trajectories
|
||||
|
||||
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
|
||||
|
||||
A sequence of trajectory steps has the **extension property** when each successive step's prompt contains all previous prompts and completions as an exact prefix. The trainer relies on this property — when it holds:
|
||||
|
||||
- Multiple steps merge into one training sample.
|
||||
- Compute scales as $O(T)$ in the trajectory length.
|
||||
|
||||
When it breaks (chat template strips past thinking, environment compacts context, an agent hands off to a sub-agent, etc.), the trainer starts a new training sample from that step:
|
||||
|
||||
- Graceful fallback to multiple samples — no corrupted data.
|
||||
- Worst case (every step breaks extension) is $O(T^2)$.
|
||||
|
||||
### Best-Effort Interleaving
|
||||
|
||||
Concretely:
|
||||
|
||||
```
|
||||
5-step trajectory where extension breaks at step 4:
|
||||
|
||||
steps 1–3: extension holds → merged into Sample 1
|
||||
step 4: extension breaks (e.g. thinking stripped from history)
|
||||
steps 4–5: extension holds → merged into Sample 2
|
||||
|
||||
result: 2 training samples instead of 5
|
||||
```
|
||||
|
||||
The orchestrator enforces an **exact prefix invariant**: the prompt at turn $t$ must be the exact concatenation of prior messages exactly as the LLM originally generated them. If turn 2's prompt is `U1, A1', U2` while `A1' ≠ A1`, the orchestrator can't safely merge — either choice produces logprob drift between trainer and inference. Starting a fresh sample is the only correct behavior, so that's what happens.
|
||||
|
||||
### Renderers
|
||||
|
||||
Best-effort interleaving works because the renderer guarantees the exact-prefix invariant *by construction* — it never re-renders prior turns, so it can't lose tokens to chat-template normalization, BPE retokenization drift, or thinking stripping. A renderer turns a model's chat template into a Python object that can:
|
||||
|
||||
- `render_ids(messages)` — tokenize messages to ids the inference engine accepts.
|
||||
- `parse_response(completion_ids)` — recover structured `(content, reasoning_content, tool_calls)` from sampled ids.
|
||||
- `bridge_to_next_turn(prev_prompt_ids, prev_completion_ids, new_messages)` — extend the previous turn's tokens verbatim with the new environment turn, instead of re-rendering history.
|
||||
|
||||
When `bridge_to_next_turn` succeeds, the trainer sees the exact token stream the sampler produced; when it can't be proven safe (e.g. the renderer is `DefaultRenderer` and the template's stop sequence is unknown), it returns `None` and the orchestrator falls back to a full re-render — which triggers the new-sample fallback above.
|
||||
|
||||
A common source of breakage in the absence of a hand-coded renderer is models like Qwen3 whose chat templates strip past `<think>` blocks across user turns:
|
||||
|
||||
```python
|
||||
from transformers import AutoTokenizer
|
||||
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
|
||||
messages = [
|
||||
{"role": "user", "content": "U1"},
|
||||
{"role": "assistant", "content": "<think>R1</think>A1"},
|
||||
{"role": "user", "content": "U2"},
|
||||
]
|
||||
tok.apply_chat_template(messages[:1], tokenize=False)
|
||||
# <|im_start|>user
|
||||
# U1<|im_end|>
|
||||
|
||||
tok.apply_chat_template(messages, tokenize=False)
|
||||
# <|im_start|>user\nU1<|im_end|>\n<|im_start|>assistant\nA1<|im_end|>\n<|im_start|>user\nU2<|im_end|>
|
||||
# (the <think>R1</think> from turn 2 is gone)
|
||||
```
|
||||
|
||||
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `glm5`, `glm4.5`, `minimax-m2`, `deepseek-v3`, `kimi-k2`, `kimi-k2.5`, `nemotron-3`, `gpt-oss`; anything else falls back to `DefaultRenderer` (a generic `apply_chat_template` wrapper). Pick one via:
|
||||
|
||||
```toml
|
||||
[orchestrator.renderer]
|
||||
name = "auto" # detect from tokenizer; pass an explicit name for fine-tunes
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
Some envs are discontinuous by design — e.g. a main agent delegating to a sub-agent and getting back only a summarized result, not the sub-agent's whole conversation. Best-effort interleaving handles this naturally: each agent's contiguous turns merge, the handoff starts a new sample. The trainer never sees fabricated extension where there is none.
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 500 KiB After Width: | Height: | Size: 108 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 53 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 22 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 440 KiB |
@@ -1,39 +0,0 @@
|
||||
# Asynchronous Training
|
||||
|
||||
PRIME-RL implements asynchronous off-policy training, instead of the traditional synchronous on-policy training. This means that we allow inference to generate rollouts from a stale policy up to $k$ (in the code we call this `max_async_level`) steps ahead of the trainer. With `k=1` and trainer and inference step timings being equal, this allows to run without any idle time on either the trainer or inference. By default, we set `k=2` to allow overlap with a weight broadcast over the Internet, which is needed for decentralized training.
|
||||
|
||||

|
||||
|
||||
## Loss Objective
|
||||
|
||||
We adopt a loss objective capable of handling the natural distribution shift caused by the off-policy nature of the training. By default, we use a token-level loss variant of the [AIPO](https://arxiv.org/abs/2505.24034) training objective introduced in Llama-RL,
|
||||
but omit the entropy and KL loss terms.
|
||||
|
||||
At each step, we sample $N$ prompts from our dataset. For
|
||||
each prompt $x$, we sample a group of rollouts $\{y_i\}^G_{i=1}$
|
||||
and use a verifier to assign scores $s_i$ to each $y_i$.
|
||||
Then, the optimization objective is given by
|
||||
|
||||
$$
|
||||
\mathcal{J}_{\text{AIPO}}(\theta)
|
||||
= \frac{1}{\sum_{j=1}^N \sum_{i=1}^G |y_i^{(j)}|}
|
||||
\sum_{j=1}^N
|
||||
\sum_{i=1}^G
|
||||
\sum_{t=1}^{|y_i^{(j)}|}
|
||||
\min\left(
|
||||
\frac{\pi(y^{(j)}_{i,t}\mid x_j, y^{(j)}_{i,<t})}{\mu(y^{(j)}_{i,t}\mid x_j, y^{(j)}_{i,<t})},
|
||||
\delta
|
||||
\right)\hat{A}^{(j)}_{i,t}
|
||||
$$
|
||||
|
||||
where $\mu$ refers to the policy that generated the rollout, $\pi$ refers to the current policy, $\hat{A}_{i,t}$ is the token-level advantage, and $\delta$ is the importance sampling clipping ratio.
|
||||
|
||||
|
||||
## Step Semantics
|
||||
|
||||
PRIME-RL uses a global training step $n=1,2,3,\dots$ that is used to tag artifacts:
|
||||
|
||||
- **Trainer**: Produces policy $\pi_n$ with weights $\theta_n$ from rollouts $(x_n, y_n)$
|
||||
- **Inference**: Produces rollouts $(x_n, y_n)$ from policy $\pi_{max(0, n-k)}$
|
||||
|
||||
Here, $k$ is the `max_async_level` parameter, which defaults to 2. Note that we use 0-indexed steps to cleanly indicate that at each step, the divergence off-policy gap is at most $k$ steps.
|
||||
@@ -1,79 +0,0 @@
|
||||
# Benchmarking
|
||||
|
||||
We provide a convenient way to benchmark the performance, mainly measured in throughput and MFU, of the inference engine and trainer using the `--bench` flag. It will run each module in isolation for a few steps and log performance benchmark results in a rich table to the console.
|
||||
|
||||
## SFT
|
||||
|
||||
Benchmark on the default fake data configuration
|
||||
|
||||
```bash
|
||||
uv run sft ... --data.type fake --bench
|
||||
```
|
||||
|
||||
Benchmark with variable-length, instead of fixed-length, fake data to more closely simulate real data.
|
||||
|
||||
```bash
|
||||
uv run sft ... --data.type fake --data.length variable --bench
|
||||
```
|
||||
|
||||
Benchmark different batch configurations, i.e. the (micro) batch size and sequence length
|
||||
|
||||
```bash
|
||||
uv run sft ... --data.type fake --data.seq-len 4096 --data.batch-size 64 --data.micro-batch-size 2 --bench
|
||||
```
|
||||
|
||||
Benchmark against a real dataset
|
||||
|
||||
```bash
|
||||
uv run sft ... --data.name PrimeIntellect/Reverse-Text-SFT --bench
|
||||
```
|
||||
|
||||
Benchmark against a training configuration
|
||||
|
||||
```bash
|
||||
uv run sft @ path/to/config.toml --bench
|
||||
```
|
||||
|
||||
## RL
|
||||
|
||||
### Trainer
|
||||
|
||||
Benchmark on a fake data loader
|
||||
|
||||
```bash
|
||||
uv run trainer ... --data.fake --bench
|
||||
```
|
||||
|
||||
Benchmark different batch configurations, i.e. the (micro) batch size and sequence length
|
||||
|
||||
```bash
|
||||
uv run trainer ... --model.seq-len 4096 --data.fake.batch-size 64 --data.fake.micro-batch-size 2 --bench
|
||||
```
|
||||
|
||||
*Note, that it is not yet possible to benchmark the RL trainer against real data when benchmarking the RL trainer in isolation.*
|
||||
|
||||
### Inference
|
||||
|
||||
To benchmark the inference engine in isolation, start the inference server with the correct configuration file and run the orchestrator with the `--bench` flag.
|
||||
|
||||
```bash
|
||||
uv run inference @ path/to/config.toml
|
||||
```
|
||||
|
||||
```bash
|
||||
uv run orchestrator @ path/to/config.toml --bench
|
||||
```
|
||||
|
||||
*Note, that it is not yet possible to benchmark the inference engine against fake data.*
|
||||
|
||||
## Trainer + Inference
|
||||
|
||||
To benchmark the full RL training, you can add the `--bench` flag to your RL entrypoint. This will benchmark the RL trainer against fake data and the inference engine against real data from the orchestrator.
|
||||
|
||||
```bash
|
||||
uv run rl \
|
||||
--trainer @ path/to/train.toml \
|
||||
--orchestrator @ path/to/orch.toml \
|
||||
--inference @ path/to/infer.toml \
|
||||
--bench
|
||||
```
|
||||
@@ -1,142 +0,0 @@
|
||||
# Bring Your Own Algorithms
|
||||
|
||||
Prime-RL supports custom implementations for key algorithmic components, allowing you to experiment with different RL objectives and techniques.
|
||||
|
||||
## 1. Custom Loss Functions
|
||||
|
||||
The loss is computed **per-sequence** (per-sample). You provide a function that computes the loss for a single sequence, and the framework handles iteration and aggregation.
|
||||
|
||||
### Interface
|
||||
|
||||
```python
|
||||
from prime_rl.trainer.rl.loss import LossInputs, LossOutputs
|
||||
|
||||
def my_custom_loss(inputs: LossInputs, **kwargs) -> LossOutputs:
|
||||
...
|
||||
```
|
||||
|
||||
#### LossInputs
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class LossInputs:
|
||||
trainer_logprobs: Float[Tensor, "seq"] # Log probs from current policy
|
||||
inference_logprobs: Float[Tensor, "seq"] # Log probs from reference policy
|
||||
teacher_logprobs: Float[Tensor, "seq"] | None # Optional teacher log probs
|
||||
advantages: Float[Tensor, "seq"] # Per-token advantages
|
||||
loss_mask: Bool[Tensor, "seq"] # Mask for valid tokens
|
||||
```
|
||||
|
||||
#### LossOutputs
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class LossOutputs:
|
||||
loss: Float[Tensor, ""] # Scalar loss for this sequence
|
||||
metrics: dict[str, Tensor] # Metrics to log
|
||||
```
|
||||
|
||||
### Example: PPO Clipped Loss
|
||||
|
||||
```python
|
||||
import torch
|
||||
from prime_rl.trainer.rl.loss import LossInputs, LossOutputs
|
||||
|
||||
def ppo_clip_loss(inputs: LossInputs, clip_eps: float = 0.2) -> LossOutputs:
|
||||
ratio = torch.exp(inputs.trainer_logprobs - inputs.inference_logprobs)
|
||||
clipped_ratio = torch.clamp(ratio, 1 - clip_eps, 1 + clip_eps)
|
||||
|
||||
surr1 = ratio * inputs.advantages
|
||||
surr2 = clipped_ratio * inputs.advantages
|
||||
|
||||
loss = -torch.min(surr1, surr2)[inputs.loss_mask].sum()
|
||||
|
||||
return LossOutputs(
|
||||
loss=loss,
|
||||
metrics={"clip_frac": (ratio != clipped_ratio)[inputs.loss_mask].float().mean()},
|
||||
)
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
```toml
|
||||
[loss]
|
||||
type = "custom"
|
||||
import_path = "my_module.ppo_clip_loss"
|
||||
kwargs = { clip_eps = 0.2 }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Custom Advantage Functions
|
||||
|
||||
Advantages are computed **per-group** (one example × N rollouts). You provide a function that computes advantages for a single group; the framework calls it once per group and stitches the results back together. Groups may have fewer than `group_size` rollouts when some rollouts in the group errored (partial-group training).
|
||||
|
||||
### Interface
|
||||
|
||||
```python
|
||||
from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
|
||||
|
||||
def my_custom_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
|
||||
...
|
||||
```
|
||||
|
||||
#### AdvantageInputs
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class AdvantageInputs:
|
||||
# All rollouts for a single example (one group).
|
||||
rollouts: list[vf.RolloutOutput]
|
||||
```
|
||||
|
||||
Each `vf.RolloutOutput` carries the full rollout (`reward`, `trajectory`, etc.), so custom advantages can read any metadata they need (e.g. completion-token counts, turn counts, tool calls).
|
||||
|
||||
#### AdvantageOutputs
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class AdvantageOutputs:
|
||||
advantages: list[float] # one entry per rollout in the input group
|
||||
```
|
||||
|
||||
### Example: Normalized Advantage
|
||||
|
||||
```python
|
||||
import statistics
|
||||
from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
|
||||
|
||||
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
|
||||
"""Normalize advantages to zero mean and unit variance within the group."""
|
||||
rewards = [r["reward"] for r in inputs.rollouts]
|
||||
mean = statistics.fmean(rewards)
|
||||
std = statistics.pstdev(rewards) if len(rewards) > 1 else 0.0
|
||||
return AdvantageOutputs(advantages=[(r - mean) / (std + eps) for r in rewards])
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
```toml
|
||||
[advantage]
|
||||
type = "custom"
|
||||
import_path = "my_module.normalized_advantage"
|
||||
kwargs = { eps = 1e-8 }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Default Implementations
|
||||
|
||||
If no custom function is specified:
|
||||
|
||||
- **Loss**: Uses `default_loss_fn` (masked importance sampling with KL against the inference policy, and optional masking strategies)
|
||||
- **Advantage**: Uses `default_advantage_fn` (reward minus per-example baseline, a.k.a. DR-GRPO without std normalization)
|
||||
|
||||
See `LossConfig` and `AdvantageConfig` for available parameters.
|
||||
|
||||
## Tips
|
||||
|
||||
- Your functions receive structured inputs via dataclasses with jaxtyping annotations
|
||||
- Return metrics as scalars or 1D tensors - they'll be aggregated automatically
|
||||
- Use the `loss_mask` / tensor shapes to handle variable-length sequences
|
||||
- Test your custom functions with the provided test patterns before training
|
||||
@@ -1,57 +0,0 @@
|
||||
# Checkpointing
|
||||
|
||||
Checkpointing is non-standard due to trainer/orchestrator separation and natural asynchrony.
|
||||
|
||||
- SFT+RL Trainer: Checkpoints FSDP model shard (using DCP), optimizer and scheduler state, and progress (training step, total samples, total tokens)
|
||||
- Orchestrator: Checkpoints orchestrator progress (training step, total tokens, total samples, total problems)
|
||||
- Inference: Inference is stateless. Upon restart, the orchestrator will reload the correct weights into the inference engine. No checkpointing is required.
|
||||
|
||||
The default checkpoint directory is `checkpoints` and each checkpoint step will live in a step subdirectory, i.e. `checkpoints/step_{step}`.
|
||||
|
||||
Checkpointing is configured with the config key `--ckpt`. One can specify the interval (`--ckpt.interval`), whether to save checkpoints asynchronously (`--ckpt.save-async`), how many recent step checkpoints to keep on disk (`--ckpt.keep-last`), and keep checkpoints at every N steps permanently (`--ckpt.keep-interval`). By default, we do not checkpoint to save disk space.
|
||||
|
||||
## SFT
|
||||
|
||||
Let's split the reverse text training SFT example, which does 40 steps by default, into two runs of 20 steps each.
|
||||
|
||||
First, run the first 20 steps and append `--ckpt` flag will enable the default checkpoint configuration which will only write the final checkpoint to disk, but no intermediate checkpoints.
|
||||
|
||||
```bash
|
||||
uv run sft ... --max-steps 20 --ckpt
|
||||
```
|
||||
|
||||
Then, to resume the training from step 20, run the following command
|
||||
|
||||
```bash
|
||||
uv run sft ... --max-steps 40 --ckpt.resume-step 20
|
||||
```
|
||||
|
||||
## RL
|
||||
|
||||
Similarly, let's split the reverse text training RL example, which does 20 steps by default, into two runs of 10 steps each.
|
||||
|
||||
First, start the inference server. It can stay running across restarts as the orchestrator will automatically send the right checkpoint to the inference server when resuming.
|
||||
|
||||
```bash
|
||||
uv run inference ...
|
||||
```
|
||||
|
||||
Then, run the first 20 steps and write the final checkpoint to disk
|
||||
|
||||
```bash
|
||||
uv run rl \
|
||||
--trainer @ path/to/train.toml \
|
||||
--orchestrator @ path/to/orch.toml \
|
||||
--max-steps 10 \
|
||||
--ckpt
|
||||
```
|
||||
|
||||
And finally, resume the training to do the remaining 10 steps
|
||||
|
||||
```bash
|
||||
uv run rl \
|
||||
--trainer @ path/to/train.toml \
|
||||
--orchestrator @ path/to/orch.toml \
|
||||
--max-steps 20 \
|
||||
--ckpt.resume-step 10
|
||||
```
|
||||
@@ -1,33 +0,0 @@
|
||||
# Configs
|
||||
|
||||
We use `pydantic-settings` with some custom functionality for configuring runs. We support the following sources, in this order of precedence:
|
||||
|
||||
1. **Command-line arguments**: Pass (nested) arguments as `--key.subkey value` to the script. For example, to set the model name, set `--model.name <model-name>`
|
||||
|
||||
2. **Config files**: You can pass TOML config files using the `@` prefix. For example, to set a config, run `uv run inference @ path/to/config.toml`. (*You have to leave a space between the `@` and the config file*)
|
||||
|
||||
3. **Environment variables**: You can set environment variables to override the config values. All environment variables must be prefixed with `PRIME_` and use the `__` delimiter to nest the keys. For example, to set the model name you can run `export PRIME_MODEL__NAME=Qwen/Qwen3-0.6B`.
|
||||
|
||||
4. **Defaults**: For almost all config arguments, we have a default value which will be used if no other source is provided.
|
||||
|
||||
In general we recommend setting configurations via config files to define reproducible experiments and use command-line arguments to override the config values to run variants of the same experiment. Environment variables are usually only used in production settings to communicate with the [Prime Protocol](https://github.com/PrimeIntellect-ai/protocol) worker. In most cases, you should not need to use environment variables.
|
||||
|
||||
The precedence order will be important if multiple sources try to configure the same argument. For example, in the following command, all sources will define a model name
|
||||
|
||||
```toml
|
||||
# qwen8b.toml
|
||||
[model]
|
||||
name = "Qwen/Qwen3-8B"
|
||||
```
|
||||
|
||||
```toml
|
||||
# qwen14b.toml
|
||||
[model]
|
||||
name = "Qwen/Qwen-14B"
|
||||
```
|
||||
|
||||
```bash
|
||||
PRIME_MODEL__NAME=Qwen/Qwen3-4B uv run ... @ qwen8b.toml @ qwen14b.toml --model.name Qwen/Qwen3-32B
|
||||
```
|
||||
|
||||
In this example, the CLI argument `--model.name Qwen/Qwen3-32B` will take precedence and the script will use `Qwen/Qwen3-32B` as the model name. If the CLI argument wasn't set, then the second config file would take precedence and the script would use `Qwen/Qwen-14B` as the model name. If the second config file wasn't set, then the first config file would take precedence and the script would use `Qwen/Qwen3-8B` as the model name. Finally, if the first config file wasn't set, then the environment variable would take precedence and the script would use `Qwen/Qwen3-4B` as the model name. If the environment variable wasn't set, then the default value would be used and the script would use `Qwen/Qwen3-0.6B` as the model name.
|
||||
@@ -0,0 +1,207 @@
|
||||
# Configuration
|
||||
|
||||
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, the trainer-side `token_export` flag) that aren't surfaced here.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Sources and Precedence](#sources-and-precedence)
|
||||
- [TOML Composition](#toml-composition)
|
||||
- [CLI Overrides](#cli-overrides)
|
||||
- [Inspecting and Validating](#inspecting-and-validating)
|
||||
- [Syntax](#syntax)
|
||||
- [Booleans](#booleans)
|
||||
- [Lists](#lists)
|
||||
- [Dicts](#dicts)
|
||||
- [Optional Sub-Configs](#optional-sub-configs)
|
||||
- [None](#none)
|
||||
- [Discriminated Unions](#discriminated-unions)
|
||||
- [Environments (`[[orchestrator.train.env]]`)](#environments-orchestratortrainenv)
|
||||
- [Examples](#examples)
|
||||
|
||||
## Sources and Precedence
|
||||
|
||||
Field values come from three sources — Pydantic defaults, TOML files (passed with `@`), and CLI flags. They're layered in this order, with later sources winning:
|
||||
|
||||
1. **Defaults** declared on the Pydantic model.
|
||||
2. **TOML files** passed with `@`, left to right — later files override earlier ones.
|
||||
3. **CLI flags** in dotted, kebab-case form (`--model.name`).
|
||||
|
||||
## TOML Composition
|
||||
|
||||
The `@` token introduces a TOML file. Multiple `@` arguments compose left-to-right, deep-merged — unset fields in an overlay keep the base value:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/reverse_text/rl.toml # one file
|
||||
uv run rl @ base.toml @ overlay.toml # left to right
|
||||
uv run rl --trainer @ trainer.toml --orchestrator @ orch.toml # per-section
|
||||
uv run rl @ base.toml --trainer @ trainer.toml # mixed
|
||||
```
|
||||
|
||||
> Mind the space: `@ path/to/x.toml`, not `@path/to/x.toml`.
|
||||
|
||||
## CLI Overrides
|
||||
|
||||
CLI flags mirror the TOML tree using dots:
|
||||
|
||||
```bash
|
||||
--max-steps 50 # top-level
|
||||
--model.name Qwen/Qwen3-4B # nested
|
||||
--trainer.optim.lr 1e-5 # double-nested
|
||||
--inference.parallel.tp 4
|
||||
```
|
||||
|
||||
> Field names are snake_case in TOML (`max_model_len`) and kebab-case on the CLI (`--max-model-len`).
|
||||
|
||||
> 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/check # write resolved configs
|
||||
```
|
||||
|
||||
## Syntax
|
||||
|
||||
### Booleans
|
||||
|
||||
CLI uses paired flags: bare `--flag` sets `True`, `--no-flag` sets `False`. TOML must be explicit:
|
||||
|
||||
```bash
|
||||
uv run rl @ rl.toml --clean-output-dir # True
|
||||
uv run rl @ rl.toml --no-clean-output-dir # False
|
||||
```
|
||||
|
||||
```toml
|
||||
clean_output_dir = true
|
||||
```
|
||||
|
||||
### Lists
|
||||
|
||||
CLI accepts space-separated values or a JSON literal. TOML uses an array literal. Both forms target the same field:
|
||||
|
||||
```bash
|
||||
uv run rl @ rl.toml --trainer.model.lora.target-modules q_proj k_proj v_proj
|
||||
uv run rl @ rl.toml --trainer.model.lora.target-modules '["q_proj", "k_proj", "v_proj"]'
|
||||
```
|
||||
|
||||
```toml
|
||||
[trainer.model.lora]
|
||||
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 (e.g. environments), see [Environments](#environments-orchestratortrainenv).
|
||||
|
||||
### Dicts
|
||||
|
||||
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.env.0.args \
|
||||
'{"dataset_name": "openai/gsm8k", "dataset_subset": "main"}'
|
||||
```
|
||||
|
||||
```toml
|
||||
[[orchestrator.train.env]]
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
```
|
||||
|
||||
### Optional Sub-Configs
|
||||
|
||||
Many sub-configs are typed `SomeConfig | None`. Two patterns enable them:
|
||||
|
||||
- **Bare flag with defaults**: `--model.compile` or, in TOML, an empty section `[model.compile]`. The sub-config materializes with all-default values.
|
||||
- **Enable and set fields together**: `--model.compile.fullgraph` (CLI) or any populated `[model.compile]` table (TOML).
|
||||
|
||||
To **disable** a sub-config that's on by default, use `--no-<name>` on the CLI or assign the string `"None"` in TOML (see [None](#none)). This is how `[ckpt]`, `[model.lora]`, `[model.compile]`, `[trainer.wandb]`, etc. are turned on and off.
|
||||
|
||||
### None
|
||||
|
||||
TOML has no `null`. Use the string `"None"`, which the loader coerces:
|
||||
|
||||
```toml
|
||||
[inference.model]
|
||||
max_model_len = "None"
|
||||
```
|
||||
|
||||
On the CLI: `--inference.model.max-model-len None`.
|
||||
|
||||
### Discriminated Unions
|
||||
|
||||
Loss, advantage, optimizer, scheduler, weight broadcast transport, and several others are discriminated unions. Set the `type` field to pick a variant:
|
||||
|
||||
```toml
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
lr = 1e-5
|
||||
mu = 0.95
|
||||
```
|
||||
|
||||
Omit `type` to keep the default variant.
|
||||
|
||||
### Environments (`[[orchestrator.train.env]]`)
|
||||
|
||||
Training environments are an array of tables — set one per env, optionally with sampling weights:
|
||||
|
||||
```toml
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
ratio = 0.25 # 25% of batches; remaining 75% goes to math-env
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math-env"
|
||||
name = "gsm8k-eval"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
```
|
||||
|
||||
`args` is forwarded verbatim to the environment's `load_environment(**args)`.
|
||||
|
||||
The same `id` can appear multiple times across train and eval (or with different `args`) — useful for evaluating on a held-out split of the env you're training on, or comparing two configurations of the same env side by side. When `id` is reused, set a distinct `name` on each entry; `name` defaults to `id` and must be unique across all envs in the same group.
|
||||
|
||||
## Examples
|
||||
|
||||
The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples) are the canonical, kept-up-to-date references — the rest of the repo's TOMLs (under `configs/`) are CI- and debug-internal and may drift. Each example directory has its own README with the full launch story.
|
||||
|
||||
**Basic** (1–8 GPUs):
|
||||
|
||||
- [**Reverse Text**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/reverse_text) — `Qwen3-0.6B` reversing a chunk of text. Tiny single-turn SFT + RL; runs on a single consumer GPU in minutes.
|
||||
- [**Wordle**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/wordle) — `Qwen3-1.7B` playing Wordle. Multi-turn SFT + RL; 2–4 H100s.
|
||||
- [**Alphabet Sort**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/alphabet_sort) — `Qwen3-4B-Instruct-2507` sorting names alphabetically. Multi-turn LoRA RL without SFT warmup; one H100.
|
||||
- [**Wiki Search**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/wiki_search) — `Qwen3-4B-Instruct-2507` answering trivia by web-searching Wikipedia. Multi-turn with tool use.
|
||||
- [**Hendrycks Sanity**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/hendrycks_sanity) — `DeepSeek-R1-Distill-Qwen-1.5B` on a filtered MATH subset. Useful for algorithm ablations.
|
||||
|
||||
**Advanced** (32–2048 GPUs, SLURM):
|
||||
|
||||
- [**Qwen 3 30B – A3B Math**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/qwen30b_math) — `Qwen3-30B-A3B` on hard math.
|
||||
- [**Qwen 3 30B – A3B SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/qwen30b_swe) — `Qwen3-30B-A3B` on hard SWE.
|
||||
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/Intellect-3.1) — reproduces our INTELLECT-3.1 training run.
|
||||
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/minimax_m2.5_swe) — `MiniMax-M2.5` on agentic SWE.
|
||||
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/glm5_pd_disag) — `GLM-5` with P/D disaggregation and FP8 inference.
|
||||
|
||||
### Worked Example: Compose, Override, Dry-Run
|
||||
|
||||
Start from a shipped base config, override two fields on the CLI, and dry-run:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/reverse_text/rl.toml \
|
||||
--wandb.name my-experiment \
|
||||
--trainer.optim.lr 5e-6 \
|
||||
--output-dir /tmp/reverse-dry \
|
||||
--dry-run
|
||||
```
|
||||
|
||||
Then inspect the resolved config:
|
||||
|
||||
```bash
|
||||
ls /tmp/reverse-dry/configs/
|
||||
# rl.toml trainer.toml orchestrator.toml inference.toml
|
||||
```
|
||||
|
||||
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.
|
||||
@@ -1,299 +0,0 @@
|
||||
# Deployment
|
||||
|
||||
You can deploy PRIME-RL on a single GPU and larger multi-node clusters.
|
||||
|
||||
## SFT
|
||||
|
||||
### Single-GPU
|
||||
|
||||
For training on a single GPU, no communication orchestration is required and you can choose whether to start your trainer using our trainer entrypoint or using `torchrun`.
|
||||
|
||||
To start with our `sft` entrypoint
|
||||
|
||||
```bash
|
||||
uv run sft ...
|
||||
```
|
||||
|
||||
To do the same thing, but using `torchrun`
|
||||
|
||||
```bash
|
||||
uv run torchrun src/prime_rl/trainer/sft/train.py ...
|
||||
```
|
||||
|
||||
### Multi-GPU
|
||||
|
||||
For training on multiple GPUs, use `torchrun` with the `--nproc-per-node` flag.
|
||||
|
||||
```bash
|
||||
uv run torchrun \
|
||||
--local-rank-filter 0 \
|
||||
--nproc-per-node 8 \
|
||||
src/prime_rl/trainer/sft/train.py ...
|
||||
```
|
||||
|
||||
*The `--local-rank-filter` flag is used to only log the logs from the master rank, as detailed in [logging](logging.md).*
|
||||
|
||||
### Multi-Node
|
||||
|
||||
For training on multiple nodes, use `torchrun` with the `--nnodes`, `--node-rank`, and `--rdzv-endpoint` flags.
|
||||
|
||||
First, decide which node will be your head node and find a reachable private IP address for it. If your nodes are not colocated, you will likely need to setup VPN (e.g. [Tailscale](https://tailscale.com)) for the nodes to reach each other.
|
||||
|
||||
(*Skip this step if the default network interface is sufficient.*) Make sure to set the network interface for GLOO and NCCL to one that allows all nodes to reach each other.
|
||||
|
||||
```bash
|
||||
# On both nodes
|
||||
export GLOO_SOCKET_IFNAME=...
|
||||
export NCCL_SOCKET_IFNAME=...
|
||||
```
|
||||
|
||||
Then, configure the rendezvous endpoint to allow the nodes to find each other. Here, `MASTER_ADDR` is the private IP address of the head node and `MASTER_PORT` is a free port on the head node, typically port 29500 for `torchrun`.
|
||||
|
||||
```bash
|
||||
# On both nodes
|
||||
export MASTER_ADDR=...
|
||||
export MASTER_PORT=...
|
||||
```
|
||||
|
||||
Then, on the head node, run
|
||||
|
||||
```bash
|
||||
# On node 0
|
||||
uv run torchrun \
|
||||
--nnodes 2 \
|
||||
--node-rank 0 \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--local-rank-filter 0 \
|
||||
--nproc-per-node 8 \
|
||||
src/prime_rl/trainer/sft/train.py ...
|
||||
```
|
||||
|
||||
And on the second node, run
|
||||
|
||||
```bash
|
||||
# On node 1
|
||||
uv run torchrun \
|
||||
--nnodes 2 \
|
||||
--node-rank 1 \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--local-rank-filter 0 \
|
||||
--nproc-per-node 8 \
|
||||
src/prime_rl/trainer/sft/train.py ...
|
||||
```
|
||||
|
||||
### SLURM
|
||||
|
||||
See the dedicated [SLURM guide](slurm.md).
|
||||
|
||||
## Inference
|
||||
|
||||
For SLURM-based inference deployment, see the [SLURM guide](slurm.md#inference-examples). Each node runs an independent vLLM replica — no manual coordination needed.
|
||||
|
||||
For manual multi-node deployment without SLURM, we rely on vLLM's multi-node data parallel deployment primitives ([docs](https://docs.vllm.ai/en/v0.10.0/serving/data_parallel_deployment.html)).
|
||||
|
||||
First, decide which node will be your head node and find a reachable private IP address for it. If your nodes are not colocated, you will likely need to setup VPN (e.g. [Tailscale](https://tailscale.com)) for the nodes to reach each other.
|
||||
|
||||
(*Skip this step if the default network interface is sufficient.*) Make sure to set the network interface for GLOO and NCCL to one that allows all nodes to reach each other.
|
||||
|
||||
```bash
|
||||
# On both nodes
|
||||
export GLOO_SOCKET_IFNAME=...
|
||||
export NCCL_SOCKET_IFNAME=...
|
||||
```
|
||||
|
||||
Then, configure the data parallel address as the private IP address of the head node.
|
||||
|
||||
```bash
|
||||
# On both nodes
|
||||
export DATA_PARALLEL_ADDRESS=...
|
||||
export DATA_PARALLEL_RPC_PORT=...
|
||||
```
|
||||
|
||||
To run TP=4 and DP=4 with DP ranks 0 and 1 on the head node and DP ranks 2 and 3 on the second node, run
|
||||
|
||||
```bash
|
||||
# On node 0
|
||||
uv run inference \
|
||||
--data-parallel-size 4 \
|
||||
--tensor-parallel-size 4 \
|
||||
--data-parallel-size-local 2 \
|
||||
--data-parallel-address $DATA_PARALLEL_ADDRESS \
|
||||
--data-parallel-rpc-port $DATA_PARALLEL_RPC_PORT
|
||||
```
|
||||
|
||||
```bash
|
||||
# On node 1
|
||||
uv run inference \
|
||||
--data-parallel-size 4 \
|
||||
--tensor-parallel-size 4 \
|
||||
--data-parallel-size-local 2 \
|
||||
--data-parallel-address $DATA_PARALLEL_ADDRESS \
|
||||
--data-parallel-rpc-port $DATA_PARALLEL_RPC_PORT \
|
||||
--data-parallel-start-rank 2 \
|
||||
--headless
|
||||
```
|
||||
|
||||
## RL
|
||||
|
||||
### Single-GPU Training
|
||||
|
||||
If you only have access to a single GPU, you may still be able to run small RL experiments. To do so, configure your inference server to use only a fraction of the available memory to leave some space for the trainer.
|
||||
|
||||
For example, to run an RL training on a single GPU while using 50% of the available memory for the inference server, run
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh
|
||||
```
|
||||
|
||||
```bash
|
||||
uv run rl \
|
||||
--trainer @ path/to/train.toml \
|
||||
--orchestrator @ path/to/orch.toml \
|
||||
--inference @ path/to/infer.toml \
|
||||
--trainer-gpu-ids 0 \
|
||||
--inference-gpu-ids 0 \
|
||||
--inference.gpu-memory-utilization 0.5
|
||||
```
|
||||
|
||||
*Make sure to tune the `--gpu-memory-utilization` value such that you have enough GPU memory for the RL trainer.*
|
||||
|
||||
You can also set this up by starting each submodule manually.
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
uv run inference @ path/to/infer.toml --gpu-memory-utilization 0.5
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Orchestrator` pane
|
||||
uv run orchestrator @ path/to/orch.toml
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
uv run trainer @ path/to/train.toml
|
||||
```
|
||||
|
||||
### Multi-GPU Training
|
||||
|
||||
For single-node training, we recommend using the `rl` entrypoint to conveniently start all components, i.e. the inference server, the orchestrator, and the trainer.
|
||||
|
||||
By default, the inference server starts on GPU ID 0 and the trainer on GPU ID 1.
|
||||
|
||||
```bash
|
||||
uv run rl \
|
||||
--trainer @ path/to/train.toml \
|
||||
--orchestrator @ path/to/orch.toml \
|
||||
--inference @ path/to/infer.toml \
|
||||
```
|
||||
|
||||
You can configure the GPU IDs to use for the inference server and the trainer. For example, to run the inference server on GPUs IDs 0-5 with data parallelism and the trainer on GPUs IDs 6-7
|
||||
|
||||
```bash
|
||||
uv run rl \
|
||||
--trainer @ path/to/train.toml \
|
||||
--orchestrator @ path/to/orch.toml \
|
||||
--inference @ path/to/infer.toml \
|
||||
--inference-gpu-ids 0,1,2,3,4,5 \
|
||||
--trainer-gpu-ids 6,7 \
|
||||
--inference.parallel.dp 6
|
||||
```
|
||||
|
||||
### Parallel Experiments
|
||||
|
||||
For quick ablations, it can be more efficient to parallelize experiments within a node (e.g. split your GPUs to run two experiments in parallel). For example, if you have access to 4 GPUs and your experiment fits on 2 GPUs, you can parallelize two experiments as follows:
|
||||
|
||||
Start the first experiment in a tmux session `exp1` with outputs directory `outputs1`. Specify it both in the tmux script, as well as in the start command (*will use the first 2 GPUs*)
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh -s exp1 -o outputs1
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
uv run rl \
|
||||
--trainer @ path/to/train.toml \
|
||||
--orchestrator @ path/to/orch.toml \
|
||||
--inference @ path/to/infer.toml \
|
||||
--output-dir outputs1
|
||||
```
|
||||
|
||||
For the second experiment, start a second tmux session named `exp2` with outputs directory `outputs2`. In addition, specify a new server port for the inference engine and orchestrator (*will use the last 2 GPUs*)
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh -s exp-2 -o outputs2
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
uv run rl \
|
||||
--trainer @ path/to/train.toml \
|
||||
--orchestrator @ path/to/orch.toml \
|
||||
--inference @ path/to/infer.toml \
|
||||
--inference-gpu-ids 2 \
|
||||
--trainer-gpu-ids 3 \
|
||||
--inference.server.port 8001 \
|
||||
--orchestrator.client.base-url http://localhost:8001/v1 \
|
||||
--output-dir outputs2
|
||||
```
|
||||
|
||||
### Multi-Node Training
|
||||
|
||||
> We currently require a shared file system for multi-node RL training.
|
||||
|
||||
To facilitate multi-node RL training, ensure that all nodes have access to a shared file system and that the node that will run the inference server is reachable from the orchestrator via a private or public IP address. Then, set the following environment variables on all nodes:
|
||||
|
||||
```bash
|
||||
# On all nodes
|
||||
export OUTPUT_DIR=... # Path to directory in shared file system
|
||||
export INFERENCE_SERVER_IP=... # Reachable IP address of the inference node
|
||||
export INFERENCE_SERVER_API_KEY=... # API key for the inference server
|
||||
```
|
||||
|
||||
Then, start the inference server on one node.
|
||||
|
||||
```bash
|
||||
# On one node
|
||||
uv run inference ... \
|
||||
--api-key $INFERENCE_SERVER_API_KEY --parallel ...
|
||||
```
|
||||
|
||||
Then, start a single orchestrator
|
||||
|
||||
```bash
|
||||
# On either node
|
||||
uv run orchestrator ... \
|
||||
--client.base-url http://$INFERENCE_SERVER_IP:8000/v1 \
|
||||
--client.api-key-var INFERENCE_SERVER_API_KEY \
|
||||
--output-dir $OUTPUT_DIR
|
||||
```
|
||||
|
||||
Finally, start the trainer on one as described in the [Trainer](#trainer) section.
|
||||
|
||||
```bash
|
||||
# On other node
|
||||
uv run torchrun \
|
||||
--nproc-per-node 8 \
|
||||
--local-rank-filter 0 \
|
||||
src/prime_rl/trainer/rl/train.py ... \
|
||||
--output-dir $OUTPUT_DIR
|
||||
```
|
||||
|
||||
Of course, you can further scale up the number of nodes used by the trainer and inference server, as described in the sections above. However, make sure that there is only a single orchestrator instance.
|
||||
|
||||
### SLURM
|
||||
|
||||
See the dedicated [SLURM guide](slurm.md).
|
||||
|
||||
## Kubernetes
|
||||
|
||||
For deployments on Kubernetes clusters, PRIME-RL provides a Helm chart that manages the entire training infrastructure including orchestrator, trainer, and inference components with automatic pod scheduling, GPU allocation, and shared storage.
|
||||
|
||||
See the dedicated [Kubernetes guide](kubernetes.md) for complete documentation including:
|
||||
|
||||
- Prerequisites and setup
|
||||
- Quick start examples
|
||||
- Component architecture
|
||||
- Scaling and distributed training
|
||||
- Configuration options
|
||||
- Troubleshooting
|
||||
@@ -0,0 +1,140 @@
|
||||
# Development
|
||||
|
||||
This page covers workflows for developing on `prime-rl` itself — running the test suite, contributing changes, and adding new model architectures with the small-scale tooling we use to iterate on MoE families without booting up a 100B+ run.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Test Suite](#test-suite)
|
||||
- [Layout](#layout)
|
||||
- [Running Tests Locally](#running-tests-locally)
|
||||
- [CI Workflows](#ci-workflows)
|
||||
- [Markers](#markers)
|
||||
- [Pre-Commit Hooks](#pre-commit-hooks)
|
||||
- [Adding a New Model](#adding-a-new-model)
|
||||
- [Implement the Modeling Code](#implement-the-modeling-code)
|
||||
- [Register a Mini Preset](#register-a-mini-preset)
|
||||
- [Run the Smoke Test](#run-the-smoke-test)
|
||||
|
||||
## Test Suite
|
||||
|
||||
The test suite is split into three tiers, each with its own CI workflow.
|
||||
|
||||
### Layout
|
||||
|
||||
- **`tests/unit/`** — fast-running, hermetic tests for isolated logic: config parsing and validation, advantage / loss / scheduler / packer math, individual dataset paths, model-conversion roundtrips, etc. Tests that need a GPU are tagged with the `gpu` marker.
|
||||
- **`tests/integration/`** — full-stack RL/SFT runs on a tiny model end-to-end through inference + orchestrator + trainer.
|
||||
- **`tests/nightly/`** — runs the configs in [`examples/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples) every night to catch regressions in the shipped examples.
|
||||
|
||||
### Running Tests Locally
|
||||
|
||||
```bash
|
||||
uv run pytest -v # everything
|
||||
uv run pytest tests/unit -v # unit only
|
||||
uv run pytest tests/integration -v # integration only
|
||||
uv run pytest -v -m "not gpu" # CPU-only subset (mirrors CPU CI)
|
||||
uv run pytest -v -m gpu # GPU-only subset
|
||||
uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenario
|
||||
```
|
||||
|
||||
### CI Workflows
|
||||
|
||||
| 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_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.
|
||||
|
||||
### Markers
|
||||
|
||||
Two pytest markers are declared in `pyproject.toml` (`addopts = "--strict-markers"`):
|
||||
|
||||
- `gpu` — gate a test that needs CUDA. CPU CI uses `-m "not gpu"`; the GPU unit job uses `-m gpu`.
|
||||
- `slow` — gate a test that's expensive enough you'd usually skip it locally. Deselect with `-m "not slow"`.
|
||||
|
||||
## Pre-Commit Hooks
|
||||
|
||||
Install the [pre-commit](https://pre-commit.com) hooks before your first commit so ruff check + format run on staged Python files automatically:
|
||||
|
||||
```bash
|
||||
uv run pre-commit install
|
||||
```
|
||||
|
||||
## Adding a New Model
|
||||
|
||||
Bringing up a new model family is three steps: implement the modeling code, register a mini preset, and run the smoke test. The preset and smoke test let you iterate on the modeling code at ~0.5B scale on 1–2 GPUs instead of paying the cost of the full-size model — useful for catching bugs in modeling code, state-dict conversions, and pipeline integration before scaling.
|
||||
|
||||
### Implement the Modeling Code
|
||||
|
||||
Drop the modeling code under `src/prime_rl/trainer/models/<arch>/` (HF-compatible config, modeling, and weight conversion). Mirror the layout of an existing family — `glm4_moe/` or `qwen3_moe/` are good starting points.
|
||||
|
||||
### Register a Mini Preset
|
||||
|
||||
Add an entry to [`scripts/mini_moe.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/scripts/mini_moe.py) so the smoke-test workflow can build a ~0.5B test model in your architecture. The preset names the config class, picks small dimensions, and wires up the HF + PrimeRL model classes plus a tokenizer source:
|
||||
|
||||
```python
|
||||
ARCH_PRESETS = {
|
||||
"glm4_moe": {
|
||||
"config_class": Glm4MoeConfig,
|
||||
"config_kwargs": dict(hidden_size=1024, num_hidden_layers=24, n_routed_experts=8, ...),
|
||||
"hf_model_class": HFGlm4MoeForCausalLM,
|
||||
"prime_model_class": PrimeRLGlm4MoeForCausalLM,
|
||||
"tokenizer_source": "THUDM/GLM-4-9B-0414",
|
||||
},
|
||||
# add your arch here
|
||||
}
|
||||
```
|
||||
|
||||
### Run the Smoke Test
|
||||
|
||||
Build the mini model. This creates a ~543M-parameter GLM-4 MoE (1024 hidden, 24 layers, 8 experts) with random weights, copies the tokenizer from the original GLM-4 model, and verifies the HF↔PrimeRL roundtrip is lossless:
|
||||
|
||||
```bash
|
||||
uv run python scripts/mini_moe.py --arch glm4_moe --output-dir ./mini-glm-moe
|
||||
```
|
||||
|
||||
To re-verify the roundtrip after a modeling-code change without re-creating the model:
|
||||
|
||||
```bash
|
||||
uv run python scripts/mini_moe.py --arch glm4_moe --output-dir ./mini-glm-moe --verify-only
|
||||
```
|
||||
|
||||
Warm up the random-weight mini model with SFT on reverse-text so KL divergence becomes meaningful in the RL phase. Loss drops from ~12 to ~2.5 — the output won't be coherent, but the distribution is non-trivial. A pre-built SFT'd checkpoint lives at [samsja/mini-glm-moe](https://huggingface.co/samsja/mini-glm-moe) if you want to skip this step:
|
||||
|
||||
```bash
|
||||
uv run sft @ configs/debug/moe/sft/train.toml \
|
||||
--model.name ./mini-glm-moe \
|
||||
--data.name PrimeIntellect/Reverse-Text-SFT \
|
||||
--data.type null \
|
||||
--max_steps 200 \
|
||||
--optim.lr 1e-4 \
|
||||
--ckpt.weights
|
||||
```
|
||||
|
||||
Then run the full RL stack on reverse-text:
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/ci/integration/reverse_text_moe/start.toml \
|
||||
--model.name samsja/mini-glm-moe \
|
||||
--trainer.model.impl custom \
|
||||
--inference.gpu-memory-utilization 0.7 \
|
||||
--inference.model.max-model-len 2048
|
||||
```
|
||||
|
||||
What to look for:
|
||||
|
||||
- **No crashes.** Validates the full inference + orchestrator + trainer pipeline end-to-end.
|
||||
- **Finite, non-zero KL.** Confirms the reference distribution is meaningful.
|
||||
- **Loss reasonable.** Not NaN, not stuck.
|
||||
|
||||
Don't expect reward to climb meaningfully in 20 steps on a random model.
|
||||
|
||||
### Requirements for merging a new model
|
||||
|
||||
Before merging a new model, you need to ensure the following:
|
||||
|
||||
- The model is correctly registered and defines and all the required methods - such as `convert_hf_layer_to_tt` and `convert_tt_layer_to_hf`.
|
||||
- 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.
|
||||
@@ -1,91 +0,0 @@
|
||||
# Disaggregated Prefill/Decode Inference
|
||||
|
||||
Run MoE models with separate prefill and decode node groups for higher throughput.
|
||||
|
||||
## Quick Start
|
||||
|
||||
See [`configs/glm5_disagg_inference/inference.toml`](../configs/glm5_disagg_inference/inference.toml) for an example config.
|
||||
|
||||
```bash
|
||||
uv run inference @ configs/glm5_disagg_inference/inference.toml --output-dir /data/$USER/outputs
|
||||
```
|
||||
|
||||
## Prefill/Decode Ratio
|
||||
|
||||
| Workload | Recommended ratio (P:D) | Why |
|
||||
|---|---|---|
|
||||
| Agentic (SWE, Lean) | **3:1** | Long growing contexts → prefill-heavy |
|
||||
| Non-agentic (math, chat) | **1:2** | Short prompts, long generations → decode-heavy |
|
||||
|
||||
Monitor live queue depths:
|
||||
```bash
|
||||
curl -s http://<prefill_node>:8100/metrics | grep num_requests_waiting
|
||||
curl -s http://<decode_node>:8200/metrics | grep num_requests_waiting
|
||||
```
|
||||
|
||||
If prefill has queued requests and decode has zero, add more prefill nodes (and vice versa).
|
||||
|
||||
For historical averages (cumulative over the entire run), query the histogram metrics:
|
||||
```bash
|
||||
# Average queue time per request (seconds)
|
||||
curl -s http://<node>:<port>/metrics | awk '
|
||||
/request_queue_time_seconds_sum\{/ { sum += $2 }
|
||||
/request_queue_time_seconds_count\{/ { count += $2 }
|
||||
END { if (count > 0) printf "avg queue: %.2fs (%d requests)\n", sum/count, count }
|
||||
'
|
||||
|
||||
# Average prefill/decode compute time
|
||||
curl -s http://<node>:<port>/metrics | awk '
|
||||
/request_prefill_time_seconds_sum\{/ { ps += $2 }
|
||||
/request_prefill_time_seconds_count\{/ { pc += $2 }
|
||||
/request_decode_time_seconds_sum\{/ { ds += $2 }
|
||||
/request_decode_time_seconds_count\{/ { dc += $2 }
|
||||
END {
|
||||
if (pc > 0) printf "avg prefill: %.2fs\n", ps/pc
|
||||
if (dc > 0) printf "avg decode: %.2fs\n", ds/dc
|
||||
}
|
||||
'
|
||||
```
|
||||
|
||||
Other useful metrics on the `/metrics` endpoint:
|
||||
- `vllm:e2e_request_latency_seconds` — end-to-end latency
|
||||
- `vllm:kv_cache_usage_perc` — KV cache memory pressure
|
||||
- `vllm:nixl_xfer_time_seconds` — NIXL KV transfer duration
|
||||
- `vllm:nixl_bytes_transferred` — bytes per KV transfer
|
||||
|
||||
## UCX 1.19
|
||||
|
||||
NVSHMEM requires UCX >= 1.19 for multi-GPU CUDA support. Most clusters ship UCX 1.17 (via HPC-X), which causes `cuStreamCreate: invalid device context` errors during DeepEP internode dispatch.
|
||||
|
||||
**Check your version:**
|
||||
```bash
|
||||
/opt/hpcx/ucx/bin/ucx_info -v | head -1
|
||||
# If < 1.19, you need to build from source
|
||||
```
|
||||
|
||||
**Build UCX 1.19 (run once on a GPU node):**
|
||||
```bash
|
||||
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
|
||||
```
|
||||
|
||||
This installs UCX 1.19 to `prime-rl/third_party/ucx/`. The sbatch template automatically adds it to `LD_LIBRARY_PATH`, overriding the system version.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### `DeepEP error: timeout (dispatch CPU)`
|
||||
NVSHMEM internode communication failing. Check:
|
||||
1. UCX version >= 1.19? (`third_party/ucx/bin/ucx_info -v`)
|
||||
2. NVSHMEM libs reachable at `/tmp/deepep_build/nvshmem/lib/`? If not:
|
||||
```bash
|
||||
ssh <node> 'mkdir -p /tmp/deepep_build/nvshmem && \
|
||||
ln -sfn <venv>/lib/python3.12/site-packages/nvidia/nvshmem/lib \
|
||||
/tmp/deepep_build/nvshmem/lib'
|
||||
```
|
||||
3. IBGDA driver enabled? `ssh <node> 'cat /proc/driver/nvidia/params | grep EnableStreamMemOPs'` should show `1`.
|
||||
|
||||
### Router healthy but requests hang
|
||||
NIXL side channel not running on prefill. Check:
|
||||
```bash
|
||||
ssh <prefill_node> 'ss -tlnp sport ge :5600 sport le :5608 | grep -c LISTEN'
|
||||
# Should show 8 (one per DP rank). If 0, check logs for UCX/NVSHMEM errors.
|
||||
```
|
||||
@@ -1,67 +0,0 @@
|
||||
# Entrypoints
|
||||
|
||||
## RL
|
||||
|
||||
The main usecase of PRIME-RL is RL training. Three main abstractions facilitate RL training: the **orchestrator**, the **trainer**, and the **inference** service.
|
||||
|
||||

|
||||
|
||||
### Orchestrator
|
||||
|
||||
The orchestrator is a lightweight CPU process that handles the core data and scheduling logic, serving as an intermediary between the trainer and inference service with bidirectional relays. In one direction, it collects rollouts from the inference server, assembles them into packed batches, and dispatches them to the trainer; in the other direction, it relays updated model weights from the trainer to the inference service. The orchestrator utilizes `verifiers` environments to abstract multi-turn rollout generation and scoring. Each training and evaluation environment is exposed as a `vf.EnvServer` as a sidecar to the orchestrator process (default) or as a standalone process (e.g. used in hosted training to run environments in containers).
|
||||
|
||||
### Trainer
|
||||
|
||||
The trainer is responsible for producing an updated policy model given rollouts and advantages. We use FSDP2 as the backend with compatibility for any HuggingFace (HF) model. For some models we also provide custom implementations, mostly for performance reasons. FSDP shards model parameters, gradients, and optimizer states, allowing training large models with data parallelism and minimal GPU memory footprint. We support a variety of popular training objectives, such as GRPO, GSPO, OPO, RLOO and [CISPO](https://arxiv.org/abs/2506.13585). The trainer is inspired by [`torchtitan`](https://github.com/pytorch/torchtitan) and relies on native PyTorch features to implement advanced parallelism techniques, such as tensor, context or expert parallelism.
|
||||
|
||||
### Inference
|
||||
|
||||
The inference service in its simplest form is a standard OpenAI-compatible server with a vLLM backend. The API specification is extended with a custom `update_weights` endpoint to reload model weights from a HF-compatible checkpoint on disk. Otherwise, we rely on vLLM's optimized kernels, parallelism strategies, and scheduling for fast rollout generation. Given the disaggregated nature of the service architecture, it can be directly extended to include multiple engines with a shared request pool, allowing operation across multiple clusters and straightforward integration of alternative inference engines (e.g. SGLang, Tokasaurus). We also heavily rely on native data parallelism in vLLM (also available in SGLang) for orchestrating the fleet of nodes dedicated to inference.
|
||||
|
||||
### RL
|
||||
|
||||
For doing RL training all components need to be started. One can do this manually:
|
||||
|
||||
```bash
|
||||
uv run inference ...
|
||||
```
|
||||
|
||||
```bash
|
||||
uv run orchestrator ...
|
||||
```
|
||||
|
||||
```bash
|
||||
uv run trainer ...
|
||||
```
|
||||
|
||||
Or, alternatively on a single node, use the `rl` entrypoint to start all components.
|
||||
|
||||
```bash
|
||||
uv run rl \
|
||||
--trainer @ path/to/train.toml \
|
||||
--orchestrator @ path/to/orch.toml \
|
||||
--inference @ path/to/infer.toml \
|
||||
...
|
||||
```
|
||||
|
||||
For more details on multi-node deployment options, see the [deployment](deployment.md) documentation and see the [examples](examples) for concrete training configurations. To see all available configuration options, run `uv run rl --help`.
|
||||
|
||||
## SFT
|
||||
|
||||
We provide a fairly straight-forward SFT trainer which is capable of fine-tuning any conversational model on multi-turn conversation with tool calling. It shares a lot of components with the RL trainer, such as the modeling code, parallelism techniques, checkpoint format, logger, etc. which ensures a seamless post-training workflow.
|
||||
|
||||
To start an SFT training, you need to prepare a conversational dataset in either [prompt-completion format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion) or raw `messages` format. If `messages` is provided, the trainer interprets the full conversation as a single sample with an empty prompt and applies role-based loss masking across the whole chat. If both `messages` and `prompt` / `completion` are present, `messages` takes precedence. Single-turn fine-tuning should be compatible with the chat templates of most models. However, to properly handle loss masking, we require that the tokenizer's chat template satisfies a prefix property: the tokenization of any conversation prefix must be a prefix of the tokenization of the full conversation. For instance, tokenizing message 1 should yield a token sequence that forms a prefix of tokenizing messages 1 and 2, which in turn should be a prefix of tokenizing messages 1, 2, 3, and so forth. An example of a chat template that *does not* satisfy this property is Qwen3's chat template, as it strips away past think sections.
|
||||
|
||||
On a single GPU, start the training with the `sft` entrypoint
|
||||
|
||||
```bash
|
||||
uv run sft ...
|
||||
```
|
||||
|
||||
If you have access to multiple GPUs, use [`torchrun`](https://docs.pytorch.org/docs/stable/elastic/run.html) with `--nproc-per-node` to start the training.
|
||||
|
||||
```bash
|
||||
uv run torchrun --nproc-per-node 8 src/prime_rl/trainer/sft/train.py ...
|
||||
```
|
||||
|
||||
For more details on multi-node deployment options, see the [deployment](deployment.md) documentation and see the [examples](examples) for concrete training configurations. To see all available configuration options, run `uv run sft --help`.
|
||||
@@ -1,32 +0,0 @@
|
||||
# Environments
|
||||
|
||||
PRIME-RL can train and evaluate in any [`verifiers`](https://github.com/willccbb/verifiers) environments. To train in a new environment, simply install it from the [Environment Hub](https://app.primeintellect.ai/dashboard/environments) or install a local environment.
|
||||
|
||||
## Installation
|
||||
|
||||
You can explore the installation options using
|
||||
|
||||
```bash
|
||||
prime env info <owner>/<name>
|
||||
```
|
||||
|
||||
To install an environment temporarily
|
||||
|
||||
```bash
|
||||
prime env install <owner>/<name>
|
||||
# Or: uv pip install <name> --extra-index-url https://hub.primeintellect.ai/<owner>/simple/
|
||||
```
|
||||
|
||||
To install a local environment
|
||||
|
||||
```bash
|
||||
uv pip install -e path/to/env
|
||||
```
|
||||
|
||||
To verify your installation
|
||||
|
||||
```bash
|
||||
uv run python -c "import <name>"
|
||||
```
|
||||
|
||||
For more details on environments, see our Environments Hub documentation [here](https://docs.primeintellect.ai/tutorials-environments/environments).
|
||||
@@ -1,16 +0,0 @@
|
||||
# Docs
|
||||
|
||||
This directory maintains the documentation for PRIME-RL. It is organized into the following sections:
|
||||
|
||||
- [**Entrypoints**](entrypoints.md) - Overview of the main components (orchestrator, trainer, inference) and how to run SFT, RL, and evals
|
||||
- [**Configs**](configs.md) - Configuration system using TOML files, CLI arguments, and environment variables
|
||||
- [**Environments**](environments.md) - Installing and using verifiers environments from the Environments Hub
|
||||
- [**Async Training**](async.md) - Understanding asynchronous off-policy training and step semantics
|
||||
- [**Logging**](logging.md) - Logging with loguru, torchrun, and Weights & Biases
|
||||
- [**Platform Monitoring**](platform-monitoring.md) - Register runs on the Prime Intellect platform and stream training metrics
|
||||
- [**MultiRunManager**](multi_run_manager.md) - Multi-run training with the MultiRunManager object for concurrent LoRA adapters
|
||||
- [**Checkpointing**](checkpointing.md) - Saving and resuming training from checkpoints
|
||||
- [**Benchmarking**](benchmarking.md) - Performance benchmarking and throughput measurement
|
||||
- [**Deployment**](deployment.md) - Training deployment on single-GPU, multi-GPU, and multi-node clusters
|
||||
- [**Kubernetes**](kubernetes.md) - Deploying PRIME-RL on Kubernetes with Helm
|
||||
- [**Troubleshooting**](troubleshooting.md) - Common issues and their solutions
|
||||
@@ -0,0 +1,269 @@
|
||||
# Inference
|
||||
|
||||
This page covers the inference configuration and the supported features/deployment shapes. It covers how to scale the inference server from a single GPU to 1000s of GPUs that run agentic workloads at the speed of light with all the bells and whistles configured.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Single-Node](#single-node)
|
||||
- [Multi-Node](#multi-node)
|
||||
- [Multi-replica](#multi-replica)
|
||||
- [Wide-EP](#wide-ep)
|
||||
- [P/D Dissagregation](#pd-dissagregation)
|
||||
- [Router](#router)
|
||||
- [Routing policies](#routing-policies)
|
||||
- [Advanced Configuration](#advanced-configuration)
|
||||
- [KV Cache Offload](#kv-cache-offload)
|
||||
- [Optimized P/D disaggregation deployment](#optimized-pd-disaggregation-deployment)
|
||||
- [Other vLLM features](#other-vllm-features)
|
||||
- [Router Replay](#router-replay)
|
||||
|
||||
|
||||
## Overview
|
||||
|
||||
`prime-rl` chooses to use `vLLM` as the inference engine. We aim to stay up-to-date with the latest vLLM features, being at-most 1 version behind the latest stable release. This allows us to use the latest features from vLLM as soon as they are released - such as router replay, CPU KV cache offload, and more.
|
||||
|
||||
We support 3 distinct deployment shapes:
|
||||
- [Single-Node](#single-node) - Runs the inference server on a single node. Useful for debugging, small scale experiments or smaller models. The default deployment shape.
|
||||
- [Multi-Node](#multi-node) - Runs the inference server on multiple nodes. Useful for large scale experiments or larger models, where latency is not a concern - i.e. single turn inference, long context inference, etc.
|
||||
- [Disaggregated](#disaggregated) - Runs the inference server on multiple nodes, but disaggregates the prefill and decode stages. Useful for large scale experiments or larger models, where latency is a concern and multi-node deployment creates very high E2E rollout latency, such as agentic workflows.
|
||||
|
||||
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
|
||||
|
||||
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`, `router_port`, `backend_port`, etc.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
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]
|
||||
model = "PrimeIntellect/INTELLECT-3"
|
||||
...
|
||||
```
|
||||
|
||||
We will now walk through the supported features and deployment shapes in detail, starting with the single-node deployment.
|
||||
|
||||
## Single-Node
|
||||
|
||||
The single-node deployment is the default deployment shape. It runs the inference server on a single node. It is useful for debugging, small scale experiments or smaller models. You can configure the single-node deployment with the `SingleNodeInferenceDeploymentConfig` config-field.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "single_node"
|
||||
```
|
||||
|
||||
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]
|
||||
enable_expert_parallel = true # defaults to False
|
||||
|
||||
[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 `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.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.
|
||||
|
||||
|
||||
## Multi-Node
|
||||
|
||||
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.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
|
||||
|
||||
This deployment shape runs the inference server on multiple nodes, but each node runs an independent vLLM replica.
|
||||
Parallelism configuration is the same as the single-node deployment. The shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.deployment.num_nodes` to the number of nodes you want to run the inference server on.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
|
||||
[inference]
|
||||
model = "PrimeIntellect/INTELLECT-3"
|
||||
|
||||
[inference.parallel]
|
||||
tp = 2
|
||||
dp = 4
|
||||
```
|
||||
|
||||
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing will be handled by the `vllm-router` instance running on the same node as the 1st replica. We aim to support more advanced routing options, such as `llm-d` or `dynamo` in the future. 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.enable_expert_parallel = true`.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
|
||||
[inference]
|
||||
model = "PrimeIntellect/INTELLECT-3"
|
||||
enable_expert_parallel = true
|
||||
|
||||
[inference.parallel]
|
||||
tp = 2
|
||||
dp = 8
|
||||
```
|
||||
|
||||
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 Dissagregation
|
||||
|
||||
This is the most advanced deployment shape. It allows you to disaggregate the prefill and decode stages, with KV cache flowing between them. This is useful for large scale deployments, where there are high requirements on latency, such as agentic workflows spanning 100s of turns.
|
||||
|
||||
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and `inference.deployment.num_prefill_nodes` and `inference.deployment.num_decode_nodes` to the number of nodes you want to run the prefill and decode stages on.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 2
|
||||
num_decode_nodes = 2
|
||||
```
|
||||
|
||||
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode node groups. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of replicas you want to run.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 2
|
||||
num_decode_nodes = 2
|
||||
|
||||
num_prefill_replicas = 2
|
||||
num_decode_replicas = 1
|
||||
```
|
||||
|
||||
Now the total deployment will span 6 nodes - 2x2 for prefill and 1x2 for decode. 2 prefill replicas will run on 2 nodes each - total of 4 nodes for prefill. 1 decode replica will run on 2 nodes for decode.
|
||||
|
||||
We also allow you to configure the total amount of inference replicas - this is useful if you'd like to multiply the above configuration by a factor of `k`, each running behind a separate `vllm-router` instance.
|
||||
|
||||
```toml
|
||||
[deployment] # this is a top-level RL deployment, not inference.deployment!!
|
||||
type = "multi_node"
|
||||
num_train_nodes = 4
|
||||
num_infer_nodes = 6 # this is per-replica
|
||||
|
||||
num_infer_replicas = 3
|
||||
```
|
||||
|
||||
This will run 3 inference replicas, each running on 6 nodes. Each replica will run on 2x2 nodes for prefill and 1x2 nodes for decode. The total deployment will span 18 nodes. This will also spin-up 3 separate `vllm-router` instances.
|
||||
|
||||
|
||||
## Router
|
||||
|
||||
We use our own fork of [vllm-router](https://github.com/PrimeIntellect-ai/router) as the request handler. We plan to support more advanced proxy options in the future.
|
||||
|
||||
Right now, router handles 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 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.student.client.extra_headers_from_state` to the header the `router` expects to be set.
|
||||
|
||||
We set it to a sensible default, that works with all verifiers environments.
|
||||
|
||||
```toml
|
||||
[orchestrator.student.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.
|
||||
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### KV Cache Offload
|
||||
|
||||
Maximizing KV-Cache space is crucial to support high-concurrency workloads. You can offload the KV cache to CPU memory (and, behind it, disk) by setting `inference.kv_cache_offload`. It is a discriminated config with two composable tiers, `cpu` and `disk`: a `cpu` tier is always required, and an optional `disk` tier is layered behind it (GPU → DRAM → disk). Disk-only is not supported.
|
||||
|
||||
The `type` field selects the backend:
|
||||
|
||||
- `native` — vLLM's built-in offloading. CPU-only uses `OffloadingConnector`; CPU+disk uses `TieringOffloadingSpec` (a CPU primary tier with a filesystem secondary tier). Fully self-contained — no extra processes.
|
||||
- `mooncake` — a [Mooncake](https://github.com/kvcache-ai/Mooncake) **shared distributed store** (SLURM only). One `mooncake_master` + metadata server runs on the head inference node; every inference node runs a `mooncake_client` that contributes its DRAM (and, with `disk`, SSD) segment to that *single* pool. Because blocks are keyed by model + parallel rank + content hash (no instance id), a prefix cached by one node/replica is reusable by all of them over RDMA — pooling every node's CPU RAM into one KV cache. Use `native` for local/single-process runs.
|
||||
|
||||
```toml
|
||||
# Native CPU offload (reserves 128GB of CPU KV cache for this instance)
|
||||
[inference.kv_cache_offload]
|
||||
type = "native"
|
||||
[inference.kv_cache_offload.cpu]
|
||||
num_bytes = 128_000_000_000 # 128GB
|
||||
|
||||
# Native CPU + disk tiering (self-contained)
|
||||
[inference.kv_cache_offload]
|
||||
type = "native"
|
||||
[inference.kv_cache_offload.cpu]
|
||||
num_bytes = 128_000_000_000
|
||||
[inference.kv_cache_offload.disk]
|
||||
path = "/scratch/kv" # disk capacity is bounded by the filesystem
|
||||
|
||||
# Mooncake CPU + disk (per-node distributed store, RDMA)
|
||||
[inference.kv_cache_offload]
|
||||
type = "mooncake"
|
||||
[inference.kv_cache_offload.cpu]
|
||||
num_bytes = 128_000_000_000
|
||||
[inference.kv_cache_offload.disk]
|
||||
path = "/scratch/kv"
|
||||
```
|
||||
|
||||
For `native`, `cpu.num_bytes` is the aggregate CPU KV pool for the instance (vLLM shards it across workers). For `mooncake`, `cpu.num_bytes` is the DRAM each node contributes to the shared pool (so the total pool ≈ `num_bytes × #inference-nodes`); the store uses RDMA, so it requires an RDMA-capable fabric. Enabling offload automatically enables prefix caching.
|
||||
|
||||
|
||||
### Optimized P/D disaggregation deployment
|
||||
|
||||
For optimal P/D disaggregation deployment, we automatically set the decode `all2all_backend` to `deepep_low_latency` and the prefill `all2all_backend` to `deepep_high_throughput`. We currently don't support customizing all2all backends for P/D disaggragation out of the box. You can do this by overriding the slurm template only.
|
||||
|
||||
For KV cache transfer, we utilize the NIXL connector. This is the default and only currently supported connector. We aim to support more advanced options, such as D->P transfer, or Mooncake Connector in the future.
|
||||
|
||||
For configuring various knobs with environment variables, we enable you to configure prefill and decode environment variables separately. This is useful if you want to configure different environment variables for the prefill and decode stages.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
|
||||
prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
|
||||
decode_env_overrides = {"VLLM_DEEP_GEMM_WARMUP"="skip"}
|
||||
```
|
||||
|
||||
### Other vLLM features
|
||||
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_extra]
|
||||
headless = true
|
||||
```
|
||||
|
||||
### 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.enable_return_routed_experts = true`.
|
||||
|
||||
```toml
|
||||
[trainer]
|
||||
enable_router_replay = true # this will also auto-set the inference.enable_return_routed_experts = true
|
||||
|
||||
[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 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.
|
||||
@@ -1,308 +0,0 @@
|
||||
# Kubernetes
|
||||
|
||||
This guide covers deploying PRIME-RL training infrastructure on Kubernetes clusters using the provided Helm chart.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Kubernetes cluster with GPU nodes
|
||||
- [NVIDIA GPU Operator](https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/getting-started.html) installed
|
||||
- [Helm 3.x](https://helm.sh/docs/intro/install/) installed
|
||||
- Storage class that supports `ReadWriteMany` (e.g., NFS, CephFS, or cloud provider storage)
|
||||
|
||||
### Verify Prerequisites
|
||||
|
||||
```bash
|
||||
# Check Helm installation
|
||||
helm version
|
||||
|
||||
# Check GPU operator
|
||||
kubectl get pods -n gpu-operator
|
||||
|
||||
# Check available storage classes
|
||||
kubectl get storageclass
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Deploy
|
||||
|
||||
```bash
|
||||
# Deploy with a release name
|
||||
helm install my-exp ./k8s/prime-rl -f ./k8s/prime-rl/examples/reverse-text.yaml
|
||||
|
||||
# Or with defaults (no example-specific config)
|
||||
helm install my-exp ./k8s/prime-rl --set trainer.replicas=3 --set inference.replicas=2
|
||||
```
|
||||
|
||||
### 2. Verify deployment
|
||||
|
||||
```bash
|
||||
# Check pod status
|
||||
kubectl get pods -l app.kubernetes.io/instance=my-exp
|
||||
|
||||
# Should show 3 pods:
|
||||
# my-exp-orchestrator-0
|
||||
# my-exp-inference-0
|
||||
# my-exp-trainer-0
|
||||
```
|
||||
|
||||
### 3. Run training
|
||||
|
||||
```bash
|
||||
# Exec into trainer
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
|
||||
# Inside the pod, run training
|
||||
cd /data
|
||||
uv run trainer @ /app/examples/reverse_text/configs/train.toml
|
||||
```
|
||||
|
||||
### 4. Monitor progress
|
||||
|
||||
```bash
|
||||
# Get logs
|
||||
kubectl logs my-exp-trainer-0
|
||||
|
||||
# Follow logs in real-time
|
||||
kubectl logs -f my-exp-trainer-0
|
||||
```
|
||||
|
||||
## Available Examples
|
||||
|
||||
The chart includes pre-configured values for each example:
|
||||
|
||||
### reverse-text (Small - 1 GPU)
|
||||
|
||||
```bash
|
||||
helm install my-exp ./k8s/prime-rl -f ./k8s/prime-rl/examples/reverse-text.yaml
|
||||
```
|
||||
|
||||
- Model: Qwen3-0.6B
|
||||
- GPUs: 1 per component
|
||||
- Runs on consumer GPUs (RTX 3090/4090)
|
||||
- **Note:** You can use any release name - the chart automatically configures service URLs
|
||||
|
||||
## Configuration
|
||||
|
||||
### Storage Configuration
|
||||
|
||||
By default, the chart creates a 1TB PVC with NFS storage. To customize:
|
||||
|
||||
```yaml
|
||||
# custom-values.yaml
|
||||
storage:
|
||||
storageClassName: my-storage-class
|
||||
size: 500Gi
|
||||
```
|
||||
|
||||
Deploy with custom storage:
|
||||
|
||||
```bash
|
||||
helm install my-release ./k8s/prime-rl -f custom-values.yaml
|
||||
```
|
||||
|
||||
### GPU Configuration
|
||||
|
||||
Adjust GPU count per component:
|
||||
|
||||
```yaml
|
||||
# custom-gpu.yaml
|
||||
inference:
|
||||
gpu:
|
||||
count: 4 # Use 4 GPUs for inference
|
||||
|
||||
trainer:
|
||||
gpu:
|
||||
count: 2 # Use 2 GPUs for training
|
||||
```
|
||||
|
||||
### Resource Limits
|
||||
|
||||
Customize memory and CPU:
|
||||
|
||||
```yaml
|
||||
# custom-resources.yaml
|
||||
trainer:
|
||||
resources:
|
||||
requests:
|
||||
memory: "64Gi"
|
||||
cpu: "16"
|
||||
limits:
|
||||
memory: "128Gi"
|
||||
cpu: "32"
|
||||
```
|
||||
|
||||
### Secrets (Optional)
|
||||
|
||||
For W&B and HuggingFace authentication:
|
||||
|
||||
```bash
|
||||
# Create secret
|
||||
kubectl create secret generic prime-rl-secrets \
|
||||
--from-literal=wandb-api-key=YOUR_WANDB_KEY \
|
||||
--from-literal=hf-token=YOUR_HF_TOKEN
|
||||
|
||||
# Enable in values
|
||||
helm install my-release ./k8s/prime-rl \
|
||||
--set config.secrets.enabled=true \
|
||||
--set config.secrets.name=prime-rl-secrets
|
||||
```
|
||||
|
||||
## Common Operations
|
||||
|
||||
### Deploy a new experiment
|
||||
|
||||
```bash
|
||||
# With example config
|
||||
helm install my-exp ./k8s/prime-rl -f ./k8s/prime-rl/examples/reverse-text.yaml
|
||||
|
||||
# With custom settings
|
||||
helm install my-exp ./k8s/prime-rl --set trainer.replicas=10 --set inference.replicas=5
|
||||
```
|
||||
|
||||
### Exec into pods
|
||||
|
||||
```bash
|
||||
# Exec into trainer-0
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
|
||||
# Exec into specific trainer pod
|
||||
kubectl exec -it my-exp-trainer-3 -- bash
|
||||
|
||||
# Exec into inference
|
||||
kubectl exec -it my-exp-inference-0 -- bash
|
||||
```
|
||||
|
||||
### View logs
|
||||
|
||||
```bash
|
||||
# Get logs from trainer-0
|
||||
kubectl logs my-exp-trainer-0
|
||||
|
||||
# Follow logs in real-time
|
||||
kubectl logs -f my-exp-trainer-2
|
||||
|
||||
# Get logs from all trainers
|
||||
kubectl logs -l app.kubernetes.io/instance=my-exp,role=trainer
|
||||
```
|
||||
|
||||
### List all pods
|
||||
|
||||
```bash
|
||||
# List pods for specific experiment
|
||||
kubectl get pods -l app.kubernetes.io/instance=my-exp
|
||||
|
||||
# List all prime-rl pods
|
||||
kubectl get pods -l app=prime-rl
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Components
|
||||
|
||||
The chart deploys three main components (all using StatefulSets):
|
||||
|
||||
1. **Orchestrator** (StatefulSet) - Coordinates training workflow
|
||||
- Always 1 replica: `prime-rl-orchestrator-0`
|
||||
- No GPU required
|
||||
- Communicates with trainer and inference
|
||||
|
||||
2. **Inference** (StatefulSet) - Runs vLLM inference server
|
||||
- Scalable replicas with stable pod names: `prime-rl-inference-0`, `prime-rl-inference-1`, ...
|
||||
- Each pod gets predictable DNS: `prime-rl-inference-0.prime-rl-inference-headless.default.svc.cluster.local`
|
||||
- Requires GPU(s)
|
||||
- Serves model predictions
|
||||
|
||||
3. **Trainer** (StatefulSet) - Runs SFT or RL training
|
||||
- Scalable replicas with stable pod names: `prime-rl-trainer-0`, `prime-rl-trainer-1`, ...
|
||||
- Each pod gets predictable DNS: `prime-rl-trainer-0.prime-rl-trainer-headless.default.svc.cluster.local`
|
||||
- Requires GPU(s)
|
||||
- Updates model weights on shared storage
|
||||
|
||||
**Why StatefulSets for all components?**
|
||||
|
||||
- **Consistent naming**: All pods have predictable names (`orchestrator-0`, `trainer-0`, `trainer-1`, ...)
|
||||
- **Stable networking**: Each pod gets its own DNS hostname via headless service
|
||||
- **Required for distributed training**: PyTorch/vLLM need to discover peers by stable hostname
|
||||
- **Clean naming**: No random pod suffixes, easier to identify and debug
|
||||
|
||||
### Shared Storage
|
||||
|
||||
All components mount the same PVC at `/data` for:
|
||||
|
||||
- Model checkpoint sharing
|
||||
- Training data
|
||||
- Experiment outputs
|
||||
|
||||
This is **required** for coordinating weight updates between trainer and inference.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Each pod has these K8s environment variables set:
|
||||
|
||||
- `$POD_NAME` - Full pod name (e.g., `my-exp-trainer-3`)
|
||||
- `$POD_IP` - Pod IP address
|
||||
- `$STATEFUL_REPLICAS` - Total number of replicas for that component
|
||||
- `$HEADLESS_SERVICE` - DNS name for peer discovery (e.g., `my-exp-trainer-headless.default.svc.cluster.local`)
|
||||
- `$INFERENCE_URL` - Full URL to the first inference pod (available in orchestrator and trainer pods)
|
||||
|
||||
For distributed training, extract the rank from the pod name:
|
||||
|
||||
```bash
|
||||
# Extract ordinal from pod name
|
||||
RANK=$(echo $POD_NAME | grep -o '[0-9]*$') # e.g., "my-exp-trainer-3" -> "3"
|
||||
|
||||
# Use in torchrun
|
||||
torchrun \
|
||||
--nnodes=$STATEFUL_REPLICAS \
|
||||
--node-rank=$RANK \
|
||||
--nproc-per-node=8 \
|
||||
--rdzv-endpoint=my-exp-trainer-0.$HEADLESS_SERVICE:29501 \
|
||||
src/prime_rl/trainer/sft/train.py @ configs/train.toml
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Can't access shared storage
|
||||
|
||||
Verify PVC is bound:
|
||||
|
||||
```bash
|
||||
kubectl get pvc prime-rl-shared-data
|
||||
# STATUS should be "Bound"
|
||||
```
|
||||
|
||||
Check mount inside pod:
|
||||
|
||||
```bash
|
||||
kubectl exec -it prime-rl-trainer-xxx -- df -h /data
|
||||
```
|
||||
|
||||
### Pod stuck in Pending
|
||||
|
||||
Check if GPU resources are available:
|
||||
|
||||
```bash
|
||||
kubectl describe pod my-exp-trainer-0
|
||||
```
|
||||
|
||||
Look for events like `Insufficient nvidia.com/gpu`.
|
||||
|
||||
### Inference server not responding
|
||||
|
||||
Check if the inference pod is ready:
|
||||
|
||||
```bash
|
||||
kubectl get pods -l role=inference
|
||||
kubectl logs my-exp-inference-0
|
||||
```
|
||||
|
||||
## Uninstalling
|
||||
|
||||
```bash
|
||||
# Remove the Helm release
|
||||
helm uninstall my-exp
|
||||
|
||||
# Delete PVC (data will be lost!)
|
||||
kubectl delete pvc prime-rl-shared-data
|
||||
```
|
||||
@@ -1,86 +0,0 @@
|
||||
# Logging
|
||||
|
||||
prime-rl uses [loguru](https://loguru.readthedocs.io/en/stable/) for logging with a global logger pattern. All logs are captured at the deployment level (stdout/stderr redirection for local, `tee` for SLURM) under `{output_dir}/logs/`. For RL training, we recommend streaming logs into tmux panes (as set up by `tmux.sh`).
|
||||
|
||||
## Logger Architecture
|
||||
|
||||
### `setup_logger` and `get_logger`
|
||||
|
||||
We use a **singleton pattern** with a module-level global logger instance (`_LOGGER`).
|
||||
|
||||
```python
|
||||
from prime_rl.utils.logger import setup_logger, get_logger
|
||||
|
||||
# At entrypoint - call ONCE
|
||||
logger = setup_logger("info")
|
||||
|
||||
# Anywhere else in codebase
|
||||
logger = get_logger()
|
||||
logger.info("Hello world")
|
||||
```
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **`get_logger()`** - Returns the global logger instance. Always works — if `setup_logger` hasn't been called yet, it initializes a default logger automatically. Safe to call from any module at any time.
|
||||
|
||||
2. **`setup_logger(log_level)`** - Configures (or reconfigures) the global logger:
|
||||
- Creates an isolated loguru `Logger` instance (not the default `loguru.logger`) to prevent third-party code from hijacking our logs
|
||||
- Adds a stdout handler with colorized output (or JSON output if `json_logging=True`)
|
||||
- Can be called multiple times — cleans up the previous logger before creating a new one
|
||||
|
||||
3. **`reset_logger()`** - Resets the global logger to `None`:
|
||||
- Used in subprocesses that inherit parent state (e.g., env workers)
|
||||
- Used in tests between test cases
|
||||
|
||||
## Log File Structure
|
||||
|
||||
Logs are captured at the deployment level — the entrypoint redirects subprocess stdout/stderr to files (local) or `tee` captures them (SLURM). The structure is consistent across deployment types: `logs/trainer.log` and `logs/inference.log` always exist, regardless of whether the run is local or multi-node SLURM.
|
||||
|
||||
### Local (single node)
|
||||
|
||||
```
|
||||
{output_dir}/logs/
|
||||
├── trainer.log # trainer stdout (rank 0 only)
|
||||
├── orchestrator.log # orchestrator stdout
|
||||
├── inference.log # vLLM inference server stdout
|
||||
├── trainer/
|
||||
│ └── torchrun/ # per-rank stdout/stderr (all ranks)
|
||||
└── envs/
|
||||
├── train/{env_name}/
|
||||
│ ├── env_server.log
|
||||
│ └── env_worker_{id}.log
|
||||
└── eval/{env_name}/
|
||||
└── ...
|
||||
```
|
||||
|
||||
### SLURM multi-node
|
||||
|
||||
```
|
||||
{output_dir}/logs/
|
||||
├── trainer.log -> trainer/node_0.log (symlink)
|
||||
├── inference.log -> inference/node_0.log (symlink)
|
||||
├── orchestrator.log # orchestrator stdout
|
||||
├── trainer/
|
||||
│ ├── node_0.log # per-node trainer output (rank 0 only)
|
||||
│ ├── node_1.log
|
||||
│ └── torchrun/ # per-rank stdout/stderr (all ranks)
|
||||
├── inference/
|
||||
│ ├── node_0.log # per-node inference output
|
||||
│ ├── node_1.log
|
||||
│ └── router_0.log # vllm-router per replica
|
||||
└── envs/
|
||||
└── ...
|
||||
```
|
||||
|
||||
Environment logs live under `logs/envs/train/{env_name}/` and `logs/envs/eval/{env_name}/`. Env log verbosity is controlled by `orchestrator.log.vf_level`.
|
||||
|
||||
Only rank 0 output is shown in `trainer.log`. Per-rank logs from all ranks are available under `logs/trainer/torchrun/{rdzv_id}/attempt_0/{rank}/{stdout,stderr}.log`, written by torchrun's `--log-dir`.
|
||||
|
||||
## tmux helper (`scripts/tmux.sh`)
|
||||
|
||||
`scripts/tmux.sh` sets up a tmux session for RL runs with **four panes**:
|
||||
|
||||
- **Trainer**: follows `{output_dir}/logs/trainer.log`
|
||||
- **Orchestrator**: follows `{output_dir}/logs/orchestrator.log`
|
||||
- **Envs**: follows `{output_dir}/logs/envs/*/*/*.log`
|
||||
- **Inference**: follows `{output_dir}/logs/inference.log`
|
||||
@@ -1,132 +0,0 @@
|
||||
# Reducing memory usage
|
||||
|
||||
While most of our parallelism techniques in prime-rl are designed to scale training up (FSDP, EP, CP, ...), we also provide many tools to scale training down that allow training large MoE models on a limited amount of GPUs.
|
||||
|
||||
These techniques target the trainer part of prime-rl.
|
||||
|
||||
|
||||
## TLDR: config to use for maximum memory usage reduction with correct throughput
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
ep = 8
|
||||
cp = 2
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
```
|
||||
|
||||
## Activation checkpointing
|
||||
|
||||
Activation checkpointing discards intermediate activations during the forward pass and recomputes them during the backward pass, trading compute for memory.
|
||||
|
||||
To enable it, use:
|
||||
|
||||
```toml
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
```
|
||||
|
||||
`freq` controls how often layers are checkpointed: every `freq` layers. Lower values yield lower memory usage (e.g. `freq = 1` checkpoints every layer).
|
||||
|
||||
## Activation offloading
|
||||
|
||||
Activation offloading offloads the activations to CPU to reduce the memory usage of the trainer. It can be used in combination with activation checkpointing.
|
||||
|
||||
To enable it, use:
|
||||
|
||||
```toml
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
```
|
||||
|
||||
## Chunk loss
|
||||
|
||||
Chunk loss splits the loss computation into smaller chunks to reduce the memory usage of the trainer.
|
||||
|
||||
To enable it, use:
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
fused_lm_head_token_chunk_size = auto
|
||||
```
|
||||
|
||||
|
||||
## Expert parallelism
|
||||
|
||||
While expert parallelism splits the weights of the experts across all GPUs like FSDP, using EP still reduces memory usage by reducing the communication size and therefore the FSDP buffer.
|
||||
|
||||
EP is only available for models with MoE layers using the custom model implementation.
|
||||
|
||||
```
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
ep = 8
|
||||
```
|
||||
|
||||
## Context parallelism
|
||||
|
||||
Context parallelism splits the context into smaller chunks to reduce the memory usage of the activations. We don't advise using CP across multiple nodes (i.e., increasing CP beyond 8).
|
||||
|
||||
CP is only available for certain models and only with the custom model implementation.
|
||||
|
||||
```
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
cp = 2
|
||||
```
|
||||
|
||||
We recommend CP 2 or CP 4 for most 128K sequence length training runs. Can be pushed to 8.
|
||||
|
||||
|
||||
## torch compile
|
||||
|
||||
Enabling torch.compile can reduce the memory usage for certain model architectures, especially MoE with the custom model implementation.
|
||||
|
||||
```
|
||||
[trainer.model.compile]
|
||||
```
|
||||
|
||||
## CPU Optimizer offloading
|
||||
|
||||
Offloading the optimizer states to CPU can reduce the memory usage of the trainer significantly, especially at low GPU counts where the optimizer states take a lot of memory as they won't be sharded enough.
|
||||
|
||||
In RL, in contrast with pretraining, we end up with many gradient accumulation steps, so the cost of offloading the optimizer states is not as high as in pretraining, and indeed barely noticeable.
|
||||
|
||||
```
|
||||
[trainer.optim]
|
||||
optim_cpu_offload = true
|
||||
```
|
||||
|
||||
## :warning: FSDP CPU offloading
|
||||
|
||||
FSDP CPU offloading offloads the parameters, gradients, and optimizer states to CPU to reduce the memory usage of the trainer.
|
||||
|
||||
This will make training significantly slower and is not recommended most of the time.
|
||||
|
||||
```
|
||||
[trainer.model]
|
||||
fsdp_cpu_offload = true
|
||||
```
|
||||
|
||||
## :warning: Lora training
|
||||
|
||||
LoRA training significantly reduces the memory usage of the trainer at the cost of smaller gradient updates.
|
||||
|
||||
```
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
```
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
# Metrics
|
||||
|
||||
## W&B
|
||||
|
||||
For most runs we recommend logging metrics to [W&B](https://wandb.ai). Before enabling W&B, make sure that you have an account and are logged in.
|
||||
|
||||
```bash
|
||||
uv run wandb login
|
||||
# Or set `export WANDB_API_KEY=...`
|
||||
```
|
||||
|
||||
### SFT
|
||||
|
||||
Logging to W&B is disabled by default. Enable the default configuration with `--wandb`
|
||||
|
||||
```bash
|
||||
uv run sft ... --wandb
|
||||
```
|
||||
|
||||
This will log to the `prime-rl` project with a random run name. You can specify which project and name to log to
|
||||
|
||||
```bash
|
||||
uv run sft ... --wandb.project my-project --wandb.name my-run
|
||||
```
|
||||
|
||||
The same settings also work for multi-node training with `torchrun`. Note, that we only log global metrics from the master rank (e.g. the all-reduced loss)
|
||||
|
||||
```bash
|
||||
uv run torchrun --nproc-per-node 8 ... --wandb
|
||||
```
|
||||
|
||||
### RL
|
||||
|
||||
For RL training, both the trainer and orchestrator log to W&B as separate runs. Again, logging to W&B is disabled by default. Enable the default configuration with `--wandb`
|
||||
|
||||
```bash
|
||||
uv run rl ... --wandb
|
||||
```
|
||||
|
||||
This will log to the `prime-rl` project with a random run name. The trainer run is suffixed with `-trainer` and the orchestrator run is suffixed with `-orchestrator`. You can specify which project and name to log to using the same flags as for SFT.
|
||||
|
||||
```bash
|
||||
uv run rl ... --wandb.project my-project --wandb.name my-run
|
||||
```
|
||||
|
||||
For the RL trainer, we support logging samples (e.g. prompt, completion, reward, advantage for selected rollouts) and distributions (e.g. reward, advantage, entropy distributions) as W&B tables using the `wandb.log-extras` subconfig. If W&B is setup, this is enabled by default and will log for the RL trainer and orchestrator every 10 steps.
|
||||
|
||||
You can configure this on the trainer and orchestrator separately. For example, to only log samples on the orchestrator every 50 steps, but not distribution on either
|
||||
|
||||
```bash
|
||||
uv run rl ... \
|
||||
--no-trainer.wandb.log-extras.distributions \
|
||||
--orchestrator.wandb.log-extras.interval 50
|
||||
```
|
||||
|
||||
+8
-14
@@ -4,20 +4,14 @@
|
||||
{
|
||||
"group": "PRIME-RL",
|
||||
"pages": [
|
||||
"index",
|
||||
"entrypoints",
|
||||
"configs",
|
||||
"training_modes",
|
||||
"environments",
|
||||
"async",
|
||||
"logging",
|
||||
"multi_run_manager",
|
||||
"checkpointing",
|
||||
"benchmarking",
|
||||
"deployment",
|
||||
"kubernetes",
|
||||
"testing-moe-at-small-scale",
|
||||
"troubleshooting"
|
||||
"overview",
|
||||
"configuration",
|
||||
"training",
|
||||
"inference",
|
||||
"scaling",
|
||||
"algorithms",
|
||||
"advanced",
|
||||
"development"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,244 +0,0 @@
|
||||
# MultiRunManager
|
||||
|
||||
The `MultiRunManager` object is a global singleton that manages the parameters and components for multiple concurrent training runs within a single trainer process.
|
||||
This allows multiple orchestrator deployments to share the same trainer.
|
||||
|
||||
When `max_concurrent_runs > 1`, the trainer can train multiple runs in parallel. Each run:
|
||||
|
||||
- Has its own LoRA adapter parameters
|
||||
- Has its own optimizer and scheduler
|
||||
- Saves its own checkpoints
|
||||
- Tracks its own training progress (step, tokens, samples)
|
||||
- Loads its own orchestrator configuration
|
||||
|
||||
The `MultiRunManager` object provides:
|
||||
|
||||
- **Bidirectional mapping** between run IDs (e.g., `run_abc123`) and run indices (0, 1, 2, ...)
|
||||
- **Progress tracking** per run (step count, total tokens, total samples)
|
||||
- **Configuration management** for orchestrator configs
|
||||
- **Distributed synchronization** across ranks via the PyTorch distributed store
|
||||
- **LoRA module registration** for multi-adapter parameter management
|
||||
- **Creation hooks** for initializing per-run resources (optimizers, schedulers)
|
||||
- **Run eviction** for removing runs that are misbehaving
|
||||
|
||||
## **Initialization and run discovery**
|
||||
|
||||
The `MultiRunManager` singleton is set up at the start of training:
|
||||
|
||||
```python
|
||||
from prime_rl.trainer.runs import setup_multi_run_manager, get_multi_run_manager
|
||||
|
||||
# Initialize with output directory and max concurrent runs
|
||||
setup_multi_run_manager(output_dir=Path("outputs/my-experiment"), max_runs=4)
|
||||
|
||||
# Get the singleton instance anywhere in the codebase
|
||||
multi_run_manager = get_multi_run_manager()
|
||||
```
|
||||
|
||||
Each run's directory follows this structure:
|
||||
|
||||
```
|
||||
{output_dir}/
|
||||
├── run_abc123/
|
||||
│ ├── control/
|
||||
│ │ ├── orch.toml # Orchestrator configuration
|
||||
│ │ ├── config_validation_error.txt # Config validation errors (if any)
|
||||
│ │ └── evicted.txt # Eviction reason (if evicted)
|
||||
│ ├── checkpoints/
|
||||
│ │ └── step_100/ # Orchestrator checkpoints
|
||||
│ ├── rollouts/
|
||||
│ │ └── step_100/ # Rollouts
|
||||
│ └── broadcast/
|
||||
│ └── step_100/ # Broadcasted weights for inference
|
||||
├── run_def456/
|
||||
│ └── ...
|
||||
└── ...
|
||||
|
||||
```
|
||||
|
||||
Runs are discovered by scanning the output directory for the pattern `run_*`. Each run must contain a valid orchestrator config at `{run_dir}/control/orch.toml` before they are added to the active runs otherwise they are ignored. When the maximum number of runs is reached, new `run_*` directories will not be picked up until old ones are deleted.
|
||||
|
||||
```python
|
||||
# Master rank scans for new/deleted runs
|
||||
multi_run_manager.discover_runs()
|
||||
|
||||
# All ranks synchronize state (must be called after discover_runs)
|
||||
multi_run_manager.synchronize_state()
|
||||
```
|
||||
|
||||
The `discover_runs()` method (master only):
|
||||
|
||||
1. Scans the output directory for `run_*` directories
|
||||
2. Filters out evicted runs (those with `control/evicted.txt`)
|
||||
3. Detects new runs and deleted runs
|
||||
4. Calls `forgotten_hook` for deleted runs (master only)
|
||||
5. Loads and validates the orchestrator config for each new run
|
||||
6. Updates internal mappings and data structures
|
||||
7. Calls `discovered_hook` for new runs (master only)
|
||||
|
||||
The `synchronize_state()` method (all ranks):
|
||||
|
||||
1. Master broadcasts run state to all ranks via the distributed store
|
||||
2. Non-master ranks catch up by calling internal `_delete_run_data` / `_create_run_data`
|
||||
3. All ranks execute `deletion_hook` for deleted runs
|
||||
4. All ranks execute `creation_hook` for new runs (e.g., optimizer setup, LoRA parameter reset)
|
||||
|
||||
## Run Eviction
|
||||
|
||||
The master proc on the trainer can evict a run using the `evict_run(idx: int, reason: str)` method.
|
||||
This is useful when the trainer detects an issue with a run that requires it to be stopped (e.g., invalid data, resource constraints, or policy violations).
|
||||
|
||||
```python
|
||||
# Evict a run by its index (master only)
|
||||
multi_run_manager.evict_run(idx=0, reason="Run exceeded memory limits")
|
||||
```
|
||||
|
||||
The `evict_run()` method (master only):
|
||||
|
||||
1. Writes the eviction reason to `{run_dir}/control/evicted.txt`
|
||||
2. Logs a warning with the eviction details
|
||||
3. The run is **not** immediately removed from the manager's data structures
|
||||
|
||||
The eviction takes effect through two mechanisms:
|
||||
|
||||
**On the trainer side:**
|
||||
- The next `discover_runs()` call will filter out the evicted run (it checks for `evicted.txt`)
|
||||
- The run will then be treated as deleted, triggering forgotten/deletion hooks
|
||||
- The run index is returned to the unused pool
|
||||
|
||||
**On the orchestrator side:**
|
||||
- The orchestrator checks for `evicted.txt` at the start of each iteration in its main loop
|
||||
- If found, it raises a `RuntimeError` with the eviction reason, causing the orchestrator to exit
|
||||
- This surfaces the eviction reason to the user
|
||||
- The orchestrator also self-evicts by writing `evicted.txt` if a training batch has no learning signal (all rollouts filtered out) on `MAX_EMPTY_BATCH_ATTEMPTS` (3) consecutive attempts
|
||||
|
||||
## LoRA Module Registration
|
||||
|
||||
LoRA modules register themselves with `MultiRunManager` for parameter management:
|
||||
|
||||
```python
|
||||
# In apply_lora_to_model()
|
||||
lora_module = MultiLoRALinear(
|
||||
base_layer=base_module,
|
||||
rank=config.rank,
|
||||
n_adapters=get_multi_run_manager().max_runs,
|
||||
...
|
||||
)
|
||||
lora_module.register_with_runs(get_multi_run_manager(), module_name)
|
||||
|
||||
```
|
||||
|
||||
The `MultiRunManager` object then exposes:
|
||||
|
||||
```python
|
||||
# Get parameters for a specific run (used by optimizer creation)
|
||||
multi_run_manager.get_named_parameters_for_run(idx)
|
||||
|
||||
# Get state dict for a specific run (used by weight broadcast)
|
||||
multi_run_manager.get_state_dict_for_run(idx)
|
||||
|
||||
# Reset parameters for a new run
|
||||
multi_run_manager.reset_run_parameters(idx)
|
||||
|
||||
```
|
||||
|
||||
## Hooks
|
||||
|
||||
The `MultiRunManager` object supports several types of hooks for different lifecycle events.
|
||||
Deletion hooks are always called before creation hooks.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph master["Rank 0 (Master)"]
|
||||
discover["discover_runs()"]
|
||||
forgotten["forgotten_hooks"]
|
||||
validation["config_validation_hooks"]
|
||||
discovered["discovered_hooks"]
|
||||
|
||||
discover --> forgotten
|
||||
forgotten --> validation
|
||||
validation --> discovered
|
||||
discovered --> discover
|
||||
end
|
||||
|
||||
subgraph rank1["Rank 1"]
|
||||
wait1["waiting..."]
|
||||
end
|
||||
|
||||
subgraph rankN["Rank N"]
|
||||
waitN["waiting..."]
|
||||
end
|
||||
|
||||
discovered --> barrier
|
||||
wait1 --> barrier
|
||||
waitN --> barrier
|
||||
|
||||
barrier[["synchronize_state()"]]
|
||||
|
||||
barrier --> deletion["deletion_hooks"]
|
||||
deletion --> creation["creation_hooks"]
|
||||
|
||||
style barrier fill:#fff9c4
|
||||
```
|
||||
|
||||
### Hook Registration
|
||||
|
||||
```python
|
||||
# These hooks are only called on the master as only master uses `discover_runs()`
|
||||
# These hooks are thus only relevant to master only components (packer)
|
||||
multi_run_manager.register_discovered_hook(callback)
|
||||
multi_run_manager.register_forgotten_hook(callback)
|
||||
|
||||
# These hooks are executed by all ranks in the order they were added during `synchronize_state()`
|
||||
# This ensures DTensor creations and other distributed operations happen together
|
||||
# Calling torch.dist.barrier() in a hook here should work
|
||||
multi_run_manager.register_creation_hook(callback)
|
||||
multi_run_manager.register_deletion_hook(callback)
|
||||
|
||||
# These hooks validate the orchestrator config when runs are discovered:
|
||||
multi_run_manager.register_config_validation_hook(callback)
|
||||
```
|
||||
|
||||
The callback signatures:
|
||||
|
||||
```python
|
||||
def discovered_callback(idx: int, run_id: str, config: OrchestratorConfig) -> None:
|
||||
"""Called when a new run is discovered (master only).
|
||||
|
||||
Args:
|
||||
idx: The run's index (0 to max_runs-1)
|
||||
run_id: The run's ID (e.g., "run_abc123")
|
||||
config: The orchestrator config for the run
|
||||
"""
|
||||
# Example: Set the scaling factor for the run
|
||||
multi_run_manager.scaling_factors[idx] = config.model.lora.alpha / config.model.lora.rank
|
||||
|
||||
def forgotten_callback(idx: int, run_id: str) -> None:
|
||||
"""Called when a run is forgotten/removed (master only).
|
||||
|
||||
Args:
|
||||
idx: The run's index (0 to max_runs-1)
|
||||
run_id: The run's ID (e.g., "run_abc123")
|
||||
"""
|
||||
pass
|
||||
|
||||
def callback(idx: int, run_id: str) -> None:
|
||||
"""Called when a run is created/deleted.
|
||||
|
||||
Args:
|
||||
idx: The run's index (0 to max_runs-1)
|
||||
run_id: The run's ID (e.g., "run_abc123")
|
||||
"""
|
||||
pass
|
||||
|
||||
def config_validation_callback(config: OrchestratorConfig) -> tuple[bool, str]:
|
||||
"""Validate an orchestrator config.
|
||||
|
||||
Args:
|
||||
config: The orchestrator config to validate
|
||||
|
||||
Returns:
|
||||
(is_valid, error_message): If invalid, error_message is written to config dir
|
||||
"""
|
||||
return True, ""
|
||||
```
|
||||
@@ -1,60 +0,0 @@
|
||||
# Multimodal (VLM) Support
|
||||
|
||||
Prime-RL supports training vision-language models (VLMs) like Qwen3-VL.
|
||||
|
||||
## VLM Configuration
|
||||
|
||||
### Supported Models
|
||||
|
||||
The built-in registry supports these model families out of the box:
|
||||
|
||||
| Model Family | model_type | Vision Encoder | Language Model |
|
||||
|-------------|------------|---------------|----------------|
|
||||
| Qwen3-VL | `qwen3_vl` | `model.visual` | `model.language_model` |
|
||||
| Qwen3.5 | `qwen3_5` | `model.visual` | `model.language_model` |
|
||||
| Qwen3.5-MoE | `qwen3_5_moe` | `model.visual` | `model.language_model` |
|
||||
|
||||
Enable VLM mode by adding a `[model.vlm]` section. Both fields are required — they tell prime-rl where the vision encoder and language model live on the model object:
|
||||
|
||||
```toml
|
||||
[model]
|
||||
name = "Qwen/Qwen3-VL-4B-Instruct"
|
||||
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
```
|
||||
|
||||
For the registered models in the table above, use the attrs shown there. For custom VLMs, check your model's structure with `model.named_children()`.
|
||||
|
||||
Both fields are dotted attribute paths resolved on the loaded model. A bad path raises a `ValueError` immediately — there are no silent fallbacks.
|
||||
|
||||
The weight key prefix for NCCL broadcasting is derived automatically as `{language_model_attr}.layers.`.
|
||||
|
||||
To add permanent support for a new model family, add an entry to `VLM_REGISTRY` in `src/prime_rl/utils/vlm.py`.
|
||||
|
||||
## Current Limitations
|
||||
|
||||
- **Vision encoder is frozen by default**: The vision encoder is frozen during training by default. Set `freeze_vision_encoder = false` in `[model.vlm]` to make it trainable. When unfrozen, the vision encoder is FSDP-sharded per-block for proper gradient flow. Note: this has no effect when using LoRA.
|
||||
|
||||
- **No multimodal-safe truncation**: Token sequences are truncated to `seq_len`, but `pixel_values` and `image_grid_thw` are passed through unchanged. If a multimodal sample exceeds `seq_len`, image tokens can be dropped while image tensors still describe the full set of images. Ensure `seq_len` covers your longest VLM samples.
|
||||
|
||||
- **Optimization dtype must be bfloat16**: Set `optimization_dtype = "bfloat16"` and `reduce_dtype = "bfloat16"` in your trainer config.
|
||||
|
||||
- **Higher KL mismatch with multi-image inputs**: VLM training exhibits higher KL mismatch compared to text-only, especially with multiple images.
|
||||
|
||||
- **Images are not logged**: The images the VLM sees during training are not logged to monitors.
|
||||
|
||||
## How Multi-Turn VLM RL Training Works
|
||||
|
||||
VLM rollouts go through the renderer-backed TITO client (`orchestrator.use_renderer = true`, the default and required for VLMs). The renderer owns the HuggingFace processor per-slot and emits multimodal tensors alongside tokens.
|
||||
|
||||
1. **Render**: For each trajectory step, the renderer tokenizes messages and emits per-image multimodal tensors (e.g. `pixel_values`, `image_grid_thw` for Qwen3-VL) as `multi_modal_data`.
|
||||
2. **Pack**: `interleave_rollout` concatenates the per-image tensors emitted across a sample's merged step range into a single `mm_kwargs` dict on the `TrainingSample`. Per-token `mm_token_type_ids` (0=text, 1=image, 2=video) come from `renderer.mm_token_type_id_map`.
|
||||
3. **Forward**: The trainer `**`-unpacks `mm_kwargs` into the model's `forward` signature, so any VLM whose HF processor and forward agree on kwarg names works without touching the transport.
|
||||
|
||||
Each multimodal sample becomes its own micro-batch during training (no packing) since image tensor sizes vary.
|
||||
|
||||
## vLLM Configuration
|
||||
|
||||
`VLLM_WORKER_MULTIPROC_METHOD=spawn` is required for VLM inference. This is set automatically when using `uv run rl @ ...`, but if you start the vLLM server yourself, make sure this environment variable is set.
|
||||
@@ -0,0 +1,45 @@
|
||||
# Overview
|
||||
|
||||
`prime-rl` is a framework for large-scale, asynchronous reinforcement learning of large language models. It is designed to be easy to use and hackable, yet capable of training 1T+-parameter MoE models on 1000+ GPU clusters.
|
||||
|
||||
## Architecture
|
||||
|
||||
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 `/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+, 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 the local filesystem, and weight broadcast uses the filesystem (or NCCL for synchronous setups). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
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) / [`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.
|
||||
|
||||
## Quick Run
|
||||
|
||||
Train an SFT-warmed `Qwen3-0.6B` on the `reverse-text` task — the env is bundled with the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) submodule so no separate install is needed. This config ships in the repo and runs on two GPUs (one for inference, one for the trainer):
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/reverse_text/rl.toml
|
||||
```
|
||||
|
||||
The `rl` entrypoint reads `examples/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
|
||||
|
||||
- **[Configuration](configuration.md)** — TOML composition, CLI overrides, dry-run.
|
||||
- **[Training](training.md)** — Launch and observe RL and SFT runs.
|
||||
- **[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, multi-tenant, P/D inference.
|
||||
- **[Development](development.md)** — Test suite, pre-commit hooks, adding a new model.
|
||||
@@ -1,48 +0,0 @@
|
||||
# Platform Monitoring
|
||||
|
||||
Use `orchestrator.prime_monitor` to register a run on the Prime Intellect platform and stream training metrics, samples, and distributions.
|
||||
|
||||
> **Internal-only for now:** external run registration is currently only enabled for internal / allowlisted teams.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
You need a Prime API key with `rft:write` scope.
|
||||
|
||||
Use the CLI:
|
||||
|
||||
```bash
|
||||
prime login
|
||||
```
|
||||
|
||||
Or set an environment variable directly:
|
||||
|
||||
```bash
|
||||
export PRIME_API_KEY=pit_...
|
||||
```
|
||||
|
||||
## Minimal config
|
||||
|
||||
```toml
|
||||
[orchestrator.prime_monitor]
|
||||
run_name = "my-experiment"
|
||||
```
|
||||
|
||||
You can also override from the CLI:
|
||||
|
||||
```bash
|
||||
uv run rl @ config.toml --orchestrator.prime_monitor.run_name "my-experiment"
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### `API key not found`
|
||||
|
||||
Set the env var from `api_key_var` or run:
|
||||
|
||||
```bash
|
||||
prime login
|
||||
```
|
||||
|
||||
### `External training runs are not enabled for this team`
|
||||
|
||||
Your team is not allowlisted yet. This feature is currently internal-only.
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
# Scaling
|
||||
|
||||
This page covers how to scale `prime-rl` from a single GPU to a 1000-GPU cluster: single-node and multi-node deployments, FSDP / expert parallelism / context parallelism, and throughput benchmarking. See [Training](training.md) for detailed documentation of the trainer configuration and [Inference](inference.md) for the inference configuration.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Single-Node vs. Multi-Node Deployment](#single-node-vs-multi-node-deployment)
|
||||
- [Single-Node](#single-node)
|
||||
- [RL Placement](#rl-placement)
|
||||
- [SFT and Torchrun](#sft-and-torchrun)
|
||||
- [Multi-Node](#multi-node)
|
||||
- [Parallelism Knobs](#parallelism-knobs)
|
||||
- [FSDP](#fsdp)
|
||||
- [Expert Parallelism](#expert-parallelism)
|
||||
- [Context Parallelism](#context-parallelism)
|
||||
- [Activation Checkpointing and Offloading](#activation-checkpointing-and-offloading)
|
||||
- [Optimizer Offloading](#optimizer-offloading)
|
||||
- [LM Head Chunking](#lm-head-chunking)
|
||||
- [Memory-Tight Recipe](#memory-tight-recipe)
|
||||
- [SLURM](#slurm)
|
||||
- [Activation](#activation)
|
||||
- [`[deployment]` Block](#deployment-block)
|
||||
- [Examples](#examples)
|
||||
- [Custom Templates](#custom-templates)
|
||||
- [Benchmarking](#benchmarking)
|
||||
|
||||
## Single-Node vs. Multi-Node Deployment
|
||||
|
||||
The `rl`, `sft`, and `inference` entrypoints all accept a `[deployment]` block (`type = "single_node"` or `"multi_node"`) that picks how the trainer / orchestrator / inference processes are placed across hardware. **Single-node** runs locally; **multi-node** currently goes through [SLURM](#slurm) — the launcher writes an sbatch script that places inference replicas, the orchestrator, and the trainer with the right rendezvous endpoints, IPs, ports, and shared-filesystem paths wired in.
|
||||
|
||||
### Single-Node
|
||||
|
||||
#### RL Placement
|
||||
|
||||
`rl` defaults to 1 trainer GPU and 1 inference GPU. To give inference 6 GPUs with data parallelism and the trainer the remaining 2 on an 8-GPU node:
|
||||
|
||||
```bash
|
||||
uv run rl @ rl.toml \
|
||||
--deployment.num-infer-gpus 6 \
|
||||
--deployment.num-train-gpus 2 \
|
||||
--inference.parallel.dp 6
|
||||
```
|
||||
|
||||
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next, teacher last. 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 tmux sessions, each pinned to half the GPUs and a separate inference port:
|
||||
|
||||
```bash
|
||||
# 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
|
||||
|
||||
# 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.client.base-url http://localhost:8001/v1 \
|
||||
--output-dir outputs/exp2
|
||||
```
|
||||
|
||||
#### SFT and Torchrun
|
||||
|
||||
`uv run sft` handles distributed launch internally. To scale from 1 to N GPUs, set the deployment GPU count (or just let it pick up `WORLD_SIZE`). For non-default layouts, the manual equivalent is:
|
||||
|
||||
```bash
|
||||
uv run torchrun \
|
||||
--nproc-per-node 8 \
|
||||
--local-ranks-filter 0 \
|
||||
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 `<output_dir>/logs/trainer/torchrun/`.
|
||||
|
||||
### Multi-Node
|
||||
|
||||
Multi-node deployments (RL or SFT) are launched via [SLURM](#slurm) — set `[deployment] type = "multi_node"` plus the matching `[slurm]` block, and the launcher writes the sbatch script that places inference, orchestrator, and trainer across the requested nodes with the inter-process wiring set up correctly. See [SLURM § Examples](#examples) for full configs.
|
||||
|
||||
## Parallelism Knobs
|
||||
|
||||
### FSDP
|
||||
|
||||
FSDP2 is the default model sharding strategy. By default the trainer fully shards parameters, gradients, and optimizer state across the data-parallel mesh. Tweakable knobs:
|
||||
|
||||
| Knob | Effect |
|
||||
|---|---|
|
||||
| `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 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).
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
ep = 8 # EP degree; must divide num_experts
|
||||
ep_comm_backend = "torch" # or "deepep"
|
||||
```
|
||||
|
||||
`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. 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.
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2" # or fa3 / fa4
|
||||
cp = 2 # CP degree
|
||||
cp_style = "ulysses" # "ring"
|
||||
```
|
||||
|
||||
### Activation Checkpointing and Offloading
|
||||
|
||||
| Knob | Memory ↓ | Throughput ↓ |
|
||||
|---|---|---|
|
||||
| `trainer.model.ac` | large | ~25% |
|
||||
| `trainer.model.ac.mode = "selective"` | medium | small |
|
||||
| `trainer.model.ac_offloading` | extra | a bit more |
|
||||
|
||||
Enable selective AC (custom impl only) for the best memory/throughput tradeoff:
|
||||
|
||||
```toml
|
||||
[trainer.model.ac]
|
||||
mode = "selective"
|
||||
targets = ["norm", "attn_proj"] # see Reference for the full list per architecture
|
||||
```
|
||||
|
||||
We reccomend also using `ac_offloading` and `ac_offloading.max_inflight_activations = 5` to further reduce the memory footprint in tradeoff for some throughput. 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:
|
||||
|
||||
```toml
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
```
|
||||
|
||||
### Optimizer Offloading
|
||||
|
||||
Offloading optimizer states to CPU is a near-free memory win at low GPU counts:
|
||||
|
||||
```toml
|
||||
[trainer.optim]
|
||||
# any optimizer type
|
||||
type = "adamw"
|
||||
|
||||
[trainer.model]
|
||||
optim_cpu_offload = true
|
||||
```
|
||||
|
||||
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training). Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
|
||||
|
||||
### LM Head Chunking
|
||||
|
||||
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization:
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
fused_lm_head_token_chunk_size = "auto" # picks 8192 for RL
|
||||
# or explicit:
|
||||
# fused_lm_head_token_chunk_size = 1024 # smaller = lower memory, more launches
|
||||
# fused_lm_head_token_chunk_size = "disabled" # default; vanilla LM head
|
||||
```
|
||||
|
||||
`auto` is a safe starting point for RL. Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. Only available with `model.impl = "custom"`, and currently RL-only — the SFT trainer rejects integer values.
|
||||
|
||||
## Memory-Tight Recipe
|
||||
|
||||
The kitchen-sink config for fitting large MoE on limited GPUs at acceptable throughput:
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
ep = 8
|
||||
cp = 2
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
```
|
||||
|
||||
Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
|
||||
|
||||
## SLURM
|
||||
|
||||
The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]` table is present — there's no separate entrypoint.
|
||||
|
||||
### Activation
|
||||
|
||||
A SLURM config is usually a thin overlay that adds `[slurm]` (and `[deployment]` for multi-node) on top of a base config. Configs are composed left-to-right via the `@` CLI syntax — see [Configuration § TOML Composition](configuration.md#toml-composition):
|
||||
|
||||
```toml
|
||||
# my_slurm.toml
|
||||
output_dir = "/shared/outputs/my-rl"
|
||||
|
||||
[slurm]
|
||||
job_name = "my-rl-run"
|
||||
```
|
||||
|
||||
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 the sbatch script + resolved config, exits
|
||||
```
|
||||
|
||||
### `[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:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
gpus_per_node = 8 # default
|
||||
nodes_per_fsdp_group = 1 # optional — controls FSDP island size
|
||||
```
|
||||
|
||||
SFT multi-node:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
gpus_per_node = 8
|
||||
```
|
||||
|
||||
### Examples
|
||||
|
||||
Full multi-node configs ship in [`examples/multinode/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/multinode):
|
||||
|
||||
- [`rl.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/multinode/rl.toml) — two-node RL run with NCCL weight broadcast on a 30B MoE student.
|
||||
- [`sft.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/multinode/sft.toml) — two-node SFT against the same model.
|
||||
|
||||
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
|
||||
|
||||
For unusual partitions, module loads, or environment setup, supply your own Jinja2 template:
|
||||
|
||||
```bash
|
||||
uv run rl @ my_config.toml --slurm.template-path path/to/my_template.sbatch.j2
|
||||
```
|
||||
|
||||
The default templates live under [`src/prime_rl/templates/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/src/prime_rl/templates) — copy one as a starting point.
|
||||
|
||||
## Benchmarking
|
||||
|
||||
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 --bench
|
||||
uv run sft ... --data.type fake --data.length variable --bench # variable-length fake data
|
||||
|
||||
# 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
|
||||
```
|
||||
|
||||
Persist results with `--bench.output-json`. Use this to compare parallelism configs before committing a multi-day run.
|
||||
-297
@@ -1,297 +0,0 @@
|
||||
# SLURM
|
||||
|
||||
The `rl`, `sft`, and `inference` entrypoints all have built-in SLURM support. Adding a `[slurm]` section to your config switches from local execution to SLURM job submission — no separate entrypoint needed.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Local run
|
||||
uv run rl @ examples/reverse_text/rl.toml
|
||||
|
||||
# SLURM run — overlay slurm_rl.toml on top of the base config
|
||||
uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml
|
||||
```
|
||||
|
||||
The SLURM config is a thin overlay that adds `[slurm]` (and optionally `[deployment]`) on top of a base config. Configs are composed left-to-right via the `@` CLI syntax — see [`configs.md`](configs.md) for details.
|
||||
|
||||
```toml
|
||||
# examples/reverse_text/slurm_rl.toml
|
||||
output_dir = "outputs/reverse-text-rl"
|
||||
|
||||
[slurm]
|
||||
job_name = "reverse-text-rl"
|
||||
```
|
||||
|
||||
## How it works
|
||||
|
||||
When `[slurm]` is present, the entrypoint:
|
||||
|
||||
1. Resolves the full config
|
||||
2. Renders a SLURM batch script from a Jinja2 template
|
||||
3. Writes the script and resolved config to `{output_dir}/`
|
||||
4. Submits via `sbatch` (or prints the script with `--slurm.dry-run`)
|
||||
|
||||
For **single-node** jobs, the entire config is dumped to a TOML file and the template simply runs `uv run rl @` or `uv run sft @` on the allocated node.
|
||||
|
||||
For **multi-node** jobs, sub-configs are written separately and `srun` dispatches processes across nodes.
|
||||
|
||||
## Configuration
|
||||
|
||||
### `[slurm]` — Job submission (shared between RL and SFT)
|
||||
|
||||
| Field | Description | Default |
|
||||
|---|---|---|
|
||||
| `job_name` | SLURM job name | `"prime-rl"` |
|
||||
| `project_dir` | Path to the project root on the cluster | `"."` |
|
||||
| `template_path` | Path to a custom Jinja2 template | auto-selected |
|
||||
| `partition` | SLURM partition | `"cluster"` |
|
||||
| `nodelist` | Comma-separated list of specific nodes to run on (`--nodelist`) | `None` |
|
||||
| `exclude` | Comma-separated list of nodes to exclude (`--exclude`) | `None` |
|
||||
| `account` | SLURM account to charge (`--account`) | `None` |
|
||||
| `time` | Maximum wall time, e.g. `"24:00:00"` (`--time`) | `None` |
|
||||
| `pre_run_command` | Shell command to run on head node after env setup, before starting the job (e.g. cleanup) | `None` |
|
||||
|
||||
### `[deployment]` — Node and GPU allocation
|
||||
|
||||
**RL** uses a discriminated union with `type = "single_node"` (default) or `type = "multi_node"`:
|
||||
|
||||
| Field | single_node | multi_node |
|
||||
|---|---|---|
|
||||
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
|
||||
| `num_train_gpus` | Training GPUs | — |
|
||||
| `num_infer_gpus` | Inference GPUs | — |
|
||||
| `num_train_nodes` | — | Training nodes |
|
||||
| `num_infer_nodes` | — | Inference nodes |
|
||||
| `nodes_per_fsdp_group` | — | Nodes per FSDP island (optional) |
|
||||
|
||||
**SFT** follows the same pattern but only has training nodes:
|
||||
|
||||
| Field | single_node | multi_node |
|
||||
|---|---|---|
|
||||
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
|
||||
| `num_gpus` | Number of GPUs (default: 1) | — |
|
||||
| `num_nodes` | — | Training nodes (default: 2) |
|
||||
| `nodes_per_fsdp_group` | — | Nodes per FSDP island (optional) |
|
||||
|
||||
**Inference** runs independent vLLM replicas per node:
|
||||
|
||||
| Field | single_node | multi_node |
|
||||
|---|---|---|
|
||||
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
|
||||
| `num_nodes` | — | Number of inference nodes (default: 1) |
|
||||
|
||||
The SLURM template is auto-selected based on `deployment.type`. You can override it with `slurm.template_path`.
|
||||
|
||||
### Constraints
|
||||
|
||||
- `output_dir` should be explicitly set when using SLURM (defaults to `"outputs"`)
|
||||
- Multi-node deployment requires `[slurm]` to be set
|
||||
|
||||
---
|
||||
|
||||
## RL Examples
|
||||
|
||||
### Single-node SLURM
|
||||
|
||||
The simplest case: run on a single allocated node. No `[deployment]` needed — defaults to `single_node`.
|
||||
|
||||
```toml
|
||||
output_dir = "/shared/outputs/my-rl-run"
|
||||
|
||||
[slurm]
|
||||
job_name = "my-rl-run"
|
||||
```
|
||||
|
||||
### Multi-node SLURM (Hendrycks Math)
|
||||
|
||||
```toml
|
||||
output_dir = "outputs/rl-math-moe"
|
||||
max_steps = 500
|
||||
seq_len = 2048
|
||||
|
||||
[slurm]
|
||||
job_name = "hendrycks-math-rl-moe"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 4
|
||||
dp = 2
|
||||
```
|
||||
|
||||
See [`examples/multinode/rl.toml`](../examples/multinode/rl.toml) for the full example.
|
||||
|
||||
---
|
||||
|
||||
## SFT Examples
|
||||
|
||||
### Single-node SLURM
|
||||
|
||||
```toml
|
||||
output_dir = "/shared/outputs/my-sft-run"
|
||||
|
||||
[slurm]
|
||||
job_name = "my-sft-run"
|
||||
```
|
||||
|
||||
### Multi-node SLURM (MoE SFT)
|
||||
|
||||
```toml
|
||||
output_dir = "outputs/sft-moe-math"
|
||||
max_steps = 500
|
||||
|
||||
[slurm]
|
||||
job_name = "sft-moe-math"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
optim_cpu_offload = true
|
||||
|
||||
[model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
[data]
|
||||
type = "sft"
|
||||
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
|
||||
subsets = ["default"]
|
||||
splits = ["math"]
|
||||
batch_size = 128
|
||||
seq_len = 8192
|
||||
```
|
||||
|
||||
See [`examples/multinode/sft.toml`](../examples/multinode/sft.toml) for the full example.
|
||||
|
||||
---
|
||||
|
||||
## Inference Examples
|
||||
|
||||
### Single-node SLURM
|
||||
|
||||
Run a vLLM server on a single allocated node:
|
||||
|
||||
```toml
|
||||
# my_inference.toml
|
||||
output_dir = "/shared/outputs/my-inference"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-8B"
|
||||
|
||||
[parallel]
|
||||
tp = 8
|
||||
|
||||
[slurm]
|
||||
job_name = "my-inference"
|
||||
```
|
||||
|
||||
```bash
|
||||
uv run inference @ my_inference.toml
|
||||
```
|
||||
|
||||
### Multi-node SLURM
|
||||
|
||||
Each node runs an independent vLLM replica. TP and DP must fit within a single node — there is no cross-node parallelism.
|
||||
|
||||
```toml
|
||||
output_dir = "/shared/outputs/my-inference"
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/INTELLECT-3-RL-600"
|
||||
|
||||
[parallel]
|
||||
tp = 4
|
||||
dp = 2
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 4
|
||||
|
||||
[slurm]
|
||||
job_name = "my-inference"
|
||||
```
|
||||
|
||||
After submission, the SLURM template prints the inference URLs for all nodes (one per node).
|
||||
|
||||
### Dry run
|
||||
|
||||
Use `--dry-run` (or `dry_run = true` in TOML) to generate the sbatch script without submitting:
|
||||
|
||||
```bash
|
||||
uv run inference @ config.toml --dry-run
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Custom SLURM Templates
|
||||
|
||||
The default templates handle standard setups with InfiniBand detection, environment setup, and `srun`-based process dispatch. For advanced use cases (custom partitions, account settings, module loads, etc.), provide your own Jinja2 template:
|
||||
|
||||
```bash
|
||||
uv run rl @ my_config.toml --slurm.template-path path/to/my_template.sbatch.j2
|
||||
```
|
||||
|
||||
See [`src/prime_rl/templates/`](../src/prime_rl/templates/) for the default templates as a starting point.
|
||||
|
||||
## Monitoring
|
||||
|
||||
After submission, logs are available at:
|
||||
|
||||
```bash
|
||||
# All deployment types (trainer.log and inference.log are symlinks for multi-node)
|
||||
tail -F {output_dir}/logs/trainer.log
|
||||
tail -F {output_dir}/logs/orchestrator.log
|
||||
tail -F {output_dir}/logs/inference.log
|
||||
|
||||
# Multi-node: per-node logs
|
||||
tail -F {output_dir}/logs/trainer/node_*.log
|
||||
tail -F {output_dir}/logs/inference/node_*.log
|
||||
|
||||
# Multi-node inference: per-replica router logs
|
||||
tail -F {output_dir}/logs/inference/router_*.log
|
||||
```
|
||||
|
||||
For convenience, a tmux launcher sets up a session with all log streams:
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh my-rl-job /shared/outputs/my-rl-job
|
||||
```
|
||||
@@ -1,113 +0,0 @@
|
||||
# Testing MoE at Small Scale
|
||||
|
||||
When working on MoE architectures (GLM-4, Kimi, etc.), you can't iterate on a 100B+ parameter model locally. This guide shows how to create a small (~0.5B) MoE model with the same architecture, run SFT to warm it up, and run RL on it — all on 1-2 GPUs.
|
||||
|
||||
The goal isn't performance. It's catching bugs in modeling code, state dict conversions, and training pipeline integration before running at scale.
|
||||
|
||||
## Overview
|
||||
|
||||
1. **Create + verify** a mini model with random weights and check HF <-> PrimeRL roundtrip
|
||||
2. **SFT** to give it a non-trivial distribution
|
||||
3. **RL** on reverse-text to validate the full pipeline
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- At least 1 GPU for steps 1-2, 2 GPUs for step 3 (RL)
|
||||
- Architecture presets are defined in `scripts/mini_moe.py`
|
||||
|
||||
## Step 1: Create and verify the mini model
|
||||
|
||||
```bash
|
||||
uv run python scripts/mini_moe.py --arch glm4_moe --output-dir ./mini-glm-moe
|
||||
```
|
||||
|
||||
This creates a ~543M parameter GLM-4 MoE (1024 hidden, 24 layers, 8 experts) with random weights, copies the tokenizer from the original GLM-4 model, then verifies that:
|
||||
- Logits match between HF and PrimeRL implementations (`convert_to_prime`)
|
||||
- The HF -> PrimeRL -> HF roundtrip is lossless (`convert_to_hf`)
|
||||
|
||||
To re-run verification only (e.g. after a modeling code change):
|
||||
|
||||
```bash
|
||||
uv run python scripts/mini_moe.py --arch glm4_moe --output-dir ./mini-glm-moe --verify-only
|
||||
```
|
||||
|
||||
## Step 2: SFT warmup
|
||||
|
||||
Using the existing debug MoE SFT config with overrides for real data:
|
||||
|
||||
```bash
|
||||
uv run sft @ configs/debug/moe/sft/train.toml \
|
||||
--model.name ./mini-glm-moe \
|
||||
--data.name PrimeIntellect/Reverse-Text-SFT \
|
||||
--data.type null \
|
||||
--max_steps 200 \
|
||||
--optim.lr 1e-4 \
|
||||
--ckpt.weights
|
||||
```
|
||||
|
||||
This fine-tunes on [PrimeIntellect/Reverse-Text-SFT](https://huggingface.co/datasets/PrimeIntellect/Reverse-Text-SFT) for 200 steps. Loss should drop from ~12 to ~2.5. The model won't be coherent, but it will have a non-trivial distribution so KL divergence is meaningful during RL.
|
||||
|
||||
The latest weight checkpoint is saved under `outputs/weights/step_<N>`. You can verify the roundtrip on it:
|
||||
|
||||
```bash
|
||||
uv run python scripts/mini_moe.py --arch glm4_moe --output-dir outputs/weights/step_200 --verify-only
|
||||
```
|
||||
|
||||
A pre-built SFT'd model is available at [samsja/mini-glm-moe](https://huggingface.co/samsja/mini-glm-moe).
|
||||
|
||||
## Step 3: RL (reverse-text)
|
||||
|
||||
Requires 2 GPUs (one for inference, one for training).
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/ci/integration/rl/start.toml \
|
||||
--model.name samsja/mini-glm-moe \
|
||||
--trainer.model.impl custom \
|
||||
--inference.gpu-memory-utilization 0.7 \
|
||||
--inference.model.max-model-len 2048
|
||||
```
|
||||
|
||||
Or to use the checkpoint from step 2:
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/ci/integration/rl/start.toml \
|
||||
--model.name outputs/weights/step_200 \
|
||||
--trainer.model.impl custom \
|
||||
--inference.gpu-memory-utilization 0.7 \
|
||||
--inference.model.max-model-len 2048
|
||||
```
|
||||
|
||||
What to look for:
|
||||
- **Training runs without crashing** — validates the full pipeline (inference server, orchestrator, trainer)
|
||||
- **KL divergence is non-zero and finite** — confirms the reference model distribution is working
|
||||
- **Loss is reasonable** — not NaN, not stuck at a constant value
|
||||
|
||||
Don't expect the reward to go up meaningfully in 20 steps on a random model.
|
||||
|
||||
## Adding a new architecture
|
||||
|
||||
To test a new MoE architecture (e.g., Kimi2.5):
|
||||
|
||||
1. Add modeling code under `src/prime_rl/trainer/models/<arch>/`
|
||||
2. Add a preset to `scripts/mini_moe.py` with the config class, small dimensions, HF model class, PrimeRL model class, and tokenizer source
|
||||
3. Run steps 1-3 above with `--arch <your_arch>`
|
||||
|
||||
The preset defines the small config:
|
||||
|
||||
```python
|
||||
ARCH_PRESETS = {
|
||||
"glm4_moe": {
|
||||
"config_class": Glm4MoeConfig,
|
||||
"config_kwargs": dict(
|
||||
hidden_size=1024,
|
||||
num_hidden_layers=24,
|
||||
n_routed_experts=8,
|
||||
# ...
|
||||
),
|
||||
"hf_model_class": HFGlm4MoeForCausalLM,
|
||||
"prime_model_class": PrimeRLGlm4MoeForCausalLM,
|
||||
"tokenizer_source": "THUDM/GLM-4-9B-0414",
|
||||
},
|
||||
# Add your new arch here
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,328 @@
|
||||
# Training
|
||||
|
||||
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer, the SFT trainer, and the related on-policy distillation mode. 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).
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Entrypoints](#entrypoints)
|
||||
- [RL Trainer](#rl-trainer)
|
||||
- [Launch](#launch)
|
||||
- [Useful Knobs](#useful-knobs)
|
||||
- [Training Modes (RL / OPD / SFT)](#training-modes-rl--opd--sft)
|
||||
- [Important Metrics](#important-metrics)
|
||||
- [SFT Trainer](#sft-trainer)
|
||||
- [Dataset Format](#dataset-format)
|
||||
- [Launch](#launch-1)
|
||||
- [SFT-Specific Knobs](#sft-specific-knobs)
|
||||
- [Important Metrics](#important-metrics-1)
|
||||
- [Checkpointing](#checkpointing)
|
||||
- [Enabling Checkpoints](#enabling-checkpoints)
|
||||
- [Resuming a Run](#resuming-a-run)
|
||||
- [Serving Checkpoints](#serving-checkpoints)
|
||||
- [Observability](#observability)
|
||||
- [Log Files](#log-files)
|
||||
- [Console Output](#console-output)
|
||||
- [Weights & Biases](#weights--biases)
|
||||
- [Platform Monitoring](#platform-monitoring)
|
||||
- [Rules of Thumb](#rules-of-thumb)
|
||||
|
||||
## Entrypoints
|
||||
|
||||
| Command | Purpose | Notes |
|
||||
|---|---|---|
|
||||
| `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 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
|
||||
|
||||
### Launch
|
||||
|
||||
The minimal RL run trains an SFT-warmed `Qwen3-0.6B` on the `reverse-text` task — the env is bundled with the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) submodule, so nothing else needs to be installed:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/reverse_text/rl.toml
|
||||
```
|
||||
|
||||
### Useful Knobs
|
||||
|
||||
A condensed view of the knobs you'll most often tune. For trainer-side parallelism, sampling, optimizer, and loss knobs see [Scaling](scaling.md) and [Algorithms](algorithms.md).
|
||||
|
||||
**Data and algorithm:**
|
||||
|
||||
| Knob | What it does |
|
||||
|---|---|
|
||||
| `orchestrator.batch_size` | Tasks per trainer step. |
|
||||
| `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.training_mode` | `rl` (default), `opd`, or `sft`. See [Training modes](#training-modes-rl--opd--sft). |
|
||||
| `[[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:**
|
||||
|
||||
| Knob | What it does |
|
||||
|---|---|
|
||||
| `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). |
|
||||
| `--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 |
|
||||
|---|---|
|
||||
| `--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 TOMLs to `<output_dir>/configs/`, and exit without launching. The fastest way to debug a misbehaving config. |
|
||||
|
||||
### Training Modes (RL / OPD / SFT)
|
||||
|
||||
The RL entrypoint supports three training modes, switched via `orchestrator.training_mode`:
|
||||
|
||||
| Mode | Student | Teacher | Use case |
|
||||
|---|---|---|---|
|
||||
| `rl` | Required | Forbidden | Standard RL |
|
||||
| `opd` | Required | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): student generates rollouts, trainer minimizes KL to teacher logprobs |
|
||||
| `sft` | Required | Required, any OpenAI-compatible endpoint | Hard-distill: teacher generates rollouts, student trains on them |
|
||||
|
||||
The `rl` entrypoint only manages student-policy inference. For OPD and (local-vLLM) SFT, start the teacher inference server manually and point `[orchestrator.teacher.client]` at it:
|
||||
|
||||
```bash
|
||||
CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
--model.name <teacher> --server.port 8001
|
||||
```
|
||||
|
||||
The standalone `uv run sft` entrypoint is the more traditional SFT path — pure dataset-based, no teacher, no orchestrator. Use `orchestrator.training_mode = "sft"` only when you want a teacher to generate the supervision on the fly.
|
||||
|
||||
### Important Metrics
|
||||
|
||||
Pulled from the console logs and mirrored to W&B.
|
||||
|
||||
**Progress** (orchestrator):
|
||||
|
||||
- `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.
|
||||
- `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.
|
||||
|
||||
**Stability** (trainer):
|
||||
|
||||
- `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.
|
||||
- `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):
|
||||
|
||||
| Source | Metric | Reading |
|
||||
|---|---|---|
|
||||
| trainer | `time/wait_for_batch` | **high → orchestrator bottleneck** |
|
||||
| orchestrator | `time/wait_for_ckpt` | **high → trainer bottleneck** |
|
||||
|
||||
## SFT Trainer
|
||||
|
||||
`uv run sft` runs supervised fine-tuning from a HF dataset. It shares model loaders, FSDP setup, checkpointing, and the chat-template plumbing with the RL trainer, so a typical workflow is _SFT → RL → SFT → …_ without any reformatting.
|
||||
|
||||
### Dataset Format
|
||||
|
||||
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.
|
||||
|
||||
**Tool definitions.** 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 chat template's `tools=...` argument. The `chat_template_kwargs` column, if present, is forwarded verbatim into `apply_chat_template`.
|
||||
|
||||
**Position-dependent chat templates.** Multi-turn SFT under the default tokenization path (`build_incremental_token_mask`) requires that tokenizing the first _k_ turns of a conversation be a strict prefix of tokenizing all _n ≥ k_ turns. Qwen3's upstream template _violates_ this — it strips past `<think>` blocks across user turns, silently corrupting the loss mask. Two fixes:
|
||||
|
||||
- **Enable the renderer** (set a typed `[renderer]` config, e.g. `name = "qwen3"`, recommended; defaults to `"auto"` for RL). The [`renderers`](algorithms.md#renderers) package owns tokenization end-to-end and is robust to position-dependent templates. 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. Not supported for VLMs.
|
||||
- **Patched chat template** — the prime-rl–patched checkpoints (e.g. `PrimeIntellect/Qwen3-0.6B`, used in `examples/reverse_text/sft.toml`) ship a chat template that preserves thinking. Or supply your own.
|
||||
|
||||
See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectories) for the full picture.
|
||||
|
||||
### Launch
|
||||
|
||||
The minimal SFT run trains `Qwen3-0.6B` on the `reverse-text` SFT dataset:
|
||||
|
||||
```bash
|
||||
uv run sft @ examples/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)).
|
||||
|
||||
### SFT-Specific Knobs
|
||||
|
||||
| Knob | What it controls |
|
||||
|---|---|
|
||||
| `data.name` | HF dataset name or local path |
|
||||
| `data.batch_size` | Tokens per trainer step (packed) |
|
||||
| `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` |
|
||||
|
||||
### Important Metrics
|
||||
|
||||
Pulled from the console log and mirrored to W&B.
|
||||
|
||||
**Progress and loss:**
|
||||
|
||||
- `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`, `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:**
|
||||
|
||||
| Metric | Reading |
|
||||
|---|---|
|
||||
| `perf/throughput`, `perf/throughput_per_gpu` | tokens/s overall and per GPU |
|
||||
| `perf/mfu` | MFU |
|
||||
| `perf/peak_memory` | peak GPU memory (GiB) |
|
||||
| `time/step`, `time/forward_backward`, `time/save_ckpt` | step breakdown |
|
||||
|
||||
## Checkpointing
|
||||
|
||||
Checkpointing is split across processes because the orchestrator and trainer can be on different machines and on different steps at any given time. Inference is stateless.
|
||||
|
||||
| Process | What's saved | Where |
|
||||
|---|---|---|
|
||||
| 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
|
||||
|
||||
Checkpointing is **off by default** to save disk. Enable it with `--ckpt`:
|
||||
|
||||
```bash
|
||||
uv run rl @ rl.toml --ckpt # default: end-of-training only
|
||||
uv run rl @ rl.toml --ckpt.interval 25 # every 25 steps
|
||||
uv run rl @ rl.toml --ckpt.interval 25 --ckpt.keep-last 3 # rolling window of 3
|
||||
uv run rl @ rl.toml --ckpt.interval 25 --ckpt.keep-interval 100 # …plus permanent every 100
|
||||
```
|
||||
|
||||
### Resuming a Run
|
||||
|
||||
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 0–10
|
||||
uv run rl @ rl.toml --max-steps 10 --ckpt
|
||||
|
||||
# Resume: continue to step 20
|
||||
uv run rl @ rl.toml --max-steps 20 --ckpt.resume-step 10
|
||||
```
|
||||
|
||||
### Serving Checkpoints
|
||||
|
||||
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
|
||||
uv run hf upload <user>/<model>-RL outputs/weights/step_100
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
### Log Files
|
||||
|
||||
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):
|
||||
|
||||
```
|
||||
<output_dir>/logs/
|
||||
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
|
||||
├── orchestrator.log # single instance, single file
|
||||
├── 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 # vllm-router per replica (multi-node only)
|
||||
└── envs/{train,eval}/<env_name>/
|
||||
├── env_server.log
|
||||
└── env_worker_<id>.log
|
||||
```
|
||||
|
||||
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 <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
|
||||
```
|
||||
|
||||
### Console Output
|
||||
|
||||
`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:
|
||||
|
||||
```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. Enable with `--wandb`:
|
||||
|
||||
```bash
|
||||
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 `wandb.offline = true`.
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
### Platform Monitoring
|
||||
|
||||
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 --orchestrator.prime-monitor
|
||||
```
|
||||
|
||||
Or set it in TOML:
|
||||
|
||||
```toml
|
||||
[orchestrator.prime_monitor]
|
||||
run_name = "my-experiment"
|
||||
```
|
||||
|
||||
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/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.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.
|
||||
@@ -1,39 +0,0 @@
|
||||
# Training Modes
|
||||
|
||||
PRIME-RL supports three training modes through our RL trainer, selected via `training_mode`:
|
||||
|
||||
- **`rl`** — reinforcement learning: student generates rollouts, no teacher
|
||||
- **`opd`** — [on-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): students generates rollouts, train to minimize the KL divergence between the student and teacher's logprobs for each token in the rollout
|
||||
- **`sft`** — supervised fine-tuning on teacher-generated rollouts
|
||||
|
||||
> Note: PRIME-RL also has a dedicated `sft` entrypoint for more traditional supervised fine-tuning from a HF dataset. When using the `sft` training mode on the orchestrator, teacher rollouts are generated on-the-fly and used for training.
|
||||
|
||||
The mode determines who generates rollouts, what role the teacher plays, and what must be configured.
|
||||
|
||||
| Mode | Student | Teacher |
|
||||
|---|---|---|
|
||||
| `rl` | required | forbidden |
|
||||
| `opd` | required | required (local vLLM) |
|
||||
| `sft` | required | required (any OAI-compatible endpoint) |
|
||||
|
||||
**SFT vs OPD teachers** differ in what the orchestrator asks of them. SFT only calls `/v1/chat/completions` to generate rollouts — any OpenAI-compatible endpoint works (PI inference, OpenAI, Anthropic, a local vLLM). OPD additionally needs token-level logprobs scored over the student's tokens, which today only vLLM's `/inference/v1/generate` with `prompt_logprobs` exposes — so the OPD teacher must be a vLLM server.
|
||||
|
||||
### Reference configs
|
||||
|
||||
Debug-scale configs for all three modes (and LoRA variants) live in [`configs/debug/training_modes/`](../configs/debug/training_modes/):
|
||||
|
||||
- `rl.toml` / `opd.toml` / `opd_lora.toml`
|
||||
- `sft.toml` / `sft_lora.toml` (local vLLM teacher)
|
||||
- `sft_external.toml` (PI inference teacher)
|
||||
|
||||
See [`configs/debug/training_modes/README.md`](../configs/debug/training_modes/README.md) for run commands.
|
||||
|
||||
## Parameter reference
|
||||
|
||||
| Parameter | Default | Description |
|
||||
|-----------|---------|-------------|
|
||||
| `training_mode` | `"rl"` | One of `rl`, `opd`, `sft`. Propagates to `orchestrator.training_mode` and (for sft) `trainer.loss.type`. |
|
||||
| `deployment.num_teacher_gpus` | `None` | Number of GPUs for the teacher vLLM server. Auto-starts when set. OPD only. |
|
||||
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Must be `> 0` in OPD. |
|
||||
| `trainer.loss.adv_tau` | `1.0` | Weight for the RL advantage signal. Set `0` for pure distillation. |
|
||||
| `orchestrator.verification.enabled` | `true` | Enable/disable verification. Set to `false` for pure distillation with `adv_tau = 0`. |
|
||||
@@ -1,96 +0,0 @@
|
||||
# Trajectories
|
||||
|
||||
Verifiers [v0.1.8](https://github.com/PrimeIntellect-ai/verifiers/releases/tag/v0.1.8) introduced trajectory-based rollouts, where each LLM request/response pair in a multi-turn interaction is recorded as an independent step. For details on the design decision, check the detailed [design document](https://github.com/PrimeIntellect-ai/verifiers/blob/main/notes/TRAJECTORIES.md) in the verifiers repository.
|
||||
|
||||
## Best-Effort Interleaved Rollouts
|
||||
|
||||
PRIME-RL uses a best-effort interleaving strategy that automatically merges consecutive trajectory steps when possible, and starts a new training sample when the extension property breaks.
|
||||
|
||||
### The Extension Property
|
||||
|
||||
A sequence of trajectory steps has the **extension property** when each successive step's prompt contains all previous prompts and completions as a prefix. When this holds:
|
||||
- Multiple steps can be merged into a single training sample
|
||||
- Compute scales as O(T) for a trajectory of length T
|
||||
|
||||
When extension breaks (e.g., due to context compaction or thinking being stripped):
|
||||
- A new training sample is started from that step
|
||||
- Compute scales as O(T²) in the worst case (every step breaks extension)
|
||||
|
||||
### How It Works
|
||||
|
||||
```
|
||||
5-step trajectory where extension breaks at step 4:
|
||||
|
||||
Steps 1-3: extension holds → merged into Sample 1
|
||||
Step 4: extension breaks (e.g., thinking stripped from history)
|
||||
Steps 4-5: extension holds → merged into Sample 2
|
||||
|
||||
Result: 2 training samples instead of 5
|
||||
```
|
||||
|
||||
This approach gives you the best of both worlds:
|
||||
- When extension holds: O(T) compute, single merged sample
|
||||
- When extension breaks: graceful fallback, no corrupted data
|
||||
- Mixed scenarios: optimal merging where possible
|
||||
|
||||
### The Exact Prefix Invariant
|
||||
|
||||
Interleaving enforces a strict invariant:
|
||||
|
||||
> The prompt at turn $t$ must be the exact concatenation of prior messages exactly as the LLM originally generated them
|
||||
|
||||
We call this the "exact prefix" invariant. For example, at turn 2, the LLM should see U1,A1,U2 as the prompt, where U1 exactly matches the user message in turn 1 and A1 exactly matches the produced assistant message in turn 1. Any violation of this invariant will result in downstream problems when computing the importance sampling ratio during training.
|
||||
|
||||
For example, assume that at turn 2 the prompt is U1,A1',U2 where A1' varies from A1. In this scenario it is not clear whether to add A1 or A1' to the interleaved rollout:
|
||||
- If we add A1', the logprobs from turn 1 might be off because the inference LLM produced A1 but the trainer LLM is computing logprobs for A1'
|
||||
- If we add A1, the logprobs from turn 2 might be off because the inference LLM is attending to A1' but the trainer LLM is attending to A1
|
||||
|
||||
When the invariant is violated (extension breaks), PRIME-RL automatically starts a new training sample rather than producing corrupted data.
|
||||
|
||||
### Arbitrary Chat Templates
|
||||
|
||||
There exist chat templates which add, modify, or remove tokens across turns. One good example is the chat template of the Qwen3-series of models, which strips thinking across user turns.
|
||||
|
||||
```python
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
|
||||
|
||||
messages = [
|
||||
{"role": "user", "content": "U1"},
|
||||
{"role": "assistant", "content": "<think>R1</think>A1"},
|
||||
{"role": "user", "content": "U2"},
|
||||
]
|
||||
|
||||
print(tokenizer.apply_chat_template(messages[:1], tokenize=False))
|
||||
# <|im_start|>user
|
||||
# U1<|im_end|>
|
||||
|
||||
print(tokenizer.apply_chat_template(messages, tokenize=False))
|
||||
# <|im_start|>user
|
||||
# U1<|im_end|>
|
||||
# <|im_start|>assistant
|
||||
# A1<|im_end|>
|
||||
# <|im_start|>user
|
||||
# U2<|im_end|>
|
||||
```
|
||||
|
||||
The chat template automatically strips away past thinking sections across user turns, which is often referred to as "interleaved thinking". Many chat templates, such as GLM or MiniMax, implement this approach.
|
||||
|
||||
With best-effort interleaving, PRIME-RL handles this gracefully: when the thinking is stripped and the prefix no longer matches, a new training sample is started automatically.
|
||||
|
||||
### Discontinuous Trajectories by Design
|
||||
|
||||
Some multi-turn environments are intentionally discontinuous. For example, in a sub-agent calling scenario:
|
||||
|
||||
1. Main agent receives a task and decides to delegate to a sub-agent
|
||||
2. Sub-agent runs independently (possibly multiple turns with its own context)
|
||||
3. Control returns to main agent with only the sub-agent's final result
|
||||
|
||||
The main agent's trajectory is discontinuous because the sub-agent's internal conversation isn't part of its context. When the main agent resumes, its prompt doesn't extend the previous turn - it contains a summarized result instead.
|
||||
|
||||
Best-effort interleaving handles this naturally: each agent's contiguous turns get merged, but the handoff between agents starts a new sample.
|
||||
|
||||
## Deprecated: Branching Mode
|
||||
|
||||
The `--trajectory-strategy branching` option is deprecated. The best-effort interleaving strategy now handles all cases automatically, falling back to separate samples (equivalent to branching) when the extension property breaks.
|
||||
@@ -1,21 +0,0 @@
|
||||
# Troubleshooting
|
||||
|
||||
> My API keeps timing out.
|
||||
|
||||
We already set much larger timeout limits for the API clients that we use for training and evals. If you still encounter API timeout or connection errors, then this may be caused by your OS limiting the number of open file descriptors. Try increasing the maximum number of open files with
|
||||
|
||||
```bash
|
||||
ulimit -n 32000
|
||||
```
|
||||
|
||||
> I'm getting CUDA out of memory errors.
|
||||
|
||||
Assuming this is happening on the RL or SFT trainer, you can try the following:
|
||||
- Use full activation checkpointing (`--model.ac`)
|
||||
- Reduce the micro batch size (`--data.micro-batch-size`) and sequence length (`--data.seq-len`)
|
||||
- (*Experimental*) Use context parallelism with `--model.cp`
|
||||
|
||||
> I cannot pass my TOML config file
|
||||
|
||||
Check that you *did* leave a whitespace between the `@` and the config file (e.g. `uv run ... @ path/to/config.toml` instead of `uv run ... @path/to/config.toml`). Also, make sure that your TOML config matches the configuration schema. If not, the Pydantic error message (which arguably is quite ugly) will hopefully point you in the right direction.
|
||||
|
||||
@@ -77,10 +77,9 @@ name = "code"
|
||||
ratio = 0.2
|
||||
args = { pool_size = 512 }
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
online_difficulty_filtering = true
|
||||
seed = 42
|
||||
[[orchestrator.pre_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
enforce = true
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
@@ -77,15 +77,10 @@ id = "mini-swe-agent-plus"
|
||||
name = "swe-bench-verified-quick"
|
||||
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
|
||||
[[orchestrator.filters]]
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "gibberish"
|
||||
enforce = true
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
seed = 42
|
||||
|
||||
[inference]
|
||||
enable_expert_parallel = true
|
||||
# we need <0.85 bc glm5 layers are too large for 0.85
|
||||
|
||||
@@ -62,11 +62,6 @@ id = "mini-swe-agent-plus"
|
||||
name = "swe-bench-verified-quick"
|
||||
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
seed = 42
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
|
||||
|
||||
@@ -46,10 +46,6 @@ id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
|
||||
[inference.parallel]
|
||||
tp = 4
|
||||
dp = 2
|
||||
|
||||
@@ -58,10 +58,5 @@ interval = 25
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2025"
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
seed = 42
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -59,10 +59,5 @@ id = "mini-swe-agent-plus"
|
||||
name = "swe-bench-verified-quick"
|
||||
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
seed = 42
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -40,8 +40,9 @@ name = "qwen3-4b-wiki-search"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[orchestrator.buffer]
|
||||
online_difficulty_filtering = true
|
||||
[[orchestrator.pre_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
enforce = true
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wiki-search"
|
||||
|
||||
@@ -7,12 +7,7 @@ requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"pydantic>=1.10.13",
|
||||
"prime-pydantic-config>=0.3.0.dev82",
|
||||
# OrchestratorConfig validates renderer.name='auto' against
|
||||
# renderers.base.MODEL_RENDERER_MAP. Renderers itself is light; its only
|
||||
# weighty transitive (transformers) is lazy-imported via the validator,
|
||||
# so plain `from prime_rl.configs.orchestrator import OrchestratorConfig`
|
||||
# still doesn't pull it into sys.modules.
|
||||
"renderers>=0.1.8.dev4",
|
||||
"renderers>=0.1.8.dev28",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
]
|
||||
|
||||
@@ -5,7 +5,7 @@ from typing import Annotated, Any, Literal, TypeAlias
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
from prime_rl.configs.shared import BaseModelConfig, SlurmConfig
|
||||
from prime_rl.configs.shared import BaseModelConfig, LogConfig, SlurmConfig
|
||||
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
|
||||
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
|
||||
|
||||
@@ -86,9 +86,71 @@ class WeightBroadcastConfig(BaseConfig):
|
||||
"""Weight broadcast transport."""
|
||||
|
||||
|
||||
class KVCacheOffloadConfig(BaseConfig):
|
||||
cpu_bytes: int = Field(1_000_000_000, gt=0)
|
||||
"""CPU bytes available for KV cache offloading per worker."""
|
||||
class CPUOffloadTier(BaseConfig):
|
||||
num_bytes: int = Field(..., gt=0)
|
||||
"""CPU/DRAM offload capacity. For the ``native`` backend this is vLLM's aggregate ``cpu_bytes_to_use`` (scaled across workers internally). For the ``mooncake`` backend this is the per-node store client's DRAM segment (``-global_segment_size``)."""
|
||||
|
||||
|
||||
class DiskOffloadTier(BaseConfig):
|
||||
path: Path
|
||||
"""Filesystem root for the disk tier. For ``native`` this is the ``fs_python`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
|
||||
|
||||
|
||||
class BaseKVCacheOffloadConfig(BaseConfig):
|
||||
cpu: CPUOffloadTier | None = None
|
||||
"""CPU/DRAM offload tier. Always required — disk-only offload is not supported."""
|
||||
|
||||
disk: DiskOffloadTier | None = None
|
||||
"""Optional disk tier, layered behind the CPU tier (GPU → DRAM → disk)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def valid_tiers(self):
|
||||
# Both backends support only two shapes: cpu-only or cpu+disk. Native disk
|
||||
# tiering needs a CPU primary tier; Mooncake standalone-store needs a DRAM
|
||||
# staging tier. Disk-only is rejected for both.
|
||||
if self.cpu is None:
|
||||
raise ValueError("inference.kv_cache_offload requires a cpu tier (disk-only offload is not supported).")
|
||||
return self
|
||||
|
||||
|
||||
class NativeKVCacheOffloadConfig(BaseKVCacheOffloadConfig):
|
||||
type: Literal["native"] = "native"
|
||||
"""vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs_python`` disk secondary). Fully self-contained — no external processes."""
|
||||
|
||||
def to_connector_dict(self) -> dict[str, Any]:
|
||||
assert self.cpu is not None
|
||||
extra: dict[str, Any] = {"cpu_bytes_to_use": int(self.cpu.num_bytes)}
|
||||
if self.disk is not None:
|
||||
extra["spec_name"] = "TieringOffloadingSpec"
|
||||
extra["secondary_tiers"] = [{"type": "fs_python", "root_dir": str(self.disk.path)}]
|
||||
return {
|
||||
"kv_connector": "OffloadingConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": extra,
|
||||
}
|
||||
|
||||
|
||||
class MooncakeKVCacheOffloadConfig(BaseKVCacheOffloadConfig):
|
||||
type: Literal["mooncake"] = "mooncake"
|
||||
"""Mooncake distributed store offloading (SLURM only). One ``mooncake_master`` + metadata server runs on the head inference node; every node runs a ``mooncake_client`` contributing its segment to the single shared pool, so prefixes cached on any node are reusable by all. The cpu tier sizes each node's DRAM segment; the optional disk tier adds an SSD tier."""
|
||||
|
||||
device_name: str = ""
|
||||
"""RDMA device name(s) for the store (empty = auto-detect)."""
|
||||
|
||||
def to_connector_dict(self) -> dict[str, Any]:
|
||||
# Addresses/sizes/tiers are realized by the per-node store launch in the sbatch
|
||||
# template (MOONCAKE_CONFIG_PATH JSON); blocks are keyed by model + parallel rank +
|
||||
# content hash (no instance id), so the shared pool is reused across nodes/replicas.
|
||||
return {
|
||||
"kv_connector": "MooncakeStoreConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {},
|
||||
}
|
||||
|
||||
|
||||
KVCacheOffloadConfig: TypeAlias = Annotated[
|
||||
NativeKVCacheOffloadConfig | MooncakeKVCacheOffloadConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
# Valid vLLM max_lora_rank values (from vllm/config/lora.py)
|
||||
@@ -105,10 +167,33 @@ All2AllBackend = Literal[
|
||||
]
|
||||
|
||||
|
||||
class VllmRouterConfig(BaseConfig):
|
||||
"""PrimeIntellect vllm-router fronting the per-rank (external-LB) endpoints."""
|
||||
|
||||
type: Literal["vllm-router"] = "vllm-router"
|
||||
|
||||
port: int = 8000
|
||||
"""Port the router listens on — becomes the client-facing router URL."""
|
||||
|
||||
policy: str = "consistent_hash"
|
||||
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
|
||||
|
||||
|
||||
# Discriminated on ``type`` so additional router backends can be added to the
|
||||
# union (a single member needs no discriminator yet).
|
||||
RouterConfig: TypeAlias = VllmRouterConfig
|
||||
|
||||
|
||||
class BaseInferenceDeploymentConfig(BaseConfig):
|
||||
gpus_per_node: int = 8
|
||||
"""GPUs per node."""
|
||||
|
||||
backend_port: int = 8100
|
||||
"""Port for the per-rank vLLM backend instances."""
|
||||
|
||||
router: RouterConfig = VllmRouterConfig()
|
||||
"""Router fronting the per-rank endpoints."""
|
||||
|
||||
|
||||
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
type: Literal["single_node"] = "single_node"
|
||||
@@ -121,15 +206,6 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
num_nodes: int = Field(2, ge=1)
|
||||
"""Inference nodes."""
|
||||
|
||||
router_port: int = 8000
|
||||
"""Port for the vllm-router."""
|
||||
|
||||
backend_port: int = 8100
|
||||
"""Port for vLLM backend instances."""
|
||||
|
||||
router_policy: str = "consistent_hash"
|
||||
"""vllm-router routing policy (e.g. ``consistent_hash``, ``round_robin``)."""
|
||||
|
||||
|
||||
# Disaggregated prefill/decode inference. Each replica is split into separate
|
||||
# prefill and decode node groups. Requires NIXL for KV transfer and a vllm-router
|
||||
@@ -152,18 +228,12 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
num_decode_replicas: int = Field(1, ge=1)
|
||||
"""Independent decode vLLM instances. Must evenly divide ``num_decode_nodes``."""
|
||||
|
||||
router_port: int = 8000
|
||||
"""Port for the vllm-router on each replica."""
|
||||
|
||||
prefill_port: int = 8100
|
||||
"""Port for prefill vLLM instances."""
|
||||
|
||||
decode_port: int = 8200
|
||||
"""Port for decode vLLM instances."""
|
||||
|
||||
router_policy: str = "consistent_hash"
|
||||
"""vllm-router routing policy (e.g. ``consistent_hash``, ``round_robin``)."""
|
||||
|
||||
prefill_env_overrides: dict[str, str] = {}
|
||||
"""Extra environment variables exported only on prefill nodes."""
|
||||
|
||||
@@ -207,6 +277,9 @@ class InferenceConfig(BaseConfig):
|
||||
parallel: ParallelConfig = ParallelConfig()
|
||||
"""Multi-node and multi-GPU parallelism (TP, DP, PP)."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
"""Logging configuration."""
|
||||
|
||||
enable_lora: bool = False
|
||||
"""Enable LoRA. Forwarded as ``--enable-lora``."""
|
||||
|
||||
@@ -256,17 +329,20 @@ class InferenceConfig(BaseConfig):
|
||||
"""Enable dual batch overlap (DBO). Forwarded as ``--enable-dbo``."""
|
||||
|
||||
use_deep_gemm: bool = False
|
||||
"""Force DeepGEMM FP8 kernels via ``VLLM_USE_DEEP_GEMM=1``. Only works with per-tensor FP8 quantization (e.g. GLM-5-FP8)."""
|
||||
"""Enable vLLM DeepGEMM FP8 kernels ``VLLM_USE_DEEP_GEMM=1``. Only works with block-wise FP8 quantization (e.g. GLM-5-FP8)."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig = WeightBroadcastConfig()
|
||||
|
||||
kv_cache_offload: KVCacheOffloadConfig | None = None
|
||||
"""CPU KV cache offload for inference workers. Standard inference uses vLLM's ``OffloadingConnector``. Disaggregated P/D deployments combine it with NIXL through ``MultiConnector`` in the SLURM launcher."""
|
||||
"""KV cache offload for inference workers, as composable CPU/disk tiers. Discriminated on ``type``: ``native`` (vLLM ``OffloadingConnector``/``TieringOffloadingSpec``, self-contained) or ``mooncake`` (per-node Mooncake distributed store). Disaggregated P/D combines the chosen connector with NIXL through ``MultiConnector``."""
|
||||
|
||||
use_pd_kv_transfer: bool = False
|
||||
"""Auto-set for disaggregated P/D: emit the NIXL transfer connector. Persisted into the per-node config (which drops ``deployment``) so the connector is still built per worker. Not meant to be set by hand."""
|
||||
|
||||
enable_return_routed_experts: bool = False
|
||||
"""Return routed experts in responses. Forwarded as ``--enable-return-routed-experts``."""
|
||||
|
||||
enable_fp32_lm_head: bool = False
|
||||
enable_fp32_lm_head: bool = True
|
||||
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
|
||||
|
||||
vllm_extra: dict[str, Any] = {}
|
||||
@@ -289,8 +365,8 @@ class InferenceConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_multi_node_requires_slurm(self):
|
||||
if self.deployment.type == "multi_node" and self.slurm is None:
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
if self.deployment.type in ("multi_node", "disaggregated") and self.slurm is None:
|
||||
raise ValueError("Must use SLURM for multi-node / disaggregated deployment.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -307,6 +383,7 @@ class InferenceConfig(BaseConfig):
|
||||
def auto_setup_disaggregated(self):
|
||||
"""Auto-configure inference for disaggregated P/D: enable EP and compute DP."""
|
||||
if self.deployment.type == "disaggregated":
|
||||
self.use_pd_kv_transfer = True
|
||||
if "enable_expert_parallel" not in self.model_fields_set:
|
||||
self.enable_expert_parallel = True
|
||||
if "enable_eplb" not in self.model_fields_set:
|
||||
@@ -368,6 +445,35 @@ class InferenceConfig(BaseConfig):
|
||||
self.api_server_count = 1 # LoRA requires only one API server
|
||||
return self
|
||||
|
||||
def build_kv_transfer_config(self) -> dict[str, Any] | None:
|
||||
"""Build the single vLLM ``kv_transfer_config`` from the transfer + offload connectors.
|
||||
|
||||
Disaggregated P/D always uses NIXL for prefill→decode transfer. KV cache offload (if
|
||||
configured) contributes its own connector. When both are present they are composed via
|
||||
``MultiConnector``. Returns None when neither applies.
|
||||
"""
|
||||
connectors: list[dict[str, Any]] = []
|
||||
if self.use_pd_kv_transfer:
|
||||
connectors.append(
|
||||
{
|
||||
"kv_connector": "NixlConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {"num_threads": 1},
|
||||
}
|
||||
)
|
||||
if self.kv_cache_offload is not None:
|
||||
connectors.append(self.kv_cache_offload.to_connector_dict())
|
||||
|
||||
if not connectors:
|
||||
return None
|
||||
if len(connectors) == 1:
|
||||
return connectors[0]
|
||||
return {
|
||||
"kv_connector": "MultiConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {"connectors": connectors},
|
||||
}
|
||||
|
||||
def to_vllm(self) -> Namespace:
|
||||
"""Convert InferenceConfig to vLLM-compatible Namespace."""
|
||||
namespace = Namespace()
|
||||
@@ -411,18 +517,9 @@ class InferenceConfig(BaseConfig):
|
||||
# Set `logprobs_mode` to `processed_logprobs` by default
|
||||
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
|
||||
|
||||
if self.kv_cache_offload is not None:
|
||||
rsetattr(
|
||||
namespace,
|
||||
"kv_transfer_config",
|
||||
{
|
||||
"kv_connector": "OffloadingConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {
|
||||
"cpu_bytes_to_use": int(self.kv_cache_offload.cpu_bytes),
|
||||
},
|
||||
},
|
||||
)
|
||||
kv_transfer_config = self.build_kv_transfer_config()
|
||||
if kv_transfer_config is not None:
|
||||
rsetattr(namespace, "kv_transfer_config", kv_transfer_config)
|
||||
|
||||
# Pass prime-rl-specific flags through vLLM's additional_config dict;
|
||||
# workers read these via get_current_vllm_config().additional_config.
|
||||
|
||||
@@ -3,7 +3,9 @@ import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import AliasChoices, Field, model_validator
|
||||
from pydantic import AliasChoices, Field, model_serializer, model_validator
|
||||
from pydantic_core.core_schema import SerializerFunctionWrapHandler
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
@@ -12,7 +14,6 @@ from prime_rl.configs.shared import (
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
PrimeMonitorConfig,
|
||||
RendererConfig,
|
||||
TransportConfig,
|
||||
WandbWithExtrasConfig,
|
||||
)
|
||||
@@ -45,20 +46,11 @@ class TrainSamplingConfig(BaseConfig):
|
||||
temperature: float = Field(1.0, ge=0)
|
||||
"""Sampling temperature."""
|
||||
|
||||
repetition_penalty: float = Field(1.0, ge=0)
|
||||
"""Repetition penalty. Values > 1.0 discourage repetition, < 1.0 encourage it, 1.0 disables."""
|
||||
|
||||
max_completion_tokens: int | None = Field(
|
||||
None, validation_alias=AliasChoices("max_completion_tokens", "max_tokens")
|
||||
)
|
||||
"""Maximum output tokens per turn. If None, generates until max context length or EOS."""
|
||||
|
||||
min_tokens: int = Field(0, ge=0)
|
||||
"""Minimum output tokens per sequence."""
|
||||
|
||||
seed: int | None = None
|
||||
"""Random seed for sampling. If None, no seeding is used."""
|
||||
|
||||
# Strictly speaking, extra_body is not a sampling parameter, but it is the
|
||||
# easiest way to pass arbitrary extra parameters to the server via verifiers
|
||||
extra_body: dict[str, Any] = {}
|
||||
@@ -66,7 +58,6 @@ class TrainSamplingConfig(BaseConfig):
|
||||
|
||||
def to_sampling_args(self) -> dict[str, Any]:
|
||||
"""Convert to OAI-compatible sampling args dict, omitting None values."""
|
||||
# Top-level OAI params
|
||||
args: dict[str, Any] = {
|
||||
"temperature": self.temperature,
|
||||
"top_p": 1.0,
|
||||
@@ -74,17 +65,9 @@ class TrainSamplingConfig(BaseConfig):
|
||||
}
|
||||
if self.max_completion_tokens is not None:
|
||||
args["max_completion_tokens"] = self.max_completion_tokens
|
||||
if self.seed is not None:
|
||||
args["seed"] = self.seed
|
||||
|
||||
# vLLM extra_body params
|
||||
extra_body = dict(self.extra_body)
|
||||
if self.min_tokens > 0:
|
||||
extra_body["min_tokens"] = self.min_tokens
|
||||
if self.repetition_penalty != 1.0:
|
||||
extra_body["repetition_penalty"] = self.repetition_penalty
|
||||
if extra_body:
|
||||
args["extra_body"] = extra_body
|
||||
if self.extra_body:
|
||||
args["extra_body"] = dict(self.extra_body)
|
||||
|
||||
return args
|
||||
|
||||
@@ -105,9 +88,6 @@ class EvalSamplingConfig(BaseConfig):
|
||||
temperature: float | None = Field(None, ge=0)
|
||||
"""Sampling temperature. None defers to the inference server default."""
|
||||
|
||||
repetition_penalty: float | None = Field(None, ge=0)
|
||||
"""Repetition penalty. None defers to the inference server default."""
|
||||
|
||||
top_p: float | None = None
|
||||
"""Nucleus sampling threshold. None defers to the inference server default."""
|
||||
|
||||
@@ -122,15 +102,9 @@ class EvalSamplingConfig(BaseConfig):
|
||||
)
|
||||
"""Maximum output tokens per turn. None defers to the inference server default."""
|
||||
|
||||
min_tokens: int | None = Field(None, ge=0)
|
||||
"""Minimum output tokens per sequence. None defers to the inference server default."""
|
||||
|
||||
reasoning_effort: Literal["minimal", "low", "medium", "high"] | None = None
|
||||
"""Reasoning effort constraint for reasoning models."""
|
||||
|
||||
seed: int | None = None
|
||||
"""Random seed for sampling. None means no seeding."""
|
||||
|
||||
extra_body: dict[str, Any] = {}
|
||||
"""Extra body parameters forwarded to the inference server."""
|
||||
|
||||
@@ -145,18 +119,12 @@ class EvalSamplingConfig(BaseConfig):
|
||||
args["max_completion_tokens"] = self.max_completion_tokens
|
||||
if self.reasoning_effort is not None:
|
||||
args["reasoning_effort"] = self.reasoning_effort
|
||||
if self.seed is not None:
|
||||
args["seed"] = self.seed
|
||||
|
||||
extra_body = dict(self.extra_body)
|
||||
if self.top_k is not None:
|
||||
extra_body["top_k"] = self.top_k
|
||||
if self.min_p is not None:
|
||||
extra_body["min_p"] = self.min_p
|
||||
if self.min_tokens is not None:
|
||||
extra_body["min_tokens"] = self.min_tokens
|
||||
if self.repetition_penalty is not None:
|
||||
extra_body["repetition_penalty"] = self.repetition_penalty
|
||||
if extra_body:
|
||||
args["extra_body"] = extra_body
|
||||
|
||||
@@ -175,6 +143,49 @@ class EvalSamplingConfig(BaseConfig):
|
||||
return data
|
||||
|
||||
|
||||
class TokensLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["tokens"] = "tokens"
|
||||
|
||||
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on model completion tokens. Finite and non-negative."""
|
||||
|
||||
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
|
||||
|
||||
|
||||
class TurnsLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["turns"] = "turns"
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = Annotated[
|
||||
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class DefaultAdvantageConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
length_penalty: LengthPenaltyConfig | None = None
|
||||
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
import_path: str
|
||||
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
|
||||
|
||||
kwargs: dict[str, Any] = Field(default_factory=dict)
|
||||
"""Kwargs forwarded to the advantage function."""
|
||||
|
||||
|
||||
AdvantageConfig: TypeAlias = Annotated[
|
||||
DefaultAdvantageConfig | CustomAdvantageConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class EnvConfig(BaseConfig):
|
||||
id: str = "reverse-text"
|
||||
"""Registered verifiers environment ID (e.g. ``math-env``, ``primeintellect/math-env``). May include an ``@version`` suffix for installation."""
|
||||
@@ -242,6 +253,15 @@ class TrainEnvConfig(EnvConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
|
||||
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
|
||||
"""Rollouts generated per example for GRPO group-relative advantages.
|
||||
Inherits from ``orchestrator.group_size`` when unset."""
|
||||
|
||||
advantage: AdvantageConfig | None = None
|
||||
"""Advantage strategy for this env's GRPO groups. Inherits from the top-level
|
||||
``orchestrator.advantage`` when unset; set a different ``default``/``custom``
|
||||
config to give this env its own advantage computation."""
|
||||
|
||||
|
||||
class EvalEnvConfig(EnvConfig):
|
||||
sampling: EvalSamplingConfig = EvalSamplingConfig()
|
||||
@@ -328,6 +348,10 @@ class EvalConfig(BaseConfig):
|
||||
interval: int = Field(100, ge=1)
|
||||
"""Step interval at which to evaluate the model."""
|
||||
|
||||
skip_first_step: bool = False
|
||||
"""If True, skip the startup eval that otherwise runs before any
|
||||
train rollouts."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_workers, max_retries, num_examples, group_size, and interval. Then resolve auto num_workers."""
|
||||
@@ -357,6 +381,16 @@ class EvalConfig(BaseConfig):
|
||||
env.num_workers = max(1, math.ceil(max_concurrent / 256))
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_non_empty_envs(self):
|
||||
if not self.env:
|
||||
raise ValueError(
|
||||
"EvalConfig must define at least one env. Either drop the "
|
||||
"[orchestrator.eval] block entirely (to disable eval) or "
|
||||
"add a [[orchestrator.eval.env]] block."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_env_names(self):
|
||||
env_names = [env.resolved_name for env in self.env]
|
||||
@@ -367,17 +401,6 @@ class EvalConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
eval_base_model: bool = True
|
||||
"""Evaluate the base model we are training on."""
|
||||
|
||||
skip_eval_on_resume: bool = Field(
|
||||
True, validation_alias=AliasChoices("skip_eval_on_resume", "skip_eval_on_restart")
|
||||
)
|
||||
"""When resuming the orchestrator from a checkpoint, skip the (potentially redundant) online eval that would otherwise run immediately at the resumed step."""
|
||||
|
||||
cancel_inflight_rollouts_on_eval: bool = False
|
||||
"""Cancel in-flight training rollouts before starting online evals. Avoids congestion (no training + eval rollouts at the same time) at the cost of slower training steps as the pipeline has to refill after each eval."""
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
interval: int | None = Field(None, ge=1)
|
||||
@@ -398,81 +421,6 @@ class CheckpointConfig(BaseConfig):
|
||||
skip_progress: bool = False
|
||||
"""Skip loading the progress from checkpoint."""
|
||||
|
||||
skip_buffer: bool = False
|
||||
"""Skip loading the buffer from checkpoint."""
|
||||
|
||||
|
||||
class BufferConfig(BaseConfig):
|
||||
seed: int | None = None
|
||||
"""Random seed for the buffer. When set, sampling from the buffer is deterministic."""
|
||||
|
||||
easy_threshold: float | None = None
|
||||
"""Average-reward threshold above which a problem is classified ``easy``."""
|
||||
|
||||
hard_threshold: float | None = None
|
||||
"""Average-reward threshold below which a problem is classified ``hard``."""
|
||||
|
||||
easy_fraction: float = Field(0.0, ge=0, le=1)
|
||||
"""Fraction of easy problems to convert to ``normal`` when resuming or starting training. Only problems with difficulty ``normal`` are sampled."""
|
||||
|
||||
hard_fraction: float = Field(0.0, ge=0, le=1)
|
||||
"""Fraction of hard problems to convert to ``normal`` when resuming or starting training. Only problems with difficulty ``normal`` are sampled."""
|
||||
|
||||
online_difficulty_filtering: bool = False
|
||||
"""Filter rollouts based on difficulty. When True, rollouts with average reward 0.0 or 1.0 are not added to the buffer."""
|
||||
|
||||
hash_keys: list[str] = Field(["env_name", "prompt"], min_length=1)
|
||||
"""Keys used to compute example hashes. Used to match examples from buffer checkpoints and determine buffer resume behavior."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_thresholds(self):
|
||||
if self.easy_threshold is not None and self.hard_threshold is not None:
|
||||
assert self.easy_threshold > self.hard_threshold, "easy_threshold must be greater than hard_threshold."
|
||||
return self
|
||||
|
||||
|
||||
class TokensLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["tokens"] = "tokens"
|
||||
|
||||
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on model completion tokens. Finite and non-negative."""
|
||||
|
||||
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
|
||||
|
||||
|
||||
class TurnsLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["turns"] = "turns"
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = Annotated[
|
||||
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class DefaultAdvantageConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
length_penalty: LengthPenaltyConfig | None = None
|
||||
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
import_path: str
|
||||
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
|
||||
|
||||
kwargs: dict[str, Any] = Field(default_factory=dict)
|
||||
"""Kwargs forwarded to the advantage function."""
|
||||
|
||||
|
||||
AdvantageConfig: TypeAlias = Annotated[
|
||||
DefaultAdvantageConfig | CustomAdvantageConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
# Flags rare tokens generated at high entropy (Section 5.2, https://arxiv.org/abs/2510.02387).
|
||||
class GibberishFilterConfig(BaseConfig):
|
||||
@@ -570,8 +518,30 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
renderer: RendererConfig = RendererConfig()
|
||||
"""Client-side renderer configuration. Only consumed when ``use_renderer=true``."""
|
||||
renderer: RendererConfig | None = AutoRendererConfig()
|
||||
"""Typed renderer config (``renderers.RendererConfig`` discriminated
|
||||
union). Defaults to ``"auto"``, which resolves from
|
||||
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. ``None``
|
||||
opts into MITO (``openai_chat_completions``)."""
|
||||
|
||||
pool_size: int | None = Field(None, ge=1)
|
||||
"""Number of renderer slots shared across concurrent rollouts. Bump
|
||||
for long multi-turn prompts where client-side jinja tokenization
|
||||
serializes. Only meaningful when ``renderer`` is not ``None``."""
|
||||
|
||||
@model_serializer(mode="wrap")
|
||||
def _preserve_mito_renderer(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
|
||||
"""Emit ``renderer = "None"`` (string) when MITO so
|
||||
``model_dump(exclude_none=True)`` round-trips: dumped TOML has
|
||||
``renderer = "None"``, and on reload
|
||||
``BaseConfig._none_str_to_none`` coerces it back to ``None``.
|
||||
Without this, a MITO orchestrator config saved to
|
||||
``control/orch.toml`` would lose the renderer key entirely and
|
||||
reload as the default ``AutoRendererConfig()`` (TITO)."""
|
||||
result = handler(self)
|
||||
if self.renderer is None:
|
||||
result["renderer"] = "None"
|
||||
return result
|
||||
|
||||
optim: OptimizerConfig = OptimizerConfig()
|
||||
"""Per-run optimizer configuration for multi-run training."""
|
||||
@@ -579,12 +549,25 @@ class OrchestratorConfig(BaseConfig):
|
||||
eval: EvalConfig | None = None
|
||||
"""Evaluation configuration."""
|
||||
|
||||
buffer: BufferConfig = BufferConfig()
|
||||
|
||||
advantage: AdvantageConfig | None = DefaultAdvantageConfig()
|
||||
|
||||
filters: list[FilterConfig] = [GibberishFilterConfig(), RepetitionFilterConfig(), ZeroAdvantageFilterConfig()]
|
||||
"""Rollout filters. Each filter can ``monitor`` (default) or ``enforce`` (skip rollouts)."""
|
||||
pre_batch_filters: list[FilterConfig] = [
|
||||
GibberishFilterConfig(enforce=False),
|
||||
RepetitionFilterConfig(enforce=False),
|
||||
ZeroAdvantageFilterConfig(enforce=False),
|
||||
]
|
||||
"""Filters applied *before* a rollout enters the training batch buffer.
|
||||
All three filter types are registered in monitor mode by default; flip ``enforce=true`` per type
|
||||
to drop matching rollouts before they consume a slot in the batch (e.g. a zero-advantage group
|
||||
never makes it into a training batch)."""
|
||||
|
||||
post_batch_filters: list[FilterConfig] = [
|
||||
GibberishFilterConfig(),
|
||||
RepetitionFilterConfig(),
|
||||
ZeroAdvantageFilterConfig(),
|
||||
]
|
||||
"""Filters applied *after* a batch has been assembled. Each filter annotates each rollout;
|
||||
rollouts flagged by an enforcing filter are still recorded but not shipped to the trainer."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
@@ -595,6 +578,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
collect_inference_metrics: bool = True
|
||||
"""Collect inference-server metrics (requires wandb)."""
|
||||
|
||||
inference_metrics_roles: list[Literal["prefill", "decode"]] | None = None
|
||||
"""Role for each student admin client when collecting P/D inference metrics."""
|
||||
|
||||
ckpt: CheckpointConfig | None = None
|
||||
"""Checkpoint configuration."""
|
||||
|
||||
@@ -638,24 +624,12 @@ class OrchestratorConfig(BaseConfig):
|
||||
max_off_policy_steps: int = Field(8, ge=0)
|
||||
"""Maximum policies allowed to generate a single rollout. Rollouts generated more than ``max_off_policy_steps`` ahead of training are discarded. Higher values yield better throughput at the cost of off-policy noise."""
|
||||
|
||||
max_async_level: int = Field(1, ge=0)
|
||||
"""Maximum steps inference can be ahead of training. ``0`` degenerates to synchronous on-policy RL; ``≥1`` overlaps training and inference."""
|
||||
|
||||
strict_async_level: bool = False
|
||||
"""Strictly enforce ``max_async_level``. When True, the rollout policy is always exactly ``max_async_level`` steps ahead of training. When False, any policy within ``max_async_level`` steps is allowed (always uses the latest available policy)."""
|
||||
|
||||
bench: bool = False
|
||||
"""Benchmark mode. Sets ``max_steps`` to 5, ``max_async_level`` to ~∞, and disables W&B."""
|
||||
|
||||
seed: int | None = 42
|
||||
"""Random seed for the orchestrator."""
|
||||
"""Benchmark mode. Sets ``max_steps`` to 5 and disables W&B."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
use_renderer: bool = True
|
||||
"""Use the renderer-backed TITO client (client-side tokenization via the ``renderers`` package, served by ``/v1/generate``). When True, the ``[orchestrator.renderer]`` block (name / tool_parser / reasoning_parser / pool_size) applies. Default for both text-only and VLM rollouts; VLMs require it. False falls back to MITO (``openai_chat_completions``)."""
|
||||
|
||||
env_install_prerelease: bool = False
|
||||
"""Allow pre-release versions when installing environments (e.g. ``verifiers>=0.1.12.dev5``). Passes ``--prerelease`` to ``prime env install``."""
|
||||
|
||||
@@ -775,19 +749,21 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_filter_types(self):
|
||||
types = [f.type for f in self.filters]
|
||||
if len(types) != len(set(types)):
|
||||
raise ValueError(f"Duplicate filter types: {types}. Each filter type may only appear once.")
|
||||
for slot_name in ("pre_batch_filters", "post_batch_filters"):
|
||||
types = [f.type for f in getattr(self, slot_name)]
|
||||
if len(types) != len(set(types)):
|
||||
raise ValueError(
|
||||
f"Duplicate filter types in {slot_name}: {types}. Each filter type may only appear once per slot."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _force_no_renderer_for_sft(self):
|
||||
"""SFT rolls out via the teacher's plain chat-completions endpoint; the
|
||||
renderer client doesn't apply. Force use_renderer=False so the user
|
||||
doesn't have to remember to set it. Declared before the renderer
|
||||
validators below so they see the corrected value."""
|
||||
if self.training_mode == "sft":
|
||||
self.use_renderer = False
|
||||
"""Teacher-backed SFT rolls out via the teacher's plain chat-completions
|
||||
endpoint; the renderer client doesn't apply. When no teacher is
|
||||
configured, SFT uses the student rollout path and keeps the renderer."""
|
||||
if self.training_mode == "sft" and self.teacher is not None:
|
||||
self.renderer = None
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -796,38 +772,20 @@ class OrchestratorConfig(BaseConfig):
|
||||
has_teacher = self.teacher is not None
|
||||
if self.training_mode == "rl" and has_teacher:
|
||||
raise ValueError("orchestrator.teacher must not be set when training_mode = 'rl'.")
|
||||
if self.training_mode in ("opd", "sft") and not has_teacher:
|
||||
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
|
||||
if self.training_mode == "opd" and not has_teacher:
|
||||
raise ValueError("orchestrator.teacher must be configured when training_mode = 'opd'.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_args(self):
|
||||
"""``[orchestrator.renderer]`` knobs are only meaningful when
|
||||
``use_renderer=True``. Reject otherwise so callers don't silently
|
||||
pass them and wonder why they're ignored."""
|
||||
if self.use_renderer:
|
||||
return self
|
||||
|
||||
renderer_args_set = []
|
||||
if self.renderer.name != "auto":
|
||||
renderer_args_set.append(f"renderer.name={self.renderer.name!r}")
|
||||
if self.renderer.tool_parser is not None:
|
||||
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
|
||||
if self.renderer.reasoning_parser is not None:
|
||||
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
|
||||
if self.renderer.pool_size is not None:
|
||||
renderer_args_set.append(f"renderer.pool_size={self.renderer.pool_size!r}")
|
||||
if self.renderer.preserve_all_thinking:
|
||||
renderer_args_set.append(f"renderer.preserve_all_thinking={self.renderer.preserve_all_thinking!r}")
|
||||
if self.renderer.preserve_thinking_between_tool_calls:
|
||||
renderer_args_set.append(
|
||||
f"renderer.preserve_thinking_between_tool_calls={self.renderer.preserve_thinking_between_tool_calls!r}"
|
||||
)
|
||||
|
||||
if renderer_args_set:
|
||||
def validate_pool_size(self):
|
||||
"""``pool_size`` is only meaningful when the renderer is enabled
|
||||
(``renderer is not None``). Reject otherwise so callers don't
|
||||
silently pass it and wonder why it's ignored."""
|
||||
if self.renderer is None and self.pool_size is not None:
|
||||
raise ValueError(
|
||||
"Renderer-specific args set without orchestrator.use_renderer=True: "
|
||||
f"{', '.join(renderer_args_set)}. Either enable the renderer client or remove these knobs."
|
||||
f"orchestrator.pool_size={self.pool_size!r} is set but "
|
||||
"orchestrator.renderer is None (MITO mode). Either configure a renderer "
|
||||
"or remove pool_size."
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -839,9 +797,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
tokens, and ships generic ``mm_kwargs`` keyed by whatever the
|
||||
model's forward signature expects.
|
||||
"""
|
||||
if self.student.model.vlm is not None and not self.use_renderer:
|
||||
if self.student.model.vlm is not None and self.renderer is None:
|
||||
raise ValueError(
|
||||
"orchestrator.use_renderer must be true when model.vlm is set. "
|
||||
"orchestrator.renderer must be set when model.vlm is set. "
|
||||
"VLMs must go through a renderer (e.g. Qwen3VLRenderer) that owns the processor."
|
||||
)
|
||||
return self
|
||||
@@ -850,16 +808,16 @@ class OrchestratorConfig(BaseConfig):
|
||||
def validate_renderer_auto_resolves(self):
|
||||
"""Reject the silent DefaultRenderer fallback at config time.
|
||||
|
||||
When ``use_renderer=True`` with ``renderer.name='auto'`` and the
|
||||
model isn't in ``MODEL_RENDERER_MAP``, ``create_renderer`` would
|
||||
fall back to ``DefaultRenderer``. That fallback doesn't fix the
|
||||
position-dependent chat-template bug the renderer client exists to
|
||||
solve, and rejects envs that pass tools (the rollout dies with
|
||||
"RendererPool does not support tools") unless
|
||||
``renderer.tool_parser`` is configured. Surface at config time so
|
||||
``--dry-run`` reports the error.
|
||||
When ``renderer.name='auto'`` and the model isn't in
|
||||
``MODEL_RENDERER_MAP``, ``create_renderer`` would fall back to
|
||||
``DefaultRenderer``. That fallback doesn't fix the
|
||||
position-dependent chat-template bug the renderer client exists
|
||||
to solve, and rejects envs that pass tools (the rollout dies
|
||||
with "RendererPool does not support tools") unless
|
||||
``DefaultRendererConfig.tool_parser`` is configured. Surface at
|
||||
config time so ``--dry-run`` reports the error.
|
||||
"""
|
||||
if not self.use_renderer or self.renderer.name != "auto":
|
||||
if self.renderer is None or self.renderer.name != "auto":
|
||||
return self
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
@@ -867,28 +825,21 @@ class OrchestratorConfig(BaseConfig):
|
||||
if model_id in MODEL_RENDERER_MAP:
|
||||
return self
|
||||
raise ValueError(
|
||||
f"orchestrator.use_renderer=True with renderer.name='auto' but "
|
||||
f"orchestrator.renderer.name='auto' but "
|
||||
f"{model_id!r} is not in renderers.base.MODEL_RENDERER_MAP, so it "
|
||||
f"would silently fall back to DefaultRenderer. Pick one: "
|
||||
f"(a) [orchestrator.renderer] name='default' — for fine-tunes / "
|
||||
f"vendored mirrors with custom chat templates (DefaultRenderer "
|
||||
f"calls apply_chat_template); pair with tool_parser=<name> if "
|
||||
f"the env uses tools. "
|
||||
f"calls apply_chat_template); set tool_parser=<name> if the env "
|
||||
f"uses tools. "
|
||||
f"(b) [orchestrator.renderer] name=<model-specific renderer> — "
|
||||
f"if {model_id!r} is template-identical to a mapped family "
|
||||
f"(and ideally also add it upstream to "
|
||||
f"renderers.base.MODEL_RENDERER_MAP). "
|
||||
f"(c) orchestrator.use_renderer=false — opt out of the renderer "
|
||||
f"client entirely."
|
||||
f"(c) orchestrator.renderer='none' — opt out of the renderer "
|
||||
f"client entirely (MITO)."
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def nccl_max_async_level(self):
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
if not self.max_async_level == 1:
|
||||
raise ValueError("max_async_level must be 1 for NCCL broadcast")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_batching(self):
|
||||
has_rollout_batch = self.batch_size is not None
|
||||
@@ -924,6 +875,16 @@ class OrchestratorConfig(BaseConfig):
|
||||
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.group_size:
|
||||
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
|
||||
|
||||
# Propagate the top-level ``group_size`` into each train env that didn't set its own.
|
||||
for env_cfg in self.train.env:
|
||||
if "group_size" not in env_cfg.model_fields_set:
|
||||
env_cfg.group_size = self.group_size
|
||||
|
||||
# Propagate the top-level ``advantage`` into each train env that didn't set its own.
|
||||
for env_cfg in self.train.env:
|
||||
if "advantage" not in env_cfg.model_fields_set:
|
||||
env_cfg.advantage = self.advantage
|
||||
|
||||
# Resolve train env num_workers from max_inflight_rollouts
|
||||
for env_cfg in self.train.env:
|
||||
if env_cfg.num_workers == "auto":
|
||||
@@ -936,7 +897,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
def auto_setup_bench(self):
|
||||
if self.bench:
|
||||
self.max_steps = 4 # Run for 1 warmup step + 3 evaluation steps
|
||||
self.max_async_level = int(1e9) # Never wait for RL weight checkpoints
|
||||
|
||||
# Disable evaluation
|
||||
self.eval = None
|
||||
|
||||
@@ -35,7 +35,6 @@ from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
from prime_rl.utils.validation import (
|
||||
propagate_shared_fields,
|
||||
validate_shared_ckpt_config,
|
||||
validate_shared_max_async_level,
|
||||
validate_shared_max_steps,
|
||||
validate_shared_model_name,
|
||||
validate_shared_output_dir,
|
||||
@@ -52,10 +51,10 @@ class RLExperimentalConfig(BaseConfig):
|
||||
|
||||
class SharedLogConfig(BaseConfig):
|
||||
level: str | None = None
|
||||
"""Log level for trainer and orchestrator. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
|
||||
"""Log level for trainer, orchestrator, and inference. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
|
||||
|
||||
json_logging: bool = False
|
||||
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.)."""
|
||||
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.). Propagated to trainer, orchestrator, and inference."""
|
||||
|
||||
|
||||
class SharedWandbConfig(BaseConfig):
|
||||
@@ -75,15 +74,17 @@ class SharedWandbConfig(BaseConfig):
|
||||
"""W&B tags attached to the run."""
|
||||
|
||||
offline: bool | None = False
|
||||
"""Run W&B in offline mode."""
|
||||
|
||||
shared: bool = True
|
||||
"""Log trainer and orchestrator metrics to a single shared W&B run. Requires wandb SDK ≥ 0.19.9. Incompatible with offline mode."""
|
||||
"""Run W&B in offline mode. Incompatible with shared mode, which is always on for the ``rl`` entrypoint."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_shared_not_offline(self):
|
||||
if self.shared and self.offline:
|
||||
raise ValueError("W&B shared mode requires server connectivity and is incompatible with offline mode")
|
||||
def validate_not_offline(self):
|
||||
if self.offline:
|
||||
raise ValueError(
|
||||
"W&B shared mode is always on for the rl entrypoint and requires server "
|
||||
"connectivity; wandb.offline = true is not supported. Use offline mode "
|
||||
"via the sub-config wandb blocks (trainer.wandb.offline, "
|
||||
"orchestrator.wandb.offline) if you really need it per-process."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
@@ -140,16 +141,13 @@ class SingleNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
num_infer_gpus: int = 1
|
||||
"""GPUs allocated to inference."""
|
||||
|
||||
num_teacher_gpus: int | None = None
|
||||
"""GPUs allocated to teacher inference (None disables the teacher server)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_gpu_count(self):
|
||||
total = self.num_train_gpus + self.num_infer_gpus + (self.num_teacher_gpus or 0)
|
||||
total = self.num_train_gpus + self.num_infer_gpus
|
||||
if total > self.gpus_per_node:
|
||||
raise ValueError(
|
||||
f"Total GPU count ({total} = {self.num_train_gpus} train + {self.num_infer_gpus} infer"
|
||||
f" + {self.num_teacher_gpus or 0} teacher) exceeds gpus_per_node ({self.gpus_per_node})."
|
||||
f"Total GPU count ({total} = {self.num_train_gpus} train + {self.num_infer_gpus} infer)"
|
||||
f" exceeds gpus_per_node ({self.gpus_per_node})."
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -166,9 +164,6 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
num_infer_replicas: int = Field(1, ge=1)
|
||||
"""Independent inference replicas. Total inference nodes = ``num_infer_nodes * num_infer_replicas``."""
|
||||
|
||||
num_teacher_nodes: int | None = None
|
||||
"""Teacher inference nodes."""
|
||||
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Training nodes per FSDP island. Auto-sets ``trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
|
||||
@@ -176,12 +171,6 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
def total_infer_nodes(self) -> int:
|
||||
return self.num_infer_nodes * self.num_infer_replicas
|
||||
|
||||
@model_validator(mode="after")
|
||||
def teacher_inference_not_supported(self):
|
||||
if self.num_teacher_nodes is not None:
|
||||
raise ValueError("Teacher inference is not yet supported in multi node deployment.")
|
||||
return self
|
||||
|
||||
|
||||
DeploymentConfig: TypeAlias = Annotated[
|
||||
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
|
||||
@@ -196,9 +185,6 @@ class RLConfig(BaseConfig):
|
||||
inference: InferenceConfig | None = None
|
||||
"""Inference server configuration. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."""
|
||||
|
||||
teacher_inference: InferenceConfig | None = None
|
||||
"""Teacher inference server configuration. If None, falls back to the same config as ``inference`` (or a default). Only used when teacher GPUs/nodes are set."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Output directory. Should be unique per experiment."""
|
||||
|
||||
@@ -228,9 +214,6 @@ class RLConfig(BaseConfig):
|
||||
seq_len: int | None = None
|
||||
"""Shared sequence length. Propagates to ``trainer.model.seq_len`` and ``orchestrator.seq_len`` only when those values were not explicitly set; explicit per-component values always win."""
|
||||
|
||||
max_async_level: int | None = None
|
||||
"""Shared async level. If None, falls back to the sub-config ``max_async_level``."""
|
||||
|
||||
weight_broadcast: SharedWeightBroadcastConfig | None = None
|
||||
|
||||
bench: bool = False
|
||||
@@ -248,27 +231,6 @@ class RLConfig(BaseConfig):
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _stub_orchestrator_teacher_for_auto_setup(cls, data):
|
||||
"""When `deployment.num_teacher_gpus > 0` and the user didn't write an
|
||||
`[orchestrator.teacher]` block, inject an empty one so
|
||||
`OrchestratorConfig.validate_training_mode` (which fires during nested
|
||||
validation) doesn't reject `training_mode = "opd"` for "missing teacher".
|
||||
`auto_setup_teacher_inference` (after) then fills in client.base_url and
|
||||
model.name from the auto-launched teacher_inference server."""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
deployment = data.get("deployment")
|
||||
if not isinstance(deployment, dict):
|
||||
return data
|
||||
if not deployment.get("num_teacher_gpus"):
|
||||
return data
|
||||
orch = data.setdefault("orchestrator", {})
|
||||
if isinstance(orch, dict) and "teacher" not in orch and "teacher_model" not in orch:
|
||||
orch["teacher"] = {}
|
||||
return data
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_deployment(self):
|
||||
if self.deployment.type == "multi_node":
|
||||
@@ -288,16 +250,6 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
# TODO: fix this
|
||||
@model_validator(mode="after")
|
||||
def validate_no_teacher_in_multinode(self):
|
||||
if self.deployment.type == "multi_node" and self.teacher_inference is not None:
|
||||
raise ValueError(
|
||||
"Teacher inference is not supported in multi-node deployment. "
|
||||
"The SLURM template only handles inference and training nodes."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_enough_devices_for_nccl(self):
|
||||
if self.deployment.type == "single_node":
|
||||
@@ -344,7 +296,6 @@ class RLConfig(BaseConfig):
|
||||
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
|
||||
validate_shared_tokenizer(self.trainer, self.orchestrator, self.inference)
|
||||
validate_shared_max_steps(self.trainer, self.orchestrator)
|
||||
validate_shared_max_async_level(self.trainer, self.orchestrator)
|
||||
validate_shared_seq_len(self.trainer, self.orchestrator)
|
||||
validate_shared_ckpt_config(self.trainer, self.orchestrator)
|
||||
validate_shared_wandb_config(self.trainer, self.orchestrator)
|
||||
@@ -497,6 +448,20 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_mooncake_offload_requires_slurm(self):
|
||||
if (
|
||||
self.slurm is None
|
||||
and self.inference is not None
|
||||
and self.inference.kv_cache_offload is not None
|
||||
and self.inference.kv_cache_offload.type == "mooncake"
|
||||
):
|
||||
raise ValueError(
|
||||
"Mooncake KV offload requires SLURM — the per-node store is launched by the sbatch "
|
||||
"template. Use inference.kv_cache_offload.type='native' for local runs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_deployment(self):
|
||||
if self.deployment.type == "single_node": # single-node
|
||||
@@ -583,11 +548,14 @@ class RLConfig(BaseConfig):
|
||||
self.inference.api_server_count = dp_per_node
|
||||
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
|
||||
# Compute inference_world_size from actual worker count per server:
|
||||
# each api_server runs tp workers that participate in collective_rpc.
|
||||
api_server_count = self.inference.api_server_count if self.inference else 1
|
||||
tp = self.inference.parallel.tp if self.inference else 1
|
||||
total_infer_workers = self.deployment.total_infer_nodes * api_server_count * tp
|
||||
# Every allocated inference GPU is a NCCL rank in the weight broadcast.
|
||||
# The external-LB launcher starts dp_per_node (= gpus_per_node / tp)
|
||||
# TP-sharded servers per node, i.e. gpus_per_node workers per node, so use
|
||||
# the GPU count directly. Deriving it from api_server_count double-counts:
|
||||
# api_server_count can resolve to the *global* DP size, making the node
|
||||
# factor count twice and NCCL wait for ranks that never connect. Matches
|
||||
# the disaggregated path below.
|
||||
total_infer_workers = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
|
||||
assert self.trainer.weight_broadcast.type == "nccl"
|
||||
self.trainer.weight_broadcast.host = "0.0.0.0"
|
||||
self.trainer.weight_broadcast.inference_world_size = total_infer_workers
|
||||
@@ -614,6 +582,15 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
|
||||
total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
|
||||
if "inference_metrics_roles" not in self.orchestrator.model_fields_set:
|
||||
# External-LB: one admin client per DP rank, so roles expand per rank
|
||||
# (stride = dp_local = gpus_per_node / tp). ADMIN_URLS lists all prefill
|
||||
# ranks, then all decode ranks, per replica — match that order.
|
||||
stride = self.deployment.gpus_per_node // self.inference.parallel.tp
|
||||
role_order = ["prefill"] * (infer_deploy.num_prefill_nodes * stride) + ["decode"] * (
|
||||
infer_deploy.num_decode_nodes * stride
|
||||
)
|
||||
self.orchestrator.inference_metrics_roles = role_order * self.deployment.num_infer_replicas
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
|
||||
assert self.trainer.weight_broadcast.type == "nccl"
|
||||
self.trainer.weight_broadcast.inference_world_size = total_infer_gpus
|
||||
@@ -642,47 +619,6 @@ class RLConfig(BaseConfig):
|
||||
client.base_url = [f"http://{host}:{port}/v1"]
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_teacher_inference(self):
|
||||
"""Auto-configure teacher inference server and orchestrator teacher_model client."""
|
||||
if self.deployment.type != "single_node":
|
||||
return self
|
||||
if self.deployment.num_teacher_gpus is None or self.deployment.num_teacher_gpus == 0:
|
||||
return self
|
||||
|
||||
import copy
|
||||
|
||||
from prime_rl.configs.orchestrator import RolloutModelConfig
|
||||
|
||||
if self.teacher_inference is None:
|
||||
if self.inference is None:
|
||||
self.teacher_inference = InferenceConfig()
|
||||
else:
|
||||
self.teacher_inference = copy.deepcopy(self.inference)
|
||||
self.teacher_inference.server.port = (self.inference.server.port if self.inference else 8000) + 1
|
||||
elif self.inference is not None and self.teacher_inference.server.port == self.inference.server.port:
|
||||
raise ValueError(
|
||||
f"teacher_inference.server.port ({self.teacher_inference.server.port}) conflicts with "
|
||||
f"inference.server.port ({self.inference.server.port}). "
|
||||
"Either use different ports or let teacher_inference be auto-configured."
|
||||
)
|
||||
|
||||
tp = self.teacher_inference.parallel.tp
|
||||
num_teacher_gpus = self.deployment.num_teacher_gpus
|
||||
if num_teacher_gpus != self.teacher_inference.parallel.dp * tp:
|
||||
assert num_teacher_gpus % tp == 0, "Number of teacher GPUs must be divisible by tensor parallel size"
|
||||
assert num_teacher_gpus > 0, "num_teacher_gpus cannot be zero"
|
||||
self.teacher_inference.parallel.dp = num_teacher_gpus // tp
|
||||
|
||||
if self.orchestrator.teacher is None:
|
||||
self.orchestrator.teacher = RolloutModelConfig()
|
||||
host = self.teacher_inference.server.host or "localhost"
|
||||
port = self.teacher_inference.server.port
|
||||
self.orchestrator.teacher.client.base_url = [f"http://{host}:{port}/v1"]
|
||||
self.orchestrator.teacher.model.name = self.teacher_inference.model.name
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_slurm_template(self):
|
||||
"""Auto-setup the default single-node/multi-node SLURM template if no custom template is provided."""
|
||||
|
||||
@@ -3,10 +3,10 @@ from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from renderers import RendererConfig
|
||||
|
||||
from prime_rl.configs.shared import (
|
||||
HeartbeatConfig,
|
||||
RendererConfig,
|
||||
SlurmConfig,
|
||||
TrainerLogConfig,
|
||||
WandbConfig,
|
||||
@@ -175,11 +175,13 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
renderer: RendererConfig = RendererConfig()
|
||||
"""Client-side renderer configuration. Only consumed when ``use_renderer=true``."""
|
||||
|
||||
use_renderer: bool = False
|
||||
"""Tokenize SFT samples through the ``renderers`` library (single ``render()`` + ``message_indices`` mask) instead of the default ``build_incremental_token_mask`` path. Required for chat templates that render position-dependently (e.g. Qwen3, Qwen3.5)."""
|
||||
renderer: RendererConfig | None = None
|
||||
"""Typed renderer config (``renderers.RendererConfig`` discriminated
|
||||
union). When set, SFT tokenizes samples through the ``renderers``
|
||||
library (single ``render()`` + ``message_indices`` mask) instead of
|
||||
the default ``build_incremental_token_mask`` path. Required for chat
|
||||
templates that render position-dependently (e.g. Qwen3, Qwen3.5).
|
||||
``None`` (default) uses the legacy tokenization path."""
|
||||
|
||||
data: DataConfig = SFTDataConfig()
|
||||
|
||||
@@ -319,59 +321,13 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_vs_vlm(self):
|
||||
if self.use_renderer and self.model.vlm is not None:
|
||||
if self.renderer is not None and self.model.vlm is not None:
|
||||
raise ValueError(
|
||||
"use_renderer is not supported for VLMs. The renderer tokenizes "
|
||||
"renderer is not supported for VLMs in SFT. The renderer tokenizes "
|
||||
"text-only message dicts client-side and cannot handle image inputs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_args(self):
|
||||
# pool_size is orchestrator-only. An in-process renderer pool exists
|
||||
# to amortize tokenization across concurrent rollouts in the
|
||||
# orchestrator (many async requests render at once, HF fast
|
||||
# tokenizers release the GIL during Rust encoding, so a pool of N
|
||||
# tokenizer copies parallelizes well). SFT has no such concurrency:
|
||||
# the StatefulDataLoader is constructed with num_workers=0, so the
|
||||
# main process tokenizes one example at a time, between training
|
||||
# steps. Across DP, each rank already owns its own renderer — an
|
||||
# implicit pool of size world_size. Pooling within a rank gives
|
||||
# nothing on top of that. Reject so callers don't silently set a
|
||||
# knob that does nothing; if SFT tokenization ever becomes a
|
||||
# bottleneck the fix is num_workers on the dataloader, not a pool.
|
||||
if self.renderer.pool_size is not None:
|
||||
raise ValueError(
|
||||
f"renderer.pool_size={self.renderer.pool_size!r} is only used by the orchestrator. "
|
||||
"SFT tokenizes synchronously (num_workers=0) and already gets one renderer per DP "
|
||||
"rank — an in-process pool adds nothing. If tokenization is a bottleneck, raise "
|
||||
"num_workers on the dataloader instead."
|
||||
)
|
||||
|
||||
if self.use_renderer:
|
||||
return self
|
||||
|
||||
renderer_args_set = []
|
||||
if self.renderer.name != "auto":
|
||||
renderer_args_set.append(f"renderer.name={self.renderer.name!r}")
|
||||
if self.renderer.tool_parser is not None:
|
||||
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
|
||||
if self.renderer.reasoning_parser is not None:
|
||||
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
|
||||
if self.renderer.preserve_all_thinking:
|
||||
renderer_args_set.append(f"renderer.preserve_all_thinking={self.renderer.preserve_all_thinking!r}")
|
||||
if self.renderer.preserve_thinking_between_tool_calls:
|
||||
renderer_args_set.append(
|
||||
f"renderer.preserve_thinking_between_tool_calls={self.renderer.preserve_thinking_between_tool_calls!r}"
|
||||
)
|
||||
|
||||
if renderer_args_set:
|
||||
raise ValueError(
|
||||
"Renderer-specific args set without use_renderer=True: "
|
||||
f"{', '.join(renderer_args_set)}. Either enable the renderer or remove these knobs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_adapter_saving(self):
|
||||
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
|
||||
|
||||
@@ -35,6 +35,9 @@ class SlurmConfig(BaseConfig):
|
||||
pre_run_command: str | None = None
|
||||
"""Shell command to run on the head node after cd, .env sourcing, and venv activation. Useful for cleanup like ``sudo pkill -f vllm``; wrap with ``srun bash -c '...'`` to fan out to all nodes."""
|
||||
|
||||
cleanup_grace_period: int = Field(3600, ge=0)
|
||||
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
|
||||
|
||||
@property
|
||||
def template_vars(self) -> dict:
|
||||
"""Common template variables for all SLURM templates."""
|
||||
@@ -47,6 +50,7 @@ class SlurmConfig(BaseConfig):
|
||||
"account": self.account,
|
||||
"time": self.time,
|
||||
"pre_run_command": self.pre_run_command,
|
||||
"cleanup_grace_period": self.cleanup_grace_period,
|
||||
}
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -84,26 +88,6 @@ class BaseModelConfig(BaseConfig):
|
||||
return self.vlm is not None
|
||||
|
||||
|
||||
class RendererConfig(BaseConfig):
|
||||
name: str = "auto"
|
||||
"""Renderer used for chat-template tokenization. One of: ``auto`` (detect from tokenizer), ``qwen3``, ``qwen3_vl``, ``qwen3.5``, ``glm5``, ``glm4.5``, ``minimax-m2``, ``deepseek_v3``, ``kimi_k2``, ``kimi_k25``, ``nemotron3``, ``gpt_oss``, ``default``."""
|
||||
|
||||
tool_parser: str | None = None
|
||||
"""Tool parser from ``renderers.parsers``. Only consumed by DefaultRenderer; model-specific renderers bake their own parsing in. Options: ``qwen3``, ``qwen3.5``, ``glm``, ``deepseek_v3``."""
|
||||
|
||||
reasoning_parser: str | None = None
|
||||
"""Reasoning parser from ``renderers.parsers``. Only consumed by DefaultRenderer. Options: ``think``."""
|
||||
|
||||
pool_size: int | None = Field(None, ge=1)
|
||||
"""Number of renderer slots shared across concurrent rollouts. Bump for long multi-turn prompts where client-side jinja tokenization serializes."""
|
||||
|
||||
preserve_all_thinking: bool = False
|
||||
"""Re-emit every past-assistant turn's ``reasoning_content`` between ``<think>``/``</think>`` (or the model's equivalent), even when the chat template would drop it. Strict superset of preserve_thinking_between_tool_calls."""
|
||||
|
||||
preserve_thinking_between_tool_calls: bool = False
|
||||
"""Preserve past-assistant ``reasoning_content`` only inside the current tool cycle — the contiguous assistant→tool→…→assistant block after the most recent user message, when that block contains at least one tool response. A new user turn closes the block."""
|
||||
|
||||
|
||||
class ElasticConfig(BaseConfig):
|
||||
hostname: str
|
||||
"""DNS hostname that resolves to inference server IPs."""
|
||||
@@ -174,6 +158,9 @@ class LogConfig(BaseConfig):
|
||||
log_data: bool = False
|
||||
"""Log the first data sample at startup."""
|
||||
|
||||
interval: float = Field(10.0, gt=0)
|
||||
"""Interval (seconds) for periodic logs across components."""
|
||||
|
||||
|
||||
class TrainerLogConfig(LogConfig):
|
||||
ranks_filter: list[int] = [0]
|
||||
|
||||
@@ -68,6 +68,14 @@ class BenchConfig(BaseConfig):
|
||||
"""Path to write benchmark results as JSON. If unset, results are only printed to the console."""
|
||||
|
||||
|
||||
class IndexCacheConfig(BaseConfig):
|
||||
topk_freq: int = Field(1, ge=1)
|
||||
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
|
||||
|
||||
topk_pattern: str | None = None
|
||||
"""Optional per-layer schedule that overrides ``topk_freq``. ``'F'`` computes fresh indices for that layer; ``'S'`` reuses the previously cached indices. Length should match the number of decoder layers."""
|
||||
|
||||
|
||||
class LoRAConfig(BaseConfig):
|
||||
rank: int = Field(16, ge=1)
|
||||
"""Rank of the low-rank decomposition matrices."""
|
||||
@@ -168,6 +176,9 @@ class ModelConfig(BaseModelConfig):
|
||||
fp8: bool = False
|
||||
"""FP8 training via DeepGEMM. Replaces ``nn.Linear`` with FP8 blockwise linear and uses FP8 grouped GEMM for MoE experts. Requires SM90 (Hopper) GPUs and ``model.impl='custom'``."""
|
||||
|
||||
index_cache: IndexCacheConfig | None = None
|
||||
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
|
||||
|
||||
freeze_moe_router: bool = False
|
||||
"""Freeze MoE router parameters during training."""
|
||||
|
||||
@@ -524,9 +535,6 @@ class TrainerConfig(BaseConfig):
|
||||
max_steps: int | None = None
|
||||
"""Maximum number of training steps. If None, runs indefinitely."""
|
||||
|
||||
max_async_level: int = Field(1, ge=0)
|
||||
"""Maximum steps inference can be ahead of training (how off-policy inference can be). Higher values yield better throughput via async execution at the cost of policy lag; ``0`` is fully synchronous."""
|
||||
|
||||
enable_router_replay: bool = False
|
||||
"""Return routed experts in the batch so the trainer can replay routing. Requires ``enable_return_routed_experts=true`` on the vLLM server (or ``--enable-return-routed-experts``) and is only supported for custom models."""
|
||||
|
||||
@@ -618,12 +626,6 @@ class TrainerConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_weight_broadcast_type(self):
|
||||
if self.weight_broadcast.type == "nccl" and self.max_async_level != 1:
|
||||
raise ValueError("NCCL weight broadcast only works with async level 1")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_opt_and_fsdp_offload(self):
|
||||
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
|
||||
|
||||
@@ -15,10 +15,13 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
Behaviour:
|
||||
- **Fill-if-absent**: an explicit sub-config value is never overwritten.
|
||||
The shared block acts as a default, not a stomper.
|
||||
- **Up-front mutex**: setting the same field at both the shared and
|
||||
sub-config level raises. Under fill-if-absent the sub would silently
|
||||
win, and any later CLI override of the shared field would invisibly
|
||||
no-op.
|
||||
- **Consistency mutex**: setting the same field at both the shared and
|
||||
sub-config level only raises when the values *disagree*. Matching
|
||||
values are accepted as a harmless no-op so that the materialized
|
||||
config (``model_dump`` writes both copies) round-trips through re-load.
|
||||
The original footgun the mutex was designed to catch — a sub-config
|
||||
value silently winning over a later CLI shared override — is still
|
||||
caught because that scenario produces *different* values.
|
||||
- **Aliased sub-paths**: ``orchestrator.model.*`` is checked against its
|
||||
``orchestrator.student.model.*`` alias (and vice versa), so the
|
||||
conflict fires regardless of which spelling the user wrote.
|
||||
@@ -49,14 +52,17 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
conflicts: list[tuple[str, str]] = []
|
||||
|
||||
def propagate(shared_path: str, *targets: str, aliases: tuple[str, ...] = ()) -> None:
|
||||
"""Verbatim shared → targets. Records overlap (incl. alias spellings)
|
||||
into ``conflicts`` and fills each target if the shared value is set.
|
||||
"""Verbatim shared → targets. Records *disagreeing* overlap (incl. alias
|
||||
spellings) into ``conflicts`` and fills each target if the shared value
|
||||
is set. Matching values are silently accepted so the materialized
|
||||
config round-trips through re-load.
|
||||
"""
|
||||
value = get(shared_path)
|
||||
if value is None:
|
||||
return
|
||||
for sub in (*targets, *aliases):
|
||||
if get(sub) is not None:
|
||||
sub_value = get(sub)
|
||||
if sub_value is not None and sub_value != value:
|
||||
conflicts.append((shared_path, sub))
|
||||
for target in targets:
|
||||
fill(target, value)
|
||||
@@ -78,8 +84,13 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
)
|
||||
|
||||
# [log]
|
||||
propagate("log.level", "trainer.log.level", "orchestrator.log.level")
|
||||
propagate("log.json_logging", "trainer.log.json_logging", "orchestrator.log.json_logging")
|
||||
propagate("log.level", "trainer.log.level", "orchestrator.log.level", "inference.log.level")
|
||||
propagate(
|
||||
"log.json_logging",
|
||||
"trainer.log.json_logging",
|
||||
"orchestrator.log.json_logging",
|
||||
"inference.log.json_logging",
|
||||
)
|
||||
|
||||
# [ckpt] leaves. (Bare empty ``[ckpt]`` block enablement is at the end.)
|
||||
# ``orchestrator.ckpt`` has no ``output_dir`` field — trainer-only.
|
||||
@@ -90,25 +101,16 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
propagate("ckpt.keep_interval", "trainer.ckpt.keep_interval", "orchestrator.ckpt.keep_interval")
|
||||
|
||||
# [wandb] leaves. (Bare empty ``[wandb]`` block enablement is at the end.)
|
||||
# ``wandb.name`` flows verbatim to both sub-configs — shared W&B mode is
|
||||
# always on for the rl entrypoint, so the legacy ``-trainer`` /
|
||||
# ``-orchestrator`` suffix split is gone.
|
||||
propagate("wandb.project", "trainer.wandb.project", "orchestrator.wandb.project")
|
||||
propagate("wandb.entity", "trainer.wandb.entity", "orchestrator.wandb.entity")
|
||||
propagate("wandb.name", "trainer.wandb.name", "orchestrator.wandb.name")
|
||||
propagate("wandb.group", "trainer.wandb.group", "orchestrator.wandb.group")
|
||||
propagate("wandb.tags", "trainer.wandb.tags", "orchestrator.wandb.tags")
|
||||
propagate("wandb.offline", "trainer.wandb.offline", "orchestrator.wandb.offline")
|
||||
|
||||
# wandb.name: in non-shared mode the two sub-configs get distinct
|
||||
# ``-trainer`` / ``-orchestrator`` suffixes so the W&B runs are
|
||||
# distinguishable. ``OrchestratorConfig.auto_setup_prime_monitor_run_name``
|
||||
# then defaults prime_monitor.run_name to the (unsuffixed) value.
|
||||
wandb_name = get("wandb.name")
|
||||
if wandb_name is not None:
|
||||
for sub in ("trainer.wandb.name", "orchestrator.wandb.name"):
|
||||
if get(sub) is not None:
|
||||
conflicts.append(("wandb.name", sub))
|
||||
non_shared = get("wandb.shared") is False
|
||||
fill("trainer.wandb.name", f"{wandb_name}-trainer" if non_shared else wandb_name)
|
||||
fill("orchestrator.wandb.name", f"{wandb_name}-orchestrator" if non_shared else wandb_name)
|
||||
|
||||
# [tokenizer]. ``chat_template`` also flows to ``inference.model`` (vLLM's
|
||||
# ``--chat-template``); ``name`` and ``trust_remote_code`` can legitimately
|
||||
# differ between sub-configs (auto-derived from model names, which may
|
||||
@@ -128,18 +130,29 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
|
||||
# Top-level scalars.
|
||||
propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps")
|
||||
propagate("max_async_level", "trainer.max_async_level", "orchestrator.max_async_level")
|
||||
propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len")
|
||||
|
||||
# [slurm] → inference: a multi-node RL run drives its inference deployment under
|
||||
# the same SLURM allocation, so the nested inference inherits [slurm]. This is
|
||||
# what lets the nested InferenceConfig's multi-node / disaggregated SLURM check
|
||||
# pass (the per-rank inference.toml drops slurm, so each rank still runs locally).
|
||||
propagate("slurm", "inference.slurm")
|
||||
|
||||
# output_dir: orchestrator gets a ``/run_default`` subdir so trainer +
|
||||
# orchestrator nest under the same experiment root without colliding.
|
||||
# Conflicts are reported against the *transformed* sub-config value, not
|
||||
# the raw shared path, so the materialized config round-trips cleanly.
|
||||
output_dir = get("output_dir")
|
||||
if output_dir is not None:
|
||||
for sub in ("trainer.output_dir", "orchestrator.output_dir"):
|
||||
if get(sub) is not None:
|
||||
expected = {
|
||||
"trainer.output_dir": output_dir,
|
||||
"orchestrator.output_dir": f"{output_dir}/run_default",
|
||||
}
|
||||
for sub, expected_value in expected.items():
|
||||
sub_value = get(sub)
|
||||
if sub_value is not None and sub_value != expected_value:
|
||||
conflicts.append(("output_dir", sub))
|
||||
fill("trainer.output_dir", output_dir)
|
||||
fill("orchestrator.output_dir", f"{output_dir}/run_default")
|
||||
fill(sub, expected_value)
|
||||
|
||||
# Cascade trainer.tokenizer.chat_template → inference.model.chat_template
|
||||
# (vLLM ``--chat-template``). Read trainer's value *after* the shared
|
||||
@@ -160,9 +173,12 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
# conflicts (e.g. shared ``ckpt.interval`` vs ``trainer.ckpt.interval``)
|
||||
# are already caught above; the bare block is exempt because
|
||||
# ``[ckpt]`` + ``[trainer.ckpt] keep_last = 3`` is a legitimate
|
||||
# "enable + customise per side" pattern.
|
||||
# "enable + customise per side" pattern. The ``isinstance(dict)`` check
|
||||
# (not ``is not None``) is what makes CLI ``--no-wandb`` / ``--no-ckpt``
|
||||
# work — those land as the *string* ``"None"`` until ``BaseConfig``'s
|
||||
# parent-class validator converts it, which happens after this one.
|
||||
for key in ("ckpt", "wandb"):
|
||||
if get(key) is not None:
|
||||
if isinstance(get(key), dict):
|
||||
fill(f"trainer.{key}", {})
|
||||
fill(f"orchestrator.{key}", {})
|
||||
|
||||
@@ -266,16 +282,6 @@ def validate_shared_max_steps(
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_max_async_level(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.max_async_level != orchestrator.max_async_level:
|
||||
raise ValueError(
|
||||
f"Trainer max async level ({trainer.max_async_level}) and orchestrator max async level ({orchestrator.max_async_level}) are not the same. Please specify the same max async level for both."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_seq_len(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
|
||||
+83
-77
@@ -6,6 +6,7 @@ readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"prime-rl-configs",
|
||||
"prime-pydantic-config",
|
||||
"beartype>=0.21.0",
|
||||
"datasets>=4.0.0",
|
||||
"jaxtyping>=0.3.2",
|
||||
@@ -17,8 +18,9 @@ dependencies = [
|
||||
"torchvision",
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers",
|
||||
"vllm>=0.21.0",
|
||||
"transformers==5.6.2",
|
||||
"vllm>=0.22.0",
|
||||
"mooncake-transfer-engine>=0.3.10.post2",
|
||||
"wandb>=0.26.1",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.6.4",
|
||||
@@ -26,6 +28,7 @@ dependencies = [
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
"openai>=1.106.1",
|
||||
"orjson>=3.11.0",
|
||||
"rich>=14.0.0",
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
@@ -66,6 +69,7 @@ envs = [
|
||||
"code-env",
|
||||
"color-codeword",
|
||||
"deepdive",
|
||||
"general-agent",
|
||||
"gpqa",
|
||||
"hle",
|
||||
"ifeval",
|
||||
@@ -75,7 +79,6 @@ envs = [
|
||||
"math-python",
|
||||
"math500",
|
||||
"mini-swe-agent-plus",
|
||||
"mini-swe-agent-plus-rlm",
|
||||
"mmlu-pro",
|
||||
"opencode-cp",
|
||||
"opencode-deepdive",
|
||||
@@ -83,10 +86,12 @@ envs = [
|
||||
"opencode-science",
|
||||
"opencode-swe",
|
||||
"reverse-text",
|
||||
"rlm-swe",
|
||||
"science-env",
|
||||
"simpleqa-verified",
|
||||
"tau2-bench",
|
||||
"wiki-search",
|
||||
"wordle",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
@@ -98,6 +103,9 @@ disagg = [
|
||||
gpt-oss = [
|
||||
"kernels",
|
||||
]
|
||||
modelexpress = [
|
||||
"modelexpress==0.3.0",
|
||||
]
|
||||
quack = [
|
||||
"quack-kernels>=0.4.1",
|
||||
]
|
||||
@@ -118,46 +126,16 @@ dev = [
|
||||
"ipywidgets>=8.1.7",
|
||||
"pre-commit>=4.2.0",
|
||||
"pytest>=8.4.1",
|
||||
"pytest-asyncio>=0.23",
|
||||
"ruff>=0.12.1",
|
||||
]
|
||||
|
||||
|
||||
[tool.uv.workspace]
|
||||
members = [
|
||||
"packages/prime-rl-configs",
|
||||
"deps/pydantic-config",
|
||||
"deps/verifiers",
|
||||
"deps/renderers",
|
||||
"deps/verifiers/environments/alphabet_sort",
|
||||
"deps/verifiers/environments/math_python",
|
||||
"deps/verifiers/environments/reverse_text",
|
||||
"deps/verifiers/environments/wiki_search",
|
||||
"deps/research-environments/environments/aime2024",
|
||||
"deps/research-environments/environments/aime2025",
|
||||
"deps/research-environments/environments/code_env",
|
||||
"deps/research-environments/environments/color_codeword",
|
||||
"deps/research-environments/environments/deepdive",
|
||||
"deps/research-environments/environments/gpqa",
|
||||
"deps/research-environments/environments/hle",
|
||||
"deps/research-environments/environments/ifeval",
|
||||
"deps/research-environments/environments/livecodebench",
|
||||
"deps/research-environments/environments/logic_env",
|
||||
"deps/research-environments/environments/math500",
|
||||
"deps/research-environments/environments/math_env",
|
||||
"deps/research-environments/environments/mini_swe_agent_plus",
|
||||
"deps/research-environments/environments/mini_swe_agent_plus_rlm",
|
||||
"deps/research-environments/environments/mmlu_pro",
|
||||
"deps/research-environments/environments/opencode_cp",
|
||||
"deps/research-environments/environments/opencode_deepdive",
|
||||
"deps/research-environments/environments/opencode_math",
|
||||
"deps/research-environments/environments/opencode_science",
|
||||
"deps/research-environments/environments/opencode_swe",
|
||||
"deps/research-environments/environments/science_env",
|
||||
"deps/research-environments/environments/simpleqa_verified",
|
||||
"deps/research-environments/environments/tau2_bench",
|
||||
]
|
||||
|
||||
[tool.uv]
|
||||
# Enforce a uv version that supports the friendly-duration form
|
||||
# (`"7 days"`) in the static pyproject parser. Older uvs silently parse
|
||||
# the value as an RFC 3339 date, emit a TOML parse warning, and proceed
|
||||
# *without* the cooldown — bypassing this security policy.
|
||||
required-version = ">=0.11.1"
|
||||
exclude-newer = "7 days"
|
||||
preview = true
|
||||
no-build-isolation-package = ["flash-attn"]
|
||||
@@ -170,9 +148,26 @@ environments = [
|
||||
override-dependencies = [
|
||||
"nvidia-cudnn-cu12>=9.15",
|
||||
"nvidia-cutlass-dsl>=4.4.1",
|
||||
"transformers>=5.1.0.dev0",
|
||||
"transformers==5.6.2",
|
||||
"torch>=2.9.0",
|
||||
"openenv-core",
|
||||
"verifiers[packages]>=0.1.15.dev150",
|
||||
]
|
||||
|
||||
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
|
||||
# compatible with protobuf 6. prime-sandboxes requires protobuf>=6.31.1; keep
|
||||
# this capped to the validated protobuf major.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
name = "modelexpress"
|
||||
version = "0.3.0"
|
||||
requires-dist = [
|
||||
"grpcio>=1.66.2",
|
||||
"huggingface_hub>=0.20.0",
|
||||
"nixl[cu12]",
|
||||
"numpy>=1.24.0",
|
||||
"protobuf>=5.27.0,<7.0.0",
|
||||
"pydantic>=2.0.0",
|
||||
"torch>=2.6.0",
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
@@ -181,11 +176,19 @@ vllm = false
|
||||
tokenspeed-mla = false
|
||||
fastokens = false
|
||||
flash_attn_3 = false
|
||||
# PrimeIntellect-published on PyPI (trusted publisher)
|
||||
# PrimeIntellect-published packages in this project's dependency closure —
|
||||
# fast-track so first-party releases can land same-day. Only packages that
|
||||
# appear in `uv tree` need to be listed; the resolver ignores entries for
|
||||
# packages it never sees.
|
||||
prime = false
|
||||
prime-sandboxes = false
|
||||
prime-tunnel = false
|
||||
prime-evals = false
|
||||
verifiers = false
|
||||
renderers = false
|
||||
tasksets = false
|
||||
harnesses = false
|
||||
prime-pydantic-config = false
|
||||
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
|
||||
vllm-router = false
|
||||
dion = false
|
||||
@@ -194,48 +197,51 @@ deep-gemm = false
|
||||
nixl-cu12 = false
|
||||
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { workspace = true }
|
||||
verifiers = { workspace = true }
|
||||
renderers = { workspace = true }
|
||||
aime2024 = { workspace = true }
|
||||
aime2025 = { workspace = true }
|
||||
alphabet-sort = { workspace = true }
|
||||
code-env = { workspace = true }
|
||||
color-codeword = { workspace = true }
|
||||
deepdive = { workspace = true }
|
||||
gpqa = { workspace = true }
|
||||
hle = { workspace = true }
|
||||
ifeval = { workspace = true }
|
||||
livecodebench = { workspace = true }
|
||||
logic-env = { workspace = true }
|
||||
math-env = { workspace = true }
|
||||
math-python = { workspace = true }
|
||||
math500 = { workspace = true }
|
||||
mini-swe-agent-plus = { workspace = true }
|
||||
mini-swe-agent-plus-rlm = { workspace = true }
|
||||
mmlu-pro = { workspace = true }
|
||||
opencode-cp = { workspace = true }
|
||||
opencode-deepdive = { workspace = true }
|
||||
opencode-math = { workspace = true }
|
||||
opencode-science = { workspace = true }
|
||||
opencode-swe = { workspace = true }
|
||||
reverse-text = { workspace = true }
|
||||
science-env = { workspace = true }
|
||||
simpleqa-verified = { workspace = true }
|
||||
tau2-bench = { workspace = true }
|
||||
wiki-search = { workspace = true }
|
||||
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
verifiers = { path = "deps/verifiers", editable = true }
|
||||
renderers = { path = "deps/renderers", editable = true }
|
||||
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
|
||||
aime2024 = { path = "deps/research-environments/environments/aime2024", editable = true }
|
||||
aime2025 = { path = "deps/research-environments/environments/aime2025", editable = true }
|
||||
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
|
||||
code-env = { path = "deps/research-environments/environments/code_env", editable = true }
|
||||
color-codeword = { path = "deps/research-environments/environments/color_codeword", editable = true }
|
||||
deepdive = { path = "deps/research-environments/environments/deepdive", editable = true }
|
||||
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
|
||||
gpqa = { path = "deps/research-environments/environments/gpqa", editable = true }
|
||||
harnesses = { path = "deps/verifiers/packages/harnesses", editable = true }
|
||||
hle = { path = "deps/research-environments/environments/hle", editable = true }
|
||||
ifeval = { path = "deps/research-environments/environments/ifeval", editable = true }
|
||||
livecodebench = { path = "deps/research-environments/environments/livecodebench", editable = true }
|
||||
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
|
||||
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
|
||||
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
|
||||
math500 = { path = "deps/research-environments/environments/math500", editable = true }
|
||||
mini-swe-agent-plus = { path = "deps/research-environments/environments/mini_swe_agent_plus", editable = true }
|
||||
mmlu-pro = { path = "deps/research-environments/environments/mmlu_pro", editable = true }
|
||||
opencode-cp = { path = "deps/research-environments/environments/opencode_cp", editable = true }
|
||||
opencode-deepdive = { path = "deps/research-environments/environments/opencode_deepdive", editable = true }
|
||||
opencode-math = { path = "deps/research-environments/environments/opencode_math", editable = true }
|
||||
opencode-science = { path = "deps/research-environments/environments/opencode_science", editable = true }
|
||||
opencode-swe = { path = "deps/research-environments/environments/opencode_swe", editable = true }
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
|
||||
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
|
||||
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
|
||||
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
|
||||
tasksets = { path = "deps/verifiers/packages/tasksets", editable = true }
|
||||
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
|
||||
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "c1c3424" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
prime-pydantic-config = { workspace = true }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.25/vllm_router-0.1.25-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
vllm = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/vllm-0.21.0+cu129.r42434.pr39568.a106aa6-cp38-abi3-manylinux_2_34_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.22.0/vllm-0.22.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.22.0/vllm-0.22.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
|
||||
@@ -266,7 +272,7 @@ select = ["F", "I"]
|
||||
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
# `prime_rl` is split across two workspace wheels (prime-rl + prime-rl-configs).
|
||||
# `prime_rl` is split across two editable wheels (prime-rl + prime-rl-configs).
|
||||
# Without this, ruff classifies prime_rl.configs.* as third-party because it
|
||||
# doesn't live under src/.
|
||||
known-first-party = ["prime_rl"]
|
||||
|
||||
@@ -1,17 +1,44 @@
|
||||
#!/bin/bash
|
||||
# arm64 post-install fixups for Docker builds.
|
||||
set -e
|
||||
# arm64 post-install fixups: rebuild flash-attn from source for the target GPU.
|
||||
#
|
||||
# Why this exists: pyproject.toml sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE to keep
|
||||
# `uv sync` fast; on x86_64 it pins a prebuilt wheel to fill in the binary, but no
|
||||
# such wheel exists for aarch64. Without this script, `import flash_attn` fails on
|
||||
# aarch64 with `ModuleNotFoundError: No module named 'flash_attn_2_cuda'`.
|
||||
#
|
||||
# Defaults preserve the existing Docker behavior (sm_100 / GB200). On a host with
|
||||
# `nvidia-smi` available, the compute capability is auto-detected from the local
|
||||
# GPU. Override via env vars if needed:
|
||||
# TORCH_CUDA_ARCH_LIST e.g. 9.0 (Hopper), 10.0 (Blackwell)
|
||||
# VENV_PATH path to the venv (default: $(pwd)/.venv)
|
||||
# MAX_JOBS parallel nvcc jobs (default: 4)
|
||||
set -euo pipefail
|
||||
|
||||
echo "=== building flash-attn from source (sm_100 / GB200) ==="
|
||||
# Run from /tmp so uv doesn't read pyproject.toml's [tool.uv.extra-build-variables]
|
||||
# which sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and prevents CUDA kernel compilation.
|
||||
export TORCH_CUDA_ARCH_LIST="10.0"
|
||||
export MAX_JOBS=4
|
||||
if [ -z "${TORCH_CUDA_ARCH_LIST:-}" ]; then
|
||||
# Try to detect from the local GPU. Tolerate any failure mode (binary missing,
|
||||
# driver not loaded, Docker buildx without --gpus) and fall back to GB200.
|
||||
TORCH_CUDA_ARCH_LIST="$(nvidia-smi --query-gpu=compute_cap --format=csv,noheader 2>/dev/null | head -1 | tr -d ' ' || true)"
|
||||
: "${TORCH_CUDA_ARCH_LIST:=10.0}"
|
||||
fi
|
||||
export TORCH_CUDA_ARCH_LIST
|
||||
|
||||
VENV_PATH="${VENV_PATH:-$(pwd)/.venv}"
|
||||
if [ ! -x "$VENV_PATH/bin/python" ]; then
|
||||
echo "ERROR: no python at $VENV_PATH/bin/python. Run from the project root or set VENV_PATH." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export MAX_JOBS="${MAX_JOBS:-4}"
|
||||
export FLASH_ATTENTION_FORCE_BUILD=TRUE
|
||||
export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
|
||||
(cd /tmp && uv pip install --python /app/.venv/bin/python \
|
||||
"flash-attn==2.8.3" --no-build-isolation --no-binary flash-attn --no-cache)
|
||||
|
||||
echo "=== building flash-attn from source (TORCH_CUDA_ARCH_LIST=$TORCH_CUDA_ARCH_LIST, MAX_JOBS=$MAX_JOBS) ==="
|
||||
echo " target venv: $VENV_PATH"
|
||||
# Run from /tmp so uv ignores the project's [tool.uv.extra-build-variables],
|
||||
# which sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and would prevent kernel compilation.
|
||||
(cd /tmp && uv pip install --python "$VENV_PATH/bin/python" \
|
||||
"flash-attn==2.8.3" --no-build-isolation --no-binary flash-attn --no-cache --reinstall-package flash-attn)
|
||||
|
||||
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
|
||||
uv pip install --reinstall --no-deps \
|
||||
uv pip install --python "$VENV_PATH/bin/python" --reinstall --no-deps \
|
||||
"flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
|
||||
|
||||
+11
-17
@@ -74,27 +74,11 @@ ensure_known_hosts() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Initialize each submodule independently so that a missing private repo
|
||||
# (e.g. configs/private when the user lacks access) does not abort the install.
|
||||
init_submodules() {
|
||||
if [ ! -f .gitmodules ]; then
|
||||
return 0
|
||||
fi
|
||||
local paths failures
|
||||
paths=$(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | awk '{print $2}')
|
||||
failures=()
|
||||
for path in $paths; do
|
||||
log_info "Initializing submodule: ${path}"
|
||||
if git submodule update --init --recursive -- "$path"; then
|
||||
:
|
||||
else
|
||||
log_warn "Could not initialize submodule '${path}' (likely no access). Continuing without it."
|
||||
failures+=("$path")
|
||||
fi
|
||||
done
|
||||
if [ "${#failures[@]}" -gt 0 ]; then
|
||||
log_warn "Skipped submodules: ${failures[*]}"
|
||||
fi
|
||||
git submodule update --init --recursive
|
||||
}
|
||||
|
||||
main() {
|
||||
@@ -159,6 +143,16 @@ main() {
|
||||
log_info "Installing pre-commit hooks..."
|
||||
uv run pre-commit install
|
||||
|
||||
# aarch64 has no prebuilt flash-attn wheel; build it from source for the local GPU.
|
||||
# Without this, `import flash_attn` fails with `ModuleNotFoundError: flash_attn_2_cuda`.
|
||||
# Run last so no subsequent uv operation (which implicitly syncs against the lockfile)
|
||||
# rebuilds flash-attn from PyPI with FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and undoes this.
|
||||
if [ "$(uname -m)" = "aarch64" ]; then
|
||||
log_info "aarch64 detected: building flash-attn from source (this takes 20-30 minutes)..."
|
||||
log_warn "Future 'uv sync --all-extras' or 'uv run' will remove this build. Use 'uv sync --inexact' or 'uv run --no-sync' to keep it."
|
||||
bash scripts/docker-arm64-post-install.sh
|
||||
fi
|
||||
|
||||
log_info "Installation completed!"
|
||||
}
|
||||
|
||||
|
||||
@@ -74,5 +74,4 @@ Leave it unset for normal training. When enabled, it exports every sequence from
|
||||
|
||||
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
|
||||
- `configs/debug/` — minimal debug configs
|
||||
- `configs/private/` — private configs submodule (internal)
|
||||
- `examples/` — full example configs
|
||||
|
||||
@@ -16,11 +16,9 @@ bash scripts/install.sh # clones, inits submodules, installs uv, runs `uv sync
|
||||
For an existing clone, init submodules explicitly:
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
Do **not** run `git submodule update --init --recursive` without paths — it tries to clone the private `configs/private` submodule and aborts for users without access. `scripts/install.sh` walks submodules one at a time and skips failures, so it works for everyone.
|
||||
|
||||
## Sync
|
||||
|
||||
```bash
|
||||
|
||||
@@ -34,6 +34,12 @@ uv run rl @ examples/reverse_text/rl.toml --dry-run
|
||||
- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
|
||||
- SLURM: single- and multi-node
|
||||
- Environment packages: before launching a config with a non-core verifier env id,
|
||||
verify the package imports under `uv run` (for example
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('rlm_swe'))"`).
|
||||
If a local env exists under `deps/research-environments/environments/` but does not
|
||||
import, add it to the root `pyproject.toml` env extra, workspace members, and
|
||||
`[tool.uv.sources]`, then run `uv sync --all-extras`.
|
||||
|
||||
## `sft` — SFT training
|
||||
|
||||
|
||||
@@ -36,6 +36,9 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
is_disaggregated = config.deployment.type == "disaggregated"
|
||||
dp_per_node = config.deployment.gpus_per_node // config.parallel.tp
|
||||
|
||||
offload = config.kv_cache_offload
|
||||
is_mooncake = offload is not None and offload.type == "mooncake"
|
||||
|
||||
template_vars = dict(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
@@ -45,7 +48,11 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
num_nodes=getattr(config.deployment, "num_nodes", 1),
|
||||
port=config.server.port,
|
||||
disaggregated=is_disaggregated,
|
||||
kv_offload=config.kv_cache_offload is not None,
|
||||
kv_offload=offload is not None,
|
||||
kv_offload_mooncake=is_mooncake,
|
||||
kv_offload_cpu_bytes=int(offload.cpu.num_bytes) if is_mooncake else 0,
|
||||
kv_offload_disk_path=str(offload.disk.path) if (is_mooncake and offload.disk is not None) else "",
|
||||
kv_offload_device_name=offload.device_name if is_mooncake else "",
|
||||
)
|
||||
|
||||
is_multi_node = config.deployment.type == "multi_node"
|
||||
@@ -58,19 +65,20 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
num_decode_replicas=config.deployment.num_decode_replicas,
|
||||
prefill_port=config.deployment.prefill_port,
|
||||
decode_port=config.deployment.decode_port,
|
||||
router_port=config.deployment.router_port,
|
||||
router_policy=config.deployment.router_policy,
|
||||
router_port=config.deployment.router.port,
|
||||
router_policy=config.deployment.router.policy,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
use_deep_gemm=config.use_deep_gemm,
|
||||
prefill_env_overrides=config.deployment.prefill_env_overrides,
|
||||
decode_env_overrides=config.deployment.decode_env_overrides,
|
||||
kv_offload_cpu_bytes=int(config.kv_cache_offload.cpu_bytes) if config.kv_cache_offload else 0,
|
||||
)
|
||||
elif is_multi_node:
|
||||
template_vars.update(
|
||||
router_port=config.deployment.router_port,
|
||||
router_port=config.deployment.router.port,
|
||||
backend_port=config.deployment.backend_port,
|
||||
router_policy=config.deployment.router_policy,
|
||||
router_policy=config.deployment.router.policy,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
enable_expert_parallel=config.enable_expert_parallel,
|
||||
)
|
||||
|
||||
script = template.render(**template_vars)
|
||||
@@ -83,7 +91,7 @@ def inference_slurm(config: InferenceConfig):
|
||||
"""Run inference via SLURM."""
|
||||
assert config.slurm is not None
|
||||
|
||||
logger = setup_logger("info")
|
||||
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = get_config_dir(config.output_dir)
|
||||
exclude = (
|
||||
@@ -119,7 +127,7 @@ def inference_local(config: InferenceConfig):
|
||||
"""Run inference locally."""
|
||||
from prime_rl.inference.server import setup_vllm_env
|
||||
|
||||
logger = setup_logger("info")
|
||||
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
|
||||
if config.dry_run:
|
||||
logger.success("Dry run complete. To start inference locally, remove --dry-run from your command.")
|
||||
|
||||
@@ -19,9 +19,9 @@ from prime_rl.utils.process import set_proc_title
|
||||
def main():
|
||||
set_proc_title("Orchestrator")
|
||||
config = cli(OrchestratorConfig)
|
||||
from prime_rl.orchestrator.orchestrator import orchestrate
|
||||
from prime_rl.orchestrator.orchestrator import run_orchestrator
|
||||
|
||||
asyncio.run(orchestrate(config))
|
||||
asyncio.run(run_orchestrator(config))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -31,7 +31,6 @@ RL_SBATCH = "rl.sbatch"
|
||||
TRAINER_TOML = "trainer.toml"
|
||||
ORCHESTRATOR_TOML = "orchestrator.toml"
|
||||
INFERENCE_TOML = "inference.toml"
|
||||
TEACHER_INFERENCE_TOML = "teacher_inference.toml"
|
||||
|
||||
|
||||
def get_physical_gpu_ids() -> list[int]:
|
||||
@@ -67,11 +66,6 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
with open(output_dir / INFERENCE_TOML, "wb") as f:
|
||||
tomli_w.dump(config.inference.model_dump(exclude=exclude_inference, exclude_none=True, mode="json"), f)
|
||||
|
||||
teacher_inference = getattr(config, "teacher_inference", None)
|
||||
if teacher_inference is not None:
|
||||
with open(output_dir / TEACHER_INFERENCE_TOML, "wb") as f:
|
||||
tomli_w.dump(teacher_inference.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
|
||||
def rl_local(config: RLConfig):
|
||||
assert config.deployment.type == "single_node"
|
||||
@@ -95,11 +89,8 @@ def rl_local(config: RLConfig):
|
||||
infer_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_infer_gpus))
|
||||
gpu_offset += num_infer_gpus
|
||||
trainer_local_gpu_ids = list(range(gpu_offset, gpu_offset + config.deployment.num_train_gpus))
|
||||
gpu_offset += config.deployment.num_train_gpus
|
||||
num_teacher_gpus = config.deployment.num_teacher_gpus or 0
|
||||
teacher_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_teacher_gpus)) if num_teacher_gpus > 0 else []
|
||||
|
||||
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus + num_teacher_gpus
|
||||
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
|
||||
physical_gpu_ids = get_physical_gpu_ids()
|
||||
if total_requested_gpus > len(physical_gpu_ids):
|
||||
raise ValueError(
|
||||
@@ -111,17 +102,18 @@ def rl_local(config: RLConfig):
|
||||
|
||||
infer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in infer_local_gpu_ids]
|
||||
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
|
||||
teacher_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in teacher_local_gpu_ids]
|
||||
|
||||
start_command = sys.argv
|
||||
logger.info("Starting RL run")
|
||||
logger.debug(f"RL start command: {' '.join(start_command)}")
|
||||
|
||||
# Build shared W&B env vars for subprocesses
|
||||
wandb_shared_env: dict[str, str] = {}
|
||||
if config.wandb and config.wandb.shared:
|
||||
wandb_shared_env["WANDB_SHARED_MODE"] = "1"
|
||||
wandb_shared_env["WANDB_SHARED_RUN_ID"] = os.environ.get("WANDB_SHARED_RUN_ID", uuid.uuid4().hex)
|
||||
# Build shared W&B env vars for subprocesses. Shared mode is always on for
|
||||
# the rl entrypoint — trainer and orchestrator log to a single W&B run.
|
||||
# The monitor short-circuits when WANDB_MODE=disabled/offline is also set.
|
||||
wandb_shared_env: dict[str, str] = {
|
||||
"WANDB_SHARED_MODE": "1",
|
||||
"WANDB_SHARED_RUN_ID": os.environ.get("WANDB_SHARED_RUN_ID", uuid.uuid4().hex),
|
||||
}
|
||||
|
||||
# Validate client port matches inference server port
|
||||
if config.inference is not None and not config.orchestrator.student.client.is_elastic:
|
||||
@@ -194,52 +186,15 @@ def rl_local(config: RLConfig):
|
||||
"will hang waiting for it."
|
||||
)
|
||||
|
||||
# Optionally, start teacher inference process
|
||||
if config.teacher_inference:
|
||||
if not teacher_gpu_ids:
|
||||
raise ValueError(
|
||||
"teacher_inference is configured but deployment.num_teacher_gpus is not set. "
|
||||
"Either set deployment.num_teacher_gpus to start a teacher inference server, "
|
||||
"or omit teacher_inference and configure orchestrator.teacher to use an existing server."
|
||||
)
|
||||
|
||||
teacher_inference_cmd = ["inference", "@", (config_dir / TEACHER_INFERENCE_TOML).as_posix()]
|
||||
logger.info(f"Starting teacher inference process on GPU(s) {' '.join(map(str, teacher_gpu_ids))}")
|
||||
logger.debug(f"Teacher inference start command: {' '.join(teacher_inference_cmd)}")
|
||||
with open(log_dir / "teacher_inference.log", "w") as log_file:
|
||||
teacher_inference_process = Popen(
|
||||
teacher_inference_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, teacher_gpu_ids)),
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(teacher_inference_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["teacher_inference"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(teacher_inference_process, stop_event, error_queue, "teacher_inference"),
|
||||
daemon=True,
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
elif config.orchestrator.teacher:
|
||||
logger.warning(
|
||||
"No teacher_inference config specified, skipping starting teacher inference server. "
|
||||
"Is your teacher inference server running? Make sure orchestrator.teacher is configured."
|
||||
if config.orchestrator.teacher:
|
||||
logger.info(
|
||||
"orchestrator.teacher is configured - the rl entrypoint does not start teacher inference "
|
||||
"servers. Make sure your teacher endpoint at "
|
||||
f"{', '.join(config.orchestrator.teacher.client.base_url)} is running before the "
|
||||
"orchestrator starts, otherwise rollouts will hang."
|
||||
)
|
||||
|
||||
# Start orchestrator process
|
||||
orchestrator_cmd = [
|
||||
"orchestrator",
|
||||
"@",
|
||||
(config_dir / ORCHESTRATOR_TOML).as_posix(),
|
||||
]
|
||||
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_TOML).as_posix()]
|
||||
logger.info("Starting orchestrator process")
|
||||
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
|
||||
with open(log_dir / "orchestrator.log", "w") as log_file:
|
||||
@@ -353,7 +308,7 @@ def rl_local(config: RLConfig):
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
logger.success("RL training finished!")
|
||||
logger.success("Training finished!")
|
||||
|
||||
# Cleanup threads and processes
|
||||
cleanup_threads(monitor_threads)
|
||||
@@ -381,6 +336,16 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
|
||||
template = env.get_template(config.slurm.template_path.name)
|
||||
|
||||
offload = config.inference.kv_cache_offload if config.inference is not None else None
|
||||
is_mooncake = offload is not None and offload.type == "mooncake"
|
||||
mooncake_vars = dict(
|
||||
kv_offload=offload is not None,
|
||||
kv_offload_mooncake=is_mooncake,
|
||||
kv_offload_cpu_bytes=int(offload.cpu.num_bytes) if is_mooncake else 0,
|
||||
kv_offload_disk_path=str(offload.disk.path) if (is_mooncake and offload.disk is not None) else "",
|
||||
kv_offload_device_name=offload.device_name if is_mooncake else "",
|
||||
)
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
@@ -406,7 +371,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
num_prefill_replicas=infer_deploy.num_prefill_replicas,
|
||||
num_decode_replicas=infer_deploy.num_decode_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router_port=infer_deploy.router_port,
|
||||
router_port=infer_deploy.router.port,
|
||||
prefill_port=infer_deploy.prefill_port,
|
||||
decode_port=infer_deploy.decode_port,
|
||||
inference_tp=config.inference.parallel.tp,
|
||||
@@ -415,12 +380,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
prefill_env_overrides=infer_deploy.prefill_env_overrides,
|
||||
decode_env_overrides=infer_deploy.decode_env_overrides,
|
||||
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
|
||||
kv_offload=config.inference.kv_cache_offload is not None,
|
||||
kv_offload_cpu_bytes=int(config.inference.kv_cache_offload.cpu_bytes)
|
||||
if config.inference.kv_cache_offload
|
||||
else 0,
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
wandb_shared=config.wandb is not None and config.wandb.shared,
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
)
|
||||
else:
|
||||
@@ -434,17 +395,15 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
num_infer_nodes=config.deployment.total_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.num_infer_nodes,
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
num_teacher_nodes=config.deployment.num_teacher_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router_port=getattr(config.inference.deployment, "router_port", 8000) if config.inference else 8000,
|
||||
backend_port=getattr(config.inference.deployment, "backend_port", 8100) if config.inference else 8100,
|
||||
router_port=config.inference.deployment.router.port if config.inference else 8000,
|
||||
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
|
||||
inference_tp=config.inference.parallel.tp if config.inference else 1,
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
|
||||
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
|
||||
dp_per_node=(config.deployment.gpus_per_node // config.inference.parallel.tp) if config.inference else 1,
|
||||
kv_offload=config.inference is not None and config.inference.kv_cache_offload is not None,
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
wandb_shared=config.wandb is not None and config.wandb.shared,
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Stdlib `logging`-based JSON formatter and dictConfig for vLLM.
|
||||
|
||||
Trainer and orchestrator emit JSON via loguru
|
||||
(`prime_rl.utils.logger.json_sink`). vLLM uses Python's stdlib
|
||||
`logging` and spawns workers via `multiprocessing.spawn`, so we can't
|
||||
share the loguru sink directly. We emit the same flat shape from a
|
||||
stdlib `Formatter` and drive it via a dictConfig file pointed to by
|
||||
`VLLM_LOGGING_CONFIG_PATH` — env vars cross the spawn boundary, so
|
||||
worker processes inherit the same logging config.
|
||||
"""
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import logging
|
||||
import tempfile
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
"""Emit one JSON object per record matching `build_log_entry` in
|
||||
`prime_rl.utils.logger` so the platform's JsonLogsViewer renders
|
||||
inference rows identically to trainer / orchestrator rows."""
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
entry: dict[str, Any] = {
|
||||
"timestamp": datetime.datetime.fromtimestamp(record.created, tz=datetime.timezone.utc).isoformat(),
|
||||
"level": record.levelname,
|
||||
"message": record.getMessage(),
|
||||
"module": record.module,
|
||||
"function": record.funcName,
|
||||
"line": record.lineno,
|
||||
}
|
||||
if record.exc_info:
|
||||
entry["exception"] = "".join(traceback.format_exception(*record.exc_info))
|
||||
return json.dumps(entry, default=str)
|
||||
|
||||
|
||||
# Loguru-only level names that stdlib `logging` doesn't recognize.
|
||||
# Mapped to the nearest stdlib level so `dictConfig` accepts them.
|
||||
_LOGURU_TO_STDLIB = {"TRACE": "DEBUG", "SUCCESS": "INFO"}
|
||||
|
||||
|
||||
def build_dict_config(level: str = "info") -> dict[str, Any]:
|
||||
"""`logging.config.dictConfig` payload that routes vLLM, uvicorn,
|
||||
fastapi, and the root logger through `JsonFormatter` to stdout.
|
||||
|
||||
Used inline for the parent process and serialized to disk for vLLM
|
||||
workers (via `VLLM_LOGGING_CONFIG_PATH`).
|
||||
"""
|
||||
upper = _LOGURU_TO_STDLIB.get(level.upper(), level.upper())
|
||||
handler = {
|
||||
"class": "logging.StreamHandler",
|
||||
"formatter": "prime_rl_json",
|
||||
"level": upper,
|
||||
"stream": "ext://sys.stdout",
|
||||
}
|
||||
# Each named logger is configured explicitly: vLLM, uvicorn, and
|
||||
# transformers all set propagate=False on their own loggers, so a
|
||||
# root-only setup wouldn't reach them.
|
||||
named = ("vllm", "uvicorn", "uvicorn.error", "uvicorn.access", "fastapi", "transformers")
|
||||
return {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"formatters": {
|
||||
"prime_rl_json": {
|
||||
"()": "prime_rl.inference.json_logging.JsonFormatter",
|
||||
},
|
||||
},
|
||||
"handlers": {"stdout_json": handler},
|
||||
"loggers": {
|
||||
"": {"handlers": ["stdout_json"], "level": upper},
|
||||
**{name: {"handlers": ["stdout_json"], "level": upper, "propagate": False} for name in named},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def write_logging_config(level: str = "info") -> Path:
|
||||
"""Persist a dictConfig JSON to a temp path. Caller sets the path on
|
||||
`VLLM_LOGGING_CONFIG_PATH` so vLLM (and its spawned workers) load
|
||||
the same config at import time."""
|
||||
config = build_dict_config(level)
|
||||
fd, path_str = tempfile.mkstemp(prefix="prime_rl_logging_", suffix=".json")
|
||||
path = Path(path_str)
|
||||
with open(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(config, f)
|
||||
return path
|
||||
@@ -18,8 +18,6 @@ def transformers_v5_compat():
|
||||
_patch_qwen35_lora()
|
||||
_patch_lora_key_prefix()
|
||||
monkey_patch_deep_gemm_silu_mul_quant_int64()
|
||||
monkey_patch_dp_engine_core_pause_resume_deadlock()
|
||||
monkey_patch_vllm_layerwise_reload_alias_buffers()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
|
||||
@@ -68,38 +66,6 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
|
||||
|
||||
|
||||
def monkey_patch_vllm_layerwise_reload_alias_buffers():
|
||||
# vLLM's layerwise reload materializes each buffer as an independent tensor
|
||||
# and then copies it back into the original kernel storage. When a buffer
|
||||
# aliases a parameter (e.g. NemotronH Mamba's mixer.conv_weights, a view of
|
||||
# mixer.conv1d.weight), the buffer copy stamps garbage into the parameter's
|
||||
# storage *after* the parameter has been correctly reloaded. Skip the copy
|
||||
# for any buffer that shares storage with a parameter; _place_kernel_tensors
|
||||
# re-registers the original view, which trivially reflects the parameter.
|
||||
# Remove this patch once https://github.com/vllm-project/vllm/pull/42481 is
|
||||
# included in the vLLM release we pin/use.
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.reload import layerwise as reload_layerwise
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
def _copy_and_restore_kernel_tensors(layer: torch.nn.Module, info: reload_layerwise.LayerReloadingInfo):
|
||||
assert info.kernel_tensors is not None
|
||||
parameters, buffers = info.kernel_tensors
|
||||
param_storage_ptrs = {p.untyped_storage().data_ptr() for p in layer.parameters(recurse=True)}
|
||||
for name, param in parameters.items():
|
||||
param.data.copy_(getattr(layer, name))
|
||||
for name, buffer in buffers.items():
|
||||
if buffer.untyped_storage().data_ptr() in param_storage_ptrs:
|
||||
continue
|
||||
buffer.data.copy_(getattr(layer, name))
|
||||
|
||||
reload_layerwise._place_kernel_tensors(layer, info)
|
||||
|
||||
reload_layerwise._copy_and_restore_kernel_tensors = _copy_and_restore_kernel_tensors
|
||||
logger.warning("Enabled vLLM layerwise reload alias-buffer patch.")
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel(
|
||||
y_ptr,
|
||||
@@ -782,87 +748,6 @@ def monkey_patch_harmony_stop_token_propagation():
|
||||
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
|
||||
|
||||
|
||||
def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
"""Fix DP pause/resume deadlocks around weight updates.
|
||||
|
||||
Bug 1 (job 3756): while paused, START_DP_WAVE can wake idle ranks into the
|
||||
DP loop. Those ranks then run dummy batches and hit DP collectives while
|
||||
other ranks are still in NCCL weight transfer.
|
||||
|
||||
Bug 2 (jobs 3769/3771): resume ties the DP running state to local
|
||||
unfinished requests, but the DP wave state is global. Ranks with no local
|
||||
work still need to re-enter the loop so they can participate in the same
|
||||
DP collectives as ranks that are resuming remote-KV or decode work.
|
||||
|
||||
Fix:
|
||||
- ignore START_DP_WAVE wakeups while paused
|
||||
- on resume, wake every DP rank and force an immediate global unfinished
|
||||
sync instead of waiting for the normal 32-step cadence
|
||||
|
||||
This also bypasses vLLM's two-phase DP pause implementation
|
||||
(https://github.com/vllm-project/vllm/pull/39366), which makes resume
|
||||
reject states that our weight-update flow can validly hit.
|
||||
"""
|
||||
from vllm.config import ParallelConfig
|
||||
from vllm.v1.core.sched.interface import PauseState
|
||||
from vllm.v1.engine import EngineCoreOutputs, EngineCoreRequestType
|
||||
from vllm.v1.engine.core import DPEngineCoreProc, EngineCore, EngineCoreProc
|
||||
from vllm.v1.request import Request
|
||||
|
||||
_base_add_request = EngineCore.add_request
|
||||
_base_handle_client_request = EngineCoreProc._handle_client_request
|
||||
_base_pause_complete = EngineCoreProc._pause_complete
|
||||
_base_resume_scheduler = EngineCoreProc.resume_scheduler
|
||||
|
||||
def _patched_add_request(self, request: Request, request_wave: int = 0):
|
||||
_base_add_request(self, request, request_wave)
|
||||
if self.has_coordinator and request_wave != self.current_wave:
|
||||
if request_wave > self.current_wave:
|
||||
self.current_wave = request_wave
|
||||
elif not self.engines_running and self.scheduler.pause_state == PauseState.UNPAUSED:
|
||||
self.engines_running = True
|
||||
self.output_queue.put_nowait((-1, EngineCoreOutputs(start_wave=self.current_wave)))
|
||||
|
||||
def _patched_handle_client_request(self, request_type, request):
|
||||
if request_type == EngineCoreRequestType.START_DP_WAVE:
|
||||
new_wave, exclude_eng_index = request
|
||||
if exclude_eng_index != self.engine_index and new_wave >= self.current_wave:
|
||||
self.current_wave = new_wave
|
||||
if not self.engines_running and self.scheduler.pause_state == PauseState.UNPAUSED:
|
||||
self.engines_running = True
|
||||
else:
|
||||
_base_handle_client_request(self, request_type, request)
|
||||
|
||||
def _patched_pause_complete(self) -> bool:
|
||||
self.pending_pause = False
|
||||
self.ignore_start_dp_wave = False
|
||||
return _base_pause_complete(self)
|
||||
|
||||
def _patched_resume_scheduler(self):
|
||||
was_paused = self.scheduler.pause_state != PauseState.UNPAUSED
|
||||
self.pending_pause = False
|
||||
self.ignore_start_dp_wave = False
|
||||
_base_resume_scheduler(self)
|
||||
if was_paused:
|
||||
self.engines_running = True
|
||||
self._force_dp_running_state_sync = True
|
||||
|
||||
def _patched_has_global_unfinished_reqs(self, local_unfinished: bool) -> bool:
|
||||
self.step_counter += 1
|
||||
if getattr(self, "_force_dp_running_state_sync", False):
|
||||
self._force_dp_running_state_sync = False
|
||||
return ParallelConfig.has_unfinished_dp(self.dp_group, local_unfinished)
|
||||
if self.step_counter % 32 != 0:
|
||||
return True
|
||||
return ParallelConfig.has_unfinished_dp(self.dp_group, local_unfinished)
|
||||
|
||||
DPEngineCoreProc.add_request = _patched_add_request
|
||||
DPEngineCoreProc._handle_client_request = _patched_handle_client_request
|
||||
DPEngineCoreProc._pause_complete = _patched_pause_complete
|
||||
DPEngineCoreProc.resume_scheduler = _patched_resume_scheduler
|
||||
DPEngineCoreProc._has_global_unfinished_reqs = _patched_has_global_unfinished_reqs
|
||||
|
||||
|
||||
def monkey_patch_no_moe_lora():
|
||||
"""This disables LoRA for MoE layers and makes them pick better kernels.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import logging.config
|
||||
import os
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
@@ -10,9 +11,28 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
deep_gemm_enabled = "1" if config.use_deep_gemm else "0"
|
||||
os.environ["VLLM_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
os.environ["VLLM_MOE_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
|
||||
if config.enable_lora:
|
||||
os.environ["VLLM_ALLOW_RUNTIME_LORA_UPDATING"] = "True"
|
||||
|
||||
if config.log.json_logging:
|
||||
# Route vLLM's stdlib loggers through a JSON formatter matching
|
||||
# trainer / orchestrator. The env var (not in-process dictConfig)
|
||||
# is what reaches vLLM's spawned workers.
|
||||
from prime_rl.inference.json_logging import build_dict_config, write_logging_config
|
||||
|
||||
config_path = write_logging_config(config.log.level)
|
||||
# vLLM raises if VLLM_LOGGING_CONFIG_PATH is set while
|
||||
# VLLM_CONFIGURE_LOGGING=0 (its supported way to disable logger
|
||||
# setup). Force it on — opting into JSON logging is an explicit
|
||||
# request to configure vLLM's logger.
|
||||
os.environ["VLLM_CONFIGURE_LOGGING"] = "1"
|
||||
os.environ["VLLM_LOGGING_CONFIG_PATH"] = str(config_path)
|
||||
logging.config.dictConfig(build_dict_config(config.log.level))
|
||||
|
||||
|
||||
def main():
|
||||
config = cli(InferenceConfig)
|
||||
|
||||
@@ -8,7 +8,7 @@ import pybase64
|
||||
from vllm.outputs import RequestOutput
|
||||
|
||||
|
||||
def serialize_routed_experts(routed_experts: Any) -> dict[str, Any] | None:
|
||||
def serialize_routed_experts(routed_experts: Any, start: int = 0) -> dict[str, Any] | None:
|
||||
if routed_experts is None:
|
||||
return None
|
||||
|
||||
@@ -23,18 +23,20 @@ def serialize_routed_experts(routed_experts: Any) -> dict[str, Any] | None:
|
||||
return {
|
||||
"data": pybase64.b64encode(memoryview(compact)).decode("ascii"),
|
||||
"shape": list(compact.shape),
|
||||
"start": start,
|
||||
}
|
||||
|
||||
|
||||
class RoutedExpertsCapture:
|
||||
def __init__(self, generator: AsyncIterator[RequestOutput]):
|
||||
def __init__(self, generator: AsyncIterator[RequestOutput], start: int = 0):
|
||||
self._generator = generator
|
||||
self._start = start
|
||||
self.routed_experts: dict[int, dict[str, Any]] = {}
|
||||
|
||||
async def __aiter__(self):
|
||||
async for request_output in self._generator:
|
||||
for output in request_output.outputs:
|
||||
encoded = serialize_routed_experts(getattr(output, "routed_experts", None))
|
||||
encoded = serialize_routed_experts(getattr(output, "routed_experts", None), start=self._start)
|
||||
if encoded is not None:
|
||||
self.routed_experts[output.index] = encoded
|
||||
yield request_output
|
||||
|
||||
@@ -61,6 +61,7 @@ WORKER_EXTENSION_CLS = {
|
||||
|
||||
@router.post("/pause")
|
||||
async def pause(request: Request):
|
||||
logger.debug("Received /pause request (mode=keep, clear_cache=False)")
|
||||
await engine_client(request).pause_generation(mode="keep", clear_cache=False)
|
||||
return {"status": "paused"}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user