Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
84f072bc99 |
@@ -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
|
||||
|
||||
@@ -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,10 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`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)
|
||||
|
||||
+38
-1
@@ -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,7 +52,7 @@ 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 | ✅ | ❌ |
|
||||
@@ -217,17 +217,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 +245,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
|
||||
|
||||
@@ -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,4 @@
|
||||
max_steps = 5
|
||||
max_async_level = 5
|
||||
batch_size = 16
|
||||
|
||||
[train.sampling]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -19,10 +19,6 @@ 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"
|
||||
@@ -39,7 +35,11 @@ gpus_per_node = 2
|
||||
[orchestrator]
|
||||
batch_size = 16
|
||||
group_size = 8
|
||||
use_renderer = true
|
||||
# 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
|
||||
|
||||
# Track zero-advantage groups but don't drop them — we're validating the
|
||||
# multimodal renderer path on 20 steps, not optimizing training efficiency.
|
||||
@@ -62,13 +62,8 @@ max_completion_tokens = 64
|
||||
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
|
||||
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
|
||||
# MODEL_RENDERER_MAP to Qwen3VLRenderer at runtime; no explicit name needed.
|
||||
|
||||
[trainer]
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ level = "debug"
|
||||
[wandb]
|
||||
project = "sami_debug_nemotron"
|
||||
name = "nemotron-120b-math"
|
||||
shared = true
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
@@ -17,7 +17,6 @@ level = "debug"
|
||||
[wandb]
|
||||
project = "nemotron_sami_debug"
|
||||
name = "nemotron-120b-math"
|
||||
shared = true
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
+1
-1
Submodule configs/private updated: 894caa0047...70c3503e1d
Vendored
+1
-1
Submodule deps/pydantic-config updated: 94d71ecdec...896ade4e69
Vendored
+1
-1
Submodule deps/renderers updated: 3ae276c446...35c2407e92
Vendored
+1
-1
Submodule deps/research-environments updated: d141472268...c752781984
Vendored
+1
-1
Submodule deps/verifiers updated: 04651bec3e...43016ea6e4
@@ -0,0 +1,147 @@
|
||||
# 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 EP, 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`**: Custom kernels from DeepEP. Faster but requires DeepEP build (`bash scripts/install_deep_gemm.sh`, `bash scripts/install_ep_kernels.sh`) and tuning of `deepep_num_sms` (default 20) and `deepep_token_chunk_size` for your hardware.
|
||||
|
||||
DeepEP intranode dispatch derives the RDMA channel count as `deepep_num_sms / 2`. Lower SM count leaves more for compute; higher speeds up dispatch. Useful starting points: 16–24 SMs on H100, 20–40 on B200.
|
||||
|
||||
When you enable DeepEP, gradient clipping is auto-disabled (`optim.max_norm` set to `None`) because the kernels don't currently support it.
|
||||
|
||||
## 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
|
||||
```
|
||||
|
||||
A bad attribute path errors immediately — no silent fallbacks. 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/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/src/prime_rl/trainer/runs).
|
||||
|
||||
## 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. Most clusters ship UCX 1.17 via HPC-X, which manifests as `cuStreamCreate: invalid device context` errors during DeepEP internode dispatch. Check with `/opt/hpcx/ucx/bin/ucx_info -v` and, if needed, build from source:
|
||||
|
||||
```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,304 @@
|
||||
# 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.
|
||||
|
||||
## 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,131 @@
|
||||
# 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.
|
||||
@@ -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
|
||||
@@ -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
|
||||
```
|
||||
|
||||
+7
-14
@@ -4,20 +4,13 @@
|
||||
{
|
||||
"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",
|
||||
"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,44 @@
|
||||
# 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). Supports data + tensor + expert parallelism (with `deepep` and `flashinfer` all-to-all backends and EPLB), FP8 inference, prefill/decode disaggregation behind a `vllm-router`, CPU KV-cache offload, and *router replay* (the routed-expert mask is returned to the trainer for FP8 MoE numerical parity). Weights are pushed in place through a custom `update_weights` endpoint over filesystem or NCCL transports.
|
||||
- **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).
|
||||
|
||||
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, MoE-only installs (DeepGEMM / DeepEP / NIXL), 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.
|
||||
- **[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.
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
# 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. For knobs that fit on one box, see [Training](training.md) first. For prefill/decode disaggregated inference, see [Advanced](advanced.md#disaggregated-prefilldecode-inference).
|
||||
|
||||
## 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. 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. Only available with the custom impl and flash-attention.
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2" # or fa3 / fa4
|
||||
cp = 2 # CP degree
|
||||
cp_style = "ring" # "ulysses" for non-FA kernels
|
||||
```
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
@@ -256,7 +256,7 @@ 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. Only works with per-tensor FP8 quantization (e.g. GLM-5-FP8)."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig = WeightBroadcastConfig()
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -570,8 +538,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``); SFT mode forces this."""
|
||||
|
||||
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."""
|
||||
@@ -595,6 +585,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,14 +631,8 @@ 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."""
|
||||
"""Benchmark mode. Sets ``max_steps`` to 5 and disables W&B."""
|
||||
|
||||
seed: int | None = 42
|
||||
"""Random seed for the orchestrator."""
|
||||
@@ -653,9 +640,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
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``."""
|
||||
|
||||
@@ -783,11 +767,11 @@ class OrchestratorConfig(BaseConfig):
|
||||
@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
|
||||
renderer client doesn't apply. Force ``renderer=None`` 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
|
||||
self.renderer = None
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -801,33 +785,15 @@ class OrchestratorConfig(BaseConfig):
|
||||
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 +805,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 +816,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 +833,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
|
||||
@@ -936,7 +895,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,
|
||||
@@ -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)
|
||||
@@ -614,6 +565,9 @@ 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:
|
||||
role_order = ["prefill"] * infer_deploy.num_prefill_nodes + ["decode"] * infer_deploy.num_decode_nodes
|
||||
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 +596,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."""
|
||||
|
||||
@@ -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)
|
||||
@@ -90,25 +96,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 +125,23 @@ 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")
|
||||
|
||||
# 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 +162,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 +271,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,
|
||||
|
||||
+36
-2
@@ -66,6 +66,7 @@ envs = [
|
||||
"code-env",
|
||||
"color-codeword",
|
||||
"deepdive",
|
||||
"general-agent",
|
||||
"gpqa",
|
||||
"hle",
|
||||
"ifeval",
|
||||
@@ -98,6 +99,9 @@ disagg = [
|
||||
gpt-oss = [
|
||||
"kernels",
|
||||
]
|
||||
modelexpress = [
|
||||
"modelexpress==0.3.0",
|
||||
]
|
||||
quack = [
|
||||
"quack-kernels>=0.4.1",
|
||||
]
|
||||
@@ -118,6 +122,7 @@ dev = [
|
||||
"ipywidgets>=8.1.7",
|
||||
"pre-commit>=4.2.0",
|
||||
"pytest>=8.4.1",
|
||||
"pytest-asyncio>=0.23",
|
||||
"ruff>=0.12.1",
|
||||
]
|
||||
|
||||
@@ -137,6 +142,7 @@ members = [
|
||||
"deps/research-environments/environments/code_env",
|
||||
"deps/research-environments/environments/color_codeword",
|
||||
"deps/research-environments/environments/deepdive",
|
||||
"deps/research-environments/environments/general_agent",
|
||||
"deps/research-environments/environments/gpqa",
|
||||
"deps/research-environments/environments/hle",
|
||||
"deps/research-environments/environments/ifeval",
|
||||
@@ -158,6 +164,11 @@ members = [
|
||||
]
|
||||
|
||||
[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"]
|
||||
@@ -175,17 +186,39 @@ override-dependencies = [
|
||||
"openenv-core",
|
||||
]
|
||||
|
||||
# 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]
|
||||
# we want latest vllm, remove next patch
|
||||
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
|
||||
prime-pydantic-config = false
|
||||
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
|
||||
vllm-router = false
|
||||
dion = false
|
||||
@@ -203,6 +236,7 @@ alphabet-sort = { workspace = true }
|
||||
code-env = { workspace = true }
|
||||
color-codeword = { workspace = true }
|
||||
deepdive = { workspace = true }
|
||||
general-agent = { workspace = true }
|
||||
gpqa = { workspace = true }
|
||||
hle = { workspace = true }
|
||||
ifeval = { workspace = true }
|
||||
@@ -232,7 +266,7 @@ 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'" },
|
||||
|
||||
@@ -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,44 +186,12 @@ 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
|
||||
@@ -420,7 +380,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
if config.inference.kv_cache_offload
|
||||
else 0,
|
||||
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,7 +393,6 @@ 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,
|
||||
@@ -444,7 +402,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
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,
|
||||
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)),
|
||||
)
|
||||
|
||||
|
||||
@@ -10,6 +10,10 @@ 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"
|
||||
|
||||
|
||||
@@ -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"}
|
||||
|
||||
|
||||
@@ -266,7 +266,11 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
# experts surface in the JSON.
|
||||
capture: _GenerateRoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
capture = _GenerateRoutedExpertsCapture(result_generator)
|
||||
start = request.sampling_params.routed_experts_prompt_start
|
||||
capture = _GenerateRoutedExpertsCapture(
|
||||
result_generator,
|
||||
start=start,
|
||||
)
|
||||
result_generator = capture
|
||||
|
||||
response = await super().serve_tokens_full_generator(
|
||||
|
||||
@@ -186,7 +186,6 @@ class EvalEnv(Env):
|
||||
self,
|
||||
model_name: str,
|
||||
get_client: Callable[[], Awaitable[vf.ClientConfig]],
|
||||
ckpt_step: int,
|
||||
step: int,
|
||||
cache_salt: str,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
@@ -256,7 +255,6 @@ class EvalEnv(Env):
|
||||
get_monitor().log(
|
||||
{
|
||||
f"eval/{self.name}/failed_rollouts": failed_count / total_rollouts,
|
||||
"progress/ckpt_step": ckpt_step,
|
||||
"step": step,
|
||||
},
|
||||
step=step,
|
||||
@@ -319,7 +317,7 @@ class EvalEnv(Env):
|
||||
assert pass_at_k is not None
|
||||
eval_metrics.update(pd.Series(pass_at_k.mean()).to_dict())
|
||||
eval_metrics = {f"eval/{self.name}/{key}": v for key, v in eval_metrics.items()}
|
||||
eval_metrics.update({"progress/ckpt_step": ckpt_step, "step": step})
|
||||
eval_metrics["step"] = step
|
||||
monitor.log(eval_metrics, step=step)
|
||||
monitor.log_eval_samples(successful_outputs, env_name=self.name, step=step)
|
||||
|
||||
|
||||
@@ -1,32 +1,6 @@
|
||||
import numpy as np
|
||||
|
||||
|
||||
def compute_eval_ckpt_step(
|
||||
ckpt_step: int,
|
||||
prev_ckpt_step: int,
|
||||
last_eval_step: int,
|
||||
interval: int,
|
||||
eval_base_model: bool = True,
|
||||
) -> int | None:
|
||||
"""Determine which checkpoint step (if any) should trigger an eval.
|
||||
|
||||
Handles the case where ckpt_step jumps over interval boundaries by finding
|
||||
the highest interval-aligned step in (prev_ckpt_step, ckpt_step].
|
||||
|
||||
Returns the interval step to eval at, or None if no eval should run.
|
||||
"""
|
||||
if ckpt_step <= prev_ckpt_step:
|
||||
return None
|
||||
highest_interval_step = (ckpt_step // interval) * interval
|
||||
if highest_interval_step > prev_ckpt_step and highest_interval_step > last_eval_step:
|
||||
if highest_interval_step == 0:
|
||||
if ckpt_step == 0 and eval_base_model:
|
||||
return 0
|
||||
else:
|
||||
return highest_interval_step
|
||||
return None
|
||||
|
||||
|
||||
def _pass_at_k(n: int, c: int, k: int) -> float:
|
||||
"""Unbiased estimator of pass@k (Chen et al., 2021).
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import time
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import wandb
|
||||
from httpx import AsyncClient
|
||||
@@ -12,93 +13,390 @@ from prime_rl.utils.logger import get_logger
|
||||
|
||||
POLL_INTERVAL = 5.0
|
||||
WINDOW_SIZE = 20
|
||||
PD_ROLES = {"prefill", "decode"}
|
||||
|
||||
# Gauge metrics: collected as instantaneous values
|
||||
GAUGE_METRICS = {
|
||||
"vllm:num_requests_running",
|
||||
"vllm:num_requests_waiting",
|
||||
"vllm:gpu_cache_usage_perc",
|
||||
"vllm:gpu_prefix_cache_hit_rate",
|
||||
COUNTER_KEYS = {
|
||||
"vllm:prompt_tokens": "prompt_tokens_total",
|
||||
"vllm:prompt_tokens_total": "prompt_tokens_total",
|
||||
"vllm:generation_tokens": "generation_tokens_total",
|
||||
"vllm:generation_tokens_total": "generation_tokens_total",
|
||||
"vllm:request_success": "request_success_total",
|
||||
"vllm:request_success_total": "request_success_total",
|
||||
"vllm:prefix_cache_queries": "prefix_cache_queries",
|
||||
"vllm:prefix_cache_queries_total": "prefix_cache_queries",
|
||||
"vllm:prefix_cache_hits": "prefix_cache_hits",
|
||||
"vllm:prefix_cache_hits_total": "prefix_cache_hits",
|
||||
"vllm:nixl_num_failed_transfers_total": "nixl_failed_transfers_total",
|
||||
"vllm:nixl_num_failed_notifications_total": "nixl_failed_notifications_total",
|
||||
"vllm:nixl_num_kv_expired_reqs_total": "nixl_kv_expired_requests_total",
|
||||
}
|
||||
|
||||
# Counter metrics: converted to per-second rates via delta/dt
|
||||
COUNTER_METRICS = {
|
||||
"vllm:prompt_tokens",
|
||||
"vllm:generation_tokens",
|
||||
"vllm:request_success",
|
||||
GAUGE_KEYS = {
|
||||
"vllm:num_requests_running": "running_requests",
|
||||
"vllm:num_requests_waiting": "waiting_requests",
|
||||
"vllm:kv_cache_usage_perc": "kv_cache_usage_perc",
|
||||
"vllm:gpu_cache_usage_perc": "kv_cache_usage_perc",
|
||||
"vllm:cpu_cache_usage_perc": "cpu_cache_usage_perc",
|
||||
"vllm:gpu_prefix_cache_hit_rate": "gpu_prefix_cache_hit_rate",
|
||||
"vllm:cpu_prefix_cache_hit_rate": "cpu_prefix_cache_hit_rate",
|
||||
}
|
||||
|
||||
COUNTER_RATE_NAMES = {
|
||||
"vllm:prompt_tokens": "prefill_throughput_tps",
|
||||
"vllm:generation_tokens": "decode_throughput_tps",
|
||||
"vllm:request_success": "completed_requests_per_s",
|
||||
HISTOGRAM_SUM_KEYS = {
|
||||
"vllm:request_prefill_time_seconds_sum": "request_prefill_time_seconds_sum",
|
||||
"vllm:request_decode_time_seconds_sum": "request_decode_time_seconds_sum",
|
||||
"vllm:request_queue_time_seconds_sum": "request_queue_time_seconds_sum",
|
||||
"vllm:time_to_first_token_seconds_sum": "time_to_first_token_seconds_sum",
|
||||
"vllm:inter_token_latency_seconds_sum": "inter_token_latency_seconds_sum",
|
||||
"vllm:e2e_request_latency_seconds_sum": "e2e_request_latency_seconds_sum",
|
||||
"vllm:nixl_xfer_time_seconds_sum": "nixl_xfer_time_seconds_sum",
|
||||
"vllm:nixl_bytes_transferred_sum": "nixl_bytes_transferred_sum",
|
||||
}
|
||||
|
||||
# Histogram metrics: converted to average latency per interval
|
||||
HISTOGRAM_METRICS = {
|
||||
"vllm:nixl_xfer_time_seconds",
|
||||
HISTOGRAM_COUNT_KEYS = {
|
||||
"vllm:request_prefill_time_seconds_count": "request_prefill_time_seconds_count",
|
||||
"vllm:request_decode_time_seconds_count": "request_decode_time_seconds_count",
|
||||
"vllm:request_queue_time_seconds_count": "request_queue_time_seconds_count",
|
||||
"vllm:time_to_first_token_seconds_count": "time_to_first_token_seconds_count",
|
||||
"vllm:inter_token_latency_seconds_count": "inter_token_latency_seconds_count",
|
||||
"vllm:e2e_request_latency_seconds_count": "e2e_request_latency_seconds_count",
|
||||
"vllm:nixl_xfer_time_seconds_count": "nixl_xfer_time_seconds_count",
|
||||
"vllm:nixl_bytes_transferred_count": "nixl_bytes_transferred_count",
|
||||
}
|
||||
|
||||
_COUNTER_TOTAL_TO_NAME = {f"{name}_total": name for name in COUNTER_METRICS}
|
||||
|
||||
# Gauges where we log both max and mean across engines (to show imbalance)
|
||||
_DUAL_AGG_GAUGES = {"vllm:gpu_cache_usage_perc", "vllm:gpu_prefix_cache_hit_rate"}
|
||||
@dataclass
|
||||
class EngineRollup:
|
||||
running_requests: float = 0.0
|
||||
waiting_requests: float = 0.0
|
||||
kv_cache_usage_perc: float = 0.0
|
||||
cpu_cache_usage_perc: float | None = None
|
||||
gpu_prefix_cache_hit_rate: float | None = None
|
||||
cpu_prefix_cache_hit_rate: float | None = None
|
||||
prompt_tokens_total: float = 0.0
|
||||
generation_tokens_total: float = 0.0
|
||||
request_success_total: float = 0.0
|
||||
prefix_cache_queries: float = 0.0
|
||||
prefix_cache_hits: float = 0.0
|
||||
nixl_failed_transfers_total: float = 0.0
|
||||
nixl_failed_notifications_total: float = 0.0
|
||||
nixl_kv_expired_requests_total: float = 0.0
|
||||
request_prefill_time_seconds_sum: float = 0.0
|
||||
request_prefill_time_seconds_count: float = 0.0
|
||||
request_decode_time_seconds_sum: float = 0.0
|
||||
request_decode_time_seconds_count: float = 0.0
|
||||
request_queue_time_seconds_sum: float = 0.0
|
||||
request_queue_time_seconds_count: float = 0.0
|
||||
time_to_first_token_seconds_sum: float = 0.0
|
||||
time_to_first_token_seconds_count: float = 0.0
|
||||
inter_token_latency_seconds_sum: float = 0.0
|
||||
inter_token_latency_seconds_count: float = 0.0
|
||||
e2e_request_latency_seconds_sum: float = 0.0
|
||||
e2e_request_latency_seconds_count: float = 0.0
|
||||
nixl_xfer_time_seconds_sum: float = 0.0
|
||||
nixl_xfer_time_seconds_count: float = 0.0
|
||||
nixl_bytes_transferred_sum: float = 0.0
|
||||
nixl_bytes_transferred_count: float = 0.0
|
||||
|
||||
|
||||
def parse_prometheus_text(text: str) -> tuple[dict[str, float], dict[str, float], dict[str, tuple[float, float]]]:
|
||||
"""Parse Prometheus exposition format into (gauges, counters, histograms).
|
||||
@dataclass
|
||||
class NodeRollup:
|
||||
engines: dict[str, EngineRollup] = field(default_factory=dict)
|
||||
|
||||
For gauge metrics, returns the per-server aggregate (sum for queue sizes,
|
||||
max for per-engine metrics like kv cache within a single server).
|
||||
"""
|
||||
gauges: dict[str, float] = {}
|
||||
counters: dict[str, float] = {}
|
||||
histograms: dict[str, tuple[float, float]] = {}
|
||||
@property
|
||||
def engine_count(self) -> int:
|
||||
return len(self.engines)
|
||||
|
||||
def summed(self, attribute: str) -> float:
|
||||
return sum(getattr(engine, attribute) for engine in self.engines.values())
|
||||
|
||||
def values(self, attribute: str) -> list[float]:
|
||||
return [value for engine in self.engines.values() if (value := getattr(engine, attribute)) is not None]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MetricsEndpoint:
|
||||
client: AsyncClient
|
||||
role: str | None
|
||||
key: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TimedRollup:
|
||||
timestamp: float
|
||||
rollup: NodeRollup
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EndpointSample:
|
||||
endpoint: MetricsEndpoint
|
||||
timestamp: float
|
||||
rollup: NodeRollup
|
||||
|
||||
|
||||
def parse_prometheus_text(text: str) -> NodeRollup:
|
||||
"""Parse vLLM Prometheus metrics into per-engine counters, gauges, and histogram totals."""
|
||||
engines: dict[str, EngineRollup] = {}
|
||||
for family in text_string_to_metric_families(text):
|
||||
if family.type == "gauge" and family.name in GAUGE_METRICS:
|
||||
for sample in family.samples:
|
||||
if family.name in _DUAL_AGG_GAUGES:
|
||||
gauges[family.name] = max(gauges.get(family.name, 0.0), sample.value)
|
||||
else:
|
||||
gauges[family.name] = gauges.get(family.name, 0.0) + sample.value
|
||||
for sample in family.samples:
|
||||
engine_id = sample.labels.get("engine", "aggregate")
|
||||
engine = engines.setdefault(engine_id, EngineRollup())
|
||||
if sample.name in GAUGE_KEYS:
|
||||
setattr(engine, GAUGE_KEYS[sample.name], float(sample.value))
|
||||
elif sample.name in COUNTER_KEYS:
|
||||
attribute = COUNTER_KEYS[sample.name]
|
||||
setattr(engine, attribute, getattr(engine, attribute) + float(sample.value))
|
||||
elif sample.name in HISTOGRAM_SUM_KEYS:
|
||||
setattr(engine, HISTOGRAM_SUM_KEYS[sample.name], float(sample.value))
|
||||
elif sample.name in HISTOGRAM_COUNT_KEYS:
|
||||
setattr(engine, HISTOGRAM_COUNT_KEYS[sample.name], float(sample.value))
|
||||
return NodeRollup(engines=engines)
|
||||
|
||||
elif family.type == "counter" and family.name in COUNTER_METRICS:
|
||||
for sample in family.samples:
|
||||
counters[family.name] = counters.get(family.name, 0.0) + sample.value
|
||||
|
||||
elif family.name in _COUNTER_TOTAL_TO_NAME:
|
||||
canonical = _COUNTER_TOTAL_TO_NAME[family.name]
|
||||
for sample in family.samples:
|
||||
counters[canonical] = counters.get(canonical, 0.0) + sample.value
|
||||
def build_metrics_endpoints(
|
||||
admin_clients: list[AsyncClient], roles: list[str | None] | None = None
|
||||
) -> list[MetricsEndpoint]:
|
||||
"""Attach optional P/D roles to admin clients used for metrics polling."""
|
||||
if roles is None:
|
||||
roles = [None] * len(admin_clients)
|
||||
if len(roles) != len(admin_clients):
|
||||
raise ValueError(f"Got {len(roles)} inference metric role(s) for {len(admin_clients)} admin client(s)")
|
||||
|
||||
elif family.type == "histogram" and family.name in HISTOGRAM_METRICS:
|
||||
h_sum = 0.0
|
||||
h_count = 0.0
|
||||
for sample in family.samples:
|
||||
if sample.name.endswith("_sum"):
|
||||
h_sum += sample.value
|
||||
elif sample.name.endswith("_count"):
|
||||
h_count += sample.value
|
||||
histograms[family.name] = (h_sum, h_count)
|
||||
endpoints: list[MetricsEndpoint] = []
|
||||
for client, role in zip(admin_clients, roles):
|
||||
normalized_role = role if role in PD_ROLES else None
|
||||
if role is not None and normalized_role is None:
|
||||
raise ValueError(f"Unsupported inference metrics role: {role}")
|
||||
endpoints.append(MetricsEndpoint(client=client, role=normalized_role, key=str(client.base_url).rstrip("/")))
|
||||
return endpoints
|
||||
|
||||
return gauges, counters, histograms
|
||||
|
||||
def max_vio(values: list[float]) -> float:
|
||||
"""Return the max-load violation used for MoE load-balance reporting."""
|
||||
if not values:
|
||||
return 0.0
|
||||
balanced_load = sum(values) / len(values)
|
||||
if balanced_load == 0:
|
||||
return 0.0
|
||||
return (max(values) - balanced_load) / balanced_load
|
||||
|
||||
|
||||
def counter_rate(samples: list[EndpointSample], previous: dict[str, TimedRollup], attribute: str) -> float | None:
|
||||
"""Sum per-endpoint counter rates for a scope."""
|
||||
rates: list[float] = []
|
||||
for sample in samples:
|
||||
previous_sample = previous.get(sample.endpoint.key)
|
||||
if previous_sample is None:
|
||||
continue
|
||||
dt = sample.timestamp - previous_sample.timestamp
|
||||
delta = sample.rollup.summed(attribute) - previous_sample.rollup.summed(attribute)
|
||||
if dt <= 0 or delta < 0:
|
||||
continue
|
||||
rates.append(delta / dt)
|
||||
if not rates:
|
||||
return None
|
||||
return sum(rates)
|
||||
|
||||
|
||||
def counter_ratio(
|
||||
samples: list[EndpointSample],
|
||||
previous: dict[str, TimedRollup],
|
||||
numerator_attribute: str,
|
||||
denominator_attribute: str,
|
||||
) -> float | None:
|
||||
"""Compute a scope-level ratio from counter deltas."""
|
||||
numerator_delta = 0.0
|
||||
denominator_delta = 0.0
|
||||
for sample in samples:
|
||||
previous_sample = previous.get(sample.endpoint.key)
|
||||
if previous_sample is None:
|
||||
continue
|
||||
endpoint_numerator_delta = sample.rollup.summed(numerator_attribute) - previous_sample.rollup.summed(
|
||||
numerator_attribute
|
||||
)
|
||||
endpoint_denominator_delta = sample.rollup.summed(denominator_attribute) - previous_sample.rollup.summed(
|
||||
denominator_attribute
|
||||
)
|
||||
if endpoint_numerator_delta < 0 or endpoint_denominator_delta < 0:
|
||||
continue
|
||||
numerator_delta += endpoint_numerator_delta
|
||||
denominator_delta += endpoint_denominator_delta
|
||||
if denominator_delta <= 0:
|
||||
return None
|
||||
return numerator_delta / denominator_delta
|
||||
|
||||
|
||||
def histogram_average(
|
||||
samples: list[EndpointSample],
|
||||
previous: dict[str, TimedRollup],
|
||||
sum_attribute: str,
|
||||
count_attribute: str,
|
||||
) -> float | None:
|
||||
"""Compute a scope-level histogram average from sum/count deltas."""
|
||||
sum_delta = 0.0
|
||||
count_delta = 0.0
|
||||
for sample in samples:
|
||||
previous_sample = previous.get(sample.endpoint.key)
|
||||
if previous_sample is None:
|
||||
continue
|
||||
endpoint_sum_delta = sample.rollup.summed(sum_attribute) - previous_sample.rollup.summed(sum_attribute)
|
||||
endpoint_count_delta = sample.rollup.summed(count_attribute) - previous_sample.rollup.summed(count_attribute)
|
||||
if endpoint_sum_delta < 0 or endpoint_count_delta < 0:
|
||||
continue
|
||||
sum_delta += endpoint_sum_delta
|
||||
count_delta += endpoint_count_delta
|
||||
if count_delta <= 0:
|
||||
return None
|
||||
return sum_delta / count_delta
|
||||
|
||||
|
||||
def mean(values: list[float]) -> float | None:
|
||||
"""Return the arithmetic mean for non-empty metric value lists."""
|
||||
if not values:
|
||||
return None
|
||||
return sum(values) / len(values)
|
||||
|
||||
|
||||
def build_scope_metrics(
|
||||
scope: str,
|
||||
samples: list[EndpointSample],
|
||||
previous: dict[str, TimedRollup],
|
||||
) -> dict[str, float]:
|
||||
"""Build W&B metric values for one inference scope."""
|
||||
running_values = [value for sample in samples for value in sample.rollup.values("running_requests")]
|
||||
waiting_values = [value for sample in samples for value in sample.rollup.values("waiting_requests")]
|
||||
kv_values = [value for sample in samples for value in sample.rollup.values("kv_cache_usage_perc")]
|
||||
cpu_kv_values = [value for sample in samples for value in sample.rollup.values("cpu_cache_usage_perc")]
|
||||
prefix_gauge_values = [value for sample in samples for value in sample.rollup.values("gpu_prefix_cache_hit_rate")]
|
||||
cpu_prefix_values = [value for sample in samples for value in sample.rollup.values("cpu_prefix_cache_hit_rate")]
|
||||
|
||||
prefix = f"inference/{scope}"
|
||||
metrics: dict[str, float] = {
|
||||
f"{prefix}/running_requests": sum(running_values),
|
||||
f"{prefix}/waiting_requests": sum(waiting_values),
|
||||
f"{prefix}/running_imbalance": max_vio(running_values),
|
||||
f"{prefix}/waiting_imbalance": max_vio(waiting_values),
|
||||
f"{prefix}/nixl_failed_transfers_total": sum(
|
||||
sample.rollup.summed("nixl_failed_transfers_total") for sample in samples
|
||||
),
|
||||
f"{prefix}/nixl_failed_notifications_total": sum(
|
||||
sample.rollup.summed("nixl_failed_notifications_total") for sample in samples
|
||||
),
|
||||
f"{prefix}/nixl_kv_expired_requests_total": sum(
|
||||
sample.rollup.summed("nixl_kv_expired_requests_total") for sample in samples
|
||||
),
|
||||
}
|
||||
|
||||
if kv_values:
|
||||
metrics[f"{prefix}/kv_cache_usage_mean"] = sum(kv_values) / len(kv_values)
|
||||
metrics[f"{prefix}/kv_cache_usage_max"] = max(kv_values)
|
||||
if cpu_kv_values:
|
||||
metrics[f"{prefix}/cpu_kv_cache_usage_mean"] = sum(cpu_kv_values) / len(cpu_kv_values)
|
||||
metrics[f"{prefix}/cpu_kv_cache_usage_max"] = max(cpu_kv_values)
|
||||
|
||||
prefix_cache_hit_rate = counter_ratio(samples, previous, "prefix_cache_hits", "prefix_cache_queries")
|
||||
if prefix_cache_hit_rate is None:
|
||||
prefix_cache_hit_rate = mean(prefix_gauge_values)
|
||||
if prefix_cache_hit_rate is not None:
|
||||
metrics[f"{prefix}/prefix_cache_hit_rate"] = prefix_cache_hit_rate
|
||||
cpu_prefix_cache_hit_rate = mean(cpu_prefix_values)
|
||||
if cpu_prefix_cache_hit_rate is not None:
|
||||
metrics[f"{prefix}/cpu_prefix_cache_hit_rate"] = cpu_prefix_cache_hit_rate
|
||||
|
||||
prompt_token_rate = counter_rate(samples, previous, "prompt_tokens_total")
|
||||
generation_token_rate = counter_rate(samples, previous, "generation_tokens_total")
|
||||
if scope == "prefill":
|
||||
if prompt_token_rate is not None:
|
||||
metrics[f"{prefix}/throughput"] = prompt_token_rate
|
||||
elif scope == "decode":
|
||||
if generation_token_rate is not None:
|
||||
metrics[f"{prefix}/throughput"] = generation_token_rate
|
||||
else:
|
||||
token_rates = [rate for rate in (prompt_token_rate, generation_token_rate) if rate is not None]
|
||||
if token_rates:
|
||||
metrics[f"{prefix}/throughput"] = sum(token_rates)
|
||||
|
||||
counter_metrics = {
|
||||
"completed_requests": "request_success_total",
|
||||
"nixl_transfers_per_second": "nixl_xfer_time_seconds_count",
|
||||
"nixl_bytes_per_second": "nixl_bytes_transferred_sum",
|
||||
}
|
||||
for metric_name, attribute in counter_metrics.items():
|
||||
rate = counter_rate(samples, previous, attribute)
|
||||
if rate is not None:
|
||||
metrics[f"{prefix}/{metric_name}"] = rate
|
||||
|
||||
histogram_metrics = {
|
||||
"avg_queue_time_seconds": (
|
||||
"request_queue_time_seconds_sum",
|
||||
"request_queue_time_seconds_count",
|
||||
),
|
||||
"avg_ttft_seconds": (
|
||||
"time_to_first_token_seconds_sum",
|
||||
"time_to_first_token_seconds_count",
|
||||
),
|
||||
"avg_tpot_seconds": (
|
||||
"inter_token_latency_seconds_sum",
|
||||
"inter_token_latency_seconds_count",
|
||||
),
|
||||
"avg_e2e_latency_seconds": (
|
||||
"e2e_request_latency_seconds_sum",
|
||||
"e2e_request_latency_seconds_count",
|
||||
),
|
||||
"nixl_transfer_time_seconds": (
|
||||
"nixl_xfer_time_seconds_sum",
|
||||
"nixl_xfer_time_seconds_count",
|
||||
),
|
||||
"nixl_avg_bytes_per_transfer": (
|
||||
"nixl_bytes_transferred_sum",
|
||||
"nixl_bytes_transferred_count",
|
||||
),
|
||||
}
|
||||
for metric_name, (sum_attribute, count_attribute) in histogram_metrics.items():
|
||||
value = histogram_average(samples, previous, sum_attribute, count_attribute)
|
||||
if value is not None:
|
||||
metrics[f"{prefix}/{metric_name}"] = value
|
||||
|
||||
prefill_time = histogram_average(
|
||||
samples,
|
||||
previous,
|
||||
"request_prefill_time_seconds_sum",
|
||||
"request_prefill_time_seconds_count",
|
||||
)
|
||||
decode_time = histogram_average(
|
||||
samples,
|
||||
previous,
|
||||
"request_decode_time_seconds_sum",
|
||||
"request_decode_time_seconds_count",
|
||||
)
|
||||
if scope == "prefill":
|
||||
if prefill_time is not None:
|
||||
metrics[f"{prefix}/avg_time_seconds"] = prefill_time
|
||||
elif scope == "decode":
|
||||
if decode_time is not None:
|
||||
metrics[f"{prefix}/avg_time_seconds"] = decode_time
|
||||
else:
|
||||
time_values = [value for value in (prefill_time, decode_time) if value is not None]
|
||||
if time_values:
|
||||
metrics[f"{prefix}/avg_time_seconds"] = sum(time_values) / len(time_values)
|
||||
|
||||
return metrics
|
||||
|
||||
|
||||
class InferenceMetricsCollector:
|
||||
"""Polls vLLM Prometheus /metrics and logs aggregated values to W&B.
|
||||
"""Polls vLLM Prometheus /metrics and logs smoothed role-aware values to W&B.
|
||||
|
||||
Runs independently of training steps on a time-based axis.
|
||||
The ``agg`` scope is always logged. The ``prefill`` and ``decode`` scopes are
|
||||
logged only when endpoints are explicitly or implicitly identified as a
|
||||
disaggregated P/D deployment.
|
||||
"""
|
||||
|
||||
def __init__(self, admin_clients: list[AsyncClient]):
|
||||
self.admin_clients = admin_clients
|
||||
def __init__(self, admin_clients: list[AsyncClient], roles: list[str | None] | None = None):
|
||||
self.endpoints = build_metrics_endpoints(admin_clients, roles=roles)
|
||||
self.logger = get_logger()
|
||||
self._gauge_history: dict[str, deque[float]] = {}
|
||||
self._rate_history: dict[str, deque[float]] = {}
|
||||
self._prev_counters: dict[str, tuple[float, float]] = {}
|
||||
self._prev_histograms: dict[str, tuple[float, float, float]] = {}
|
||||
self._task: asyncio.Task | None = None
|
||||
self.metric_history: dict[str, deque[float]] = {}
|
||||
self.previous: dict[str, TimedRollup] = {}
|
||||
self.task: asyncio.Task | None = None
|
||||
self.has_pd_roles = {endpoint.role for endpoint in self.endpoints if endpoint.role is not None} == PD_ROLES
|
||||
|
||||
async def start(self):
|
||||
wandb.define_metric("inference/*", step_metric="_timestamp")
|
||||
@@ -106,131 +404,60 @@ class InferenceMetricsCollector:
|
||||
async def poll_loop():
|
||||
while True:
|
||||
try:
|
||||
await self._collect_and_log()
|
||||
await self.collect_and_log()
|
||||
except Exception as e:
|
||||
self.logger.debug(f"Inference metrics poll failed: {e!r}")
|
||||
await asyncio.sleep(POLL_INTERVAL)
|
||||
|
||||
self._task = asyncio.create_task(poll_loop())
|
||||
self.task = asyncio.create_task(poll_loop())
|
||||
|
||||
async def _collect_and_log(self):
|
||||
async def collect_and_log(self):
|
||||
now = time.monotonic()
|
||||
|
||||
async def fetch(client: AsyncClient) -> str | None:
|
||||
async def fetch(endpoint: MetricsEndpoint) -> str | None:
|
||||
try:
|
||||
response = await client.get("/metrics", timeout=5.0)
|
||||
response = await endpoint.client.get("/metrics", timeout=5.0)
|
||||
response.raise_for_status()
|
||||
return response.text
|
||||
except Exception as e:
|
||||
self.logger.debug(f"Failed to fetch metrics from {client.base_url}: {e!r}")
|
||||
self.logger.debug(f"Failed to fetch metrics from {endpoint.client.base_url}: {e!r}")
|
||||
return None
|
||||
|
||||
results = await asyncio.gather(*[fetch(client) for client in self.admin_clients])
|
||||
|
||||
# For dual-agg gauges, collect per-server values to compute both max and mean
|
||||
dual_agg_values: dict[str, list[float]] = {}
|
||||
agg_sum_gauges: dict[str, float] = {}
|
||||
agg_counters: dict[str, float] = {}
|
||||
agg_histograms: dict[str, tuple[float, float]] = {}
|
||||
n_servers = 0
|
||||
|
||||
for text in results:
|
||||
if text is None:
|
||||
continue
|
||||
n_servers += 1
|
||||
gauges, counters, histograms = parse_prometheus_text(text)
|
||||
|
||||
for name, value in gauges.items():
|
||||
if name in _DUAL_AGG_GAUGES:
|
||||
dual_agg_values.setdefault(name, []).append(value)
|
||||
else:
|
||||
agg_sum_gauges[name] = agg_sum_gauges.get(name, 0.0) + value
|
||||
|
||||
for name, value in counters.items():
|
||||
agg_counters[name] = agg_counters.get(name, 0.0) + value
|
||||
|
||||
for name, (h_sum, h_count) in histograms.items():
|
||||
prev = agg_histograms.get(name, (0.0, 0.0))
|
||||
agg_histograms[name] = (prev[0] + h_sum, prev[1] + h_count)
|
||||
|
||||
if n_servers == 0:
|
||||
results = await asyncio.gather(*[fetch(endpoint) for endpoint in self.endpoints])
|
||||
samples = [
|
||||
EndpointSample(endpoint=endpoint, timestamp=now, rollup=parse_prometheus_text(text))
|
||||
for endpoint, text in zip(self.endpoints, results)
|
||||
if text is not None
|
||||
]
|
||||
if not samples:
|
||||
return
|
||||
|
||||
# Update gauge history — sum gauges
|
||||
for name, value in agg_sum_gauges.items():
|
||||
short = name.removeprefix("vllm:")
|
||||
if short not in self._gauge_history:
|
||||
self._gauge_history[short] = deque(maxlen=WINDOW_SIZE)
|
||||
self._gauge_history[short].append(value)
|
||||
metrics = build_scope_metrics("agg", samples, self.previous)
|
||||
if self.has_pd_roles:
|
||||
for role in sorted(PD_ROLES):
|
||||
role_samples = [sample for sample in samples if sample.endpoint.role == role]
|
||||
if role_samples:
|
||||
metrics.update(build_scope_metrics(role, role_samples, self.previous))
|
||||
|
||||
# Update gauge history — dual-agg gauges (max + mean across engines)
|
||||
for name, values in dual_agg_values.items():
|
||||
short = name.removeprefix("vllm:")
|
||||
max_key = f"{short}_max"
|
||||
mean_key = f"{short}_mean"
|
||||
if max_key not in self._gauge_history:
|
||||
self._gauge_history[max_key] = deque(maxlen=WINDOW_SIZE)
|
||||
if mean_key not in self._gauge_history:
|
||||
self._gauge_history[mean_key] = deque(maxlen=WINDOW_SIZE)
|
||||
self._gauge_history[max_key].append(max(values))
|
||||
self._gauge_history[mean_key].append(sum(values) / len(values))
|
||||
for sample in samples:
|
||||
self.previous[sample.endpoint.key] = TimedRollup(timestamp=sample.timestamp, rollup=sample.rollup)
|
||||
|
||||
# Compute rates from counters
|
||||
for name, value in agg_counters.items():
|
||||
rate_name = COUNTER_RATE_NAMES[name]
|
||||
prev = self._prev_counters.get(name)
|
||||
self._prev_counters[name] = (now, value)
|
||||
if prev is None:
|
||||
continue
|
||||
prev_time, prev_value = prev
|
||||
dt = now - prev_time
|
||||
if dt <= 0:
|
||||
continue
|
||||
delta = value - prev_value
|
||||
if delta < 0:
|
||||
continue
|
||||
rate = delta / dt
|
||||
if rate_name not in self._rate_history:
|
||||
self._rate_history[rate_name] = deque(maxlen=WINDOW_SIZE)
|
||||
self._rate_history[rate_name].append(rate)
|
||||
smoothed_metrics = self.smooth_metrics(metrics)
|
||||
if smoothed_metrics:
|
||||
smoothed_metrics["_timestamp"] = time.time()
|
||||
wandb.log(smoothed_metrics)
|
||||
|
||||
# Compute average histogram latency
|
||||
for name, (h_sum, h_count) in agg_histograms.items():
|
||||
short = name.removeprefix("vllm:")
|
||||
rate_name = f"{short}_avg_ms"
|
||||
prev = self._prev_histograms.get(name)
|
||||
self._prev_histograms[name] = (now, h_sum, h_count)
|
||||
if prev is None:
|
||||
continue
|
||||
prev_time, prev_sum, prev_count = prev
|
||||
d_sum = h_sum - prev_sum
|
||||
d_count = h_count - prev_count
|
||||
if d_count < 0 or d_sum < 0:
|
||||
continue
|
||||
if d_count > 0:
|
||||
avg_ms = (d_sum / d_count) * 1000.0
|
||||
if rate_name not in self._rate_history:
|
||||
self._rate_history[rate_name] = deque(maxlen=WINDOW_SIZE)
|
||||
self._rate_history[rate_name].append(avg_ms)
|
||||
|
||||
# Build smoothed metrics dict
|
||||
metrics: dict[str, float] = {}
|
||||
for short, values in self._gauge_history.items():
|
||||
if values:
|
||||
metrics[f"inference/{short}"] = sum(values) / len(values)
|
||||
for rate_name, values in self._rate_history.items():
|
||||
if values:
|
||||
metrics[f"inference/{rate_name}"] = sum(values) / len(values)
|
||||
|
||||
if metrics:
|
||||
metrics["_timestamp"] = time.time()
|
||||
wandb.log(metrics)
|
||||
def smooth_metrics(self, metrics: dict[str, float]) -> dict[str, float]:
|
||||
"""Add current values to the smoothing window and return W&B-ready metrics."""
|
||||
for key, value in metrics.items():
|
||||
self.metric_history.setdefault(key, deque(maxlen=WINDOW_SIZE)).append(value)
|
||||
return {key: sum(values) / len(values) for key, values in self.metric_history.items() if values}
|
||||
|
||||
async def stop(self):
|
||||
if self._task is not None:
|
||||
self._task.cancel()
|
||||
if self.task is not None:
|
||||
self.task.cancel()
|
||||
try:
|
||||
await self._task
|
||||
await self.task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
self._task = None
|
||||
self.task = None
|
||||
|
||||
@@ -8,7 +8,6 @@ import tomli_w
|
||||
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
|
||||
from prime_rl.orchestrator.advantage import compute_advantages
|
||||
from prime_rl.orchestrator.eval_utils import compute_eval_ckpt_step
|
||||
from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.patches import monkey_patch_chat_completion_logprobs, monkey_patch_oai_iterable_types
|
||||
@@ -245,9 +244,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
student_inference=student_inference,
|
||||
teacher_inference=teacher_inference,
|
||||
max_inflight_rollouts=config.max_inflight_rollouts,
|
||||
max_async_level=config.max_async_level,
|
||||
max_off_policy_steps=config.max_off_policy_steps,
|
||||
strict_async_level=config.strict_async_level,
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
lora_name=config.student.model.lora.name if config.student.model.lora else None,
|
||||
config=config,
|
||||
@@ -266,7 +263,10 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Start inference metrics collector (requires W&B)
|
||||
inference_metrics_collector = None
|
||||
if config.wandb is not None and config.collect_inference_metrics:
|
||||
inference_metrics_collector = InferenceMetricsCollector(student_inference.admin_clients)
|
||||
inference_metrics_collector = InferenceMetricsCollector(
|
||||
student_inference.admin_clients,
|
||||
roles=config.inference_metrics_roles,
|
||||
)
|
||||
await inference_metrics_collector.start()
|
||||
|
||||
# Set up weight broadcast backend (targets student inference)
|
||||
@@ -285,11 +285,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
logger.info(f"Initializing training batch sender ({config.rollout_transport})")
|
||||
training_batch_sender = setup_training_batch_sender(config.output_dir, config.rollout_transport)
|
||||
|
||||
# Track last online eval checkpoint step per eval env
|
||||
last_eval_steps: dict[str, int] = {env.name: -1 for env in eval_envs} if eval_envs else {}
|
||||
# Track previous ckpt_step to detect when ckpt_step jumps over eval interval boundaries
|
||||
prev_ckpt_step = -1
|
||||
|
||||
# Reset weights to base model if starting from scratch
|
||||
progress = Progress()
|
||||
|
||||
@@ -297,13 +292,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
ckpt_manager.load(progress, buffer, step=checkpoint_step)
|
||||
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
|
||||
scheduler.ckpt_step = progress.step # Always resume from the latest checkpoint
|
||||
if config.eval and config.eval.skip_eval_on_resume:
|
||||
prev_ckpt_step = scheduler.ckpt_step
|
||||
last_eval_steps = {name: scheduler.ckpt_step for name in last_eval_steps}
|
||||
logger.info(f"Skipping online eval on resume (ckpt_step={scheduler.ckpt_step})")
|
||||
else:
|
||||
# Allow eval at resumed step by setting prev_ckpt_step one behind
|
||||
prev_ckpt_step = scheduler.ckpt_step - 1
|
||||
|
||||
# In NCCL mode, skip existence check - weights are broadcasted, not stored on disk
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
@@ -362,21 +350,18 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
envs_to_eval: list[EvalEnv] = []
|
||||
if config.eval:
|
||||
assert eval_envs is not None
|
||||
for eval_env in eval_envs:
|
||||
eval_ckpt_step = compute_eval_ckpt_step(
|
||||
ckpt_step=ckpt_step,
|
||||
prev_ckpt_step=prev_ckpt_step,
|
||||
last_eval_step=last_eval_steps[eval_env.name],
|
||||
interval=eval_env.config.interval,
|
||||
eval_base_model=config.eval.eval_base_model,
|
||||
)
|
||||
if eval_ckpt_step is not None:
|
||||
last_eval_steps[eval_env.name] = ckpt_step
|
||||
envs_to_eval.append(eval_env)
|
||||
if is_first_step and checkpoint_step is not None and config.eval.skip_eval_on_resume:
|
||||
logger.info(f"Skipping online eval on resume (step={progress.step})")
|
||||
else:
|
||||
for eval_env in eval_envs:
|
||||
if progress.step % eval_env.config.interval == 0 and (
|
||||
progress.step > 0 or config.eval.eval_base_model
|
||||
):
|
||||
envs_to_eval.append(eval_env)
|
||||
|
||||
if envs_to_eval:
|
||||
env_names = ", ".join(e.name for e in envs_to_eval)
|
||||
logger.info(f"Running evals at {ckpt_step=} for {env_names}")
|
||||
logger.info(f"Running evals at step={progress.step} for {env_names}")
|
||||
|
||||
# Pause weight updates and re-scheduling of training rollouts during eval
|
||||
# to avoid evaluating across different checkpoints and avoid congestion
|
||||
@@ -392,7 +377,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
eval_env.evaluate(
|
||||
model_name=student_inference.model_name,
|
||||
get_client=student_inference.get_eval_client,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
cache_salt=str(ckpt_step),
|
||||
)
|
||||
@@ -411,9 +395,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Resume weight updates
|
||||
scheduler.checkpoint_ready.set()
|
||||
|
||||
# Update prev_ckpt_step for next iteration
|
||||
prev_ckpt_step = ckpt_step
|
||||
|
||||
# Schedule generating the training batch. Retry on empty-after-filter
|
||||
# batches so the trainer never receives an empty batch.
|
||||
generate_completions_time = 0.0
|
||||
@@ -637,7 +618,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"progress/total_tokens": progress.total_tokens,
|
||||
"progress/total_samples": progress.total_samples,
|
||||
"progress/total_problems": progress.total_problems,
|
||||
"progress/ckpt_step": ckpt_step, # Shared W&B axis
|
||||
# Sequence length metrics
|
||||
"seq_len/all/mean": by_example.seq_len.mean().mean(),
|
||||
"seq_len/all/max": by_example.seq_len.mean().max(),
|
||||
@@ -797,7 +777,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
eval_env.evaluate(
|
||||
model_name=student_inference.model_name,
|
||||
get_client=student_inference.get_eval_client,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
cache_salt=str(ckpt_step),
|
||||
)
|
||||
@@ -883,39 +862,28 @@ async def setup_student_inference_pool(
|
||||
):
|
||||
"""Set up the student inference pool (rollouts when rl/opd, evals + weight sync always).
|
||||
|
||||
Routing policy is driven by ``config.use_renderer``:
|
||||
Routing policy is driven by ``config.renderer``:
|
||||
|
||||
- ``use_renderer=True`` → renderer-backed TITO client (``/v1/generate``).
|
||||
- ``renderer is not None`` → renderer-backed TITO client (``/v1/generate``).
|
||||
Default for both text-only and VLM rollouts; required for VLMs.
|
||||
- ``use_renderer=False`` → MITO (``openai_chat_completions``).
|
||||
- ``renderer is None`` → MITO (``openai_chat_completions``).
|
||||
|
||||
Eval clients always use MITO. In sft mode ``use_renderer`` is forced off
|
||||
Eval clients always use MITO. In sft mode ``renderer`` is forced to ``None``
|
||||
by a config validator, so the student pool is plain MITO end-to-end.
|
||||
"""
|
||||
client_config = config.student.client
|
||||
model_name = config.student.model.name
|
||||
|
||||
if config.use_renderer:
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
renderer=config.renderer.name,
|
||||
tool_parser=config.renderer.tool_parser,
|
||||
reasoning_parser=config.renderer.reasoning_parser,
|
||||
preserve_all_thinking=config.renderer.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=config.renderer.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
if config.renderer is not None:
|
||||
renderer = create_renderer(tokenizer, config.renderer)
|
||||
logger.info(f"Initialized {type(renderer).__name__} for {model_name}")
|
||||
inference_pool = await setup_inference_pool(
|
||||
client_config,
|
||||
model_name=model_name,
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_name=config.renderer.name,
|
||||
tool_parser=config.renderer.tool_parser,
|
||||
reasoning_parser=config.renderer.reasoning_parser,
|
||||
renderer_pool_size=config.renderer.pool_size,
|
||||
preserve_all_thinking=config.renderer.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=config.renderer.preserve_thinking_between_tool_calls,
|
||||
renderer_config=config.renderer,
|
||||
pool_size=config.pool_size,
|
||||
)
|
||||
logger.info("Using direct renderer rollout client")
|
||||
return renderer, inference_pool
|
||||
|
||||
@@ -64,9 +64,7 @@ class Scheduler:
|
||||
buffer: Buffer,
|
||||
config: OrchestratorConfig,
|
||||
max_inflight_rollouts: int,
|
||||
max_async_level: int,
|
||||
max_off_policy_steps: int,
|
||||
strict_async_level: bool,
|
||||
tasks_per_minute: int | None,
|
||||
lora_name: str | None = None,
|
||||
):
|
||||
@@ -82,9 +80,7 @@ class Scheduler:
|
||||
self.token_batch_size = config.token_batch_size
|
||||
self.group_size = config.group_size
|
||||
self.max_inflight_rollouts = max_inflight_rollouts
|
||||
self.max_async_level = max_async_level
|
||||
self.max_off_policy_steps = max_off_policy_steps
|
||||
self.strict_async_level = strict_async_level
|
||||
self.lora_name = lora_name
|
||||
self.json_logging = config.log.json_logging
|
||||
|
||||
@@ -287,18 +283,20 @@ class Scheduler:
|
||||
await asyncio.sleep(1)
|
||||
|
||||
def _compute_next_ckpt_step(self) -> int:
|
||||
# The orchestrator always runs one step ahead of the trainer, so we must advance to at
|
||||
# least step - 1. We additionally adopt anything fresher the trainer has already
|
||||
# broadcast (so a fast trainer briefly running on-policy is fine). ``latest_ckpt_step``
|
||||
# is non-negative so it also clamps a self.step == 0 startup.
|
||||
latest_ckpt_step = get_latest_ckpt_step(get_broadcast_dir(self.config.output_dir)) or 0
|
||||
async_away_ckpt_step = max(self.step - self.max_async_level, 0)
|
||||
if self.strict_async_level:
|
||||
return async_away_ckpt_step
|
||||
return max(async_away_ckpt_step, latest_ckpt_step)
|
||||
return max(self.step - 1, latest_ckpt_step)
|
||||
|
||||
async def _apply_policy_update(self, next_ckpt_step: int) -> None:
|
||||
async_away_ckpt_step = max(self.step - self.max_async_level, 0)
|
||||
if next_ckpt_step == async_away_ckpt_step:
|
||||
# If we're advancing to step - 1, the trainer hasn't broadcast it yet (otherwise
|
||||
# we would've picked something newer); block until the file lands.
|
||||
if next_ckpt_step == max(self.step - 1, 0):
|
||||
self.logger.info(
|
||||
f"Orchestrator paused: waiting for trainer process to complete checkpoint {next_ckpt_step} "
|
||||
f"(>{self.max_async_level} step(s) ahead). Training is progressing normally."
|
||||
f"Orchestrator paused: waiting for trainer to broadcast checkpoint {next_ckpt_step} "
|
||||
f"(orchestrator is one step ahead). Training is progressing normally."
|
||||
)
|
||||
self.checkpoint_ready.clear()
|
||||
wait_for_ckpt_start_time = time.perf_counter()
|
||||
@@ -392,7 +390,8 @@ class Scheduler:
|
||||
await safe_cancel(self.update_policy_task)
|
||||
|
||||
# Manually check the async barrier before starting the step, then re-create the update policy loop
|
||||
# This ensures that we respect max_async_level, while still listening for policy updates mid-step
|
||||
# This ensures the orchestrator stays at most one step ahead of the trainer, while still
|
||||
# listening for policy updates mid-step.
|
||||
await self.maybe_update_policy()
|
||||
self.update_policy_task = asyncio.create_task(self.update_policy_loop())
|
||||
|
||||
|
||||
@@ -244,11 +244,13 @@ def interleave_rollout(
|
||||
if tokens is not None:
|
||||
routed_experts_payload = tokens.get("routed_experts")
|
||||
routed_experts = None
|
||||
routed_experts_start = None
|
||||
if routed_experts_payload is not None:
|
||||
decoded_routed_experts = pybase64.b64decode_as_bytearray(routed_experts_payload["data"])
|
||||
routed_experts = np.frombuffer(decoded_routed_experts, dtype=np.uint8).reshape(
|
||||
routed_experts_payload["shape"]
|
||||
)
|
||||
routed_experts_start = routed_experts_payload["start"]
|
||||
|
||||
return {
|
||||
"prompt_ids": list(tokens["prompt_ids"]),
|
||||
@@ -257,6 +259,7 @@ def interleave_rollout(
|
||||
"completion_mask": list(map(bool, tokens["completion_mask"])),
|
||||
"completion_logprobs": list(tokens["completion_logprobs"]),
|
||||
"routed_experts": routed_experts,
|
||||
"routed_experts_start": routed_experts_start,
|
||||
# Renderer-emitted multimodal sidecar (placeholders + per-item
|
||||
# processed tensors). Populated when the rollout went through
|
||||
# a multimodal-aware renderer (e.g. Qwen3VLRenderer); absent
|
||||
@@ -277,8 +280,14 @@ def interleave_rollout(
|
||||
# Deferred routed_experts state per sample: O(N) chunk list concatenated
|
||||
# once at finalize, replacing the prior O(N²) per-extension unpack/repack.
|
||||
sample_routed_state: dict[int, dict[str, Any]] = {}
|
||||
routed_prefix_states: dict[int, list[tuple[list[int], list[int], dict[str, Any]]]] = {}
|
||||
|
||||
def make_sample(tokens: dict[str, Any]) -> TrainingSample:
|
||||
# Track (prefix_tokens, sample, step_indices) per active sample. step_indices
|
||||
# is the explicit list of prepared_steps positions merged into this sample —
|
||||
# non-contiguous when other agents' steps interleave.
|
||||
active_samples: list[tuple[list[int], TrainingSample, list[int]]] = []
|
||||
|
||||
def make_sample(tokens: dict[str, Any], step_idx: int) -> TrainingSample:
|
||||
"""Create a new TrainingSample from a trajectory step."""
|
||||
if has_error:
|
||||
completion_mask = [False] * len(tokens["completion_mask"])
|
||||
@@ -306,9 +315,50 @@ def interleave_rollout(
|
||||
# each extension is a no-op append rather than a destructive write.
|
||||
step_routed = tokens.get("routed_experts")
|
||||
if step_routed is not None:
|
||||
routed_start = tokens["routed_experts_start"]
|
||||
assert routed_start is not None, f"Missing routed_experts_start for step {step_idx}"
|
||||
chunks: list[np.ndarray] = []
|
||||
running_len = 0
|
||||
if routed_start > 0:
|
||||
source_len = routed_start + 1
|
||||
assert source_len in routed_prefix_states, (
|
||||
f"Missing routed prefix state for step {step_idx}: "
|
||||
f"routed_start={routed_start}, prompt_len={len(tokens['prompt_ids'])}"
|
||||
)
|
||||
source_state = None
|
||||
for prompt_ids, completion_ids, candidate_state in routed_prefix_states[source_len]:
|
||||
prompt_len = len(prompt_ids)
|
||||
if (
|
||||
tokens["prompt_ids"][:prompt_len] == prompt_ids
|
||||
and tokens["prompt_ids"][prompt_len:source_len] == completion_ids
|
||||
):
|
||||
source_state = candidate_state
|
||||
break
|
||||
assert source_state is not None, (
|
||||
f"No matching routed prefix for step {step_idx}: "
|
||||
f"routed_start={routed_start}, prompt_len={len(tokens['prompt_ids'])}"
|
||||
)
|
||||
assert source_state["running_len"] >= routed_start, (
|
||||
f"Routed prefix too short for step {step_idx}: "
|
||||
f"running_len={source_state['running_len']}, routed_start={routed_start}"
|
||||
)
|
||||
remaining = routed_start
|
||||
for chunk in source_state["chunks"]:
|
||||
if remaining == 0:
|
||||
break
|
||||
take = min(remaining, int(chunk.shape[0]))
|
||||
chunks.append(chunk[:take])
|
||||
remaining -= take
|
||||
assert remaining == 0, (
|
||||
f"Could not reconstruct routed prefix for step {step_idx}: "
|
||||
f"remaining={remaining}, routed_start={routed_start}"
|
||||
)
|
||||
running_len = routed_start
|
||||
chunks.append(step_routed)
|
||||
running_len += int(step_routed.shape[0])
|
||||
sample_routed_state[id(sample)] = {
|
||||
"chunks": [step_routed],
|
||||
"running_len": int(step_routed.shape[0]),
|
||||
"chunks": chunks,
|
||||
"running_len": running_len,
|
||||
}
|
||||
return sample
|
||||
|
||||
@@ -339,51 +389,82 @@ def interleave_rollout(
|
||||
|
||||
step_routed = tokens.get("routed_experts")
|
||||
state = sample_routed_state.get(id(sample))
|
||||
if step_routed is not None and state is not None:
|
||||
# vLLM doesn't capture a routing decision for the *last* token of any
|
||||
# request, so the previous step left no entry for token at index
|
||||
# (prefix_len - 1). The next step's forward pass *did* process that
|
||||
# token (as part of its prompt) and produced step_routed[prefix_len-1].
|
||||
# Append that single boundary entry as its own chunk, then append the
|
||||
# genuinely new entries from this step. No prior bytes touched.
|
||||
if prefix_len > 0 and prefix_len <= step_routed.shape[0]:
|
||||
boundary_chunk = step_routed[prefix_len - 1 : prefix_len]
|
||||
if state is not None:
|
||||
assert step_routed is not None, f"Missing routed experts for routed sample extension at step {step_idx}"
|
||||
if step_routed is not None:
|
||||
assert state is not None, f"Unexpected routed experts for unrouted sample at step {step_idx}"
|
||||
assert tokens["routed_experts_start"] == prefix_len - 1, (
|
||||
f"Routed experts delta start mismatch at step {step_idx}: "
|
||||
f"start={tokens['routed_experts_start']}, expected={prefix_len - 1}, prefix_len={prefix_len}"
|
||||
)
|
||||
# Delta payloads start at prefix_len - 1. Row 0 fills the boundary
|
||||
# token missing from the previous request; the rest is the new suffix.
|
||||
if prefix_len > 0:
|
||||
boundary_chunk = step_routed[:1]
|
||||
state["chunks"].append(boundary_chunk)
|
||||
state["running_len"] += 1
|
||||
new_chunk = step_routed[prefix_len:]
|
||||
step_routed = step_routed[1:]
|
||||
new_chunk = step_routed
|
||||
state["chunks"].append(new_chunk)
|
||||
state["running_len"] += int(new_chunk.shape[0])
|
||||
|
||||
# Track (prefix_tokens, sample, step_indices) per active sample. step_indices
|
||||
# is the explicit list of prepared_steps positions merged into this sample —
|
||||
# non-contiguous when other agents' steps interleave.
|
||||
active_samples: list[tuple[list[int], TrainingSample, list[int]]] = []
|
||||
|
||||
first_tokens = prepared_steps[0]
|
||||
first_prefix = first_tokens["prompt_ids"] + first_tokens["completion_ids"]
|
||||
first_sample = make_sample(first_tokens)
|
||||
first_sample = make_sample(first_tokens, step_idx=0)
|
||||
active_samples.append((first_prefix, first_sample, [0]))
|
||||
first_routed_state = sample_routed_state.get(id(first_sample))
|
||||
if first_routed_state is not None:
|
||||
routed_prefix_states.setdefault(len(first_prefix), []).append(
|
||||
(first_tokens["prompt_ids"], first_tokens["completion_ids"], first_routed_state)
|
||||
)
|
||||
|
||||
for step_idx, _step in enumerate(trajectory[1:], start=1):
|
||||
tokens = prepared_steps[step_idx]
|
||||
step_prompt_ids = tokens["prompt_ids"]
|
||||
|
||||
# Check if this step extends ANY active prefix
|
||||
# Pick the *longest* matching active prefix. With compaction/rollback,
|
||||
# one active sample's prefix can be a strict prefix of another (e.g. a
|
||||
# later sample re-generated tokens that overlap an earlier sample's
|
||||
# prefix). Both would satisfy the slice check; the shorter would
|
||||
# silently absorb the longer sample's generated tokens as user input.
|
||||
matched_idx = None
|
||||
matched_len = -1
|
||||
matching_prefix_lens: list[int] = []
|
||||
for idx, (prefix_tokens, _, _) in enumerate(active_samples):
|
||||
if step_prompt_ids[: len(prefix_tokens)] == prefix_tokens:
|
||||
matched_idx = idx
|
||||
break
|
||||
pl = len(prefix_tokens)
|
||||
if step_prompt_ids[:pl] == prefix_tokens:
|
||||
matching_prefix_lens.append(pl)
|
||||
if pl > matched_len:
|
||||
matched_idx = idx
|
||||
matched_len = pl
|
||||
|
||||
if len(matching_prefix_lens) > 1:
|
||||
# Ambiguous extension: rare, but reachable via compaction/rollback
|
||||
# where a new sample's prefix happens to start with an older
|
||||
# sample's prefix. Longest-match is the correct choice; surface
|
||||
# the ambiguity so we can audit if it shows up in real rollouts.
|
||||
logger.warning(
|
||||
f"Ambiguous prefix match at step {step_idx} for example {output['example_id']}: "
|
||||
f"{len(matching_prefix_lens)} of {len(active_samples)} active prefixes match "
|
||||
f"(lens={sorted(matching_prefix_lens)}, step_prompt_len={len(step_prompt_ids)}). "
|
||||
f"Extending the longest (len={matched_len})."
|
||||
)
|
||||
|
||||
if matched_idx is not None:
|
||||
# Extension holds - merge into matched sample
|
||||
prefix_tokens, sample, step_indices = active_samples[matched_idx]
|
||||
extend_sample(sample, len(prefix_tokens), step_idx=step_idx)
|
||||
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||
active_samples[matched_idx] = (
|
||||
tokens["prompt_ids"] + tokens["completion_ids"],
|
||||
new_prefix,
|
||||
sample,
|
||||
step_indices + [step_idx],
|
||||
)
|
||||
routed_state = sample_routed_state.get(id(sample))
|
||||
if routed_state is not None:
|
||||
routed_prefix_states.setdefault(len(new_prefix), []).append(
|
||||
(tokens["prompt_ids"], tokens["completion_ids"], routed_state)
|
||||
)
|
||||
else:
|
||||
# No prefix matches - start a new sample
|
||||
logger.debug(
|
||||
@@ -391,8 +472,13 @@ def interleave_rollout(
|
||||
f"Starting new sample (active_prefixes={len(active_samples)}, step_prompt_len={len(step_prompt_ids)})."
|
||||
)
|
||||
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||
sample = make_sample(tokens)
|
||||
sample = make_sample(tokens, step_idx=step_idx)
|
||||
active_samples.append((new_prefix, sample, [step_idx]))
|
||||
routed_state = sample_routed_state.get(id(sample))
|
||||
if routed_state is not None:
|
||||
routed_prefix_states.setdefault(len(new_prefix), []).append(
|
||||
(tokens["prompt_ids"], tokens["completion_ids"], routed_state)
|
||||
)
|
||||
|
||||
# Finalize routed_experts for each sample. One concat per sample (O(N) byte
|
||||
# work) replaces the previous per-step unpack/concat/repack (O(N²)). The
|
||||
|
||||
@@ -72,10 +72,8 @@ export PYTHONUNBUFFERED=1
|
||||
export OMP_NUM_THREADS=1
|
||||
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
|
||||
|
||||
{% if wandb_shared -%}
|
||||
export WANDB_SHARED_MODE=1
|
||||
export WANDB_SHARED_RUN_ID=$(python3 -c "import uuid; print(uuid.uuid4().hex)")
|
||||
{%- endif %}
|
||||
|
||||
# Networking
|
||||
HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
@@ -384,7 +382,7 @@ else
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}{% if wandb_shared %}WANDB_SHARED_LABEL=orchestrator {% endif %}uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
|
||||
fi
|
||||
{%- else %}
|
||||
@@ -398,7 +396,7 @@ else
|
||||
|
||||
echo $HOSTNAMES_STR | tee $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
|
||||
{% if wandb_shared %}WANDB_SHARED_LABEL=trainer {% endif %}uv run torchrun \
|
||||
WANDB_SHARED_LABEL=trainer uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
@@ -420,8 +418,22 @@ else
|
||||
# tears down instead of leaving zombies holding the allocation.
|
||||
wait -n
|
||||
EXIT_CODE=$?
|
||||
echo "[$(hostname)] component exited with code $EXIT_CODE - terminating remaining processes"
|
||||
for pid in $(jobs -p); do
|
||||
REMAINING_PIDS=$(jobs -p)
|
||||
{%- if cleanup_grace_period %}
|
||||
# Cross-node teardown is driven by `srun --kill-on-bad-exit=1`, which reaps peer
|
||||
# tasks only once a task *exits* non-zero. So on a non-zero exit (crash, SIGTERM,
|
||||
# wall-time) we stay alive for the grace period and signal nothing: this lets an
|
||||
# in-flight trainer checkpoint on this node finish, and — because the task has
|
||||
# not exited yet — keeps --kill-on-bad-exit from reaping checkpointing trainers
|
||||
# on peer nodes. We then propagate the exit code so the allocation tears down. A
|
||||
# clean (zero) exit can't trip --kill-on-bad-exit, so we tear down immediately.
|
||||
if [ "$EXIT_CODE" -ne 0 ]; then
|
||||
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for in-flight checkpoints to flush before teardown"
|
||||
sleep {{ cleanup_grace_period }}
|
||||
fi
|
||||
{%- endif %}
|
||||
echo "[$(hostname)] tearing down (exit code $EXIT_CODE) - terminating remaining processes"
|
||||
for pid in $REMAINING_PIDS; do
|
||||
kill -TERM $pid 2>/dev/null || true
|
||||
done
|
||||
exit $EXIT_CODE
|
||||
|
||||
@@ -393,6 +393,7 @@ def get_load_balance_stats(
|
||||
model: nn.Module, reset_stats: bool = True, try_to_avoid_padding_experts: bool = True
|
||||
) -> dict[str, Tensor | None]:
|
||||
per_layer_max_vio = []
|
||||
per_layer_routing_confidence = []
|
||||
language_model = get_language_model(model)
|
||||
for transformer_block in language_model.layers:
|
||||
# This is necessary for models that have mixed dense layers
|
||||
@@ -400,16 +401,25 @@ def get_load_balance_stats(
|
||||
if block_mlp is None or not hasattr(block_mlp, "tokens_per_expert"):
|
||||
continue
|
||||
tokens_per_expert: torch.Tensor = block_mlp.tokens_per_expert
|
||||
num_routed_tokens = tokens_per_expert.sum() / block_mlp.router.top_k
|
||||
if try_to_avoid_padding_experts:
|
||||
tokens_per_expert = tokens_per_expert.sort(dim=0, descending=True).values[block_mlp.router.top_k :]
|
||||
balanced_load = tokens_per_expert.mean()
|
||||
max_vio = (tokens_per_expert.max() - balanced_load) / balanced_load
|
||||
per_layer_max_vio.append(max_vio.item())
|
||||
per_layer_max_vio.append(max_vio.detach())
|
||||
|
||||
routing_confidence = block_mlp.routing_confidence_sum / num_routed_tokens
|
||||
per_layer_routing_confidence.append(routing_confidence.detach())
|
||||
|
||||
if reset_stats:
|
||||
block_mlp.tokens_per_expert.zero_()
|
||||
block_mlp.routing_confidence_sum.zero_()
|
||||
if len(per_layer_max_vio) == 0:
|
||||
return {"max_vio": None}
|
||||
return {"max_vio": torch.tensor(per_layer_max_vio, device=torch.device("cuda"))}
|
||||
return {"max_vio": None, "routing_confidence": None}
|
||||
return {
|
||||
"max_vio": torch.stack(per_layer_max_vio),
|
||||
"routing_confidence": torch.stack(per_layer_routing_confidence),
|
||||
}
|
||||
|
||||
|
||||
def get_model(
|
||||
@@ -472,6 +482,11 @@ def get_model(
|
||||
model_config.use_grouped_mm = config.moe_use_grouped_mm
|
||||
model_config.fp8 = config.fp8
|
||||
|
||||
if config.index_cache is not None:
|
||||
model_config.use_index_cache = True
|
||||
model_config.index_topk_freq = config.index_cache.topk_freq
|
||||
model_config.index_topk_pattern = config.index_cache.topk_pattern
|
||||
|
||||
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
|
||||
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
|
||||
if not hasattr(model_config, "pad_token_id") or model_config.pad_token_id is None:
|
||||
|
||||
@@ -43,7 +43,7 @@ class AfmoeConfig(PretrainedConfig):
|
||||
route_norm=True,
|
||||
route_scale=1.0,
|
||||
score_before_experts: bool = False,
|
||||
load_balance_coeff: float | None = None,
|
||||
load_balance_coeff: float = 5e-4,
|
||||
use_grouped_mm: bool = True,
|
||||
global_attn_every_n_layers=4,
|
||||
sliding_window=1024,
|
||||
|
||||
@@ -352,7 +352,7 @@ class AfmoeDecoderLayer(GradientCheckpointingLayer):
|
||||
score_before_experts=getattr(config, "score_before_experts", False),
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=getattr(config, "use_grouped_mm", True),
|
||||
load_balance_coeff=getattr(config, "load_balance_coeff", None),
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
if self.moe_enabled:
|
||||
|
||||
@@ -3,6 +3,17 @@ import warnings
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
def _index_cache_skip_topk(config, layer_idx: int) -> bool:
|
||||
if not getattr(config, "use_index_cache", False):
|
||||
return False
|
||||
|
||||
index_topk_pattern = getattr(config, "index_topk_pattern", None)
|
||||
if index_topk_pattern is not None:
|
||||
return layer_idx < len(index_topk_pattern) and index_topk_pattern[layer_idx] == "S"
|
||||
|
||||
return layer_idx % getattr(config, "index_topk_freq", 1) != 0
|
||||
|
||||
|
||||
class GlmMoeDsaConfig(PretrainedConfig):
|
||||
r"""
|
||||
Configuration class for the GLM-5 (GlmMoeDsa) model.
|
||||
@@ -73,6 +84,13 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
Whether to use interleaved RoPE style in the sparse indexer.
|
||||
index_topk (`int`, defaults to 2048):
|
||||
Number of top tokens selected by the sparse indexer.
|
||||
use_index_cache (`bool`, defaults to `False`):
|
||||
Whether to reuse sparse attention top-k indices across DSA layers.
|
||||
index_topk_freq (`int`, defaults to 1):
|
||||
Frequency for recomputing top-k indices when IndexCache is enabled.
|
||||
index_topk_pattern (`str`, *optional*):
|
||||
Optional per-layer pattern where ``"F"`` computes fresh indices and
|
||||
``"S"`` reuses the cached indices from the previous full layer.
|
||||
scoring_func (`str`, defaults to `"sigmoid"`):
|
||||
Scoring function for MoE router. Must match the vLLM inference
|
||||
server's expectation (vLLM defaults to ``"softmax"`` when this
|
||||
@@ -141,6 +159,9 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
indexer_rope_interleave=True,
|
||||
pad_token_id=154820,
|
||||
index_topk=2048,
|
||||
use_index_cache=False,
|
||||
index_topk_freq=1,
|
||||
index_topk_pattern=None,
|
||||
scoring_func="sigmoid",
|
||||
topk_method="noaux_tc",
|
||||
use_grouped_mm=True,
|
||||
@@ -194,6 +215,9 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
self.index_head_dim = index_head_dim
|
||||
self.indexer_rope_interleave = indexer_rope_interleave
|
||||
self.index_topk = index_topk
|
||||
self.use_index_cache = use_index_cache
|
||||
self.index_topk_freq = index_topk_freq
|
||||
self.index_topk_pattern = index_topk_pattern
|
||||
self.scoring_func = scoring_func
|
||||
self.topk_method = topk_method
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
@@ -13,7 +13,7 @@ from transformers.utils import TransformersKwargs, auto_docstring
|
||||
from transformers.utils.deprecation import deprecate_kwarg
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.glm_moe_dsa.configuration_glm_moe_dsa import GlmMoeDsaConfig
|
||||
from prime_rl.trainer.models.glm_moe_dsa.configuration_glm_moe_dsa import GlmMoeDsaConfig, _index_cache_skip_topk
|
||||
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import (
|
||||
convert_hf_layer_to_tt,
|
||||
convert_hf_to_tt_moe,
|
||||
@@ -29,7 +29,7 @@ from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
|
||||
|
||||
def _sparse_mla_attention_args(config: GlmMoeDsaConfig) -> SparseMlaAttentionArgs:
|
||||
def _sparse_mla_attention_args(config: GlmMoeDsaConfig, layer_idx: int) -> SparseMlaAttentionArgs:
|
||||
if config.q_lora_rank is None:
|
||||
raise ValueError("Sparse MLA attention requires q_lora_rank to be set")
|
||||
return SparseMlaAttentionArgs(
|
||||
@@ -46,6 +46,8 @@ def _sparse_mla_attention_args(config: GlmMoeDsaConfig) -> SparseMlaAttentionArg
|
||||
index_n_heads=config.index_n_heads,
|
||||
index_head_dim=config.index_head_dim,
|
||||
index_topk=config.index_topk,
|
||||
use_index_cache=getattr(config, "use_index_cache", False),
|
||||
skip_topk=_index_cache_skip_topk(config, layer_idx),
|
||||
)
|
||||
|
||||
|
||||
@@ -53,7 +55,7 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: GlmMoeDsaConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.self_attn = GlmMoeDsaAttention(_sparse_mla_attention_args(config))
|
||||
self.self_attn = GlmMoeDsaAttention(_sparse_mla_attention_args(config, layer_idx))
|
||||
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.n_routed_experts,
|
||||
@@ -95,15 +97,17 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
||||
ks: Optional[torch.Tensor] = None,
|
||||
ke: Optional[torch.Tensor] = None,
|
||||
cached_indices: Optional[torch.Tensor] = None,
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
) -> torch.Tensor:
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states, cached_indices = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
ks=ks,
|
||||
ke=ke,
|
||||
cached_indices=cached_indices,
|
||||
)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
@@ -111,7 +115,7 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states, routed_experts=routed_experts)
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
return hidden_states, cached_indices
|
||||
|
||||
|
||||
@auto_docstring
|
||||
@@ -256,15 +260,19 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
|
||||
else:
|
||||
ks, ke = ks_full, ke_full
|
||||
|
||||
cached_indices = None
|
||||
use_index_cache = getattr(self.config, "use_index_cache", False)
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states, next_cached_indices = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
ks=ks,
|
||||
ke=ke,
|
||||
cached_indices=cached_indices,
|
||||
routed_experts=routed_experts_layer,
|
||||
)
|
||||
cached_indices = next_cached_indices if use_index_cache else None
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
|
||||
@@ -32,6 +32,8 @@ class SparseMlaAttentionArgs:
|
||||
index_n_heads: int
|
||||
index_head_dim: int
|
||||
index_topk: int
|
||||
use_index_cache: bool = False
|
||||
skip_topk: bool = False
|
||||
|
||||
|
||||
class _SparseMLA(torch.autograd.Function):
|
||||
@@ -157,6 +159,8 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
|
||||
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, args.hidden_size, bias=args.attention_bias)
|
||||
self.indexer = Indexer(args)
|
||||
self.use_index_cache = args.use_index_cache
|
||||
self.skip_topk = args.skip_topk
|
||||
self.scaling = self.qk_head_dim ** (-0.5)
|
||||
|
||||
self._cp_group: dist.ProcessGroup | None = None
|
||||
@@ -234,6 +238,7 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
ks: torch.Tensor | None = None,
|
||||
ke: torch.Tensor | None = None,
|
||||
cached_indices: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
q_latent, k_compressed_normed, k_rope = self.attn_projections(hidden_states)
|
||||
|
||||
@@ -241,17 +246,19 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
k_compressed_normed = gather_for_cp(k_compressed_normed, self._cp_group)
|
||||
k_rope = gather_for_cp(k_rope, self._cp_group)
|
||||
|
||||
indices = self.indexer.compute_sparse_indices(
|
||||
hidden_states_local=hidden_states,
|
||||
q_latent_local=q_latent,
|
||||
ks=ks,
|
||||
ke=ke,
|
||||
index_topk=self.args.index_topk,
|
||||
position_embeddings_full=position_embeddings,
|
||||
cp_group=self._cp_group,
|
||||
cp_world_size=self._cp_world_size,
|
||||
cp_rank=self._cp_rank,
|
||||
)
|
||||
indices = cached_indices
|
||||
if not self.skip_topk:
|
||||
indices = self.indexer.compute_sparse_indices(
|
||||
hidden_states_local=hidden_states,
|
||||
q_latent_local=q_latent,
|
||||
ks=ks,
|
||||
ke=ke,
|
||||
index_topk=self.args.index_topk,
|
||||
position_embeddings_full=position_embeddings,
|
||||
cp_group=self._cp_group,
|
||||
cp_world_size=self._cp_world_size,
|
||||
cp_rank=self._cp_rank,
|
||||
)
|
||||
|
||||
sparse_q, sparse_kv, w_v = self.mla_up_proj(
|
||||
q_latent_local=q_latent,
|
||||
@@ -261,4 +268,5 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
)
|
||||
|
||||
out = _SparseMLA.apply(sparse_q, sparse_kv, indices, self.scaling)
|
||||
return self.output_proj(out, w_v), None
|
||||
cached_indices = indices if self.use_index_cache else None
|
||||
return self.output_proj(out, w_v), cached_indices
|
||||
|
||||
@@ -387,6 +387,16 @@ class GptOssGroupedExperts(nn.Module):
|
||||
nn.init.zeros_(self.down_proj_bias)
|
||||
|
||||
|
||||
def _selected_probability_mass_sum(
|
||||
scores: torch.Tensor, top_scores: torch.Tensor, score_func: Literal["softmax", "sigmoid"]
|
||||
) -> torch.Tensor:
|
||||
with torch.no_grad():
|
||||
if score_func == "softmax":
|
||||
return top_scores.sum()
|
||||
selected_prob_mass = top_scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)
|
||||
return selected_prob_mass.sum(dim=-1).sum()
|
||||
|
||||
|
||||
class TokenChoiceTopKRouter(nn.Module):
|
||||
"""This class implements token-choice routing. In token-choice top-K routing, each token is
|
||||
routed to top K experts based on the router scores.
|
||||
@@ -420,7 +430,7 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, expert_bias: torch.Tensor | None = None, routed_experts: torch.Tensor | None = None
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Args:
|
||||
x (torch.Tensor): Input tensor with shape ``(bs*slen, dim)``.
|
||||
@@ -429,13 +439,15 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
routed_experts (torch.Tensor | None, optional): Optional tensor with shape ``(bs * slen, top_k)``.
|
||||
|
||||
Returns:
|
||||
tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
- top_scores (torch.Tensor):
|
||||
Routing scores for selected experts with shape ``(bs*slen, top_k)``.
|
||||
- selected_experts_indices (torch.Tensor):
|
||||
Expert indices selected for each token with shape ``(bs*slen, top_k)``.
|
||||
- num_tokens_per_expert (torch.Tensor):
|
||||
Number of tokens assigned to each expert with shape ``(num_experts,)``.
|
||||
- routing_confidence_sum (torch.Tensor):
|
||||
Sum over tokens of the selected-expert probability mass before route normalization/scaling.
|
||||
"""
|
||||
# scores shape (bs*slen, num_experts)
|
||||
assert routed_experts is None or routed_experts.shape[-1] == self.top_k, (
|
||||
@@ -469,6 +481,8 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
else:
|
||||
top_scores, selected_experts_indices = torch.topk(scores, k=self.top_k, dim=1)
|
||||
|
||||
routing_confidence_sum = _selected_probability_mass_sum(scores, top_scores, self.score_func)
|
||||
|
||||
if self.route_norm:
|
||||
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
|
||||
top_scores = top_scores / denominator
|
||||
@@ -482,7 +496,7 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
max=self.num_experts,
|
||||
)
|
||||
|
||||
return top_scores, selected_experts_indices, num_tokens_per_expert
|
||||
return top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum
|
||||
|
||||
def init_weights(self, init_std: float):
|
||||
nn.init.trunc_normal_(self.gate.weight, mean=0.0, std=init_std)
|
||||
@@ -600,6 +614,7 @@ class MoE(nn.Module):
|
||||
torch.zeros(num_experts, dtype=torch.float32),
|
||||
persistent=False,
|
||||
)
|
||||
self.register_buffer("routing_confidence_sum", torch.tensor(0.0, dtype=torch.float32), persistent=False)
|
||||
|
||||
def set_ep_comm_backend(self, backend: EPCommBackend) -> None:
|
||||
self.ep_comm_backend = backend
|
||||
@@ -718,6 +733,7 @@ class MoE(nn.Module):
|
||||
top_scores,
|
||||
selected_experts_indices,
|
||||
num_tokens_per_expert,
|
||||
routing_confidence_sum,
|
||||
) = self.router(x, self.expert_bias, routed_experts=routed_experts)
|
||||
|
||||
# tokens_per_expert will be used to update the expert bias for load balancing.
|
||||
@@ -727,6 +743,7 @@ class MoE(nn.Module):
|
||||
# routed expert compute below.
|
||||
with torch.no_grad():
|
||||
self.tokens_per_expert.add_(num_tokens_per_expert)
|
||||
self.routing_confidence_sum.add_(routing_confidence_sum)
|
||||
|
||||
if self.ep_comm_backend == "deepep":
|
||||
routed_output = self._run_deepep_routed_experts(x, selected_experts_indices, top_scores)
|
||||
@@ -774,6 +791,7 @@ class MoE(nn.Module):
|
||||
|
||||
with torch.device(buffer_device):
|
||||
self.tokens_per_expert = torch.zeros(self.experts.num_experts, dtype=torch.float32)
|
||||
self.routing_confidence_sum = torch.tensor(0.0, dtype=torch.float32)
|
||||
if self.load_balance_coeff is not None:
|
||||
self.expert_bias = torch.zeros(self.experts.num_experts, dtype=torch.float32)
|
||||
|
||||
@@ -938,7 +956,7 @@ class NemotronHRouter(nn.Module):
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, expert_bias: torch.Tensor | None = None
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
scores = F.linear(x.float(), self.gate.float()).sigmoid()
|
||||
scores_for_choice = scores + self.e_score_correction_bias
|
||||
|
||||
@@ -964,6 +982,7 @@ class NemotronHRouter(nn.Module):
|
||||
|
||||
selected_experts_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
|
||||
top_scores = scores.gather(1, selected_experts_indices)
|
||||
routing_confidence_sum = _selected_probability_mass_sum(scores, top_scores, "sigmoid")
|
||||
|
||||
if self.norm_topk_prob:
|
||||
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
|
||||
@@ -976,7 +995,7 @@ class NemotronHRouter(nn.Module):
|
||||
max=self.num_experts,
|
||||
)
|
||||
|
||||
return top_scores, selected_experts_indices, num_tokens_per_expert
|
||||
return top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum
|
||||
|
||||
def init_weights(self, init_std: float):
|
||||
nn.init.trunc_normal_(self.gate, mean=0.0, std=init_std)
|
||||
@@ -1067,6 +1086,7 @@ class LatentMoE(nn.Module):
|
||||
torch.zeros(num_experts, dtype=torch.float32),
|
||||
persistent=False,
|
||||
)
|
||||
self.register_buffer("routing_confidence_sum", torch.tensor(0.0, dtype=torch.float32), persistent=False)
|
||||
|
||||
def set_ep_comm_backend(self, backend: EPCommBackend) -> None:
|
||||
self.ep_comm_backend = backend
|
||||
@@ -1161,10 +1181,13 @@ class LatentMoE(nn.Module):
|
||||
bs, slen, dim = x.shape
|
||||
x_flat = x.view(-1, dim)
|
||||
|
||||
top_scores, selected_experts_indices, num_tokens_per_expert = self.router(x_flat, self.expert_bias)
|
||||
top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum = self.router(
|
||||
x_flat, self.expert_bias
|
||||
)
|
||||
|
||||
with torch.no_grad():
|
||||
self.tokens_per_expert.add_(num_tokens_per_expert)
|
||||
self.routing_confidence_sum.add_(routing_confidence_sum)
|
||||
|
||||
if self.ep_comm_backend == "deepep":
|
||||
routed_output = self._run_deepep_routed_experts(x_flat, selected_experts_indices, top_scores)
|
||||
@@ -1196,5 +1219,6 @@ class LatentMoE(nn.Module):
|
||||
|
||||
with torch.device(buffer_device):
|
||||
self.tokens_per_expert = torch.zeros(self.experts.num_experts, dtype=torch.float32)
|
||||
self.routing_confidence_sum = torch.tensor(0.0, dtype=torch.float32)
|
||||
if self.load_balance_coeff is not None:
|
||||
self.expert_bias = torch.zeros(self.experts.num_experts, dtype=torch.float32)
|
||||
|
||||
@@ -109,11 +109,10 @@ class FileSystemWeightBroadcast(WeightBroadcast):
|
||||
stable_file = save_dir / "STABLE"
|
||||
stable_file.touch()
|
||||
|
||||
def maybe_clean(self, max_async_level: int, interval_to_keep: int | None):
|
||||
def maybe_clean(self, interval_to_keep: int | None):
|
||||
for idx in self.multi_run_manager.used_idxs:
|
||||
maybe_clean(
|
||||
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
|
||||
self.multi_run_manager.progress[idx].step,
|
||||
max_async_level,
|
||||
interval_to_keep,
|
||||
)
|
||||
|
||||
@@ -88,7 +88,11 @@ class TokenExporter:
|
||||
self._current_step = step
|
||||
self._sequences_this_step = 0
|
||||
step_dir = self.output_dir / f"step_{step}"
|
||||
step_dir.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
step_dir.mkdir(parents=True, exist_ok=True)
|
||||
except FileExistsError:
|
||||
if not step_dir.is_dir():
|
||||
raise
|
||||
self._file = (step_dir / f"rank_{self.rank}.jsonl").open("w", encoding="utf-8")
|
||||
|
||||
def _write(self, record: dict[str, Any]) -> None:
|
||||
|
||||
@@ -258,28 +258,43 @@ def train(config: TrainerConfig):
|
||||
gc_handler.run(progress.step)
|
||||
is_last_step = config.max_steps is not None and progress.step == config.max_steps
|
||||
|
||||
# Broadcast weights at every step, (except step 0, because no need to broadcast the base model)
|
||||
# Also, with NCCL broadcast, we do not broadcast weights the last async level step as the orchestrator is already finished and will not initialize the receive on the inference; for filesystem broadcast, we do "broadcast" until the final step to allow to resume from the broadcast directory
|
||||
# Broadcast weights every step except:
|
||||
# - step 0: nothing has changed yet, the orchestrator has the base model.
|
||||
# - the final NCCL broadcast: with a 1-step async barrier the orchestrator's last step
|
||||
# uses the trainer's penultimate ckpt, so the trainer's last broadcast has no receiver
|
||||
# (the inference NCCL group has been torn down). Filesystem broadcast still writes the
|
||||
# final step so we can resume from the broadcast directory.
|
||||
if weight_broadcast is None:
|
||||
broadcast_weights_time = 0
|
||||
else:
|
||||
last_async_level_steps = config.max_steps and progress.step >= config.max_steps - config.max_async_level
|
||||
if progress.step > 0 and (not last_async_level_steps or config.weight_broadcast.type == "filesystem"):
|
||||
nccl_broadcast_unused = (
|
||||
config.weight_broadcast.type == "nccl"
|
||||
and config.max_steps is not None
|
||||
and progress.step >= config.max_steps - 1
|
||||
)
|
||||
if progress.step > 0 and not nccl_broadcast_unused:
|
||||
broadcast_weights_start_time = time.perf_counter()
|
||||
weight_broadcast.broadcast_weights(model, step=progress.step)
|
||||
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
|
||||
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
|
||||
ckpt_interval = config.ckpt and config.ckpt.interval
|
||||
interval_to_keep = ckpt_interval if config.weight_broadcast.type == "filesystem" else None
|
||||
if config.weight_broadcast.type == "filesystem":
|
||||
weight_broadcast.maybe_clean(config.max_async_level, interval_to_keep)
|
||||
interval_to_keep = config.ckpt and config.ckpt.interval
|
||||
weight_broadcast.maybe_clean(interval_to_keep)
|
||||
else:
|
||||
broadcast_weights_time = 0
|
||||
# Usually the broadcast will set this. If broadcast is skipped, we need to reset this here.
|
||||
for idx in multi_run_manager.used_idxs:
|
||||
multi_run_manager.ready_to_update[idx] = False
|
||||
|
||||
if (
|
||||
if config.max_concurrent_runs > 1:
|
||||
# Multi-run: Save per-run checkpoints using each run's orchestrator config.
|
||||
# Trainer-level ckpt config can be set by the combined rl entrypoint,
|
||||
# but MultiCheckpointManager has a different save signature.
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(optimizer, scheduler)
|
||||
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
|
||||
ckpt_manager.maybe_clean()
|
||||
elif (
|
||||
ckpt_manager is not None
|
||||
and (config.ckpt and config.ckpt.interval)
|
||||
and not (is_first_step or is_last_step)
|
||||
@@ -303,12 +318,6 @@ def train(config: TrainerConfig):
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
elif config.max_concurrent_runs > 1:
|
||||
# Multi-run: Save per-run checkpoints (each run has its own interval from orchestrator config)
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(optimizer, scheduler)
|
||||
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
|
||||
ckpt_manager.maybe_clean()
|
||||
else:
|
||||
save_ckpt_time = 0
|
||||
|
||||
@@ -521,6 +530,8 @@ def train(config: TrainerConfig):
|
||||
micro_step_message += f" | Mismatch KL: {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
|
||||
if "max_vio" in tensors:
|
||||
micro_step_message += f" | Max Vio: {tensors['max_vio'][-1].mean().item():.4f}"
|
||||
if "routing_confidence" in tensors:
|
||||
micro_step_message += f" | Routing Conf.: {tensors['routing_confidence'][-1].mean().item():.4f}"
|
||||
logger.debug(micro_step_message)
|
||||
|
||||
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
|
||||
@@ -580,6 +591,8 @@ def train(config: TrainerConfig):
|
||||
step_message += f" | LR: {current_lr:.2e} | Throughput: {throughput:.0f} tokens/s | MFU: {mfu:.1f}% | Peak Mem.: {peak_memory:.1f} GiB"
|
||||
if "max_vio/mean" in tensor_stats:
|
||||
step_message += f" | Max Vio: {tensor_stats['max_vio/mean']:.4f}"
|
||||
if "routing_confidence/mean" in tensor_stats:
|
||||
step_message += f" | Routing Conf.: {tensor_stats['routing_confidence/mean']:.4f}"
|
||||
logger.success(step_message)
|
||||
|
||||
# Log performance metrics
|
||||
|
||||
@@ -236,7 +236,7 @@ class SFTDataset(StatefulIterableDataset):
|
||||
if self.renderer is not None:
|
||||
if example.get("chat_template_kwargs") and not self._warned_chat_template_kwargs:
|
||||
self.logger.warning(
|
||||
"Example carries chat_template_kwargs but use_renderer=True; "
|
||||
"Example carries chat_template_kwargs but a renderer is configured; "
|
||||
"renderers don't forward chat_template_kwargs (model-specific "
|
||||
"renderers bake their template behavior in). These kwargs will "
|
||||
"be ignored. Further warnings suppressed for this dataset."
|
||||
|
||||
@@ -160,22 +160,15 @@ def train(config: SFTConfig):
|
||||
tokenizer = setup_tokenizer(config.tokenizer)
|
||||
|
||||
renderer = None
|
||||
if config.use_renderer:
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
renderer=config.renderer.name,
|
||||
tool_parser=config.renderer.tool_parser,
|
||||
reasoning_parser=config.renderer.reasoning_parser,
|
||||
preserve_all_thinking=config.renderer.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=config.renderer.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
if config.renderer is not None:
|
||||
renderer = create_renderer(tokenizer, config.renderer)
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
raise ValueError(
|
||||
f"use_renderer=True for {config.tokenizer.name!r} resolved to DefaultRenderer. "
|
||||
f"renderer set for {config.tokenizer.name!r} resolved to DefaultRenderer. "
|
||||
"DefaultRenderer falls back to incremental apply_chat_template and does NOT "
|
||||
"fix position-dependent chat templates — the bug use_renderer is meant to solve. "
|
||||
"fix position-dependent chat templates — the bug the renderer client is meant to solve. "
|
||||
"Either use a model with a hand-coded renderer (see renderers.base.MODEL_RENDERER_MAP), "
|
||||
"set [renderer] name=<hand-coded renderer> explicitly, or set use_renderer=false."
|
||||
"set [renderer] name=<hand-coded renderer> explicitly, or remove the [renderer] block."
|
||||
)
|
||||
logger.info(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
|
||||
|
||||
@@ -287,8 +280,19 @@ def train(config: SFTConfig):
|
||||
total_token_count = torch.tensor(0, dtype=torch.int64, device="cuda")
|
||||
nan_count = torch.tensor(0, device="cuda")
|
||||
|
||||
# Variable-length packing yields different per-rank batch counts. Under FSDP
|
||||
# every forward is a collective, so all ranks must agree on when to stop —
|
||||
# otherwise the first rank to exit deadlocks the rest in the next all-gather.
|
||||
# Sync per batch and exit together as soon as any rank exhausts its iterator.
|
||||
data_iter = iter(data_iter)
|
||||
|
||||
with torch.no_grad():
|
||||
for micro_batch in data_iter:
|
||||
while True:
|
||||
micro_batch = next(data_iter, None)
|
||||
has_data = torch.tensor(micro_batch is not None, dtype=torch.int32, device="cuda")
|
||||
dist.all_reduce(has_data, op=dist.ReduceOp.MIN)
|
||||
if has_data.item() == 0:
|
||||
break
|
||||
loss_sum, token_count = compute_loss(micro_batch)
|
||||
if not torch.isnan(loss_sum.detach()):
|
||||
total_loss_sum += loss_sum.detach()
|
||||
@@ -381,7 +385,15 @@ def train(config: SFTConfig):
|
||||
step_loss_sum = torch.tensor(0.0, device="cuda")
|
||||
step_local_token_count = torch.tensor(0, dtype=torch.int64, device="cuda")
|
||||
nan_loss_count = torch.tensor(0, device="cuda")
|
||||
batch_max_vio = torch.tensor(0.0, device="cuda")
|
||||
is_moe_model = is_tt_moe_model(model)
|
||||
moe_stats = (
|
||||
{
|
||||
"max_vio": torch.tensor(0.0, device="cuda"),
|
||||
"routing_confidence": torch.tensor(0.0, device="cuda"),
|
||||
}
|
||||
if is_moe_model
|
||||
else {}
|
||||
)
|
||||
for micro_step in range(grad_accum_steps):
|
||||
micro_batch = next(dataiter)
|
||||
|
||||
@@ -406,12 +418,16 @@ def train(config: SFTConfig):
|
||||
with maybe_record_function("backward"):
|
||||
scaled_loss.backward()
|
||||
|
||||
if is_tt_moe_model(model):
|
||||
max_vio = get_load_balance_stats(model)["max_vio"]
|
||||
if max_vio is not None:
|
||||
max_vio = max_vio.mean()
|
||||
dist.all_reduce(max_vio, op=dist.ReduceOp.MAX)
|
||||
batch_max_vio += max_vio / grad_accum_steps
|
||||
if is_moe_model:
|
||||
for name, values in get_load_balance_stats(model).items():
|
||||
if values is None:
|
||||
continue
|
||||
value = values.mean()
|
||||
reduce_op = dist.ReduceOp.MAX if name == "max_vio" else dist.ReduceOp.SUM
|
||||
dist.all_reduce(value, op=reduce_op)
|
||||
if reduce_op == dist.ReduceOp.SUM:
|
||||
value /= dist.get_world_size()
|
||||
moe_stats[name] += value / grad_accum_steps
|
||||
|
||||
forward_backward_time = time.perf_counter() - forward_backward_start_time
|
||||
|
||||
@@ -489,8 +505,11 @@ def train(config: SFTConfig):
|
||||
if grad_norm is not None:
|
||||
step_message += f" | Grad. Norm: {grad_norm:.4f}"
|
||||
step_message += f" | LR: {current_lr:.2e} | Throughput: {throughput:.0f} tokens/s | MFU: {mfu:.1f}% | Peak Mem.: {peak_memory:.1f}/{max_memory:.1f} GiB ({peak_memory / max_memory * 100:.1f}%)"
|
||||
if is_tt_moe_model(model) and batch_max_vio.item() > 0:
|
||||
step_message += f" | Max Vio: {batch_max_vio.item():.4f}"
|
||||
if is_moe_model:
|
||||
for name, label in (("max_vio", "Max Vio"), ("routing_confidence", "Routing Conf.")):
|
||||
value = moe_stats[name].item()
|
||||
if value > 0:
|
||||
step_message += f" | {label}: {value:.4f}"
|
||||
logger.success(step_message)
|
||||
|
||||
# Log progress metrics
|
||||
@@ -558,8 +577,9 @@ def train(config: SFTConfig):
|
||||
disk_metrics["step"] = progress.step
|
||||
monitor.log(disk_metrics, step=progress.step)
|
||||
|
||||
if is_tt_moe_model(model) and batch_max_vio.item() > 0:
|
||||
monitor.log({"max_vio/mean": batch_max_vio.item(), "step": progress.step}, step=progress.step)
|
||||
moe_log_metrics = {f"{name}/mean": value.item() for name, value in moe_stats.items() if value.item() > 0}
|
||||
if moe_log_metrics:
|
||||
monitor.log({**moe_log_metrics, "step": progress.step}, step=progress.step)
|
||||
|
||||
is_first_step = False
|
||||
progress.step += 1
|
||||
|
||||
@@ -450,12 +450,18 @@ class MemoryProfiler:
|
||||
self.step_num += 1
|
||||
|
||||
|
||||
def maybe_clean(path: Path, step: int, async_level: int, interval_to_keep: int | None) -> None:
|
||||
def maybe_clean(path: Path, step: int, interval_to_keep: int | None) -> None:
|
||||
"""Delete the broadcast dir from 2 trainer steps ago.
|
||||
|
||||
With a 1-step async barrier, the orchestrator at trainer step ``step`` is still consuming the
|
||||
ckpt from ``step - 1``; ``step - 2`` is therefore safe to remove unless it falls on a
|
||||
checkpoint interval that we want to preserve.
|
||||
"""
|
||||
logger = get_logger()
|
||||
step = max(step - (async_level + 1), 0) # Consider deleting async_level + 1 steps ago
|
||||
candidate_path_to_delete = get_step_path(path, step)
|
||||
keep = bool(interval_to_keep and step % interval_to_keep == 0)
|
||||
logger.debug(f"Considering deleting path {candidate_path_to_delete}")
|
||||
if not keep:
|
||||
logger.debug(f"Removing path {candidate_path_to_delete}")
|
||||
shutil.rmtree(candidate_path_to_delete, ignore_errors=True)
|
||||
candidate_step = max(step - 2, 0)
|
||||
candidate_path = get_step_path(path, candidate_step)
|
||||
if interval_to_keep and candidate_step % interval_to_keep == 0:
|
||||
logger.debug(f"Keeping path {candidate_path} (on ckpt interval)")
|
||||
return
|
||||
logger.debug(f"Removing path {candidate_path}")
|
||||
shutil.rmtree(candidate_path, ignore_errors=True)
|
||||
|
||||
@@ -10,6 +10,7 @@ import httpx
|
||||
import verifiers as vf
|
||||
from httpx import AsyncClient
|
||||
from openai import NotFoundError
|
||||
from renderers import RendererConfig
|
||||
from tenacity import retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
@@ -69,24 +70,16 @@ class StaticInferencePool:
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
renderer_config: RendererConfig | None = None,
|
||||
pool_size: int | None = None,
|
||||
):
|
||||
renderer_model_name = model_name if train_client_type == "renderer" else None
|
||||
self._train_clients = setup_clients(
|
||||
client_config,
|
||||
client_type=train_client_type,
|
||||
renderer_name=renderer_name,
|
||||
renderer_config=renderer_config,
|
||||
renderer_model_name=renderer_model_name,
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
preserve_all_thinking=preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
|
||||
pool_size=pool_size,
|
||||
)
|
||||
self._eval_clients = setup_clients(client_config, client_type=eval_client_type)
|
||||
self._admin_clients = setup_admin_clients(client_config)
|
||||
@@ -134,12 +127,8 @@ async def setup_inference_pool(
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
renderer_config: RendererConfig | None = None,
|
||||
pool_size: int | None = None,
|
||||
) -> InferencePool:
|
||||
"""Create an inference pool from config (static or elastic)."""
|
||||
if client_config.is_elastic:
|
||||
@@ -150,12 +139,8 @@ async def setup_inference_pool(
|
||||
model_name=model_name,
|
||||
train_client_type=train_client_type,
|
||||
eval_client_type=eval_client_type,
|
||||
renderer_name=renderer_name,
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
preserve_all_thinking=preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
|
||||
renderer_config=renderer_config,
|
||||
pool_size=pool_size,
|
||||
)
|
||||
|
||||
return StaticInferencePool(
|
||||
@@ -163,36 +148,28 @@ async def setup_inference_pool(
|
||||
model_name=model_name,
|
||||
train_client_type=train_client_type,
|
||||
eval_client_type=eval_client_type,
|
||||
renderer_name=renderer_name,
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
preserve_all_thinking=preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
|
||||
renderer_config=renderer_config,
|
||||
pool_size=pool_size,
|
||||
)
|
||||
|
||||
|
||||
def setup_clients(
|
||||
client_config: ClientConfig,
|
||||
client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
renderer_config: RendererConfig | None = None,
|
||||
renderer_model_name: str | None = None,
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
pool_size: int | None = None,
|
||||
) -> list[vf.ClientConfig]:
|
||||
clients = []
|
||||
client_idx = 0
|
||||
# Only forward preserve flags when the client actually uses a renderer —
|
||||
# MITO/TITO clients ignore them and the verifiers ClientConfig may reject
|
||||
# unknown extras on older versions.
|
||||
# Only forward the renderer config when the client actually uses a
|
||||
# renderer — MITO/TITO clients ignore it.
|
||||
renderer_extra: dict = {}
|
||||
if client_type == "renderer":
|
||||
renderer_extra = {
|
||||
"preserve_all_thinking": preserve_all_thinking,
|
||||
"preserve_thinking_between_tool_calls": preserve_thinking_between_tool_calls,
|
||||
"renderer_config": renderer_config,
|
||||
"renderer_model_name": renderer_model_name,
|
||||
"renderer_pool_size": pool_size,
|
||||
}
|
||||
env_headers = {
|
||||
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
|
||||
@@ -206,11 +183,6 @@ def setup_clients(
|
||||
vf.ClientConfig(
|
||||
client_idx=client_idx,
|
||||
client_type=client_type,
|
||||
renderer=renderer_name,
|
||||
renderer_model_name=renderer_model_name,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
api_base_url=base_url,
|
||||
api_key_var=client_config.api_key_var,
|
||||
timeout=client_config.timeout,
|
||||
@@ -306,13 +278,46 @@ async def check_health(
|
||||
NCCL_READY_MARKER = "NCCL_READY"
|
||||
|
||||
|
||||
def _is_retryable_pause_error(exception: BaseException) -> bool:
|
||||
"""Check if an exception should trigger a retry for pausing engines."""
|
||||
if isinstance(exception, httpx.HTTPStatusError):
|
||||
# Retry on transient server errors (5xx, e.g. engine briefly unresponsive);
|
||||
# client errors (4xx) won't fix themselves on retry.
|
||||
return exception.response.status_code >= 500
|
||||
# Retry on transport-level failures (timeouts, connection resets, etc.) so the
|
||||
# per-attempt read timeout below turns a stuck server into a bounded retry loop
|
||||
# instead of hanging forever on the global timeout=None admin client.
|
||||
if isinstance(exception, (httpx.TimeoutException, httpx.TransportError)):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# Per-attempt and total bounds for `/pause`. Pausing drains in-flight requests
|
||||
# (mode="keep"), so a single attempt can legitimately take a while, but the global
|
||||
# admin AsyncClient uses `timeout=None`, so a stuck server would hang the weight
|
||||
# update forever. `_READ_TIMEOUT` converts a hang into a TimeoutException so
|
||||
# tenacity retries; `_TOTAL` is the wall-clock budget across all retries.
|
||||
PAUSE_READ_TIMEOUT_S = 120.0
|
||||
PAUSE_TOTAL_TIMEOUT_S = 300.0
|
||||
|
||||
|
||||
async def _pause_engines(admin_clients: list[AsyncClient]) -> None:
|
||||
"""Pause all inference engines, waiting for in-flight requests to drain."""
|
||||
logger = get_logger()
|
||||
logger.info("Pausing inference engines for weight update")
|
||||
|
||||
@retry(
|
||||
retry=retry_if_exception(_is_retryable_pause_error),
|
||||
stop=stop_after_delay(PAUSE_TOTAL_TIMEOUT_S) | stop_after_attempt(10),
|
||||
wait=wait_exponential(multiplier=1, min=1, max=10),
|
||||
reraise=True,
|
||||
)
|
||||
async def _pause(client: AsyncClient) -> None:
|
||||
response = await client.post("/pause", params={"mode": "keep", "clear_cache": "false"})
|
||||
response = await client.post(
|
||||
"/pause",
|
||||
params={"mode": "keep", "clear_cache": "false"},
|
||||
timeout=httpx.Timeout(connect=10.0, read=PAUSE_READ_TIMEOUT_S, write=60.0, pool=10.0),
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
await asyncio.gather(*[_pause(client) for client in admin_clients])
|
||||
|
||||
@@ -18,6 +18,7 @@ from typing import Literal
|
||||
import httpx
|
||||
import verifiers as vf
|
||||
from httpx import AsyncClient
|
||||
from renderers import RendererConfig
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.utils.client import load_lora_adapter, setup_admin_clients, setup_clients
|
||||
@@ -106,12 +107,8 @@ class ElasticInferencePool:
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
renderer_config: RendererConfig | None = None,
|
||||
pool_size: int | None = None,
|
||||
):
|
||||
self.logger = get_logger()
|
||||
self.client_config = client_config
|
||||
@@ -123,12 +120,8 @@ class ElasticInferencePool:
|
||||
self.sync_interval = client_config.elastic.sync_interval
|
||||
self.train_client_type = train_client_type
|
||||
self.eval_client_type = eval_client_type
|
||||
self.renderer_name = renderer_name
|
||||
self.tool_parser = tool_parser
|
||||
self.reasoning_parser = reasoning_parser
|
||||
self.renderer_pool_size = renderer_pool_size
|
||||
self.preserve_all_thinking = preserve_all_thinking
|
||||
self.preserve_thinking_between_tool_calls = preserve_thinking_between_tool_calls
|
||||
self.renderer_config = renderer_config
|
||||
self.pool_size = pool_size
|
||||
self.router_url = client_config.router_url
|
||||
|
||||
self._servers: dict[str, ServerState] = {}
|
||||
@@ -152,12 +145,8 @@ class ElasticInferencePool:
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
renderer_config: RendererConfig | None = None,
|
||||
pool_size: int | None = None,
|
||||
) -> ElasticInferencePool:
|
||||
if client_config.elastic is None:
|
||||
raise ValueError("Elastic inference pool requires elastic config")
|
||||
@@ -166,12 +155,8 @@ class ElasticInferencePool:
|
||||
model_name=model_name,
|
||||
train_client_type=train_client_type,
|
||||
eval_client_type=eval_client_type,
|
||||
renderer_name=renderer_name,
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
preserve_all_thinking=preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
|
||||
renderer_config=renderer_config,
|
||||
pool_size=pool_size,
|
||||
)
|
||||
await pool.start()
|
||||
return pool
|
||||
@@ -218,13 +203,9 @@ class ElasticInferencePool:
|
||||
setup_clients(
|
||||
url_config,
|
||||
client_type=self.train_client_type,
|
||||
renderer_name=self.renderer_name,
|
||||
renderer_config=self.renderer_config,
|
||||
renderer_model_name=self.renderer_model_name,
|
||||
tool_parser=self.tool_parser,
|
||||
reasoning_parser=self.reasoning_parser,
|
||||
renderer_pool_size=self.renderer_pool_size,
|
||||
preserve_all_thinking=self.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.preserve_thinking_between_tool_calls,
|
||||
pool_size=self.pool_size,
|
||||
)
|
||||
if urls
|
||||
else []
|
||||
|
||||
@@ -39,7 +39,11 @@ def build_log_entry(record) -> dict:
|
||||
"function": record["function"],
|
||||
"line": record["line"],
|
||||
}
|
||||
if record["exception"] is not None:
|
||||
# extra["traceback"] is set by traceback_patcher when enqueue=True (loguru
|
||||
# drops the traceback object during pickling, so it must be pre-formatted).
|
||||
if extra.get("traceback"):
|
||||
log_entry["exception"] = extra.pop("traceback")
|
||||
elif record["exception"] is not None:
|
||||
exc = record["exception"]
|
||||
log_entry["exception"] = "".join(traceback.format_exception(exc.type, exc.value, exc.traceback))
|
||||
# Extract tag from extra if present (used by workers to identify themselves)
|
||||
@@ -52,6 +56,12 @@ def build_log_entry(record) -> dict:
|
||||
return log_entry
|
||||
|
||||
|
||||
def traceback_patcher(record) -> None:
|
||||
exc = record["exception"]
|
||||
if exc is not None and exc.traceback is not None:
|
||||
record["extra"]["traceback"] = "".join(traceback.format_exception(exc.type, exc.value, exc.traceback))
|
||||
|
||||
|
||||
def json_sink(message) -> None:
|
||||
"""Sink that outputs flat JSON to stdout for log aggregation (Loki, Grafana, etc.)."""
|
||||
log_entry = build_log_entry(message.record)
|
||||
@@ -118,6 +128,10 @@ def setup_logger(
|
||||
from loguru._logger import Core as _Core
|
||||
from loguru._logger import Logger as _Logger
|
||||
|
||||
# enqueue=True drops the traceback during pickling, so pre-format it here
|
||||
# while the live traceback is still attached.
|
||||
patchers = [traceback_patcher] if json_logging else []
|
||||
|
||||
logger = _Logger(
|
||||
core=_Core(),
|
||||
exception=None,
|
||||
@@ -127,7 +141,7 @@ def setup_logger(
|
||||
colors=False,
|
||||
raw=False,
|
||||
capture=True,
|
||||
patchers=[],
|
||||
patchers=patchers,
|
||||
extra={},
|
||||
)
|
||||
|
||||
|
||||
@@ -61,10 +61,7 @@ class WandbMonitor(Monitor):
|
||||
x_primary=primary,
|
||||
x_update_finish_state=primary,
|
||||
)
|
||||
self.logger.info(
|
||||
f"Using shared W&B mode ({label=}, {primary=}). "
|
||||
"This is an experimental feature. Disable with --wandb.shared False"
|
||||
)
|
||||
self.logger.info(f"Using shared W&B mode ({label=}, {primary=})")
|
||||
else:
|
||||
run_id = None
|
||||
primary = False
|
||||
|
||||
@@ -73,7 +73,7 @@ def test_serialize_routed_experts_uses_compact_raw_payload():
|
||||
|
||||
|
||||
def test_generate_response_post_process_replaces_upstream_routed_experts():
|
||||
compact_routed_experts = {"data": "AQID", "shape": [1, 1, 3]}
|
||||
compact_routed_experts = {"data": "AQID", "shape": [1, 1, 3], "start": 0}
|
||||
capture = _GenerateRoutedExpertsCapture(_empty_request_outputs())
|
||||
capture.routed_experts[0] = compact_routed_experts
|
||||
response = GenerateResponse(
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
"""Unit tests for eval scheduling logic - specifically the range check
|
||||
that detects when ckpt_step jumps over eval interval boundaries."""
|
||||
|
||||
from prime_rl.orchestrator.eval_utils import compute_eval_ckpt_step
|
||||
|
||||
|
||||
def test_exact_hit():
|
||||
result = compute_eval_ckpt_step(ckpt_step=25, prev_ckpt_step=24, last_eval_step=0, interval=25)
|
||||
assert result == 25
|
||||
|
||||
|
||||
def test_jump_over_interval():
|
||||
result = compute_eval_ckpt_step(ckpt_step=26, prev_ckpt_step=24, last_eval_step=0, interval=25)
|
||||
assert result == 25
|
||||
|
||||
|
||||
def test_no_interval_crossed():
|
||||
result = compute_eval_ckpt_step(ckpt_step=23, prev_ckpt_step=22, last_eval_step=0, interval=25)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_base_model_eval_at_step_0():
|
||||
result = compute_eval_ckpt_step(
|
||||
ckpt_step=0, prev_ckpt_step=-1, last_eval_step=-1, interval=25, eval_base_model=True
|
||||
)
|
||||
assert result == 0
|
||||
|
||||
|
||||
def test_base_model_eval_disabled():
|
||||
result = compute_eval_ckpt_step(
|
||||
ckpt_step=0, prev_ckpt_step=-1, last_eval_step=-1, interval=25, eval_base_model=False
|
||||
)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_no_double_eval():
|
||||
result = compute_eval_ckpt_step(ckpt_step=25, prev_ckpt_step=24, last_eval_step=25, interval=25)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_no_change_in_ckpt_step():
|
||||
result = compute_eval_ckpt_step(ckpt_step=25, prev_ckpt_step=25, last_eval_step=0, interval=25)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_multiple_intervals_crossed():
|
||||
result = compute_eval_ckpt_step(ckpt_step=76, prev_ckpt_step=24, last_eval_step=0, interval=25)
|
||||
assert result == 75
|
||||
|
||||
|
||||
def test_second_interval():
|
||||
result = compute_eval_ckpt_step(ckpt_step=50, prev_ckpt_step=49, last_eval_step=25, interval=25)
|
||||
assert result == 50
|
||||
|
||||
|
||||
def test_jump_across_second_interval():
|
||||
result = compute_eval_ckpt_step(ckpt_step=51, prev_ckpt_step=48, last_eval_step=25, interval=25)
|
||||
assert result == 50
|
||||
|
||||
|
||||
def test_production_scenario_step25_skipped():
|
||||
"""Reproduces the bug from run c14miuyha2yhxkw1z3eqgyub."""
|
||||
result = compute_eval_ckpt_step(ckpt_step=26, prev_ckpt_step=24, last_eval_step=0, interval=25)
|
||||
assert result == 25
|
||||
|
||||
|
||||
def test_production_scenario_step50_exact():
|
||||
result = compute_eval_ckpt_step(ckpt_step=50, prev_ckpt_step=49, last_eval_step=26, interval=25)
|
||||
assert result == 50
|
||||
|
||||
|
||||
def test_simulate_full_run():
|
||||
ckpt_steps = [0, 0, 3, 5, 10, 15, 20, 24, 26, 30, 35, 40, 48, 51, 60, 70, 74, 76]
|
||||
interval = 25
|
||||
last_eval_step = -1
|
||||
prev_ckpt_step = -1
|
||||
eval_triggered_at = []
|
||||
|
||||
for ckpt_step in ckpt_steps:
|
||||
result = compute_eval_ckpt_step(ckpt_step, prev_ckpt_step, last_eval_step, interval)
|
||||
if result is not None:
|
||||
eval_triggered_at.append(result)
|
||||
last_eval_step = ckpt_step
|
||||
prev_ckpt_step = ckpt_step
|
||||
|
||||
assert eval_triggered_at == [0, 25, 50, 75]
|
||||
@@ -2,27 +2,23 @@ import asyncio
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from renderers import Qwen3VLRendererConfig
|
||||
|
||||
from prime_rl.orchestrator.orchestrator import setup_student_inference_pool
|
||||
|
||||
|
||||
def test_setup_student_inference_pool_uses_renderer_when_enabled():
|
||||
async def run() -> None:
|
||||
tokenizer = object()
|
||||
renderer_settings = Qwen3VLRendererConfig()
|
||||
config = SimpleNamespace(
|
||||
training_mode="rl",
|
||||
use_renderer=True,
|
||||
student=SimpleNamespace(
|
||||
client=SimpleNamespace(base_url=["http://localhost:8000/v1"]),
|
||||
model=SimpleNamespace(name="student-model"),
|
||||
),
|
||||
renderer=SimpleNamespace(
|
||||
name="qwen3_vl",
|
||||
tool_parser=None,
|
||||
reasoning_parser=None,
|
||||
pool_size=None,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=False,
|
||||
),
|
||||
renderer=renderer_settings,
|
||||
pool_size=None,
|
||||
)
|
||||
logger = MagicMock()
|
||||
renderer = object()
|
||||
@@ -43,25 +39,14 @@ def test_setup_student_inference_pool_uses_renderer_when_enabled():
|
||||
|
||||
assert returned_renderer is renderer
|
||||
assert returned_pool is inference_pool
|
||||
create_renderer_mock.assert_called_once_with(
|
||||
tokenizer,
|
||||
renderer="qwen3_vl",
|
||||
tool_parser=None,
|
||||
reasoning_parser=None,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=False,
|
||||
)
|
||||
create_renderer_mock.assert_called_once_with(tokenizer, renderer_settings)
|
||||
setup_pool_mock.assert_awaited_once_with(
|
||||
config.student.client,
|
||||
model_name="student-model",
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_name="qwen3_vl",
|
||||
tool_parser=None,
|
||||
reasoning_parser=None,
|
||||
renderer_pool_size=None,
|
||||
preserve_all_thinking=False,
|
||||
preserve_thinking_between_tool_calls=False,
|
||||
renderer_config=renderer_settings,
|
||||
pool_size=None,
|
||||
)
|
||||
|
||||
asyncio.run(run())
|
||||
@@ -74,7 +59,8 @@ def test_setup_student_inference_pool_defaults_to_mito():
|
||||
tokenizer = object()
|
||||
config = SimpleNamespace(
|
||||
training_mode="rl",
|
||||
use_renderer=False,
|
||||
renderer=None,
|
||||
pool_size=None,
|
||||
student=SimpleNamespace(
|
||||
client=SimpleNamespace(base_url=["http://localhost:8000/v1"]),
|
||||
model=SimpleNamespace(name="student-model"),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user