Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a73fa39f2f | ||
|
|
0057f3bb91 | ||
|
|
e792f9cf88 | ||
|
|
a36151c951 | ||
|
|
c5559033bd | ||
|
|
25d4b1dcc8 | ||
|
|
3b386a4489 | ||
|
|
38303f82d4 | ||
|
|
f5e8113420 | ||
|
|
ef773f1cee | ||
|
|
84f072bc99 | ||
|
|
4df5b6229f | ||
|
|
ae1461e7a1 | ||
|
|
7e8355003a | ||
|
|
81822debb6 | ||
|
|
8e978063b4 | ||
|
|
934c014bec | ||
|
|
20f6449e1f | ||
|
|
1e0fe9637d | ||
|
|
badd2b0fe2 | ||
|
|
e971d905a2 | ||
|
|
710e11912f | ||
|
|
c95a943c39 | ||
|
|
ca03d89fad | ||
|
|
e6e814697a | ||
|
|
f9cebaa19c | ||
|
|
c656d2f8f2 | ||
|
|
9ef2705898 |
@@ -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
|
||||
|
||||
@@ -50,11 +50,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.
|
||||
|
||||
- **`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)
|
||||
- **First-class `training_mode` + batch-driven loss dispatch** (collection of removals/renames). Loss selection is now driven by `TrainingSample.training_mode` (`rl` / `opd` / `sft`), set under `[orchestrator]`. The trainer is mode-agnostic and dispatches per batch.
|
||||
- **`orchestrator.use_sft_loss` removed**: replaced by `[orchestrator] training_mode = "sft"`. The orchestrator stamps each sample's `training_mode` and the trainer dispatches to `sft_loss_fn` per batch.
|
||||
|
||||
@@ -17,7 +17,7 @@ name = "stage1"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
@@ -32,15 +32,15 @@ interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
rollouts_per_example = 1
|
||||
group_size = 1
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2024"
|
||||
rollouts_per_example = 32
|
||||
group_size = 32
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2025"
|
||||
rollouts_per_example = 32
|
||||
group_size = 32
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ name = "stage2"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 2048
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
@@ -33,15 +33,15 @@ interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
rollouts_per_example = 1
|
||||
group_size = 1
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2024"
|
||||
rollouts_per_example = 32
|
||||
group_size = 32
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2025"
|
||||
rollouts_per_example = 32
|
||||
group_size = 32
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
@@ -28,7 +28,7 @@ interval = 50
|
||||
id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
num_examples = 50
|
||||
rollouts_per_example = 4
|
||||
group_size = 4
|
||||
args = { min_turns = 2, max_turns = 2 }
|
||||
|
||||
[trainer]
|
||||
|
||||
@@ -11,7 +11,7 @@ lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 384
|
||||
|
||||
@@ -12,7 +12,7 @@ lr = 3e-6
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -11,7 +11,7 @@ lr = 3e-6
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -18,7 +18,7 @@ save_adapter_separately = true
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.model.lora]
|
||||
name = "r8-1e-4"
|
||||
|
||||
@@ -17,7 +17,7 @@ save_adapter_separately = true
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.model.lora]
|
||||
name = "r8-1e-4"
|
||||
|
||||
@@ -14,7 +14,7 @@ impl = "custom"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Orchestrator config for multi-run RL integration test
|
||||
# model.lora.name and output_dir are set via CLI
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
seq_len = 2048
|
||||
max_steps = 20
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -17,7 +17,7 @@ name = "ci-rl-opd"
|
||||
[orchestrator]
|
||||
training_mode = "opd"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
@@ -17,7 +17,7 @@ name = "ci-rl-sft"
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -15,7 +15,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
|
||||
@@ -15,7 +15,7 @@ language_model_attr = "model.language_model"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 64
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -18,7 +18,7 @@ name = "debug-opd"
|
||||
[orchestrator]
|
||||
training_mode = "opd"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
@@ -18,7 +18,7 @@ name = "debug-opd-lora"
|
||||
[orchestrator]
|
||||
training_mode = "opd"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
@@ -11,7 +11,7 @@ name = "debug-rl"
|
||||
[orchestrator]
|
||||
training_mode = "rl"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
@@ -18,7 +18,7 @@ name = "debug-sft"
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 4
|
||||
group_size = 4
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -17,7 +17,7 @@ name = "debug-sft-external"
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 4
|
||||
group_size = 4
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
@@ -18,7 +18,7 @@ name = "debug-sft-lora"
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 4
|
||||
group_size = 4
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -17,7 +17,7 @@ interval = 100
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
|
||||
@@ -18,7 +18,7 @@ resume_step = 500
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
|
||||
@@ -18,7 +18,7 @@ resume_step = 1000
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
|
||||
@@ -30,7 +30,7 @@ lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
@@ -14,7 +14,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
|
||||
@@ -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
|
||||
@@ -10,7 +10,7 @@ name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
@@ -10,7 +10,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
@@ -33,7 +33,7 @@ max_completion_tokens = 2048
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
num_examples = 30
|
||||
rollouts_per_example = 4
|
||||
group_size = 4
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
@@ -23,7 +23,7 @@ interval = 50
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2024"
|
||||
name = "aime2024"
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 8
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
@@ -34,7 +34,7 @@ interval = 50
|
||||
id = "aime2024"
|
||||
name = "aime2024"
|
||||
num_examples = 30
|
||||
rollouts_per_example = 4
|
||||
group_size = 4
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 4096
|
||||
|
||||
@@ -10,7 +10,7 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
@@ -6,7 +6,7 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
# -- train envs --
|
||||
|
||||
@@ -36,13 +36,13 @@ max_completion_tokens = 512
|
||||
id = "reverse-text"
|
||||
name = "eval-default"
|
||||
num_examples = 32
|
||||
rollouts_per_example = 4
|
||||
group_size = 4
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
name = "eval-custom"
|
||||
num_examples = 16
|
||||
rollouts_per_example = 2
|
||||
group_size = 2
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.env.sampling]
|
||||
|
||||
@@ -10,7 +10,7 @@ language_model_attr = "model.language_model"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 64
|
||||
|
||||
@@ -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"
|
||||
@@ -38,7 +34,7 @@ gpus_per_node = 2
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 16
|
||||
rollouts_per_example = 8
|
||||
group_size = 8
|
||||
use_renderer = true
|
||||
|
||||
# Track zero-advantage groups but don't drop them — we're validating the
|
||||
@@ -64,7 +60,7 @@ args = { images_per_turn = 2, max_turns = 2, num_examples = 100, seed = 42 }
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "auto"
|
||||
# 64 concurrent rollouts (batch_size=16 × rollouts_per_example=4) want
|
||||
# 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.
|
||||
|
||||
@@ -11,7 +11,7 @@ language_model_attr = "model.language_model"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 16
|
||||
rollouts_per_example = 2
|
||||
group_size = 2
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 32
|
||||
|
||||
@@ -46,7 +46,7 @@ max_inflight_activations = 5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
@@ -69,7 +69,7 @@ max_completion_tokens = 2048
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
num_examples = 30
|
||||
rollouts_per_example = 4
|
||||
group_size = 4
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
|
||||
@@ -45,7 +45,7 @@ freq = 1
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 4096
|
||||
@@ -68,7 +68,7 @@ max_completion_tokens = 4096
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
num_examples = 30
|
||||
rollouts_per_example = 4
|
||||
group_size = 4
|
||||
|
||||
[inference.parallel]
|
||||
tp = 4
|
||||
|
||||
+1
-1
Submodule configs/private updated: 74c1330008...70c3503e1d
@@ -27,7 +27,7 @@ target_modules = [
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
oversampling_factor = 2.0
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
|
||||
Vendored
+1
-1
Submodule deps/pydantic-config updated: 94d71ecdec...896ade4e69
Vendored
+1
-1
Submodule deps/renderers updated: 8704f9d502...3ae276c446
Vendored
+1
-1
Submodule deps/research-environments updated: d141472268...c752781984
Vendored
+1
-1
Submodule deps/verifiers updated: 58b119fa1b...04651bec3e
+3
-3
@@ -1,6 +1,6 @@
|
||||
# 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.
|
||||
PRIME-RL implements asynchronous off-policy training, instead of the traditional synchronous on-policy training. The trainer and orchestrator/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 trainer and inference step timings being equal, this allows to run without any idle time on either side.
|
||||
|
||||

|
||||
|
||||
@@ -34,6 +34,6 @@ where $\mu$ refers to the policy that generated the rollout, $\pi$ refers to the
|
||||
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)}$
|
||||
- **Inference**: Produces rollouts $(x_n, y_n)$ from policy $\pi_{\max(0,\,n-1)}$
|
||||
|
||||
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.
|
||||
We use 0-indexed steps to cleanly indicate that at each step, inference is exactly one step behind the trainer.
|
||||
|
||||
@@ -70,7 +70,7 @@ kwargs = { clip_eps = 0.2 }
|
||||
|
||||
## 2. Custom Advantage Functions
|
||||
|
||||
Advantages are computed **per-example** (grouped by `rollouts_per_example`). You provide a function that computes advantages for a batch of examples.
|
||||
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
|
||||
|
||||
@@ -86,8 +86,8 @@ def my_custom_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
|
||||
```python
|
||||
@dataclass
|
||||
class AdvantageInputs:
|
||||
# Rollouts grouped by problem: rollouts[i][j] is the j-th rollout for problem i.
|
||||
rollouts: list[list[vf.RolloutOutput]]
|
||||
# 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).
|
||||
@@ -97,22 +97,21 @@ Each `vf.RolloutOutput` carries the full rollout (`reward`, `trajectory`, etc.),
|
||||
```python
|
||||
@dataclass
|
||||
class AdvantageOutputs:
|
||||
advantages: Float[Tensor, "num_examples rollouts_per_example"]
|
||||
advantages: list[float] # one entry per rollout in the input group
|
||||
```
|
||||
|
||||
### Example: Normalized Advantage
|
||||
|
||||
```python
|
||||
import torch
|
||||
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 per example."""
|
||||
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
|
||||
mean = rewards.mean(dim=1, keepdim=True)
|
||||
std = rewards.std(dim=1, keepdim=True)
|
||||
advantages = (rewards - mean) / (std + eps)
|
||||
return AdvantageOutputs(advantages=advantages)
|
||||
"""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
|
||||
|
||||
+13
-14
@@ -8,16 +8,14 @@ The `rl`, `sft`, and `inference` entrypoints all have built-in SLURM support. Ad
|
||||
# Local run
|
||||
uv run rl @ examples/reverse_text/rl.toml
|
||||
|
||||
# SLURM run (same entrypoint, just add [slurm] to the config)
|
||||
uv run rl @ examples/reverse_text/slurm_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 inherits from a base config and adds `[slurm]` + `[deployment]` sections:
|
||||
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
|
||||
toml_files = ["rl.toml"]
|
||||
|
||||
output_dir = "outputs/reverse-text-rl"
|
||||
|
||||
[slurm]
|
||||
@@ -138,12 +136,12 @@ freq = 1
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
@@ -153,7 +151,7 @@ tp = 4
|
||||
dp = 2
|
||||
```
|
||||
|
||||
See [`examples/hendrycks_math/rl.toml`](../examples/hendrycks_math/rl.toml) for the full example.
|
||||
See [`examples/multinode/rl.toml`](../examples/multinode/rl.toml) for the full example.
|
||||
|
||||
---
|
||||
|
||||
@@ -202,7 +200,7 @@ batch_size = 128
|
||||
seq_len = 8192
|
||||
```
|
||||
|
||||
See [`examples/hendrycks_math/sft.toml`](../examples/hendrycks_math/sft.toml) for the full example.
|
||||
See [`examples/multinode/sft.toml`](../examples/multinode/sft.toml) for the full example.
|
||||
|
||||
---
|
||||
|
||||
@@ -213,6 +211,7 @@ See [`examples/hendrycks_math/sft.toml`](../examples/hendrycks_math/sft.toml) fo
|
||||
Run a vLLM server on a single allocated node:
|
||||
|
||||
```toml
|
||||
# my_inference.toml
|
||||
output_dir = "/shared/outputs/my-inference"
|
||||
|
||||
[model]
|
||||
@@ -226,7 +225,7 @@ job_name = "my-inference"
|
||||
```
|
||||
|
||||
```bash
|
||||
uv run inference @ inference_slurm.toml
|
||||
uv run inference @ my_inference.toml
|
||||
```
|
||||
|
||||
### Multi-node SLURM
|
||||
@@ -255,10 +254,10 @@ After submission, the SLURM template prints the inference URLs for all nodes (on
|
||||
|
||||
### Dry run
|
||||
|
||||
Use `dry_run = true` to generate the sbatch script without submitting:
|
||||
Use `--dry-run` (or `dry_run = true` in TOML) to generate the sbatch script without submitting:
|
||||
|
||||
```bash
|
||||
uv run inference @ config.toml --dry-run true
|
||||
uv run inference @ config.toml --dry-run
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -33,7 +33,8 @@ See [`configs/debug/training_modes/README.md`](../configs/debug/training_modes/R
|
||||
| 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`. |
|
||||
|
||||
> Note: the `rl` entrypoint only manages student-policy inference. For OPD and (local) SFT, start the teacher inference server manually (e.g. `CUDA_VISIBLE_DEVICES=1 uv run inference --model.name <teacher> --server.port 8001`) and point `[orchestrator.teacher.client]` at it. See [`configs/debug/training_modes/README.md`](../configs/debug/training_modes/README.md) for a full example.
|
||||
|
||||
@@ -26,7 +26,7 @@ lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
@@ -62,7 +62,7 @@ weight_decay = 0.1
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 4096
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
oversampling_factor = 3
|
||||
max_off_policy_steps = 16
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ uv run rl @ examples/hendrycks_sanity/rl.toml \
|
||||
Or schedule the same training via SLURM
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/hendrycks_sanity/slurm_rl.toml \
|
||||
uv run rl @ examples/hendrycks_sanity/rl.toml @ examples/hendrycks_sanity/slurm_rl.toml \
|
||||
--wandb.project your-project \
|
||||
--wandb.name your-run
|
||||
```
|
||||
|
||||
@@ -13,7 +13,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
group_size = 8
|
||||
seq_len = 8192
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
@@ -27,7 +27,7 @@ interval = 50
|
||||
[[orchestrator.eval.env]]
|
||||
id = "primeintellect/aime2024"
|
||||
name = "aime2024"
|
||||
rollouts_per_example = 32
|
||||
group_size = 32
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 16384
|
||||
|
||||
@@ -36,7 +36,7 @@ freq = 1
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
@@ -10,7 +10,7 @@ name = "reverse-text"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -155,7 +155,7 @@ The wiki-search environment supports several configuration options:
|
||||
You can pass these via the `--env-args` flag in `vf-eval` or configure them in your `rl.toml`:
|
||||
|
||||
```toml
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wiki-search"
|
||||
args = { max_turns = 5, judge_model = "gpt-4.1" }
|
||||
```
|
||||
|
||||
@@ -31,7 +31,7 @@ target_modules = [
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
oversampling_factor = 2.0
|
||||
|
||||
[orchestrator.model.lora]
|
||||
|
||||
@@ -16,7 +16,7 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 16
|
||||
group_size = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wordle"
|
||||
|
||||
@@ -197,7 +197,7 @@ class EnvConfig(BaseConfig):
|
||||
ratio: float | None = Field(None, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
|
||||
|
||||
max_retries: int = Field(0, ge=0)
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Times the env server retries a failed rollout before returning an error."""
|
||||
|
||||
max_total_completion_tokens: int = -1
|
||||
@@ -206,6 +206,9 @@ class EnvConfig(BaseConfig):
|
||||
timeout: float | None = Field(None, validation_alias=AliasChoices("timeout", "timeout_seconds"))
|
||||
"""Per-rollout wall-clock timeout in seconds. None disables."""
|
||||
|
||||
state_columns: list[str] = []
|
||||
"""Extra ``State`` fields to persist into the saved rollout records (in addition to the always-saved ``trajectory`` and ``sampling_args``). Values must be JSON-serializable."""
|
||||
|
||||
@property
|
||||
def stripped_id(self) -> str:
|
||||
"""Environment ID without the @version suffix."""
|
||||
@@ -247,8 +250,8 @@ class EvalEnvConfig(EnvConfig):
|
||||
num_examples: int = -1
|
||||
"""Eval examples to sample from the dataset. ``-1`` uses all available examples."""
|
||||
|
||||
rollouts_per_example: int = Field(1, ge=1)
|
||||
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``rollouts_per_example=8`` enables pass@1 through pass@8)."""
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
|
||||
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8)."""
|
||||
|
||||
interval: int = Field(100, ge=1)
|
||||
"""Per-env eval interval. If unset, inherits from the group-level eval interval."""
|
||||
@@ -264,7 +267,7 @@ class TrainConfig(BaseConfig):
|
||||
num_workers: int | Literal["auto"] = "auto"
|
||||
"""Default worker processes for env servers. Can be overridden per env."""
|
||||
|
||||
max_retries: int = Field(0, ge=0)
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Default retries for failed rollouts. Can be overridden per env."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -313,13 +316,13 @@ class EvalConfig(BaseConfig):
|
||||
num_examples: int = -1
|
||||
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
|
||||
|
||||
rollouts_per_example: int = Field(1, ge=1)
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
num_workers: int | Literal["auto"] = "auto"
|
||||
"""Default worker processes for env servers. Can be overridden per env."""
|
||||
|
||||
max_retries: int = Field(0, ge=0)
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Default retries for failed rollouts. Can be overridden per env."""
|
||||
|
||||
interval: int = Field(100, ge=1)
|
||||
@@ -327,7 +330,7 @@ class EvalConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_workers, max_retries, num_examples, rollouts_per_example, and interval. Then resolve auto num_workers."""
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_workers, max_retries, num_examples, group_size, and interval. Then resolve auto num_workers."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
if "sampling" not in env.model_fields_set:
|
||||
@@ -337,20 +340,20 @@ class EvalConfig(BaseConfig):
|
||||
env.sampling = EvalSamplingConfig(**merged)
|
||||
if "num_examples" not in env.model_fields_set:
|
||||
env.num_examples = self.num_examples
|
||||
if "rollouts_per_example" not in env.model_fields_set:
|
||||
env.rollouts_per_example = self.rollouts_per_example
|
||||
if "group_size" not in env.model_fields_set:
|
||||
env.group_size = self.group_size
|
||||
if "interval" not in env.model_fields_set:
|
||||
env.interval = self.interval
|
||||
if "num_workers" not in env.model_fields_set:
|
||||
env.num_workers = self.num_workers
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
# Resolve auto num_workers now that num_examples and rollouts_per_example are set
|
||||
# Resolve auto num_workers now that num_examples and group_size are set
|
||||
if env.num_workers == "auto":
|
||||
if env.num_examples == -1:
|
||||
env.num_workers = 4
|
||||
else:
|
||||
max_concurrent = env.num_examples * env.rollouts_per_example
|
||||
max_concurrent = env.num_examples * env.group_size
|
||||
env.num_workers = max(1, math.ceil(max_concurrent / 256))
|
||||
return self
|
||||
|
||||
@@ -619,7 +622,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
max_inflight_rollouts: int | None = Field(None, ge=1)
|
||||
"""Maximum number of rollouts kept in-flight. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
|
||||
|
||||
rollouts_per_example: int = Field(1, ge=1)
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
|
||||
"""Output sequences returned per example during training."""
|
||||
|
||||
seq_len: int = 2048
|
||||
@@ -635,17 +638,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_error_reschedule_attempts: int | None = Field(3, ge=1)
|
||||
"""The group is dropped from the current step's batch once this many of its dispatch rounds have returned errored or empty rollouts (the trainer proceeds with the rollouts from other groups). Counts rounds, not individual rollouts: a non-group-scoring env that dispatches ``rollouts_per_example`` rollouts at once still only counts one round per failed batch. None retries indefinitely. Useful for unblocking single-example hangs in agent envs."""
|
||||
|
||||
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."""
|
||||
@@ -680,22 +674,34 @@ class OrchestratorConfig(BaseConfig):
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
|
||||
def deep_merge(dst: dict, src: dict) -> None:
|
||||
"""In-place recursive merge of ``src`` into ``dst``. ``src`` wins at the leaf."""
|
||||
for k, v in src.items():
|
||||
if isinstance(v, dict) and isinstance(dst.get(k), dict):
|
||||
deep_merge(dst[k], v)
|
||||
else:
|
||||
dst[k] = v
|
||||
|
||||
# 1. Re-nest top-level [orchestrator.client] under student.client.
|
||||
if "client" in data:
|
||||
legacy_client = data.pop("client", None)
|
||||
if isinstance(legacy_client, dict):
|
||||
student = data.setdefault("student", {})
|
||||
if isinstance(student, dict) and "client" not in student:
|
||||
student["client"] = data.pop("client")
|
||||
if isinstance(student, dict):
|
||||
deep_merge(student.setdefault("client", {}), legacy_client)
|
||||
else:
|
||||
# Mismatched types - put it back and let pydantic surface the error.
|
||||
data["client"] = legacy_client
|
||||
|
||||
# 2. Consolidate the legacy `model` alias into `student` so the
|
||||
# flat-layout fix-up below sees a single target.
|
||||
# flat-layout fix-up below sees a single target. Deep-merge with the
|
||||
# legacy keys winning so a CLI `--model.<k>` overrides TOML `student.model.<k>`.
|
||||
legacy_model = data.pop("model", None)
|
||||
if legacy_model is not None:
|
||||
existing = data.get("student")
|
||||
if existing is None:
|
||||
data["student"] = legacy_model
|
||||
elif isinstance(existing, dict) and isinstance(legacy_model, dict):
|
||||
for k, v in legacy_model.items():
|
||||
existing.setdefault(k, v)
|
||||
deep_merge(existing, legacy_model)
|
||||
else:
|
||||
# Mismatched types - put it back and let pydantic surface the error.
|
||||
data["model"] = legacy_model
|
||||
@@ -748,7 +754,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_session_headers(self):
|
||||
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
|
||||
self.student.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
|
||||
self.student.client.extra_headers_from_state.setdefault("X-Session-ID", "trajectory_id")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -870,13 +876,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
f"client entirely."
|
||||
)
|
||||
|
||||
@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
|
||||
@@ -895,11 +894,11 @@ class OrchestratorConfig(BaseConfig):
|
||||
raise ValueError("max_inflight_rollouts must be set when token_batch_size is set")
|
||||
else:
|
||||
assert self.batch_size is not None
|
||||
if self.batch_size % self.rollouts_per_example != 0:
|
||||
if self.batch_size % self.group_size != 0:
|
||||
raise ValueError("Batch size must be divisible by the number of samples per problem")
|
||||
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
|
||||
resolved_max_inflight_rollouts = max(
|
||||
self.rollouts_per_example,
|
||||
self.group_size,
|
||||
int(self.batch_size * oversampling_factor),
|
||||
)
|
||||
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
|
||||
@@ -909,7 +908,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
if self.max_inflight_rollouts is None:
|
||||
self.max_inflight_rollouts = resolved_max_inflight_rollouts
|
||||
|
||||
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.rollouts_per_example:
|
||||
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.group_size:
|
||||
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
|
||||
|
||||
# Resolve train env num_workers from max_inflight_rollouts
|
||||
@@ -924,7 +923,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,
|
||||
@@ -140,16 +139,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 +162,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 +169,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 +183,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 +212,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 +229,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 +248,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 +294,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)
|
||||
@@ -484,6 +433,19 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_router_replay_without_kv_offload(self):
|
||||
if (
|
||||
self.trainer.enable_router_replay
|
||||
and self.inference is not None
|
||||
and self.inference.kv_cache_offload is not None
|
||||
):
|
||||
raise ValueError(
|
||||
"Router replay with inference.kv_cache_offload is not supported. "
|
||||
"External KV cache hits do not carry routed-expert decisions."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_deployment(self):
|
||||
if self.deployment.type == "single_node": # single-node
|
||||
@@ -629,47 +591,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."""
|
||||
|
||||
@@ -138,7 +138,7 @@ class ClientConfig(BaseConfig):
|
||||
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
|
||||
|
||||
extra_headers_from_state: dict[str, str] = {}
|
||||
"""Maps HTTP header names to rollout-state field names. The header value is read from the rollout state dict on every request. e.g. ``{"X-Session-ID": "example_id"}`` enables sticky routing at the inference router."""
|
||||
"""Maps HTTP header names to rollout-state field names. The header value is read from the rollout state dict on every request. e.g. ``{"X-Session-ID": "trajectory_id"}`` enables sticky routing at the inference router."""
|
||||
|
||||
skip_model_check: bool = False
|
||||
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -479,8 +490,13 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class TokenExportConfig(BaseConfig):
|
||||
"""Configures per-token rollout exports from the RL trainer."""
|
||||
|
||||
|
||||
class TrainerExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
token_export: TokenExportConfig | None = None
|
||||
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
|
||||
|
||||
|
||||
class TrainerConfig(BaseConfig):
|
||||
@@ -519,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."""
|
||||
|
||||
@@ -613,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:
|
||||
|
||||
@@ -128,7 +128,6 @@ 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 +
|
||||
@@ -266,16 +265,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,
|
||||
|
||||
+8
-2
@@ -36,6 +36,7 @@ dependencies = [
|
||||
"tilelang>=0.1.8",
|
||||
"flash-linear-attention",
|
||||
"nvidia-ml-py>=12.575.51",
|
||||
"pybase64>=1.4.2",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
@@ -65,6 +66,7 @@ envs = [
|
||||
"code-env",
|
||||
"color-codeword",
|
||||
"deepdive",
|
||||
"general-agent",
|
||||
"gpqa",
|
||||
"hle",
|
||||
"ifeval",
|
||||
@@ -117,6 +119,7 @@ dev = [
|
||||
"ipywidgets>=8.1.7",
|
||||
"pre-commit>=4.2.0",
|
||||
"pytest>=8.4.1",
|
||||
"pytest-asyncio>=0.23",
|
||||
"ruff>=0.12.1",
|
||||
]
|
||||
|
||||
@@ -136,6 +139,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",
|
||||
@@ -178,6 +182,7 @@ override-dependencies = [
|
||||
# we want latest vllm, remove next patch
|
||||
vllm = false
|
||||
tokenspeed-mla = false
|
||||
fastokens = false
|
||||
flash_attn_3 = false
|
||||
# PrimeIntellect-published on PyPI (trusted publisher)
|
||||
prime = false
|
||||
@@ -201,6 +206,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 }
|
||||
@@ -230,9 +236,9 @@ 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.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
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 = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ 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'" },
|
||||
]
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
|
||||
+19
-5
@@ -44,11 +44,19 @@ assert_supported_platform() {
|
||||
}
|
||||
|
||||
has_ssh_access() {
|
||||
# Probe SSH auth to GitHub without prompting; treat any nonzero as "no ssh"
|
||||
# We try a quick ls-remote to avoid cloning on failure.
|
||||
# Disable -e for the probe so the script doesn't exit on a failed test.
|
||||
# Probe GitHub SSH auth directly. `ssh -T git@github.com` returns
|
||||
# "successfully authenticated" only when the local key is registered
|
||||
# with a GitHub user, which is the precondition for cloning private
|
||||
# submodules over SSH. The previous `git ls-remote` probe could
|
||||
# spuriously succeed (cached creds, public-repo edge cases) and
|
||||
# leave submodule clones to fail later.
|
||||
#
|
||||
# Note: ssh -T git@github.com always exits 1 (GitHub denies shell
|
||||
# access after authenticating), so we capture stdout/stderr to a var
|
||||
# first and grep the var. Piping directly would trigger pipefail.
|
||||
set +e
|
||||
timeout 5s git ls-remote --heads git@github.com:PrimeIntellect-ai/${REPO_ID}.git >/dev/null 2>&1
|
||||
out=$(timeout 5s ssh -o BatchMode=yes -T git@github.com 2>&1)
|
||||
echo "$out" | grep -q "successfully authenticated"
|
||||
rc=$?
|
||||
set -e
|
||||
return $rc
|
||||
@@ -122,7 +130,13 @@ main() {
|
||||
fi
|
||||
|
||||
if ! has_ssh_access; then
|
||||
git config url."https://github.com/".insteadOf "git@github.com:"
|
||||
# Propagate the rewrite via env vars so it reaches `git submodule--helper clone`,
|
||||
# which spawns fresh `git clone` processes that do not read the parent repo's
|
||||
# local `.git/config`. Local `git config url..insteadOf` is invisible to them.
|
||||
log_info "Routing git@github.com: SSH URLs to HTTPS for this run."
|
||||
export GIT_CONFIG_COUNT=1
|
||||
export GIT_CONFIG_KEY_0="url.https://github.com/.insteadOf"
|
||||
export GIT_CONFIG_VALUE_0="git@github.com:"
|
||||
fi
|
||||
|
||||
log_info "Initializing submodules..."
|
||||
|
||||
@@ -60,6 +60,16 @@ CLI: `--env.0.id reverse-text --env.1.id math-env`.
|
||||
|
||||
In TOML, an empty section header (`[ckpt]`) does the same.
|
||||
|
||||
## RL trainer token exports
|
||||
|
||||
For rollout debugging, enable trainer-side token export under `trainer.experimental.token_export` (or `experimental.token_export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
|
||||
```toml
|
||||
[trainer.experimental.token_export]
|
||||
```
|
||||
|
||||
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
|
||||
|
||||
## Key files
|
||||
|
||||
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
|
||||
|
||||
@@ -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,7 +102,6 @@ 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")
|
||||
@@ -194,44 +184,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
|
||||
@@ -434,7 +392,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,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import torch
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
|
||||
|
||||
@@ -16,9 +17,55 @@ def transformers_v5_compat():
|
||||
|
||||
_patch_qwen35_lora()
|
||||
_patch_lora_key_prefix()
|
||||
monkey_patch_deep_gemm_silu_mul_quant_int64()
|
||||
monkey_patch_dp_engine_core_pause_resume_deadlock()
|
||||
monkey_patch_vllm_layerwise_reload_alias_buffers()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm import envs
|
||||
from vllm.config.vllm import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
original_post_init = VllmConfig.__post_init__
|
||||
|
||||
if getattr(original_post_init, "_prime_rl_allows_nixl_routed_experts", False):
|
||||
return
|
||||
|
||||
def _is_nixl_routed_experts_pd_config(config: VllmConfig) -> bool:
|
||||
kv_transfer_config = config.kv_transfer_config
|
||||
return (
|
||||
config.model_config is not None
|
||||
and config.model_config.enable_return_routed_experts
|
||||
and kv_transfer_config is not None
|
||||
and kv_transfer_config.kv_connector == "NixlConnector"
|
||||
and kv_transfer_config.is_kv_transfer_instance
|
||||
)
|
||||
|
||||
def _post_init(config: VllmConfig):
|
||||
if not _is_nixl_routed_experts_pd_config(config):
|
||||
return original_post_init(config)
|
||||
|
||||
if config.parallel_config.pipeline_parallel_size > 1:
|
||||
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
|
||||
if envs.VLLM_USE_V2_MODEL_RUNNER:
|
||||
raise ValueError("VLLM_USE_V2_MODEL_RUNNER does not yet support: routed experts capture")
|
||||
|
||||
# vLLM rejects every KV connector, but our P/D path uses NIXL and
|
||||
# stitches prefill/decode routed experts in the router. CPU KV offload
|
||||
# remains rejected by prime-rl config validation.
|
||||
config.model_config.enable_return_routed_experts = False
|
||||
try:
|
||||
return original_post_init(config)
|
||||
finally:
|
||||
config.model_config.enable_return_routed_experts = True
|
||||
|
||||
_post_init._prime_rl_allows_nixl_routed_experts = True
|
||||
VllmConfig.__post_init__ = _post_init
|
||||
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
|
||||
|
||||
|
||||
def monkey_patch_vllm_layerwise_reload_alias_buffers():
|
||||
@@ -53,6 +100,147 @@ def monkey_patch_vllm_layerwise_reload_alias_buffers():
|
||||
logger.warning("Enabled vLLM layerwise reload alias-buffer patch.")
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel(
|
||||
y_ptr,
|
||||
y_q_ptr,
|
||||
y_s_ptr,
|
||||
M: tl.int64,
|
||||
N: tl.int64,
|
||||
y_s_col_stride: tl.int64,
|
||||
eps,
|
||||
clamp_limit,
|
||||
fp8_min: tl.constexpr,
|
||||
fp8_max: tl.constexpr,
|
||||
use_ue8m0: tl.constexpr,
|
||||
HAS_CLAMP: tl.constexpr,
|
||||
GROUP_SIZE: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
):
|
||||
pid_m = tl.program_id(0)
|
||||
pid_n = tl.program_id(1)
|
||||
N_2 = N // 2
|
||||
|
||||
m_offset = (pid_m * BLOCK_M).to(tl.int64)
|
||||
n_offset = (pid_n * BLOCK_N).to(tl.int64)
|
||||
if m_offset >= M:
|
||||
return
|
||||
|
||||
offs_n = tl.arange(0, BLOCK_N).to(tl.int64)
|
||||
offs_m = tl.arange(0, BLOCK_M).to(tl.int64)
|
||||
|
||||
base_y_ptr = y_ptr + m_offset * N + n_offset
|
||||
act_in_ptrs = base_y_ptr + offs_m[:, None] * N + offs_n[None, :]
|
||||
|
||||
act_in = tl.load(act_in_ptrs)
|
||||
mul_in = tl.load(act_in_ptrs + N_2)
|
||||
|
||||
if HAS_CLAMP:
|
||||
act_in = tl.minimum(act_in.to(tl.float32), clamp_limit).to(y_ptr.dtype.element_ty)
|
||||
mul_in = tl.clamp(mul_in.to(tl.float32), -clamp_limit, clamp_limit).to(y_ptr.dtype.element_ty)
|
||||
act_in = act_in.to(tl.float32)
|
||||
one_f32 = tl.cast(1, tl.float32)
|
||||
silu_out = (act_in / (one_f32 + tl.exp(-act_in))).to(y_ptr.dtype.element_ty)
|
||||
y = (silu_out * mul_in).to(tl.float32)
|
||||
|
||||
absmax = tl.maximum(tl.max(tl.abs(y), axis=1), eps)
|
||||
scale_raw = absmax * (1.0 / fp8_max)
|
||||
y_s = tl.math.exp2(tl.ceil(tl.log2(scale_raw))) if use_ue8m0 else scale_raw
|
||||
y_s = tl.reshape(y_s, (BLOCK_M, 1))
|
||||
y_q = tl.clamp(y / y_s, fp8_min, fp8_max).to(y_q_ptr.dtype.element_ty)
|
||||
|
||||
base_y_q_ptr = y_q_ptr + m_offset * N_2 + n_offset
|
||||
y_q_ptrs = base_y_q_ptr + offs_m[:, None] * N_2 + offs_n[None, :]
|
||||
tl.store(y_q_ptrs, y_q)
|
||||
|
||||
group_id = n_offset // GROUP_SIZE
|
||||
base_y_s_ptr = y_s_ptr + group_id * y_s_col_stride + m_offset
|
||||
y_s_ptrs = base_y_s_ptr + offs_m
|
||||
y_s = tl.reshape(y_s, (BLOCK_M,))
|
||||
tl.store(y_s_ptrs, y_s)
|
||||
|
||||
|
||||
def _silu_mul_per_token_group_quant_fp8_colmajor_int64(
|
||||
input: torch.Tensor,
|
||||
output: torch.Tensor | None = None,
|
||||
use_ue8m0: bool | None = None,
|
||||
eps: float = 1e-10,
|
||||
clamp_limit: float | None = None,
|
||||
):
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.deep_gemm import is_deep_gemm_e8m0_used
|
||||
|
||||
group_size = 128
|
||||
assert input.ndim == 2
|
||||
if output is not None:
|
||||
assert output.ndim == 2
|
||||
assert input.size(0) % group_size == 0
|
||||
assert input.size(1) % (group_size * 2) == 0
|
||||
|
||||
if use_ue8m0 is None:
|
||||
use_ue8m0 = is_deep_gemm_e8m0_used()
|
||||
|
||||
M, N = input.size()
|
||||
N_2 = N // 2
|
||||
|
||||
fp8_dtype = current_platform.fp8_dtype()
|
||||
if output is None:
|
||||
output = torch.empty((M, N_2), dtype=fp8_dtype, device=input.device)
|
||||
|
||||
output_scales = torch.empty(((N_2 // group_size), M), dtype=torch.float32, device=input.device).transpose(0, 1)
|
||||
|
||||
block_m = 8
|
||||
block_n = group_size
|
||||
assert M % block_m == 0
|
||||
assert N_2 % block_n == 0
|
||||
|
||||
finfo = torch.finfo(fp8_dtype)
|
||||
fp8_min = -224.0 if current_platform.is_fp8_fnuz() else finfo.min
|
||||
fp8_max = 224.0 if current_platform.is_fp8_fnuz() else finfo.max
|
||||
|
||||
has_clamp = clamp_limit is not None
|
||||
grid = (M // block_m, N_2 // block_n)
|
||||
_silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel[grid](
|
||||
input,
|
||||
output,
|
||||
output_scales,
|
||||
M,
|
||||
N,
|
||||
output_scales.stride(-1),
|
||||
eps,
|
||||
clamp_limit if has_clamp else 0.0,
|
||||
fp8_min,
|
||||
fp8_max,
|
||||
use_ue8m0,
|
||||
has_clamp,
|
||||
group_size,
|
||||
block_m,
|
||||
block_n,
|
||||
)
|
||||
|
||||
return output, output_scales
|
||||
|
||||
|
||||
def monkey_patch_deep_gemm_silu_mul_quant_int64():
|
||||
import sys
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.utils import fp8_utils
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
fp8_utils.silu_mul_per_token_group_quant_fp8_colmajor = _silu_mul_per_token_group_quant_fp8_colmajor_int64
|
||||
|
||||
deep_gemm_moe_module = sys.modules.get("vllm.model_executor.layers.fused_moe.experts.deep_gemm_moe")
|
||||
if deep_gemm_moe_module is not None:
|
||||
deep_gemm_moe_module.silu_mul_per_token_group_quant_fp8_colmajor = (
|
||||
_silu_mul_per_token_group_quant_fp8_colmajor_int64
|
||||
)
|
||||
|
||||
logger.warning("Enabled int64-addressing Triton patch for vLLM DeepGEMM SiLU/mul FP8 quant.")
|
||||
|
||||
|
||||
def _patch_qwen35_lora():
|
||||
"""Fix Qwen3.5 LoRA: align packed_modules_mapping with output_sizes.
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pybase64
|
||||
from vllm.outputs import RequestOutput
|
||||
|
||||
|
||||
def serialize_routed_experts(routed_experts: Any) -> dict[str, Any] | None:
|
||||
if routed_experts is None:
|
||||
return None
|
||||
|
||||
array = np.asarray(routed_experts)
|
||||
assert array.ndim == 3
|
||||
assert np.issubdtype(array.dtype, np.integer)
|
||||
if array.size:
|
||||
assert array.min() >= 0
|
||||
assert array.max() <= np.iinfo(np.uint8).max
|
||||
|
||||
compact = np.ascontiguousarray(array.astype(np.uint8, copy=False))
|
||||
return {
|
||||
"data": pybase64.b64encode(memoryview(compact)).decode("ascii"),
|
||||
"shape": list(compact.shape),
|
||||
}
|
||||
|
||||
|
||||
class RoutedExpertsCapture:
|
||||
def __init__(self, generator: AsyncIterator[RequestOutput]):
|
||||
self._generator = generator
|
||||
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))
|
||||
if encoded is not None:
|
||||
self.routed_experts[output.index] = encoded
|
||||
yield request_output
|
||||
@@ -10,9 +10,9 @@ we subclass it to add them back:
|
||||
header and forwarded to ``engine_client.generate``. The DP-replicated
|
||||
inference servers prime-RL runs need this to target a specific replica.
|
||||
|
||||
2. ``routed_experts`` per-token export — when the engine emits routing
|
||||
decisions (``enable_return_routed_experts``), surface them on each choice.
|
||||
This is what the trainer's router-replay path consumes.
|
||||
2. Compact ``routed_experts`` export — when the engine emits routing
|
||||
decisions, surface them as base64 raw-byte payloads without requiring a vLLM
|
||||
source fork.
|
||||
|
||||
3. Server-side ``max_tokens`` defaulting — ``ServingTokens`` hands the
|
||||
client-supplied ``SamplingParams`` to the engine verbatim, and
|
||||
@@ -30,13 +30,11 @@ delegates to upstream so we track future vLLM changes for free.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from collections.abc import AsyncGenerator
|
||||
from functools import cached_property
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
from fastapi import Request
|
||||
from pydantic import Field
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
|
||||
from vllm.entrypoints.serve.disagg.protocol import (
|
||||
GenerateRequest,
|
||||
@@ -48,64 +46,29 @@ from vllm.entrypoints.utils import get_max_tokens
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
|
||||
from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
|
||||
|
||||
|
||||
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
|
||||
routed_experts: dict | None = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"Per-token expert routing decisions (base85-encoded int32 array + shape). "
|
||||
"Populated only when the engine was launched with "
|
||||
"``enable_return_routed_experts=True``; otherwise ``None``."
|
||||
),
|
||||
)
|
||||
routed_experts: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class PrimeRlGenerateResponse(GenerateResponse):
|
||||
choices: list[PrimeRlGenerateResponseChoice]
|
||||
|
||||
|
||||
def encode_routed_experts(arr: np.ndarray) -> dict:
|
||||
return {
|
||||
"data": base64.b85encode(arr.tobytes()).decode("ascii"),
|
||||
"shape": list(arr.shape),
|
||||
}
|
||||
|
||||
|
||||
class _RoutedExpertsCaptureBase:
|
||||
"""Wraps the engine result generator and accumulates a
|
||||
``{output_index: encoded_experts}`` map as outputs stream. Subclasses
|
||||
implement ``post_process`` to fold the captured map into the response
|
||||
in whatever shape the endpoint returns (in-place vs rebuilt)."""
|
||||
|
||||
def __init__(self, generator: AsyncGenerator[RequestOutput, None]):
|
||||
self._generator = generator
|
||||
self.routed_experts: dict[int, dict] = {}
|
||||
|
||||
async def __aiter__(self):
|
||||
async for request_output in self._generator:
|
||||
for output in request_output.outputs:
|
||||
if output.routed_experts is not None:
|
||||
self.routed_experts[output.index] = encode_routed_experts(output.routed_experts)
|
||||
yield request_output
|
||||
|
||||
|
||||
class _RoutedExpertsCapture(_RoutedExpertsCaptureBase):
|
||||
"""Generate-endpoint variant: rebuilds the response with
|
||||
``PrimeRlGenerateResponseChoice`` because upstream's
|
||||
``GenerateResponseChoice`` isn't ``extra='allow'``, so an attribute
|
||||
set after construction wouldn't survive serialization."""
|
||||
|
||||
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
def post_process(self, response: GenerateResponse) -> PrimeRlGenerateResponse:
|
||||
new_choices = [
|
||||
choices = [
|
||||
PrimeRlGenerateResponseChoice(
|
||||
**choice.model_dump(),
|
||||
**choice.model_dump(exclude={"routed_experts"}),
|
||||
routed_experts=self.routed_experts.get(choice.index),
|
||||
)
|
||||
for choice in response.choices
|
||||
]
|
||||
return PrimeRlGenerateResponse(
|
||||
request_id=response.request_id,
|
||||
choices=new_choices,
|
||||
choices=choices,
|
||||
prompt_logprobs=response.prompt_logprobs,
|
||||
kv_transfer_params=response.kv_transfer_params,
|
||||
)
|
||||
@@ -135,7 +98,7 @@ async def _client_set_max_tokens(raw_request: Request | None) -> bool:
|
||||
|
||||
|
||||
class PrimeRlServingTokens(ServingTokens):
|
||||
"""ServingTokens + DP-rank routing + routed_experts export + max_tokens defaulting."""
|
||||
"""ServingTokens + DP-rank routing + compact routed experts + max_tokens defaulting."""
|
||||
|
||||
@cached_property
|
||||
def _max_tokens_defaults(self) -> tuple[dict, int | None]:
|
||||
@@ -298,15 +261,13 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
model_name: str,
|
||||
request_metadata: RequestResponseMetadata,
|
||||
) -> ErrorResponse | GenerateResponse:
|
||||
# Wrap the result generator to capture routed_experts as it streams,
|
||||
# defer the rest to upstream, then post-process the response into our
|
||||
# PrimeRlGenerateResponse subclass so the encoded experts surface in
|
||||
# the JSON. Skipping the wrapper when the engine isn't producing routed
|
||||
# experts keeps us a no-op subclass on the common path.
|
||||
capture: _RoutedExpertsCapture | None = None
|
||||
# Capture routed_experts as vLLM streams request outputs, then post-process
|
||||
# the final response into our GenerateResponse subclass so the encoded
|
||||
# experts surface in the JSON.
|
||||
capture: _GenerateRoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
capture = _RoutedExpertsCapture(result_generator)
|
||||
result_generator = capture # type: ignore[assignment]
|
||||
capture = _GenerateRoutedExpertsCapture(result_generator)
|
||||
result_generator = capture
|
||||
|
||||
response = await super().serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable
|
||||
|
||||
@@ -19,20 +20,16 @@ from prime_rl.utils.utils import import_object
|
||||
|
||||
@dataclass
|
||||
class AdvantageInputs:
|
||||
"""Inputs for advantage computation.
|
||||
"""Inputs for advantage computation of a single group (one example × N rollouts)."""
|
||||
|
||||
`rollouts` is grouped by problem: `rollouts[i][j]` is the j-th rollout for problem i,
|
||||
so `len(rollouts) == num_problems` and `len(rollouts[0]) == rollouts_per_example`.
|
||||
"""
|
||||
|
||||
rollouts: list[list[vf.RolloutOutput]]
|
||||
rollouts: list[vf.RolloutOutput]
|
||||
|
||||
|
||||
@dataclass
|
||||
class AdvantageOutputs:
|
||||
"""Outputs from advantage computation."""
|
||||
"""Outputs from advantage computation of a single group."""
|
||||
|
||||
advantages: Float[Tensor, "num_problems rollouts_per_example"]
|
||||
advantages: list[float]
|
||||
|
||||
|
||||
AdvantageFn = Callable[..., AdvantageOutputs]
|
||||
@@ -41,6 +38,9 @@ AdvantageFn = Callable[..., AdvantageOutputs]
|
||||
Expected signature:
|
||||
def my_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
|
||||
...
|
||||
|
||||
The function receives a single group and returns a list of advantages with one
|
||||
entry per rollout. `compute_advantages` calls it once per group.
|
||||
"""
|
||||
|
||||
|
||||
@@ -48,73 +48,63 @@ def default_advantage_fn(
|
||||
inputs: AdvantageInputs,
|
||||
length_penalty: LengthPenaltyConfig | None = None,
|
||||
) -> AdvantageOutputs:
|
||||
"""Default GRPO advantage: reward minus per-problem baseline.
|
||||
"""Default GRPO advantage for a single group: reward minus per-group baseline.
|
||||
|
||||
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
|
||||
cost: tokens (weighted completion + tool-response) or trajectory turn count.
|
||||
"""
|
||||
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts], dtype=torch.float32)
|
||||
rewards = torch.tensor([r["reward"] for r in inputs.rollouts], dtype=torch.float32)
|
||||
|
||||
if isinstance(length_penalty, TokensLengthPenaltyConfig):
|
||||
w_c = length_penalty.completion_weight
|
||||
w_t = length_penalty.tool_response_weight
|
||||
costs = torch.tensor(
|
||||
[
|
||||
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in group]
|
||||
for group in inputs.rollouts
|
||||
],
|
||||
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in inputs.rollouts],
|
||||
dtype=rewards.dtype,
|
||||
)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs))
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
|
||||
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
|
||||
costs = torch.tensor(
|
||||
[[get_num_turns(r) for r in group] for group in inputs.rollouts],
|
||||
dtype=rewards.dtype,
|
||||
)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs))
|
||||
costs = torch.tensor([get_num_turns(r) for r in inputs.rollouts], dtype=rewards.dtype)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
|
||||
|
||||
baseline = rewards.mean(dim=1, keepdim=True)
|
||||
return AdvantageOutputs(advantages=rewards - baseline)
|
||||
return AdvantageOutputs(advantages=(rewards - rewards.mean()).tolist())
|
||||
|
||||
|
||||
def _efficiency_shaping(
|
||||
rewards: Float[Tensor, "num_problems rollouts_per_example"],
|
||||
costs: Float[Tensor, "num_problems rollouts_per_example"],
|
||||
) -> Float[Tensor, "num_problems rollouts_per_example"]:
|
||||
rewards: Float[Tensor, "group_size"],
|
||||
costs: Float[Tensor, "group_size"],
|
||||
) -> Float[Tensor, "group_size"]:
|
||||
"""Correctness-gated efficiency shaping with bounded advantages.
|
||||
|
||||
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
|
||||
preserving zero-mean advantages per group. `costs` is a per-rollout cost (e.g.,
|
||||
completion length in tokens or number of turns).
|
||||
preserving zero-mean advantages within the group. `costs` is a per-rollout cost
|
||||
(e.g., completion length in tokens or number of turns).
|
||||
|
||||
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
|
||||
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
|
||||
"""
|
||||
max_reward = rewards.max(dim=1, keepdim=True).values
|
||||
max_reward = rewards.max()
|
||||
correct_mask = rewards >= max_reward
|
||||
num_correct = correct_mask.sum(dim=1, keepdim=True)
|
||||
num_correct = correct_mask.sum()
|
||||
|
||||
# No shaping when max reward is 0 — no correct rollouts to differentiate
|
||||
has_correct = max_reward > 0
|
||||
if max_reward <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
# Mean cost of correct rollouts per problem
|
||||
correct_costs = costs * correct_mask
|
||||
mean_correct_cost = correct_costs.sum(dim=1, keepdim=True) / num_correct.clamp(min=1)
|
||||
# Mean cost of correct rollouts
|
||||
mean_correct_cost = (costs * correct_mask).sum() / num_correct.clamp(min=1)
|
||||
|
||||
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
|
||||
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
|
||||
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
|
||||
has_cost = mean_correct_cost > 0
|
||||
safe_mean = torch.where(has_cost, mean_correct_cost, torch.ones_like(mean_correct_cost))
|
||||
bonus = (1 - costs / safe_mean).clamp(0, 1) * has_cost
|
||||
if mean_correct_cost <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
|
||||
|
||||
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
|
||||
shaped_rewards = rewards * (1 + bonus * correct_mask)
|
||||
baseline = shaped_rewards.mean(dim=1, keepdim=True)
|
||||
|
||||
shaped = shaped_rewards - baseline
|
||||
unshaped = rewards - rewards.mean(dim=1, keepdim=True)
|
||||
return torch.where(has_correct, shaped, unshaped)
|
||||
return shaped_rewards - shaped_rewards.mean()
|
||||
|
||||
|
||||
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
@@ -136,31 +126,26 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
|
||||
def compute_advantages(
|
||||
rollouts: list[vf.RolloutOutput],
|
||||
samples_per_problem: int,
|
||||
advantage_config: AdvantageConfig | None,
|
||||
) -> None:
|
||||
"""
|
||||
Computes advantages from rollouts, grouped by problem.
|
||||
Stores advantages in-place on the rollouts.
|
||||
"""Computes advantages from rollouts, grouped by (env_name, example_id), and
|
||||
stores them in-place on the rollouts.
|
||||
|
||||
Args:
|
||||
rollouts: List of rollouts to store advantages on
|
||||
samples_per_problem: Number of samples (and thus, rewards) per problem
|
||||
advantage_config: Configuration for advantage computation (DefaultAdvantageConfig or CustomAdvantageConfig)
|
||||
`advantage_fn` is called once per group, so groups may have varying sizes
|
||||
(partial-group training drops failed rollouts rather than rescheduling them).
|
||||
"""
|
||||
rewards = [r["reward"] for r in rollouts]
|
||||
|
||||
if not advantage_config:
|
||||
for rollout, reward in zip(rollouts, rewards):
|
||||
rollout["advantage"] = reward
|
||||
for rollout in rollouts:
|
||||
rollout["advantage"] = rollout["reward"]
|
||||
return
|
||||
|
||||
advantage_fn = setup_advantage_fn(advantage_config)
|
||||
grouped = [rollouts[i : i + samples_per_problem] for i in range(0, len(rollouts), samples_per_problem)]
|
||||
inputs = AdvantageInputs(rollouts=grouped)
|
||||
|
||||
result = advantage_fn(inputs)
|
||||
advantages = result.advantages.flatten().tolist()
|
||||
groups_by_example: dict[tuple[str, int], list[vf.RolloutOutput]] = defaultdict(list)
|
||||
for rollout in rollouts:
|
||||
groups_by_example[(rollout["env_name"], rollout["example_id"])].append(rollout)
|
||||
|
||||
for rollout, advantage in zip(rollouts, advantages):
|
||||
rollout["advantage"] = advantage
|
||||
for group in groups_by_example.values():
|
||||
result = advantage_fn(AdvantageInputs(rollouts=group))
|
||||
for rollout, advantage in zip(group, result.advantages):
|
||||
rollout["advantage"] = advantage
|
||||
|
||||
@@ -110,6 +110,15 @@ class Env:
|
||||
sampling_args["extra_body"] = extra_body
|
||||
return sampling_args
|
||||
|
||||
@property
|
||||
def state_columns(self) -> list[str]:
|
||||
"""Required columns plus any extras configured on the env, deduped (required first)."""
|
||||
merged: list[str] = []
|
||||
for col in (*REQUIRED_STATE_COLUMNS, *self.config.state_columns):
|
||||
if col not in merged:
|
||||
merged.append(col)
|
||||
return merged
|
||||
|
||||
async def run_rollout(
|
||||
self,
|
||||
client: vf.ClientConfig,
|
||||
@@ -124,7 +133,7 @@ class Env:
|
||||
model=model_name,
|
||||
sampling_args=self._sampling_args_with_salt(cache_salt),
|
||||
max_retries=self.config.max_retries,
|
||||
state_columns=REQUIRED_STATE_COLUMNS,
|
||||
state_columns=self.state_columns,
|
||||
env_client=self.env_client,
|
||||
)
|
||||
|
||||
@@ -133,17 +142,17 @@ class Env:
|
||||
client: vf.ClientConfig,
|
||||
example: dict,
|
||||
model_name: str,
|
||||
rollouts_per_example: int,
|
||||
group_size: int,
|
||||
cache_salt: str,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
"""Run a group of rollouts for an example. Required for group-scoring envs."""
|
||||
return await self.env.run_group(
|
||||
[vf.RolloutInput(**example) for _ in range(rollouts_per_example)],
|
||||
[vf.RolloutInput(**example) for _ in range(group_size)],
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling_args=self._sampling_args_with_salt(cache_salt),
|
||||
max_retries=self.config.max_retries,
|
||||
state_columns=REQUIRED_STATE_COLUMNS,
|
||||
state_columns=self.state_columns,
|
||||
env_client=self.env_client,
|
||||
)
|
||||
|
||||
@@ -177,35 +186,34 @@ class EvalEnv(Env):
|
||||
self,
|
||||
model_name: str,
|
||||
get_client: Callable[[], Awaitable[vf.ClientConfig]],
|
||||
ckpt_step: int,
|
||||
step: int,
|
||||
cache_salt: str,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
num_examples = len(self.examples)
|
||||
rollouts_per_example = self.config.rollouts_per_example
|
||||
get_logger().info(f"Evaluating {self.name} ({num_examples=}, {rollouts_per_example=})")
|
||||
total_rollouts = num_examples * rollouts_per_example
|
||||
group_size = self.config.group_size
|
||||
get_logger().info(f"Evaluating {self.name} ({num_examples=}, {group_size=})")
|
||||
total_rollouts = num_examples * group_size
|
||||
pbar = ProgressTracker(total=total_rollouts, desc=f"Evaluating {self.name}")
|
||||
eval_start = time.perf_counter()
|
||||
|
||||
if self.requires_group_scoring:
|
||||
|
||||
async def run_with_progress(example: dict) -> list[vf.RolloutOutput] | None:
|
||||
"""Run rollouts_per_example rollouts as a scored group for one example."""
|
||||
"""Run group_size rollouts as a scored group for one example."""
|
||||
try:
|
||||
client = await get_client()
|
||||
outputs = await self.run_group(
|
||||
client=client,
|
||||
example=example,
|
||||
model_name=model_name,
|
||||
rollouts_per_example=rollouts_per_example,
|
||||
group_size=group_size,
|
||||
cache_salt=cache_salt,
|
||||
)
|
||||
pbar.update(rollouts_per_example)
|
||||
pbar.update(group_size)
|
||||
return outputs
|
||||
except Exception as e:
|
||||
get_logger().warning(f"Group failed: {e}")
|
||||
pbar.update(rollouts_per_example)
|
||||
pbar.update(group_size)
|
||||
return None
|
||||
|
||||
coros = [run_with_progress(example) for example in self.examples]
|
||||
@@ -226,7 +234,7 @@ class EvalEnv(Env):
|
||||
pbar.update(1)
|
||||
return None
|
||||
|
||||
coros = [run_with_progress(example) for example in self.examples for _ in range(rollouts_per_example)]
|
||||
coros = [run_with_progress(example) for example in self.examples for _ in range(group_size)]
|
||||
|
||||
try:
|
||||
results = await asyncio.gather(*coros)
|
||||
@@ -247,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,
|
||||
@@ -282,9 +289,7 @@ class EvalEnv(Env):
|
||||
pass_at_k = None
|
||||
get_logger().warning("Skipping computing pass@k rates because the task rewards appear to be non-binary")
|
||||
|
||||
message = (
|
||||
f"Evaluated {self.name} in {eval_time:.2f}s (Avg@{rollouts_per_example}={results_df.reward.mean():.4f}"
|
||||
)
|
||||
message = f"Evaluated {self.name} in {eval_time:.2f}s (Avg@{group_size}={results_df.reward.mean():.4f}"
|
||||
if could_be_binary:
|
||||
assert pass_at_k is not None
|
||||
for pass_rate, pass_rate_score in pd.Series(pass_at_k.mean()).items():
|
||||
@@ -298,7 +303,7 @@ class EvalEnv(Env):
|
||||
get_logger().success(message)
|
||||
|
||||
eval_metrics = {
|
||||
f"avg@{rollouts_per_example}": float(results_df.reward.mean()),
|
||||
f"avg@{group_size}": float(results_df.reward.mean()),
|
||||
"no_response/mean": float(results_df.no_response.mean()),
|
||||
"no_response/count": int(results_df.no_response.sum()),
|
||||
"completion_len/mean": results_df.completion_len.mean().item(),
|
||||
@@ -312,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).
|
||||
|
||||
|
||||
@@ -11,24 +11,24 @@ class EventLoopLagMonitor:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
interval: float = 1.0,
|
||||
interval: float = 0.1,
|
||||
max_window_size: int = 10000,
|
||||
warn_med_lag_threshold: float = 0.5,
|
||||
warn_p90_lag_threshold: float = 1.0,
|
||||
warn_max_lag_threshold: float = 5.0,
|
||||
warn_p99_lag_threshold: float = 5.0,
|
||||
warn_max_lag_threshold: float = 30.0,
|
||||
):
|
||||
assert (
|
||||
interval > 0
|
||||
and max_window_size > 0
|
||||
and warn_max_lag_threshold > 0
|
||||
and warn_med_lag_threshold > 0
|
||||
and warn_p90_lag_threshold > 0
|
||||
and warn_p99_lag_threshold > 0
|
||||
and warn_max_lag_threshold > 0
|
||||
)
|
||||
self.interval = interval
|
||||
self.max_window_size = max_window_size
|
||||
self.warn_max_lag_threshold = warn_max_lag_threshold
|
||||
self.warn_med_lag_threshold = warn_med_lag_threshold
|
||||
self.warn_p90_lag_threshold = warn_p90_lag_threshold
|
||||
self.warn_p99_lag_threshold = warn_p99_lag_threshold
|
||||
self.warn_max_lag_threshold = warn_max_lag_threshold
|
||||
self.logger = get_logger()
|
||||
self.lags = []
|
||||
|
||||
@@ -61,15 +61,16 @@ class EventLoopLagMonitor:
|
||||
mean_lag = float(np.mean(last_lags))
|
||||
med_lag = float(np.median(last_lags))
|
||||
p90_lag = float(np.percentile(last_lags, 90))
|
||||
p99_lag = float(np.percentile(last_lags, 99))
|
||||
min_lag = float(np.min(last_lags))
|
||||
max_lag = float(np.max(last_lags))
|
||||
if (
|
||||
med_lag > self.warn_med_lag_threshold
|
||||
or p90_lag > self.warn_p90_lag_threshold
|
||||
p90_lag > self.warn_p90_lag_threshold
|
||||
or p99_lag > self.warn_p99_lag_threshold
|
||||
or max_lag > self.warn_max_lag_threshold
|
||||
):
|
||||
self.logger.warning(
|
||||
f"Detected busy event loop. Measured {mean_lag:.1f}s (min={min_lag:.1f}s, med={med_lag:.1f}s, p90={p90_lag:.1f}s, max={max_lag:.1f}s) event loop lag over the last {len(last_lags)} measurement(s)"
|
||||
f"Detected busy event loop. Measured {mean_lag:.1f}s (min={min_lag:.1f}s, med={med_lag:.1f}s, p90={p90_lag:.1f}s, p99={p99_lag:.1f}s, max={max_lag:.1f}s) event loop lag over the last {len(last_lags)} measurement(s)"
|
||||
)
|
||||
|
||||
return {
|
||||
@@ -77,5 +78,6 @@ class EventLoopLagMonitor:
|
||||
"event_loop_lag/mean": mean_lag,
|
||||
"event_loop_lag/med": med_lag,
|
||||
"event_loop_lag/p90": p90_lag,
|
||||
"event_loop_lag/p99": p99_lag,
|
||||
"event_loop_lag/max": max_lag,
|
||||
}
|
||||
|
||||
@@ -8,14 +8,13 @@ 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
|
||||
from prime_rl.orchestrator.trajectories import (
|
||||
backfill_rollout_tokens,
|
||||
interleave_rollout,
|
||||
offload_images_to_disk,
|
||||
pretokenize_rollout_trajectory,
|
||||
)
|
||||
from prime_rl.transport import TrainingBatch, TrainingSample, setup_training_batch_sender
|
||||
from prime_rl.utils.pathing import get_log_dir, get_rollout_dir, get_step_path
|
||||
@@ -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,
|
||||
@@ -285,11 +282,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 +289,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 +347,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 +374,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 +392,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
|
||||
@@ -428,10 +406,10 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Compute advantages (in-place)
|
||||
num_rollouts = len(train_rollouts)
|
||||
num_unique_examples = len({(r["env_name"], r["example_id"]) for r in train_rollouts})
|
||||
compute_advantages(train_rollouts, config.rollouts_per_example, config.advantage)
|
||||
await asyncio.to_thread(compute_advantages, train_rollouts, config.advantage)
|
||||
|
||||
# Apply rollout filters — sets rollout["filters"] and rollout["is_filtered"]
|
||||
apply_filters(rollout_filters, train_rollouts)
|
||||
await asyncio.to_thread(apply_filters, rollout_filters, train_rollouts)
|
||||
|
||||
n_trainable = sum(1 for r in train_rollouts if not r["is_filtered"])
|
||||
if n_trainable > 0:
|
||||
@@ -482,22 +460,28 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Convert rollouts to training samples
|
||||
parallel_preprocess_start = time.perf_counter()
|
||||
|
||||
# Pretokenize is a no-op when the renderer client already populated
|
||||
# ``tokens`` on each trajectory step (renderer path); the fallback
|
||||
# tokenizer-only branch handles text-only rollouts whose tokens
|
||||
# were not pre-rendered. Run on threads so CPU work overlaps with
|
||||
# inference for the next batch (via max_async_level >= 2).
|
||||
await asyncio.gather(
|
||||
*(
|
||||
asyncio.to_thread(
|
||||
pretokenize_rollout_trajectory,
|
||||
rollout,
|
||||
tokenizer,
|
||||
renderer=renderer,
|
||||
# We only expect to backfill tokens for training_mode=sft against an
|
||||
# external teacher API (OpenAI/etc.), which returns no token IDs —
|
||||
# reconstruct via tokenizer/renderer. The vLLM-served paths (RL/OPD
|
||||
# renderer + MITO, and training_mode=sft against a local vLLM teacher)
|
||||
# already populate tokens via prompt_token_ids/token_ids, so we
|
||||
# short-circuit the 256-way fanout.
|
||||
needs_backfill = any(step["tokens"] is None for rollout in train_rollouts for step in rollout["trajectory"])
|
||||
if needs_backfill:
|
||||
logger.info(
|
||||
"Backfilling tokens for rollout trajectories (expected for training_mode=sft against an external teacher API)"
|
||||
)
|
||||
await asyncio.gather(
|
||||
*(
|
||||
asyncio.to_thread(
|
||||
backfill_rollout_tokens,
|
||||
rollout,
|
||||
tokenizer,
|
||||
renderer=renderer,
|
||||
)
|
||||
for rollout in train_rollouts
|
||||
)
|
||||
for rollout in train_rollouts
|
||||
)
|
||||
)
|
||||
|
||||
# Process rollouts in parallel
|
||||
results = await asyncio.gather(
|
||||
@@ -564,7 +548,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
step=progress.step,
|
||||
)
|
||||
|
||||
training_batch_sender.send(training_batch)
|
||||
await training_batch_sender.send(training_batch)
|
||||
|
||||
step_time = time.perf_counter() - step_start_time
|
||||
|
||||
@@ -614,7 +598,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"""Compute solve_none, solve_all, effective_batch_size for a set of rollouts."""
|
||||
reward_per_problem = df.groupby(["env_name", "example_id"]).reward.sum()
|
||||
solve_none = (reward_per_problem == 0).mean()
|
||||
solve_all = (reward_per_problem == config.rollouts_per_example).mean()
|
||||
solve_all = (reward_per_problem == config.group_size).mean()
|
||||
return solve_none, solve_all, 1 - solve_none - solve_all
|
||||
|
||||
# Group by (env_name, example_id) to average across rollouts within each problem
|
||||
@@ -631,7 +615,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(),
|
||||
@@ -791,7 +774,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),
|
||||
)
|
||||
@@ -863,6 +845,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
def main():
|
||||
"""Main entry-point for orchestrator. Run using `uv run orchestrator`"""
|
||||
set_proc_title("Orchestrator")
|
||||
import uvloop
|
||||
|
||||
uvloop.install()
|
||||
asyncio.run(orchestrate(cli(OrchestratorConfig)))
|
||||
|
||||
|
||||
|
||||
@@ -32,8 +32,6 @@ class InflightRequest:
|
||||
env_name: str
|
||||
group_id: int | None = None
|
||||
rollout_count: int = 1
|
||||
# Dispatch round the request belongs to (see GroupState.current_round).
|
||||
round_id: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -44,19 +42,7 @@ class GroupState:
|
||||
rollouts_to_schedule: int
|
||||
completed_rollouts: list[vf.RolloutOutput] = field(default_factory=list)
|
||||
pinned_client: vf.ClientConfig | None = None
|
||||
# Number of dispatch rounds in which at least one rollout returned errored
|
||||
# or empty trajectories. Compared against
|
||||
# config.max_error_reschedule_attempts to decide when to drop a
|
||||
# permanently-stuck group. Counts rounds, not rollouts: a failed round in
|
||||
# an individual-scoring env that happens to dispatch N rollouts at once
|
||||
# still only counts as 1.
|
||||
failed_attempts: int = 0
|
||||
# Round id assigned to newly-dispatched rollouts. Advances after a failure
|
||||
# is counted so the resulting reschedule starts a new round.
|
||||
current_round: int = 0
|
||||
# Highest round already counted as failed; used to dedupe failures from
|
||||
# multiple rollouts in the same round.
|
||||
last_failed_round: int = -1
|
||||
failed_rollouts: int = 0
|
||||
|
||||
|
||||
class Scheduler:
|
||||
@@ -78,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,
|
||||
):
|
||||
@@ -94,11 +78,9 @@ class Scheduler:
|
||||
self.config = config
|
||||
self.batch_size = config.batch_size
|
||||
self.token_batch_size = config.token_batch_size
|
||||
self.rollouts_per_example = config.rollouts_per_example
|
||||
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
|
||||
|
||||
@@ -136,6 +118,7 @@ class Scheduler:
|
||||
self.cancelled_rollouts_count = 0
|
||||
self.empty_rollouts_by_env: dict[str, int] = defaultdict(int)
|
||||
self.errored_rollouts_by_env: dict[str, int] = defaultdict(int)
|
||||
self.errors_by_type: dict[str, int] = defaultdict(int)
|
||||
self.total_rollouts_by_env: dict[str, int] = defaultdict(int)
|
||||
self.dropped_groups_by_env: dict[str, int] = defaultdict(int)
|
||||
self.last_batch_generation_time = 0.0
|
||||
@@ -232,7 +215,7 @@ class Scheduler:
|
||||
client=client_config,
|
||||
example=group.example,
|
||||
model_name=self.model_name,
|
||||
rollouts_per_example=rollout_count,
|
||||
group_size=rollout_count,
|
||||
cache_salt=cache_salt,
|
||||
)
|
||||
)
|
||||
@@ -253,7 +236,6 @@ class Scheduler:
|
||||
env_name=env_name,
|
||||
group_id=group_id,
|
||||
rollout_count=rollout_count,
|
||||
round_id=group.current_round,
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -280,13 +262,13 @@ class Scheduler:
|
||||
await self.schedule_rollout(group_id=group_id)
|
||||
return True
|
||||
|
||||
if remaining_capacity < self.rollouts_per_example:
|
||||
if remaining_capacity < self.group_size:
|
||||
return False
|
||||
|
||||
example = self.buffer.sample_examples(n=1)[0]
|
||||
group_id = self.next_group_id
|
||||
self.next_group_id += 1
|
||||
self.groups[group_id] = GroupState(example=example, rollouts_to_schedule=self.rollouts_per_example)
|
||||
self.groups[group_id] = GroupState(example=example, rollouts_to_schedule=self.group_size)
|
||||
await self.schedule_rollout(group_id=group_id)
|
||||
return True
|
||||
|
||||
@@ -301,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()
|
||||
@@ -406,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())
|
||||
|
||||
@@ -446,74 +431,70 @@ class Scheduler:
|
||||
if group is None:
|
||||
continue
|
||||
|
||||
env = self.train_envs.get(env_name)
|
||||
result = finished_task.result()
|
||||
rollouts: list[vf.RolloutOutput] = result if isinstance(result, list) else [result]
|
||||
self.total_rollouts_by_env[env_name] += len(rollouts)
|
||||
|
||||
# Check for empty/errored rollouts and reschedule
|
||||
valid_rollouts = []
|
||||
has_failures = False
|
||||
last_failure_reason: str | None = None
|
||||
# Partition rollouts into valid vs failed and tally per-rollout
|
||||
# error metrics. Tally every failure (group-scoring envs return
|
||||
# N rollouts per task) so error-rate metrics aren't deflated.
|
||||
env = self.train_envs.get(env_name)
|
||||
valid_rollouts: list[vf.RolloutOutput] = []
|
||||
for rollout in rollouts:
|
||||
if rollout["error"] is not None:
|
||||
self.errored_rollouts_by_env[env_name] += 1
|
||||
has_failures = True
|
||||
last_failure_reason = rollout["error"]["error_chain_repr"]
|
||||
self.errors_by_type[rollout["error"]["error"]] += 1
|
||||
self.logger.warning(
|
||||
f"Rollout error in group {group_id} ({env_name}), re-scheduling "
|
||||
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete): "
|
||||
f"{last_failure_reason}"
|
||||
f"Rollout failed in group {group_id} ({env_name}) - "
|
||||
f"{rollout['error']['error_chain_repr']}"
|
||||
)
|
||||
elif len(rollout["trajectory"]) == 0:
|
||||
self.empty_rollouts_by_env[env_name] += 1
|
||||
has_failures = True
|
||||
last_failure_reason = "empty trajectory"
|
||||
self.logger.warning(
|
||||
f"Empty trajectory in group {group_id} ({env_name}), re-scheduling "
|
||||
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete)"
|
||||
)
|
||||
self.logger.warning(f"Empty trajectory in group {group_id} ({env_name})")
|
||||
else:
|
||||
rollout["env_name"] = env_name
|
||||
valid_rollouts.append(rollout)
|
||||
|
||||
if has_failures:
|
||||
# Dedupe failures within the same dispatch round: an
|
||||
# individual-scoring env dispatches N rollouts at once,
|
||||
# so a single failed round can produce up to N failed
|
||||
# tasks. We only count the round once.
|
||||
if rollout_info.round_id > group.last_failed_round:
|
||||
group.failed_attempts += 1
|
||||
group.last_failed_round = rollout_info.round_id
|
||||
group.current_round = rollout_info.round_id + 1
|
||||
max_attempts = self.config.max_error_reschedule_attempts
|
||||
if max_attempts is not None and group.failed_attempts >= max_attempts:
|
||||
# Permanently-stuck group: drop it from this step and let the
|
||||
# rest of the batch proceed. Avoids a single bad example (e.g.
|
||||
# an agent rollout whose sandbox poll keeps timing out)
|
||||
# blocking step progress forever.
|
||||
self.dropped_groups_by_env[env_name] += 1
|
||||
self.logger.warning(
|
||||
f"Dropping group {group_id} ({env_name}) after {group.failed_attempts} "
|
||||
f"failed dispatch rounds ({len(group.completed_rollouts)}/{self.rollouts_per_example} "
|
||||
f"complete). Last failure: {last_failure_reason}. Set "
|
||||
f"orchestrator.max_error_reschedule_attempts higher (or to None) "
|
||||
f"to retry more aggressively."
|
||||
)
|
||||
await self.drop_group(group_id)
|
||||
continue
|
||||
num_failed = len(rollouts) - len(valid_rollouts)
|
||||
group.failed_rollouts += num_failed
|
||||
|
||||
if has_failures and env.requires_group_scoring:
|
||||
# Group scoring requires all rollouts — discard partial results, reschedule full group
|
||||
group.completed_rollouts.clear()
|
||||
group.rollouts_to_schedule = self.rollouts_per_example
|
||||
# Group-scoring envs compute scores over all N rollouts
|
||||
# together; the surviving rollouts carry scores computed against
|
||||
# the (now-missing) failed ones, so partial salvage is unsafe.
|
||||
# Drop the whole group on any failure.
|
||||
if num_failed > 0 and env.requires_group_scoring:
|
||||
self.dropped_groups_by_env[env_name] += 1
|
||||
self.logger.warning(
|
||||
f"Dropping group-scored group {group_id} ({env_name}) after rollout failure"
|
||||
)
|
||||
await self.drop_group(group_id)
|
||||
continue
|
||||
|
||||
# For individual scoring, reschedule only the failed ones
|
||||
group.rollouts_to_schedule += len(rollouts) - len(valid_rollouts)
|
||||
group.completed_rollouts.extend(valid_rollouts)
|
||||
if len(group.completed_rollouts) < self.rollouts_per_example:
|
||||
|
||||
# Wait until every dispatched rollout has come back (succeeded
|
||||
# or failed) before finalizing. The group may finalize as a
|
||||
# partial group (< group_size) when some rollouts
|
||||
# errored - downstream advantage computation groups by
|
||||
# (env_name, example_id), so variable-size groups are fine.
|
||||
if len(group.completed_rollouts) + group.failed_rollouts < self.group_size:
|
||||
continue
|
||||
|
||||
if not group.completed_rollouts:
|
||||
self.dropped_groups_by_env[env_name] += 1
|
||||
self.logger.warning(
|
||||
f"Dropping group {group_id} ({env_name}) - all {self.group_size} rollouts failed"
|
||||
)
|
||||
self.groups.pop(group_id, None)
|
||||
continue
|
||||
|
||||
if group.failed_rollouts > 0:
|
||||
self.logger.warning(
|
||||
f"Partial group {group_id} ({env_name}) - "
|
||||
f"{len(group.completed_rollouts)}/{self.group_size} valid "
|
||||
f"({group.failed_rollouts} failed)"
|
||||
)
|
||||
|
||||
completed_rollouts = self.groups.pop(group_id).completed_rollouts
|
||||
|
||||
except asyncio.CancelledError:
|
||||
@@ -527,7 +508,7 @@ class Scheduler:
|
||||
continue
|
||||
|
||||
self.buffer.update(completed_rollouts)
|
||||
accepted_rollouts = self.buffer.sample_rollouts(n=self.rollouts_per_example)
|
||||
accepted_rollouts = self.buffer.sample_rollouts(n=len(completed_rollouts))
|
||||
|
||||
batch_rollouts.extend(accepted_rollouts)
|
||||
progress_increment = self.get_batch_progress_increment(accepted_rollouts)
|
||||
@@ -589,6 +570,8 @@ class Scheduler:
|
||||
metrics[f"errored_rollouts/{env_name}"] = self.errored_rollouts_by_env.get(env_name, 0) / env_total
|
||||
for env_name, count in self.dropped_groups_by_env.items():
|
||||
metrics[f"dropped_groups/{env_name}"] = count
|
||||
for error_type, count in self.errors_by_type.items():
|
||||
metrics[f"error/{error_type}/count"] = count
|
||||
by_env: dict[str, list[int]] = {}
|
||||
for info in self.inflight_requests.values():
|
||||
by_env.setdefault(info.env_name, []).append(info.off_policy_steps)
|
||||
@@ -598,6 +581,7 @@ class Scheduler:
|
||||
self.cancelled_rollouts_count = 0
|
||||
self.empty_rollouts_by_env.clear()
|
||||
self.errored_rollouts_by_env.clear()
|
||||
self.errors_by_type.clear()
|
||||
self.total_rollouts_by_env.clear()
|
||||
self.dropped_groups_by_env.clear()
|
||||
|
||||
|
||||
@@ -3,11 +3,13 @@ import hashlib
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pybase64
|
||||
import torch
|
||||
import verifiers as vf
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.transport import RoutedExperts, TrainingSample
|
||||
from prime_rl.utils.chat_template import (
|
||||
common_prefix_len,
|
||||
deserialize_tool_calls,
|
||||
@@ -21,25 +23,26 @@ from prime_rl.utils.logger import get_logger
|
||||
# primitives are immutable. mm_kwargs payloads are not mutated after creation.
|
||||
|
||||
|
||||
def _align_routed_experts(
|
||||
routed_experts: list[list[list[int]]] | None,
|
||||
def align_routed_experts(
|
||||
routed_experts: np.ndarray | None,
|
||||
expected_len: int,
|
||||
) -> list[list[list[int]]] | None:
|
||||
) -> np.ndarray | None:
|
||||
"""Align routed_experts length with the expected token count.
|
||||
|
||||
VLLM's capturer uses `num_tokens - 1` slot mappings because the final
|
||||
generated token was never fed as input to a forward pass and has no
|
||||
routing decision. Append zero-filled entries for the missing positions.
|
||||
"""
|
||||
if routed_experts is None or not routed_experts:
|
||||
if routed_experts is None:
|
||||
return routed_experts
|
||||
deficit = expected_len - len(routed_experts)
|
||||
assert routed_experts.ndim == 3
|
||||
if routed_experts.shape[0] > expected_len:
|
||||
return np.ascontiguousarray(routed_experts[:expected_len])
|
||||
deficit = expected_len - routed_experts.shape[0]
|
||||
if deficit <= 0:
|
||||
return routed_experts
|
||||
num_layers = len(routed_experts[0])
|
||||
topk = len(routed_experts[0][0])
|
||||
zero_entry = [[0] * topk for _ in range(num_layers)]
|
||||
return routed_experts + [zero_entry for _ in range(deficit)]
|
||||
padding = np.zeros((deficit, routed_experts.shape[1], routed_experts.shape[2]), dtype=routed_experts.dtype)
|
||||
return np.concatenate((routed_experts, padding), axis=0)
|
||||
|
||||
|
||||
def _common_prefix_len(a: list[int], b: list[int]) -> int:
|
||||
@@ -161,7 +164,7 @@ def _tokenize_step_with_renderer(
|
||||
return build_trajectory_step(renderer, prompt, completion, tools=tools)
|
||||
|
||||
|
||||
def pretokenize_rollout_trajectory(
|
||||
def backfill_rollout_tokens(
|
||||
output: vf.RolloutOutput,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
renderer=None,
|
||||
@@ -171,6 +174,9 @@ def pretokenize_rollout_trajectory(
|
||||
When a renderer is provided, uses it for tokenization (faster, deterministic).
|
||||
Otherwise falls back to the tokenizer + apply_chat_template path.
|
||||
"""
|
||||
if all(step["tokens"] is not None for step in output["trajectory"]):
|
||||
return True
|
||||
|
||||
logger = get_logger()
|
||||
tools = _convert_tools_to_oai_format(output.get("tool_defs", []))
|
||||
|
||||
@@ -236,13 +242,21 @@ def interleave_rollout(
|
||||
def prepare_step_tokens(step: vf.TrajectoryStep, step_idx: int) -> dict[str, Any] | None:
|
||||
tokens = step["tokens"]
|
||||
if tokens is not None:
|
||||
routed_experts_payload = tokens.get("routed_experts")
|
||||
routed_experts = 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"]
|
||||
)
|
||||
|
||||
return {
|
||||
"prompt_ids": list(tokens["prompt_ids"]),
|
||||
"prompt_mask": [bool(i) for i in tokens["prompt_mask"]],
|
||||
"prompt_mask": list(map(bool, tokens["prompt_mask"])),
|
||||
"completion_ids": list(tokens["completion_ids"]),
|
||||
"completion_mask": [bool(i) for i in tokens["completion_mask"]],
|
||||
"completion_mask": list(map(bool, tokens["completion_mask"])),
|
||||
"completion_logprobs": list(tokens["completion_logprobs"]),
|
||||
"routed_experts": tokens.get("routed_experts"),
|
||||
"routed_experts": routed_experts,
|
||||
# Renderer-emitted multimodal sidecar (placeholders + per-item
|
||||
# processed tensors). Populated when the rollout went through
|
||||
# a multimodal-aware renderer (e.g. Qwen3VLRenderer); absent
|
||||
@@ -260,22 +274,22 @@ def interleave_rollout(
|
||||
return None
|
||||
prepared_steps.append(prepared)
|
||||
|
||||
# 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]] = {}
|
||||
|
||||
def make_sample(tokens: dict[str, Any]) -> TrainingSample:
|
||||
"""Create a new TrainingSample from a trajectory step."""
|
||||
if has_error:
|
||||
completion_mask = [False] * len(tokens["completion_mask"])
|
||||
else:
|
||||
completion_mask = [bool(i) for i in tokens["completion_mask"]]
|
||||
completion_mask = list(tokens["completion_mask"])
|
||||
completion_ids = list(tokens["completion_ids"])
|
||||
|
||||
routed_experts = _align_routed_experts(
|
||||
tokens.get("routed_experts"),
|
||||
len(tokens["prompt_ids"]) + len(tokens["completion_ids"]),
|
||||
)
|
||||
prompt_ids = list(tokens["prompt_ids"])
|
||||
return TrainingSample(
|
||||
sample = TrainingSample(
|
||||
prompt_ids=prompt_ids,
|
||||
prompt_mask=[bool(i) for i in tokens["prompt_mask"]],
|
||||
prompt_mask=list(tokens["prompt_mask"]),
|
||||
completion_ids=completion_ids,
|
||||
completion_mask=completion_mask,
|
||||
completion_logprobs=list(tokens["completion_logprobs"]),
|
||||
@@ -283,11 +297,26 @@ def interleave_rollout(
|
||||
teacher_logprobs=None,
|
||||
advantage=None,
|
||||
env_name=output["env_name"],
|
||||
routed_experts=routed_experts,
|
||||
mm_token_type_ids=None,
|
||||
routed_experts=None, # deferred — finalized at end of interleave_rollout
|
||||
)
|
||||
# Initialize routed-experts state for this sample. First chunk is the
|
||||
# raw step routed_experts (no pad, no copy). running_len is the
|
||||
# cumulative count across chunks; tracked so the boundary fix-up at
|
||||
# each extension is a no-op append rather than a destructive write.
|
||||
step_routed = tokens.get("routed_experts")
|
||||
if step_routed is not None:
|
||||
sample_routed_state[id(sample)] = {
|
||||
"chunks": [step_routed],
|
||||
"running_len": int(step_routed.shape[0]),
|
||||
}
|
||||
return sample
|
||||
|
||||
def extend_sample(sample: TrainingSample, prefix_len: int, step_idx: int) -> None:
|
||||
def extend_sample(
|
||||
sample: TrainingSample,
|
||||
prefix_len: int,
|
||||
step_idx: int,
|
||||
) -> None:
|
||||
"""Extend an existing sample with a new trajectory step (extension property holds)."""
|
||||
tokens = prepared_steps[step_idx]
|
||||
|
||||
@@ -304,21 +333,26 @@ def interleave_rollout(
|
||||
if has_error:
|
||||
sample.completion_mask.extend([False] * len(tokens["completion_mask"]))
|
||||
else:
|
||||
sample.completion_mask.extend(bool(i) for i in tokens["completion_mask"])
|
||||
sample.completion_mask.extend(tokens["completion_mask"])
|
||||
sample.completion_logprobs.extend(tokens["completion_logprobs"])
|
||||
sample.completion_temperatures.extend([temperature] * len(completion_ids))
|
||||
|
||||
if tokens.get("routed_experts") is not None and sample.routed_experts is not None:
|
||||
step_routed = tokens["routed_experts"]
|
||||
# The previous step's last routing entry was zero-padded by _align_routed_experts
|
||||
# (vLLM only captures num_tokens-1 routings per request). This step actually
|
||||
# processed that boundary token as part of its prompt, so replace the zero-fill
|
||||
# with the real routing decision before appending new entries.
|
||||
if prefix_len > 0 and prefix_len <= len(step_routed):
|
||||
sample.routed_experts[prefix_len - 1] = step_routed[prefix_len - 1]
|
||||
sample.routed_experts.extend(step_routed[prefix_len:])
|
||||
expected_len = len(sample.prompt_ids) + len(sample.completion_ids)
|
||||
sample.routed_experts = _align_routed_experts(sample.routed_experts, expected_len)
|
||||
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]
|
||||
state["chunks"].append(boundary_chunk)
|
||||
state["running_len"] += 1
|
||||
new_chunk = step_routed[prefix_len:]
|
||||
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 —
|
||||
@@ -327,7 +361,8 @@ def interleave_rollout(
|
||||
|
||||
first_tokens = prepared_steps[0]
|
||||
first_prefix = first_tokens["prompt_ids"] + first_tokens["completion_ids"]
|
||||
active_samples.append((first_prefix, make_sample(first_tokens), [0]))
|
||||
first_sample = make_sample(first_tokens)
|
||||
active_samples.append((first_prefix, first_sample, [0]))
|
||||
|
||||
for step_idx, _step in enumerate(trajectory[1:], start=1):
|
||||
tokens = prepared_steps[step_idx]
|
||||
@@ -356,7 +391,29 @@ 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"]
|
||||
active_samples.append((new_prefix, make_sample(tokens), [step_idx]))
|
||||
sample = make_sample(tokens)
|
||||
active_samples.append((new_prefix, sample, [step_idx]))
|
||||
|
||||
# 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
|
||||
# boundary entries between steps were already inserted as one-entry chunks
|
||||
# during extend_sample, so a straight concat is correct.
|
||||
for _, sample, _ in active_samples:
|
||||
state = sample_routed_state.get(id(sample))
|
||||
if state is None:
|
||||
continue
|
||||
chunks = state["chunks"]
|
||||
if not chunks:
|
||||
continue
|
||||
combined = np.concatenate(chunks, axis=0) if len(chunks) > 1 else np.ascontiguousarray(chunks[0])
|
||||
expected_len = len(sample.prompt_ids) + len(sample.completion_ids)
|
||||
combined = align_routed_experts(combined, expected_len)
|
||||
combined = np.ascontiguousarray(combined)
|
||||
sample.routed_experts = RoutedExperts(
|
||||
data=combined.tobytes(),
|
||||
shape=list(combined.shape),
|
||||
dtype=str(combined.dtype),
|
||||
)
|
||||
|
||||
# Attach images by concatenating mm_items across every step the
|
||||
# sample covers. verifiers' ``state_to_output`` ships per-step
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
import orjson
|
||||
import verifiers as vf
|
||||
from verifiers.utils.save_utils import make_serializable
|
||||
|
||||
@@ -82,11 +82,11 @@ def get_tool_response_len(output: vf.RolloutOutput) -> int:
|
||||
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path, exclude_keys: set[str] | None = None) -> None:
|
||||
"""Save rollouts to a JSONL file using verifiers serialization."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
|
||||
with open(path, "wb") as f:
|
||||
for rollout in rollouts:
|
||||
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
|
||||
json.dump(row, f, default=make_serializable)
|
||||
f.write("\n")
|
||||
f.write(orjson.dumps(row, default=make_serializable, option=opts))
|
||||
|
||||
|
||||
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
|
||||
|
||||
@@ -116,7 +116,11 @@ echo "INFER_URLS=${INFER_URLS}"
|
||||
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
|
||||
# termination and cause the next launch to hang (e.g. decode engines stuck at
|
||||
# "Waiting for READY message from DP Coordinator"). Harmless on clean nodes.
|
||||
srun bash -c '
|
||||
#
|
||||
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
|
||||
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
|
||||
# because the surviving literal `vllm` strings below appear in the cmdline.
|
||||
srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
@@ -131,7 +135,7 @@ srun bash -c '
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
'
|
||||
CLEANUP_SH
|
||||
|
||||
# Run inference
|
||||
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
|
||||
@@ -171,6 +175,7 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
export VLLM_WORKER_MULTIPROC_METHOD=spawn
|
||||
{%- if use_deep_gemm %}
|
||||
export VLLM_USE_DEEP_GEMM=1
|
||||
export VLLM_MOE_USE_DEEP_GEMM=1
|
||||
{%- endif %}
|
||||
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
|
||||
export GLOO_SOCKET_IFNAME=bond0
|
||||
|
||||
@@ -160,7 +160,11 @@ uv sync --all-extras
|
||||
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
|
||||
# termination and cause the next launch to hang (e.g. decode engines stuck at
|
||||
# "Waiting for READY message from DP Coordinator"). Harmless on clean nodes.
|
||||
srun bash -c '
|
||||
#
|
||||
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
|
||||
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
|
||||
# because the surviving literal `vllm` strings below appear in the cmdline.
|
||||
srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
@@ -175,7 +179,7 @@ srun bash -c '
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
'
|
||||
CLEANUP_SH
|
||||
|
||||
# Run RL
|
||||
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
|
||||
@@ -224,6 +228,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
|
||||
{%- if use_deep_gemm %}
|
||||
export VLLM_USE_DEEP_GEMM=1
|
||||
export VLLM_MOE_USE_DEEP_GEMM=1
|
||||
{%- endif %}
|
||||
|
||||
export GLOO_SOCKET_IFNAME=bond0
|
||||
@@ -376,8 +381,8 @@ else
|
||||
|
||||
if [ "$TRAIN_NODE_RANK" -eq 0 ]; then
|
||||
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --client.base-url $INFER_URLS"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --client.admin-base-url $ADMIN_URLS"
|
||||
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 \
|
||||
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
|
||||
|
||||
@@ -67,7 +67,11 @@ cd $PROJECT_DIR && uv sync --all-extras
|
||||
# Cleanup stale node-local state from prior jobs. Orphan python/torchrun/vllm
|
||||
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
|
||||
# termination and cause the next launch to hang. Harmless on clean nodes.
|
||||
srun bash -c '
|
||||
#
|
||||
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
|
||||
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
|
||||
# because the surviving literal `vllm` strings below appear in the cmdline.
|
||||
srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
@@ -82,7 +86,7 @@ srun bash -c '
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
'
|
||||
CLEANUP_SH
|
||||
|
||||
# Run SFT
|
||||
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
|
||||
|
||||
@@ -1,6 +1,52 @@
|
||||
import copy
|
||||
|
||||
from prime_rl.transport.types import MicroBatch, TrainingSample
|
||||
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
|
||||
|
||||
ROUTED_EXPERTS_DTYPE_ITEMSIZE = {
|
||||
"uint8": 1,
|
||||
"int16": 2,
|
||||
"int32": 4,
|
||||
}
|
||||
|
||||
|
||||
def _copy_routed_experts(routed_experts: RoutedExperts) -> RoutedExperts:
|
||||
return RoutedExperts(
|
||||
data=routed_experts.data,
|
||||
shape=list(routed_experts.shape),
|
||||
dtype=routed_experts.dtype,
|
||||
)
|
||||
|
||||
|
||||
def _routed_experts_row_size(routed_experts: RoutedExperts) -> int:
|
||||
return routed_experts.shape[1] * routed_experts.shape[2] * ROUTED_EXPERTS_DTYPE_ITEMSIZE[routed_experts.dtype]
|
||||
|
||||
|
||||
def _slice_routed_experts(routed_experts: RoutedExperts, seq_len: int) -> RoutedExperts:
|
||||
row_size = _routed_experts_row_size(routed_experts)
|
||||
return RoutedExperts(
|
||||
data=routed_experts.data[: seq_len * row_size],
|
||||
shape=[seq_len, routed_experts.shape[1], routed_experts.shape[2]],
|
||||
dtype=routed_experts.dtype,
|
||||
)
|
||||
|
||||
|
||||
def _append_routed_experts(dst: MicroBatch, src: MicroBatch) -> None:
|
||||
dst_routed = dst.routed_experts
|
||||
src_routed = src.routed_experts
|
||||
assert dst_routed is not None
|
||||
assert src_routed is not None
|
||||
assert dst_routed.dtype == src_routed.dtype
|
||||
assert dst_routed.shape[1:] == src_routed.shape[1:]
|
||||
dst_routed.data += src_routed.data
|
||||
dst_routed.shape[0] += src_routed.shape[0]
|
||||
|
||||
|
||||
def _pad_routed_experts(micro_batch: MicroBatch, padding_size: int) -> None:
|
||||
routed_experts = micro_batch.routed_experts
|
||||
assert routed_experts is not None
|
||||
row_size = _routed_experts_row_size(routed_experts)
|
||||
routed_experts.data += b"\0" * (padding_size * row_size)
|
||||
routed_experts.shape[0] += padding_size
|
||||
|
||||
|
||||
def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch:
|
||||
@@ -12,6 +58,8 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
loss_mask = training_example.prompt_mask + training_example.completion_mask
|
||||
inference_logprobs = [0.0] * len(training_example.prompt_ids) + training_example.completion_logprobs
|
||||
advantages = [training_example.advantage] * len(input_ids)
|
||||
reward = training_example.reward if training_example.reward is not None else float("nan")
|
||||
rewards = [reward] * len(input_ids)
|
||||
position_ids = list(range(len(input_ids)))
|
||||
mm_token_type_ids = training_example.mm_token_type_ids
|
||||
assert training_example.env_name != "all", "env_name='all' is reserved for aggregate metric keys"
|
||||
@@ -25,7 +73,9 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
# Teacher logprobs already cover the full sequence (prompt + completion),
|
||||
# computed via prefill in the orchestrator when a teacher model is configured
|
||||
teacher_logprobs = training_example.teacher_logprobs
|
||||
routed_experts = training_example.routed_experts
|
||||
routed_experts = (
|
||||
_copy_routed_experts(training_example.routed_experts) if training_example.routed_experts is not None else None
|
||||
)
|
||||
|
||||
if len(input_ids) > seq_len:
|
||||
input_ids = input_ids[:seq_len]
|
||||
@@ -33,11 +83,12 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
inference_logprobs = inference_logprobs[:seq_len]
|
||||
position_ids = position_ids[:seq_len]
|
||||
advantages = advantages[:seq_len]
|
||||
rewards = rewards[:seq_len]
|
||||
temperatures = temperatures[:seq_len]
|
||||
if teacher_logprobs is not None:
|
||||
teacher_logprobs = teacher_logprobs[:seq_len]
|
||||
if routed_experts is not None:
|
||||
routed_experts = routed_experts[:seq_len]
|
||||
routed_experts = _slice_routed_experts(routed_experts, seq_len)
|
||||
if mm_token_type_ids is not None:
|
||||
mm_token_type_ids = mm_token_type_ids[:seq_len]
|
||||
env_names = env_names[:seq_len]
|
||||
@@ -48,17 +99,19 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
== len(loss_mask)
|
||||
== len(position_ids)
|
||||
== len(inference_logprobs)
|
||||
== len(rewards)
|
||||
== len(temperatures)
|
||||
), (
|
||||
f"input_ids: {len(input_ids)}, advantages: {len(advantages)}, loss_mask: {len(loss_mask)}, position_ids: {len(position_ids)}, inference_logprobs: {len(inference_logprobs)}, temperatures: {len(temperatures)}"
|
||||
f"input_ids: {len(input_ids)}, advantages: {len(advantages)}, loss_mask: {len(loss_mask)}, position_ids: {len(position_ids)}, inference_logprobs: {len(inference_logprobs)}, rewards: {len(rewards)}, temperatures: {len(temperatures)}"
|
||||
)
|
||||
if teacher_logprobs is not None:
|
||||
assert len(teacher_logprobs) == len(input_ids), f"teacher_logprobs: {len(teacher_logprobs)}"
|
||||
|
||||
if routed_experts is not None:
|
||||
assert len(routed_experts) == len(input_ids), (
|
||||
f"routed_experts: {len(routed_experts)}, input_ids: {len(input_ids)}"
|
||||
assert routed_experts.shape[0] == len(input_ids), (
|
||||
f"routed_experts: {routed_experts.shape}, input_ids: {len(input_ids)}"
|
||||
)
|
||||
assert len(routed_experts.data) == len(input_ids) * _routed_experts_row_size(routed_experts)
|
||||
|
||||
if mm_token_type_ids is not None:
|
||||
assert len(mm_token_type_ids) == len(input_ids), (
|
||||
@@ -74,6 +127,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
inference_logprobs=inference_logprobs,
|
||||
teacher_logprobs=teacher_logprobs,
|
||||
temperatures=temperatures,
|
||||
rewards=rewards,
|
||||
routed_experts=routed_experts,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
@@ -122,19 +176,28 @@ def packed_samples_into_micro_bs(
|
||||
len(bin_content.input_ids) + len(sample.input_ids) <= max_seq_len
|
||||
and bin_content.training_mode == sample.training_mode
|
||||
):
|
||||
existing_len = len(bin_content.input_ids)
|
||||
bin_content.input_ids.extend(sample.input_ids)
|
||||
bin_content.loss_mask.extend(sample.loss_mask)
|
||||
bin_content.advantages.extend(sample.advantages)
|
||||
if sample.rewards is not None:
|
||||
if bin_content.rewards is None:
|
||||
bin_content.rewards = [float("nan")] * existing_len
|
||||
bin_content.rewards.extend(sample.rewards)
|
||||
elif bin_content.rewards is not None:
|
||||
bin_content.rewards.extend([float("nan")] * len(sample.input_ids))
|
||||
bin_content.inference_logprobs.extend(sample.inference_logprobs)
|
||||
bin_content.temperatures.extend(sample.temperatures)
|
||||
if sample.teacher_logprobs is not None:
|
||||
if bin_content.teacher_logprobs is None:
|
||||
bin_content.teacher_logprobs = []
|
||||
bin_content.teacher_logprobs.extend(sample.teacher_logprobs)
|
||||
assert (bin_content.routed_experts is None) == (sample.routed_experts is None)
|
||||
if sample.routed_experts is not None:
|
||||
if bin_content.routed_experts is None:
|
||||
bin_content.routed_experts = []
|
||||
bin_content.routed_experts.extend(sample.routed_experts)
|
||||
bin_content.routed_experts = _copy_routed_experts(sample.routed_experts)
|
||||
else:
|
||||
_append_routed_experts(bin_content, sample)
|
||||
if sample.mm_token_type_ids is not None:
|
||||
if bin_content.mm_token_type_ids is None:
|
||||
bin_content.mm_token_type_ids = []
|
||||
@@ -175,6 +238,8 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
|
||||
|
||||
micro_batch.input_ids.extend([1] * padding_size)
|
||||
micro_batch.advantages.extend([0.0] * padding_size)
|
||||
if micro_batch.rewards is not None:
|
||||
micro_batch.rewards.extend([float("nan")] * padding_size)
|
||||
micro_batch.loss_mask.extend([False] * padding_size)
|
||||
micro_batch.position_ids.extend(list(range(padding_size)))
|
||||
micro_batch.inference_logprobs.extend([0.0] * padding_size)
|
||||
@@ -187,6 +252,8 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
|
||||
)
|
||||
if micro_batch.mm_token_type_ids is not None:
|
||||
micro_batch.mm_token_type_ids.extend([0] * padding_size)
|
||||
if micro_batch.routed_experts is not None:
|
||||
_pad_routed_experts(micro_batch, padding_size)
|
||||
micro_batch.env_names.extend([""] * padding_size)
|
||||
|
||||
return micro_batch
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -20,6 +20,7 @@ class TensorMicroBatch(TypedDict):
|
||||
input_ids: Int[Tensor, "batch seq"]
|
||||
position_ids: Int[Tensor, "batch seq"]
|
||||
advantages: Float[Tensor, "batch seq"]
|
||||
rewards: Float[Tensor, "batch seq"] | None
|
||||
inference_logprobs: Float[Tensor, "batch seq"]
|
||||
teacher_logprobs: Float[Tensor, "batch seq"] | None
|
||||
loss_mask: Bool[Tensor, "batch seq"]
|
||||
@@ -108,6 +109,7 @@ class FakeDataLoader:
|
||||
"input_ids": input_ids.unsqueeze(0),
|
||||
"position_ids": position_ids.unsqueeze(0),
|
||||
"advantages": advantages.unsqueeze(0),
|
||||
"rewards": None,
|
||||
"inference_logprobs": inference_logprobs.unsqueeze(0),
|
||||
"teacher_logprobs": None,
|
||||
"temperatures": torch.ones(input_ids.shape[0]).unsqueeze(0),
|
||||
@@ -135,6 +137,7 @@ class FakeDataLoader:
|
||||
),
|
||||
"position_ids": torch.cat([torch.arange(self.seq_len)]).unsqueeze(0),
|
||||
"advantages": torch.randn(self.seq_len, generator=generator).unsqueeze(0),
|
||||
"rewards": None,
|
||||
"inference_logprobs": torch.randn(self.seq_len, generator=generator).unsqueeze(0),
|
||||
"teacher_logprobs": None,
|
||||
"temperatures": torch.ones(self.seq_len).unsqueeze(0),
|
||||
@@ -207,10 +210,25 @@ class DataLoader:
|
||||
key: torch.frombuffer(bytearray(payload.data), dtype=_torch_dtype(payload.dtype)).reshape(payload.shape)
|
||||
for key, payload in micro_batch.mm_kwargs.items()
|
||||
}
|
||||
routed_experts = None
|
||||
packed_routed_experts = micro_batch.routed_experts
|
||||
if packed_routed_experts is not None:
|
||||
routed_experts = (
|
||||
torch.frombuffer(
|
||||
packed_routed_experts.data,
|
||||
dtype=_torch_dtype(packed_routed_experts.dtype),
|
||||
)
|
||||
.reshape(packed_routed_experts.shape)
|
||||
.to(torch.int32)
|
||||
.unsqueeze(0)
|
||||
)
|
||||
return TensorMicroBatch(
|
||||
input_ids=torch.tensor(micro_batch.input_ids, dtype=torch.long).unsqueeze(0),
|
||||
position_ids=torch.tensor(micro_batch.position_ids, dtype=torch.long).unsqueeze(0),
|
||||
advantages=torch.tensor(micro_batch.advantages, dtype=torch.float).unsqueeze(0),
|
||||
rewards=torch.tensor(micro_batch.rewards, dtype=torch.float).unsqueeze(0)
|
||||
if micro_batch.rewards is not None
|
||||
else None,
|
||||
inference_logprobs=torch.tensor(micro_batch.inference_logprobs, dtype=torch.float).unsqueeze(0),
|
||||
teacher_logprobs=torch.tensor(micro_batch.teacher_logprobs, dtype=torch.float).unsqueeze(0)
|
||||
if micro_batch.teacher_logprobs is not None
|
||||
@@ -223,11 +241,7 @@ class DataLoader:
|
||||
mm_token_type_ids=torch.tensor(micro_batch.mm_token_type_ids, dtype=torch.long).unsqueeze(0)
|
||||
if micro_batch.mm_token_type_ids is not None
|
||||
else None,
|
||||
routed_experts=torch.tensor(micro_batch.routed_experts, dtype=torch.int32).unsqueeze(
|
||||
0
|
||||
) # [1, seq_len, layers, topk]
|
||||
if micro_batch.routed_experts is not None
|
||||
else None,
|
||||
routed_experts=routed_experts,
|
||||
training_mode=micro_batch.training_mode,
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
import atexit
|
||||
import json
|
||||
import math
|
||||
from collections.abc import Mapping, Sequence
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import DefaultLossConfig, TrainerConfig
|
||||
from prime_rl.trainer.rl.loss import compute_importance_ratio_and_mismatch_kl
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
class DisabledTokenExporter:
|
||||
def export(self, *args: Any, **kwargs: Any) -> None:
|
||||
return
|
||||
|
||||
def close(self) -> None:
|
||||
return
|
||||
|
||||
|
||||
class TokenExporter:
|
||||
def __init__(
|
||||
self,
|
||||
output_dir: Path,
|
||||
rank: int,
|
||||
) -> None:
|
||||
self.rank = rank
|
||||
self.output_dir = output_dir / "token_exports"
|
||||
self._file: Any | None = None
|
||||
self._closed = False
|
||||
self._current_step: int | None = None
|
||||
self._sequences_this_step = 0
|
||||
atexit.register(self.close)
|
||||
|
||||
def export(
|
||||
self,
|
||||
step: int,
|
||||
micro_step: int,
|
||||
micro_batch: Mapping[str, Any],
|
||||
model_output: Mapping[str, Tensor],
|
||||
response_lengths: list[int],
|
||||
loss_config: Any,
|
||||
) -> None:
|
||||
if self._current_step != step:
|
||||
self._start_step(step)
|
||||
|
||||
columns = _export_columns(micro_batch, model_output, loss_config)
|
||||
_check_lengths(columns)
|
||||
|
||||
start = 0
|
||||
for micro_sequence_idx, length in enumerate(response_lengths):
|
||||
raw_end = start + length
|
||||
end = _trim_padding(columns, start, raw_end)
|
||||
if end > start and any(columns["loss_mask"][start:end]):
|
||||
self._write(
|
||||
{
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"step": step,
|
||||
"rank": self.rank,
|
||||
"micro_step": micro_step,
|
||||
"micro_sequence_idx": micro_sequence_idx,
|
||||
"export_sequence_idx": self._sequences_this_step,
|
||||
"env_name": _first_non_empty(columns["env_names"][start:end]),
|
||||
"training_mode": str(micro_batch["training_mode"]),
|
||||
**_slice_columns(columns, start, end),
|
||||
}
|
||||
)
|
||||
self._sequences_this_step += 1
|
||||
start = raw_end
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._file = None
|
||||
|
||||
def _start_step(self, step: int) -> None:
|
||||
if self._closed:
|
||||
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
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)
|
||||
self._file = (step_dir / f"rank_{self.rank}.jsonl").open("w", encoding="utf-8")
|
||||
|
||||
def _write(self, record: dict[str, Any]) -> None:
|
||||
if self._closed:
|
||||
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
|
||||
if self._file is None:
|
||||
raise RuntimeError("Token exporter has no active step file")
|
||||
self._file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
|
||||
|
||||
|
||||
def setup_token_exporter(
|
||||
config: TrainerConfig, parallel_dims: Any, world: Any, logger: Any
|
||||
) -> TokenExporter | DisabledTokenExporter:
|
||||
token_export_config = config.experimental.token_export
|
||||
if token_export_config is None:
|
||||
return DisabledTokenExporter()
|
||||
if parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0:
|
||||
return DisabledTokenExporter()
|
||||
|
||||
exporter = TokenExporter(config.output_dir, world.rank)
|
||||
logger.info(f"Writing token exports under {exporter.output_dir}")
|
||||
return exporter
|
||||
|
||||
|
||||
def _export_columns(
|
||||
micro_batch: Mapping[str, Any], model_output: Mapping[str, Tensor], loss_config: Any
|
||||
) -> dict[str, list[Any]]:
|
||||
token_ids = _tensor_to_ints(micro_batch["input_ids"])
|
||||
seq_len = len(token_ids)
|
||||
trainer_logprobs = model_output["logprobs"]
|
||||
export_tensors = _compute_export_tensors(micro_batch, trainer_logprobs, loss_config)
|
||||
|
||||
return {
|
||||
"token_ids": token_ids,
|
||||
"position_ids": _tensor_to_ints(micro_batch["position_ids"]),
|
||||
"loss_mask": _tensor_to_bools(micro_batch["loss_mask"]),
|
||||
"advantages": _tensor_to_floats(micro_batch["advantages"]),
|
||||
"rewards": _optional_tensor_to_floats(micro_batch.get("rewards"), seq_len),
|
||||
"inference_logprobs": _tensor_to_floats(micro_batch["inference_logprobs"]),
|
||||
"trainer_logprobs": _tensor_to_floats(trainer_logprobs),
|
||||
"entropy": _tensor_to_floats(model_output["entropy"]),
|
||||
"mismatch_kl": _optional_tensor_to_floats(export_tensors["mismatch_kl"], seq_len),
|
||||
"log_importance_ratio": _optional_tensor_to_floats(export_tensors["log_importance_ratio"], seq_len),
|
||||
"importance_ratio": _optional_tensor_to_floats(export_tensors["importance_ratio"], seq_len),
|
||||
"prob_delta": _optional_tensor_to_floats(export_tensors["prob_delta"], seq_len),
|
||||
"is_masked": _optional_tensor_to_bools(export_tensors["is_masked"], seq_len),
|
||||
"is_masked_high": _optional_tensor_to_bools(export_tensors["is_masked_high"], seq_len),
|
||||
"is_masked_low": _optional_tensor_to_bools(export_tensors["is_masked_low"], seq_len),
|
||||
"env_names": list(micro_batch["env_names"]),
|
||||
}
|
||||
|
||||
|
||||
def _compute_export_tensors(
|
||||
micro_batch: Mapping[str, Any], trainer_logprobs: Tensor, loss_config: Any
|
||||
) -> dict[str, Tensor | None]:
|
||||
fields: dict[str, Tensor | None] = {
|
||||
"log_importance_ratio": None,
|
||||
"importance_ratio": None,
|
||||
"mismatch_kl": None,
|
||||
"prob_delta": None,
|
||||
"is_masked": None,
|
||||
"is_masked_high": None,
|
||||
"is_masked_low": None,
|
||||
}
|
||||
if micro_batch["training_mode"] == "sft":
|
||||
return fields
|
||||
|
||||
inference_logprobs = micro_batch["inference_logprobs"].to(trainer_logprobs.device)
|
||||
loss_mask = micro_batch["loss_mask"].to(trainer_logprobs.device)
|
||||
advantages = micro_batch["advantages"].to(trainer_logprobs.device)
|
||||
with torch.no_grad():
|
||||
log_ratio, ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(trainer_logprobs, inference_logprobs)
|
||||
prob_delta = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
|
||||
fields["log_importance_ratio"] = log_ratio
|
||||
fields["importance_ratio"] = ratio
|
||||
fields["mismatch_kl"] = mismatch_kl
|
||||
fields["prob_delta"] = prob_delta
|
||||
if isinstance(loss_config, DefaultLossConfig):
|
||||
invalid_high = prob_delta > loss_config.dppo_mask_high
|
||||
invalid_low = prob_delta < -loss_config.dppo_mask_low
|
||||
positive_advantages = advantages > 0
|
||||
negative_advantages = advantages < 0
|
||||
invalid = torch.where(positive_advantages, invalid_high, invalid_low)
|
||||
fields["is_masked"] = loss_mask & invalid
|
||||
fields["is_masked_high"] = loss_mask & positive_advantages & invalid_high
|
||||
fields["is_masked_low"] = loss_mask & negative_advantages & invalid_low
|
||||
return fields
|
||||
|
||||
|
||||
def _tensor_to_ints(tensor: Tensor) -> list[int]:
|
||||
return [int(value) for value in tensor.detach().cpu().reshape(-1).tolist()]
|
||||
|
||||
|
||||
def _tensor_to_bools(tensor: Tensor) -> list[bool]:
|
||||
return [bool(value) for value in tensor.detach().cpu().reshape(-1).tolist()]
|
||||
|
||||
|
||||
def _tensor_to_floats(tensor: Tensor) -> list[float | None]:
|
||||
values = tensor.detach().to(dtype=torch.float32, device="cpu").reshape(-1).tolist()
|
||||
return [_json_float(value) for value in values]
|
||||
|
||||
|
||||
def _optional_tensor_to_floats(tensor: Tensor | None, seq_len: int) -> list[float | None]:
|
||||
if tensor is None:
|
||||
return [None] * seq_len
|
||||
return _tensor_to_floats(tensor)
|
||||
|
||||
|
||||
def _optional_tensor_to_bools(tensor: Tensor | None, seq_len: int) -> list[bool | None]:
|
||||
if tensor is None:
|
||||
return [None] * seq_len
|
||||
return _tensor_to_bools(tensor)
|
||||
|
||||
|
||||
def _check_lengths(columns: Mapping[str, Sequence[Any]]) -> None:
|
||||
lengths = {key: len(values) for key, values in columns.items()}
|
||||
if len(set(lengths.values())) != 1:
|
||||
raise ValueError(f"Token export fields must have aligned lengths, got {lengths}")
|
||||
|
||||
|
||||
def _slice_columns(columns: Mapping[str, Sequence[Any]], start: int, end: int) -> dict[str, list[Any]]:
|
||||
return {key: list(values[start:end]) for key, values in columns.items() if key != "env_names"}
|
||||
|
||||
|
||||
def _trim_padding(columns: Mapping[str, Sequence[Any]], start: int, end: int) -> int:
|
||||
env_names = columns["env_names"]
|
||||
loss_mask = columns["loss_mask"]
|
||||
while end > start and env_names[end - 1] == "" and not loss_mask[end - 1]:
|
||||
end -= 1
|
||||
return end
|
||||
|
||||
|
||||
def _json_float(value: float | None) -> float | None:
|
||||
if value is None:
|
||||
return None
|
||||
value = float(value)
|
||||
if not math.isfinite(value):
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def _first_non_empty(values: Sequence[str]) -> str | None:
|
||||
for value in values:
|
||||
if value:
|
||||
return value
|
||||
return None
|
||||
@@ -35,6 +35,7 @@ from prime_rl.trainer.rl.loss import (
|
||||
shift_tensor_left,
|
||||
shift_tensor_right,
|
||||
)
|
||||
from prime_rl.trainer.rl.token_export import setup_token_exporter
|
||||
from prime_rl.trainer.model import (
|
||||
forward,
|
||||
setup_tokenizer,
|
||||
@@ -239,6 +240,8 @@ def train(config: TrainerConfig):
|
||||
config.rollout_transport,
|
||||
)
|
||||
|
||||
token_exporter = setup_token_exporter(config, parallel_dims, world, logger)
|
||||
|
||||
gc_handler = GarbageCollection(config.gc.interval) if config.gc else None
|
||||
|
||||
logger.info(f"Starting training loop (max_steps={config.max_steps or 'infinite'})")
|
||||
@@ -255,21 +258,28 @@ 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.
|
||||
@@ -500,6 +510,8 @@ def train(config: TrainerConfig):
|
||||
for env_name, indices in env_to_indices.items():
|
||||
tensors[f"mismatch_kl/{env_name}"].append(mismatch_kl[indices])
|
||||
|
||||
token_exporter.export(progress.step, micro_step, micro_batch, out, response_lengths, config.loss)
|
||||
|
||||
if is_tt_moe_model(model):
|
||||
load_balance_stats = get_load_balance_stats(model)
|
||||
for k, v in load_balance_stats.items():
|
||||
@@ -516,6 +528,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
|
||||
@@ -575,6 +589,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
|
||||
@@ -678,6 +694,8 @@ def train(config: TrainerConfig):
|
||||
prof.export_chrome_trace(trace_file)
|
||||
logger.info(f"Saved trace to {trace_file}")
|
||||
|
||||
token_exporter.close()
|
||||
|
||||
# Write final checkpoint (only for single-run mode; multi-run checkpoints are managed by MultiCheckpointManager)
|
||||
if config.max_concurrent_runs == 1 and ckpt_manager is not None:
|
||||
if not (config.ckpt and config.ckpt.weights_only):
|
||||
|
||||
@@ -381,7 +381,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 +414,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 +501,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 +573,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
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user