Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
69308b88cb | ||
|
|
0630b7bff7 | ||
|
|
5ed05cf6ac | ||
|
|
1c0720d975 | ||
|
|
61f2448d1d | ||
|
|
c7a6573de5 | ||
|
|
8b2819b4c7 | ||
|
|
1fd4fefd4a | ||
|
|
15d6c81974 |
+1
-6
@@ -1,16 +1,11 @@
|
||||
# .git stays: docker-editable-pretend-versions.sh reads .git/modules via the bind mount.
|
||||
outputs
|
||||
**/.venv
|
||||
**/__pycache__
|
||||
**/*.py[cod]
|
||||
**/.pytest_cache
|
||||
**/.ruff_cache
|
||||
**/.mypy_cache
|
||||
**/wandb
|
||||
**/checkpoints
|
||||
**/weights
|
||||
**/broadcasts
|
||||
**/rollouts
|
||||
**/torchrun
|
||||
.claude
|
||||
.vscode
|
||||
*.ipynb
|
||||
|
||||
@@ -146,7 +146,7 @@ jobs:
|
||||
id: artifact
|
||||
run: echo "name=benchmark-${{ matrix.runner }}-$(echo '${{ matrix.model }}' | sed 's/\//--/')-${{ matrix.type }}-${{ matrix.lora_rank || 'full' }}-${{ matrix.num_gpus }}gpu-${{ matrix.ac }}-${{ matrix.attention }}-${{ matrix.seq_len }}-cp${{ matrix.cp }}-ep${{ matrix.ep }}" >> "$GITHUB_OUTPUT"
|
||||
- name: Upload benchmark result
|
||||
uses: actions/upload-artifact@v5
|
||||
uses: actions/upload-artifact@v7
|
||||
if: always()
|
||||
with:
|
||||
name: ${{ steps.artifact.outputs.name }}
|
||||
@@ -163,16 +163,16 @@ jobs:
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Checkout repository # We can't use the image because then no git
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync
|
||||
- name: Download all benchmark artifacts
|
||||
uses: actions/download-artifact@v6
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
path: /tmp/benchmark_artifacts
|
||||
pattern: benchmark-*
|
||||
|
||||
@@ -103,7 +103,7 @@ jobs:
|
||||
esac
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ env.BUILD_REF }}
|
||||
fetch-depth: 0
|
||||
@@ -170,7 +170,7 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ needs.prepare.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
@@ -20,7 +20,7 @@ jobs:
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
@@ -48,9 +48,9 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
|
||||
@@ -20,7 +20,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Create next .dev tag from latest release
|
||||
uses: actions/github-script@v8
|
||||
uses: actions/github-script@v9
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
apt-get install -y git
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run unit tests
|
||||
@@ -94,7 +94,7 @@ jobs:
|
||||
apt-get install -y git
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
@@ -102,7 +102,7 @@ jobs:
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run integration tests
|
||||
@@ -120,7 +120,7 @@ jobs:
|
||||
run: uv run pytest -vvs ${{ matrix.pytest_args }}
|
||||
- name: Upload run logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ${{ matrix.test }}-logs
|
||||
path: /tmp/outputs/**/*.log
|
||||
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
|
||||
@@ -70,7 +70,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
|
||||
@@ -159,7 +159,7 @@ jobs:
|
||||
echo "tag=$tag" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
|
||||
- name: Install prime CLI (latest)
|
||||
run: uv tool install prime
|
||||
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
|
||||
@@ -73,7 +73,7 @@ jobs:
|
||||
apt-get install -y git
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
@@ -81,7 +81,7 @@ jobs:
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
|
||||
@@ -15,17 +15,17 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
# Submodules are excluded from ruff via pyproject.toml; no need to fetch them.
|
||||
with:
|
||||
submodules: false
|
||||
- name: Run ruff
|
||||
uses: astral-sh/ruff-action@v4.1.0
|
||||
with:
|
||||
version: "0.13.0"
|
||||
version: "0.15.14"
|
||||
args: "check --config=pyproject.toml"
|
||||
- name: Run ruff format (check)
|
||||
uses: astral-sh/ruff-action@v4.1.0
|
||||
with:
|
||||
version: "0.13.0"
|
||||
version: "0.15.14"
|
||||
args: "format --check --config=pyproject.toml"
|
||||
|
||||
@@ -10,7 +10,7 @@ jobs:
|
||||
trigger-docs-sync:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Validate mint.json pages exist
|
||||
run: |
|
||||
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
version: ${{ steps.tag.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout main
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -148,14 +148,14 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout tagged release (dispatch)
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: refs/tags/${{ inputs.tag }}
|
||||
|
||||
- name: Checkout tagged release (push)
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
+3
-19
@@ -1,27 +1,13 @@
|
||||
.vscode/*
|
||||
.claude/scheduled_tasks.lock
|
||||
.claude/worktrees/
|
||||
.codex/
|
||||
*.ipynb
|
||||
*.jsonl
|
||||
configs/endpoints.py
|
||||
|
||||
# Artifacts
|
||||
**/slurm
|
||||
!src/prime_rl/slurm
|
||||
!examples/slurm
|
||||
!docs/slurm.md
|
||||
**/torchrun
|
||||
**/weights
|
||||
**/checkpoints
|
||||
**/broadcasts
|
||||
**/rollouts
|
||||
**/logs
|
||||
**/wandb
|
||||
!src/prime_rl/monitors/wandb/
|
||||
**/evals
|
||||
**/run_*/
|
||||
!configs/**/evals
|
||||
final_summary.json
|
||||
# Run artifacts
|
||||
outputs/
|
||||
.pydantic_config
|
||||
.chroma_db
|
||||
deps/nixl_*
|
||||
@@ -202,6 +188,4 @@ cython_debug/
|
||||
debug_I2_zero_band
|
||||
.idea
|
||||
|
||||
outputs/
|
||||
|
||||
third_party/
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
# SFT warmup for reverse-text on 2 GPUs. Dev-sized mirror of examples/basic/reverse-text/sft.toml.
|
||||
# SFT warmup for reverse-text on 2 GPUs (1 train + 1 infer for online evals).
|
||||
# Dev-sized mirror of examples/basic/reverse-text/sft.toml.
|
||||
|
||||
max_steps = 100
|
||||
|
||||
[deployment]
|
||||
num_gpus = 2
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
@@ -17,3 +19,24 @@ batch_size = 32
|
||||
|
||||
[optim]
|
||||
lr = 2e-5
|
||||
|
||||
[eval]
|
||||
interval = 25
|
||||
num_examples = 32
|
||||
|
||||
[eval.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
max_steps = 20
|
||||
|
||||
[deployment]
|
||||
num_gpus = 2
|
||||
num_train_gpus = 2
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
|
||||
@@ -19,6 +19,9 @@ lr = 1e-5
|
||||
batch_size = 128
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 384
|
||||
|
||||
|
||||
@@ -22,6 +22,9 @@ save_adapter_separately = true
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.model.lora]
|
||||
name = "r8-1e-4"
|
||||
|
||||
|
||||
@@ -19,6 +19,9 @@ save_adapter_separately = true
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.model.lora]
|
||||
name = "r8-1e-4"
|
||||
|
||||
|
||||
@@ -22,6 +22,9 @@ impl = "custom"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
|
||||
@@ -24,6 +24,9 @@ name = "ci-rl-opd"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "opd"
|
||||
|
||||
|
||||
@@ -24,6 +24,9 @@ name = "ci-rl-sft"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "sft"
|
||||
|
||||
|
||||
@@ -22,6 +22,9 @@ lr = 3e-6
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
|
||||
@@ -19,6 +19,9 @@ lr = 3e-6
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@ batch_size = 512
|
||||
group_size = 8
|
||||
seq_len = 8192
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
|
||||
@@ -17,11 +17,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
oversampling_factor = 2.0
|
||||
|
||||
[[orchestrator.pre_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
enforce = true
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 512
|
||||
max_inflight = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
|
||||
@@ -18,6 +18,9 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
|
||||
|
||||
@@ -17,6 +17,9 @@ language_model_attr = "model.language_model"
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 64
|
||||
|
||||
|
||||
@@ -44,12 +44,6 @@ type = "subprocess"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
# ECHO learns from observation tokens even when the GRPO advantage collapses
|
||||
# to zero — keep zero-advantage rollouts in the batch.
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
enforce = false
|
||||
|
||||
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
Vendored
+1
-1
Submodule deps/pydantic-config updated: 4f5ae37358...65b15dffba
Vendored
+1
-1
Submodule deps/verifiers updated: 02cc940d8f...ece7ddc7da
+38
-25
@@ -1,6 +1,6 @@
|
||||
# Algorithms
|
||||
|
||||
This page covers the math and the configurable algorithmic components: the algorithm abstraction and its algorithms, how off-policy training works, the loss components and advantage functions, how to plug in your own, the filters applied between rollout and training, and how multi-turn rollouts get merged into training samples.
|
||||
This page covers the math and the configurable algorithmic components: the algorithm abstraction and its algorithms, how off-policy training works, the loss components and advantage functions, curricula, and how multi-turn rollouts get merged into training samples.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -21,7 +21,7 @@ This page covers the math and the configurable algorithmic components: the algor
|
||||
- [Self-Play Advantage (RAE)](#self-play-advantage-rae)
|
||||
- [Authoring an Algorithm](#authoring-an-algorithm)
|
||||
- [Reference Scoring](#reference-scoring)
|
||||
- [Filters](#filters)
|
||||
- [Curricula](#curricula)
|
||||
- [Multi-Turn Trajectories](#multi-turn-trajectories)
|
||||
- [Extension Property](#extension-property)
|
||||
- [Best-Effort Interleaving](#best-effort-interleaving)
|
||||
@@ -164,12 +164,12 @@ At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_r
|
||||
| `hierarchical_grpo` | `HierarchicalGRPOAlgorithm` | `score_group`: GRPO baseline per episode for solvers, per group for the proposer |
|
||||
| `opd` | `OPDAlgorithm` | `score_rollout`: own-context prefill under the teacher |
|
||||
| `opsd` | `OPSDAlgorithm` | `score_rollout`: demo-conditioned prefill under the live policy |
|
||||
| `sft` | `SFTDistillAlgorithm` | `score_group`: group-norm credit (feeds filters) |
|
||||
| `sft` | `SFTDistillAlgorithm` | no credit assignment; CE on sampled tokens |
|
||||
|
||||
Each class owns its hooks outright — reading one top to bottom reads the algorithm, and everything on the class is an override point. The two hooks are one scope-and-timing ladder — the wider scope is unlocked by a later barrier, so the two axes coincide. Each is handed the `Rollout` directly — the env's typed trace (`reward`, `nodes`, `num_turns`, ...) with `samples` attached, plus `assign_advantages` to write credit:
|
||||
|
||||
- `async score_rollout(rollout)` — one rollout, **on arrival** (as it's tokenized, before its group is complete): rollout-local credit (`rollout.assign_advantages(...)`, scalar broadcast or per-token), observation ce weights, **or** model I/O — query a reference pool (e.g. `self.teacher_pool`, connected in `setup()` via `self.connect(...)`, or the live `self.policy_pool` for opsd) and attach per-token results (e.g. teacher logprobs) with bounded concurrency. No siblings. `echo` weights observation tokens here, identifying env-provided observation nodes by their non-sampled status and source step role attribution, applying the optional user filter, and writing the `ce_weights` stream. Model I/O runs *before* the pre-batch filters, so it pays compute on rollouts that may then be filtered out.
|
||||
- `score_group(group)` — the cohort, **before filtering** (filters read the streams), synchronous: group-relative credit (GRPO/MaxRL baselines). `group` is a list of `Rollout`.
|
||||
- `async score_rollout(rollout)` — one rollout, **on arrival** (as it's tokenized, before its group is complete): rollout-local credit (`rollout.assign_advantages(...)`, scalar broadcast or per-token), observation ce weights, **or** model I/O — query a reference pool (e.g. `self.teacher_pool`, connected in `setup()` via `self.connect(...)`, or the live `self.policy_pool` for opsd) and attach per-token results (e.g. teacher logprobs) with bounded concurrency. No siblings. `echo` weights observation tokens here, identifying env-provided observation nodes by their non-sampled status and source step role attribution, applying the optional user filter, and writing the `ce_weights` stream.
|
||||
- `score_group(group)` — the completed cohort, synchronous: group-relative credit (GRPO/MaxRL baselines). `group` is a list of `Rollout`.
|
||||
|
||||
The pipeline drives the hooks through two non-virtual methods it never looks inside: `algorithm.finalize_rollout(rollout)` per arrival (rollout-local scoring + reference I/O) and `algorithm.finalize_group(rollouts)` per group (scoring + wire stamping; after this the records are frozen — groups die at stamping). Sample construction (interleaving) is pure pipeline — observation-token provenance is available through structural attribution (`node.sampled`, `node.is_content`) for any algorithm that trains on env-provided tokens.
|
||||
|
||||
@@ -305,8 +305,8 @@ The per-token training signal is set by `algo.type` and the [algorithm](#the-alg
|
||||
| `rae` | `rl` | Reward minus a per-agent EMA baseline (SPIRAL's role-conditioned advantage estimation) — for multi-agent self-play envs. |
|
||||
| `hierarchical_grpo` | `rl` | GRPO for proposer-solver envs: solvers are compared within one proposed problem, while proposers are compared across proposals. |
|
||||
| `echo` | `rl` + `ce` | Group-norm on action tokens, plus weighted CE on env-provided tokens selected by message role (each role's `alpha` is its ECHO λ), optionally narrowed by a user filter. |
|
||||
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream; `group_size` only fans out sampling. |
|
||||
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream. |
|
||||
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` and ship no advantage stream; `group_size` only fans out sampling. |
|
||||
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` and ship no advantage stream. |
|
||||
| `sft` | `ce` | Cross-entropy on the sampled tokens. Assigns no advantage — trains on every sampled token. |
|
||||
|
||||
### Default Advantage
|
||||
@@ -382,7 +382,7 @@ id = "null"
|
||||
type = "subprocess"
|
||||
```
|
||||
|
||||
`group_size` controls how many problems are proposed from each source task. `env.n` controls how many solvers attempt each proposed problem. If a comparison contains only one trace—for example, a solver when `env.n = 1`—its advantage is zero and the zero-advantage filter removes it.
|
||||
`group_size` controls how many problems are proposed from each source task. `env.n` controls how many solvers attempt each proposed problem. If a comparison contains only one trace—for example, a solver when `env.n = 1`—its advantage is zero.
|
||||
|
||||
This algorithm is accepted only for proposer-solver envs. Use the env's `train_proposer` and `train_solver` settings if you want to train only one role.
|
||||
|
||||
@@ -439,7 +439,7 @@ class MyAlgorithm(Algorithm):
|
||||
|
||||
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick the hook by *when* your signal is ready: `score_rollout` for per-arrival credit or credit that needs a model call (it's `async`), `score_group` for group-relative credit (GRPO/MaxRL). `assign_advantages` takes a scalar (broadcast over the rollout's trainable tokens — the common case) or a full-length per-token list aligned to the concatenated sample token_ids (process rewards, step-level credit; `0.0` off-mask).
|
||||
|
||||
Each per-token list must match the rollout's completion-token count exactly — validated loudly when the view writes it. Advantage-based filters and metrics derive from the streams (the zero-advantage filter checks for all-zero streams; logged distributions use per-rollout means). Signals that depend on the live policy's weights (like OPD's reverse KL) cannot be precomputed here; those are reference-scoring algorithms, evaluated in the trainer.
|
||||
Each per-token list must match the rollout's completion-token count exactly — validated loudly when the view writes it. Curriculum admission and metrics can inspect these streams after group scoring. Signals that depend on the live policy's weights (like OPD's reverse KL) cannot be precomputed here; those are reference-scoring algorithms, evaluated in the trainer.
|
||||
|
||||
### Reference Scoring
|
||||
|
||||
@@ -454,31 +454,44 @@ type = "opsd"
|
||||
demo_key = "demonstration"
|
||||
```
|
||||
|
||||
Scoring runs at arrival, *before* the pre-batch filters, so a rollout that is later filtered still cost its reference compute — accepted for the simpler one-rollout-at-a-time shape (advantage-based filters never fire for opd/opsd anyway, since neither assigns an advantage).
|
||||
Scoring runs at arrival, before curriculum admission, so a rollout that is later rejected still costs its reference compute.
|
||||
|
||||
## Filters
|
||||
By default, zero-advantage RL tokens are removed after a complete batch cohort has been collected and before its payload is packed for the trainer. This does not backfill the batch. Samples that still carry CE or reference-KL components are retained, while pure zero-advantage RL samples are not shipped. Removing an RL token also removes its trainer/inference mismatch-KL contribution. Set `orchestrator.train.filter_zero_advantages = false` to retain them.
|
||||
|
||||
Filters drop rollouts between scoring and training. Built-ins (composable):
|
||||
## Curricula
|
||||
|
||||
| Filter | Effect |
|
||||
|---|---|
|
||||
| `gibberish` | Drops rollouts whose mean log-prob fall below a threshold — usually a sign of degenerate output. |
|
||||
| `repetition` | Drops rollouts with high n-gram repetition. |
|
||||
| `zero_advantage` | Drops rollouts whose advantage is zero, so the trainer doesn't waste tokens on them. |
|
||||
Each training source has a `Curriculum` composed from one `TaskSampler` and any number of named `AdmissionGate`s. The sampler chooses tasks and observes every finalized result. Every gate evaluates every result; the group trains only if every gate admits it. Rejected groups remain observable while the orchestrator samples again to fill the batch.
|
||||
|
||||
The default `[orchestrator]` config registers all three in both filter slots: `post_batch_filters` enforce by default (flagged rollouts are recorded but not shipped to the trainer), while `pre_batch_filters` run in monitor mode (`enforce = false`); flip `enforce = true` there to drop matching rollouts before they consume a slot in the batch. Setting a slot replaces its defaults wholesale:
|
||||
Samplers and gates can be stateful. Their `state_dict`, `load_state_dict`, and `metrics` methods are included in orchestrator checkpoints and logged under `curriculum/<env>/`.
|
||||
|
||||
Three small implementations are included:
|
||||
|
||||
- `StandardSampler` is the default: it advances the task iterator and cycles finite tasksets in source order.
|
||||
- `DifficultyPoolSampler` samples finite tasksets with replacement and tracks each task's latest valid mean group reward. Each named pool has an inclusive reward threshold and a relative per-task sampling weight; weight `0` disables sampling from that pool. Unseen tasks use neutral weight `1.0`, so pool observations affect sampling immediately without waiting for a full taskset pass.
|
||||
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in post-batch zero-advantage filtering, rejection requests replacement work. Groups without an advantage stream are admitted.
|
||||
|
||||
```toml
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
[orchestrator.train.source.curriculum.sampler]
|
||||
type = "difficulty_pool"
|
||||
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "repetition"
|
||||
threshold = 0.4
|
||||
[orchestrator.train.source.curriculum.sampler.pools.hard]
|
||||
threshold = 0.25
|
||||
weight = 0.2
|
||||
|
||||
[orchestrator.train.source.curriculum.sampler.pools.normal]
|
||||
threshold = 0.75
|
||||
weight = 1.0
|
||||
|
||||
[orchestrator.train.source.curriculum.sampler.pools.easy]
|
||||
threshold = 1.0
|
||||
weight = 0.2
|
||||
|
||||
[orchestrator.train.source.curriculum.gates.low_signal]
|
||||
type = "advantage_range"
|
||||
reject_min = -0.05
|
||||
reject_max = 0.05
|
||||
```
|
||||
|
||||
Filtered rollouts still appear in the W&B metrics, just not in the trainer batch — useful for spotting whether filtering is doing its job.
|
||||
|
||||
## Multi-Turn Trajectories
|
||||
|
||||
For multi-turn rollouts (tool use, browser environments, long conversations), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
|
||||
|
||||
+14
-1
@@ -12,6 +12,7 @@ This page covers the inference configuration and the supported features/deployme
|
||||
- [P/D Disaggregation](#pd-disaggregation)
|
||||
- [Router](#router)
|
||||
- [Routing policies](#routing-policies)
|
||||
- [Adaptive Concurrency](#adaptive-concurrency)
|
||||
- [Advanced Configuration](#advanced-configuration)
|
||||
- [KV Cache Offload](#kv-cache-offload)
|
||||
- [Optimized P/D disaggregation deployment](#optimized-pd-disaggregation-deployment)
|
||||
@@ -72,7 +73,7 @@ data_parallel_size = 4
|
||||
type = "single_node"
|
||||
```
|
||||
|
||||
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required `orchestrator.max_inflight_requests`. Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
|
||||
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required concurrency (see [Adaptive Concurrency](#adaptive-concurrency)). Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
|
||||
|
||||
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.vllm.enable_expert_parallel` or `inference.vllm.tensor_parallel_size` to maximize the available GPU memory.
|
||||
|
||||
@@ -203,6 +204,18 @@ X-Session-ID = "trajectory_id" # this is the default - each rollout has a unique
|
||||
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
|
||||
|
||||
|
||||
## Adaptive Concurrency
|
||||
|
||||
The orchestrator continuously sizes how many episodes run against the inference engines at once. A static cap cannot be right: too low starves the engines, too high crosses into KV thrash — the engines evict prefix cache, re-prefill the evicted work, and throughput collapses. The optimal value depends on the model, the deployment, and the workload's episode lengths, and it moves as training changes the policy.
|
||||
|
||||
The controller's idea is to treat the engines as ground truth and probe, instead of modeling episode cost: while the engines show headroom, admit a little more; when they show pressure, back off. Three behaviors, in increasing severity:
|
||||
|
||||
- **Grow**: while the engines look healthy and the current cap is fully used, raise it multiplicatively. Growth is clocked by the pipeline itself — the cap rises by a fixed factor each time the in-flight pool has turned over once — so a fast single-turn workload ramps in seconds while a slow agentic workload ramps at its own pace, with no tuning per workload.
|
||||
- **Trim**: episodes grow their context *while running*, so a pool that fit comfortably an hour ago can outgrow memory without a single new admission. When KV usage nears the ceiling, the controller shrinks the cap *and* the pool, cancelling the youngest episodes (least work lost) until the engines are comfortable again.
|
||||
- **Cut**: when the engines are demonstrably overloaded — requests being preempted, or piling up in the waiting queue — cut the pool hard, cancel the excess, and hold further cuts until the system settles.
|
||||
|
||||
The cap starts from a safe bound derived from the engines (KV capacity divided by the maximum context length), or from `initial_inflight` when a good value is known, and always stays within `[min_inflight, max_inflight]`.
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### KV Cache Offload
|
||||
|
||||
+2
-2
@@ -87,7 +87,7 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
|
||||
| `trainer.model.reshard_after_forward` | If `true` (default), parameters are resharded after the forward pass to free memory; the backward pass re-gathers. Set `false` to keep params resident — faster but more memory. |
|
||||
| `trainer.model.fsdp_cpu_offload` | Offload params + grads + optimizer state to CPU. Big memory win, large throughput hit. |
|
||||
| `trainer.model.optim_cpu_offload` | Offload optimizer state to CPU between steps. Enabled by default. |
|
||||
| `trainer.model.full_offload` | Offload gradients, FP32 masters, and optimizer state and run AdamW on CPU during backward. Disabled by default. |
|
||||
| `trainer.model.full_offload` | Offload gradients, FP32 masters, and optimizer state and run the optimizer (AdamW or SignSGD) on CPU during backward. Disabled by default. |
|
||||
|
||||
### Expert Parallelism
|
||||
|
||||
@@ -138,7 +138,7 @@ targets = ["norm", "attn_proj"] # see Reference for the full list per architect
|
||||
|
||||
### Optimizer Offloading
|
||||
|
||||
State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`. For full offload, set `model.optim_cpu_offload = false` and `model.full_offload = true`; this keeps BF16 compute weights on GPU and runs CPU AdamW chunks as gradients become ready during backward. Full offload only supports AdamW and disables gradient clipping.
|
||||
State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`. For full offload, set `model.optim_cpu_offload = false` and `model.full_offload = true`; this keeps BF16 compute weights on GPU and runs CPU optimizer chunks as gradients become ready during backward. Full offload only supports AdamW and SignSGD (`optim.type = "sign_sgd"`) and disables gradient clipping. SignSGD is stateless, so it halves the host RAM footprint versus AdamW (8 instead of 16 bytes per parameter: FP32 master + FP32 accumulated gradient, no moments).
|
||||
|
||||
### LM Head Chunking
|
||||
|
||||
|
||||
+54
-3
@@ -176,6 +176,55 @@ uv run sft @ examples/basic/reverse-text/sft.toml --monitors.wandb
|
||||
|
||||
Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manages this for you — see [Scaling § SFT and Torchrun](scaling.md#sft-and-torchrun) for non-default layouts; multi-node SFT goes through [SLURM](scaling.md#slurm)).
|
||||
|
||||
### Online Evals
|
||||
|
||||
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `num_examples` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
|
||||
|
||||
```toml
|
||||
[eval]
|
||||
interval = 25
|
||||
num_examples = 32
|
||||
|
||||
[[eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1 # trainer
|
||||
num_infer_gpus = 1 # inference
|
||||
```
|
||||
|
||||
The launcher starts the inference server, one env server per eval source, and an `evaluator` process next to the trainer. The handoff is the filesystem, not NCCL: the trainer writes an HF weight checkpoint at every step an eval env is due (in addition to `ckpt.interval`), and the evaluator watches `weights/step_{n}`, points the inference server at each stable checkpoint (`/update_weights` reload from disk), and runs the due envs against it — sequentially per checkpoint, so every epoch measures exactly one policy version. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final checkpoint always fires every env.
|
||||
|
||||
#### Multi-Node (Decoupled Trainer and Inference Pool)
|
||||
|
||||
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two independent SLURM jobs**. `deployment.num_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evaluator:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2 # trainer job
|
||||
num_infer_nodes = 1 # eval job (inference pool + evaluator)
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
|
||||
[slurm]
|
||||
job_name = "my-run"
|
||||
```
|
||||
|
||||
The only coupling is weight checkpoints on the shared filesystem, so the jobs' lifetimes are independent: when training finishes, the trainer job exits and releases its nodes even while evals are still running; the eval job keeps draining pending checkpoints and exits after evaluating the final one (`max_steps` — without it the eval job never sees a final checkpoint and holds its allocation until walltime). Trainer and evaluator log to a single shared W&B run across both jobs — the trainer creates it, the evaluator finalizes it. Any train × inference layout works: `num_nodes` and `num_infer_nodes` are fully independent.
|
||||
|
||||
### SFT-Specific Knobs
|
||||
|
||||
| Knob | What it controls |
|
||||
@@ -185,6 +234,7 @@ Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manag
|
||||
| `data.seq_len` | Per-sample sequence length |
|
||||
| `loss_mask.*` | Which roles contribute to loss (system / user / assistant / tool). |
|
||||
| `val.interval` | Run validation every N steps; `val.data` mirrors `data` |
|
||||
| `eval.interval` | Run online evals every N steps; see [Online Evals](#online-evals) |
|
||||
|
||||
### Important Metrics
|
||||
|
||||
@@ -192,8 +242,9 @@ Pulled from the console log and mirrored to W&B.
|
||||
|
||||
**Progress and loss:**
|
||||
|
||||
- `loss/mean` — main signal. Should decrease through the run.
|
||||
- `val/loss` — validation loss when `[val]` is set, logged every `val.interval` steps.
|
||||
- `loss/mean`, `loss/perplexity` — main signal. Should decrease through the run.
|
||||
- `val/loss`, `val/perplexity` — validation metrics when `[val]` is set, logged every `val.interval` steps.
|
||||
- `eval/{env}/...` — online eval metrics when `[eval]` is set, logged at each evaluated checkpoint step.
|
||||
- `progress/epoch`, `progress/num_samples`, `progress/num_tokens` — dataset progress.
|
||||
- `progress/<subset>/ratio_{samples,tokens}` — when training on multiple HF subsets/splits, the realized mixing ratio.
|
||||
|
||||
@@ -317,7 +368,7 @@ uv run rl @ rl.toml --no-monitors.file # disable the local me
|
||||
|
||||
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `monitors.wandb.offline = true`.
|
||||
|
||||
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, W&B mode **auto-creates an `overview` saved view** on the first run into a project — curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
|
||||
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, every training run (RL and SFT) gets an **auto-created `overview` saved view** curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
|
||||
|
||||
### Platform Monitoring
|
||||
|
||||
|
||||
@@ -71,7 +71,10 @@ type = "muon"
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_episodes = 512
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 256
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
|
||||
@@ -7,10 +7,14 @@
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
#
|
||||
# 2 train + 4 infer nodes. Trainer uses cp=4 (ulysses) plus
|
||||
# 1 train + 3 infer nodes. Inference serves FP8 via online per-tensor quantization of the bf16
|
||||
# checkpoint; weight broadcasts re-quantize through the same path on every update. The trainer fits on one
|
||||
# node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
|
||||
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), optimizer
|
||||
# CPU offload, and skip-gather / skip-optimizer checkpointing.
|
||||
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
|
||||
# skip-gather / skip-optimizer checkpointing.
|
||||
# Concurrency is fully default: the controller derives its start from the measured KV budget and
|
||||
# adapts from there.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
@@ -28,9 +32,9 @@ pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y ||
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
num_infer_replicas = 3
|
||||
|
||||
[monitors.wandb]
|
||||
project = "swe-ablations"
|
||||
@@ -46,20 +50,22 @@ keep_last = 1
|
||||
|
||||
[resume]
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
@@ -74,7 +80,7 @@ skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
type = "sign_sgd"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
@@ -82,7 +88,6 @@ type = "muon"
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_episodes = 512
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
@@ -137,6 +142,7 @@ rollout = 3600
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
@@ -145,4 +151,5 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
quantization = "fp8"
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -72,7 +72,10 @@ type = "muon"
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_episodes = 512
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 256
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
|
||||
@@ -113,9 +113,12 @@ weight_decay = 0.0
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_inflight_episodes = 2048
|
||||
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 256
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.model]
|
||||
name = "zai-org/GLM-5.1-FP8"
|
||||
|
||||
|
||||
@@ -65,9 +65,12 @@ weight_decay = 0.1
|
||||
[orchestrator]
|
||||
batch_size = 4096
|
||||
group_size = 16
|
||||
oversampling_factor = 3
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 4096
|
||||
max_inflight = 8192
|
||||
|
||||
[orchestrator.model]
|
||||
name = "zai-org/GLM-5-FP8"
|
||||
|
||||
@@ -86,11 +89,6 @@ id = "bash"
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["glm5-pd-disag", "swe-bench-verified"]
|
||||
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "gibberish"
|
||||
enforce = true
|
||||
|
||||
[inference]
|
||||
# we need <0.85 bc glm5 layers are too large for 0.85
|
||||
use_deep_gemm = true
|
||||
|
||||
|
||||
@@ -45,11 +45,15 @@ weight_decay = 0.01
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 2048
|
||||
oversampling_factor = 2
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 4096
|
||||
max_inflight = 4096
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
ratio = 0.3
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "r2e-gym"
|
||||
@@ -63,6 +67,7 @@ labels = ["intellect-3.1", "swe"]
|
||||
[[orchestrator.train.source]]
|
||||
name = "deepdive"
|
||||
ratio = 0.2
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "deepdive"
|
||||
@@ -78,6 +83,7 @@ labels = ["intellect-3.1", "deepdive"]
|
||||
[[orchestrator.train.source]]
|
||||
name = "math"
|
||||
ratio = 0.3
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_math"
|
||||
@@ -91,6 +97,7 @@ type = "subprocess"
|
||||
[[orchestrator.train.source]]
|
||||
name = "logic"
|
||||
ratio = 0.2
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_logic"
|
||||
@@ -107,6 +114,7 @@ type = "subprocess"
|
||||
[[orchestrator.train.source]]
|
||||
name = "code"
|
||||
ratio = 0.2
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_code"
|
||||
@@ -117,10 +125,6 @@ id = "null"
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.pre_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
enforce = true
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
|
||||
@@ -45,9 +45,12 @@ weight_decay = 0.01
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 2048
|
||||
oversampling_factor = 2
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 4096
|
||||
max_inflight = 4096
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
|
||||
|
||||
@@ -66,7 +66,10 @@ type = "adamw"
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_episodes = 1536
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 1536
|
||||
max_inflight = 1536
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
@@ -42,9 +42,11 @@ lr = 1e-6
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
oversampling_factor = 2
|
||||
max_off_policy_steps = 8
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 1024
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 32768
|
||||
|
||||
|
||||
@@ -43,9 +43,11 @@ lr = 1e-6
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
oversampling_factor = 2
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 1024
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
|
||||
|
||||
@@ -8,7 +8,32 @@ name = "PrimeIntellect/Qwen3-0.6B"
|
||||
[data]
|
||||
name = "willcb/R1-reverse-wikipedia-paragraphs-v1-1000"
|
||||
seq_len = 4096
|
||||
batch_size = 32
|
||||
batch_size = 32
|
||||
|
||||
[optim]
|
||||
lr = 2e-5
|
||||
lr = 2e-5
|
||||
|
||||
[eval]
|
||||
interval = 25
|
||||
num_examples = 32
|
||||
|
||||
[eval.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
@@ -32,7 +32,9 @@ target_modules = [
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
oversampling_factor = 2.0
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 1024
|
||||
|
||||
[orchestrator.model.lora]
|
||||
name = "qwen3-4b-wiki-search"
|
||||
@@ -42,6 +44,7 @@ max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wiki-search"
|
||||
@@ -52,10 +55,6 @@ id = "null"
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.pre_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
enforce = true
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference.vllm]
|
||||
|
||||
@@ -8,7 +8,7 @@ optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2"
|
||||
ep = 8 # keep in sync with deployment.num_gpus
|
||||
ep = 8 # keep in sync with deployment.num_train_gpus
|
||||
|
||||
[renderer]
|
||||
name = "auto"
|
||||
@@ -52,4 +52,4 @@ save_adapter_separately = true
|
||||
|
||||
[deployment]
|
||||
type = "single_node"
|
||||
num_gpus = 8
|
||||
num_train_gpus = 8
|
||||
|
||||
@@ -6,7 +6,7 @@ readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"pydantic>=1.10.13",
|
||||
"prime-pydantic-config>=0.4.2",
|
||||
"prime-pydantic-config>=0.4.3",
|
||||
"renderers>=0.1.9",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
|
||||
@@ -234,8 +234,7 @@ class MaxRLAlgoConfig(BaseAlgoConfig):
|
||||
objective: low-pass-rate examples get ~1/p weight, and ``group_size`` is
|
||||
the truncation order interpolating REINFORCE (1) → exact maximum
|
||||
likelihood (∞). Designed for non-negative (canonically binary) rewards;
|
||||
a group with mean reward 0 carries zero advantages everywhere (the
|
||||
zero-advantage filter drops it, matching the paper's K=0 convention)."""
|
||||
a group with mean reward 0 carries zero advantages everywhere."""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
@@ -300,8 +299,8 @@ class OPDAlgoConfig(BaseAlgoConfig):
|
||||
a reference model, evaluated in the trainer from reference prefill
|
||||
logprobs scored over each sample's own context (``ref_logprobs`` on the
|
||||
wire, ``ref_kl`` loss component). No scalar advantage is assigned —
|
||||
rollouts keep ``advantages=None`` (advantage-based filters never fire) and
|
||||
samples ship no advantage stream. ``group_size`` only fans out sampling."""
|
||||
rollouts keep ``advantages=None`` and samples ship no advantage stream.
|
||||
``group_size`` only fans out sampling."""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "ref_kl"
|
||||
|
||||
@@ -322,8 +321,7 @@ class OPSDAlgoConfig(BaseAlgoConfig):
|
||||
prepended as a leading system message. The sample is scored verbatim (no
|
||||
re-rendering), so it's robust to tool/multimodal prompts and works for any
|
||||
number of turns. No scalar advantage is assigned — rollouts keep
|
||||
``advantages=None`` (advantage-based filters never fire) and samples ship no
|
||||
advantage stream."""
|
||||
``advantages=None`` and samples ship no advantage stream."""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "ref_kl"
|
||||
|
||||
@@ -347,8 +345,8 @@ class SFTAlgoConfig(BaseAlgoConfig):
|
||||
type: Literal["sft"] = "sft"
|
||||
"""SFT distillation: cross-entropy on the sampled tokens. The ``ce`` loss
|
||||
ignores advantages and SFT assigns none — it trains on every sampled token.
|
||||
Reward-based filtering, if wanted, is an explicit filter, not smuggled
|
||||
through an unused advantage stream."""
|
||||
A curriculum can reject results using reward or any other finalized
|
||||
rollout data."""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "ce"
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.orchestrator import EvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, LogConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class OnlineEvalConfig(EvalConfig):
|
||||
"""Online evals against a live inference server, driven by weight checkpoints
|
||||
on disk. Extends the orchestrator ``EvalConfig`` (sources, sampling, intervals)
|
||||
with the client of the inference deployment and evaluator-side knobs."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
"""Client of the inference server evals run against. Auto-wired from the
|
||||
``[inference]`` block when the launcher manages the server."""
|
||||
|
||||
env_server_base_port: int = Field(5000, ge=1, le=65535)
|
||||
"""First port of the env-server port range: the eval source at position ``i`` is
|
||||
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
|
||||
keep it instead, without shifting the other sources' ports."""
|
||||
|
||||
max_inflight_episodes: int = Field(128, ge=1)
|
||||
"""Maximum eval episodes in flight — one episode is one agent run against an env server."""
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str]:
|
||||
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
|
||||
Same contract as ``OrchestratorConfig.env_addresses``: the launcher binds env
|
||||
servers at exactly these addresses and the evaluator connects to them."""
|
||||
return {
|
||||
("eval", source.resolved_name): source.serve.address
|
||||
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
|
||||
for index, source in enumerate(self.source)
|
||||
}
|
||||
|
||||
|
||||
class EvaluatorConfig(BaseConfig):
|
||||
"""``uv run evaluator``: watch a weights directory for new HF checkpoints, point
|
||||
the inference server at each one (``/update_weights`` from disk), and run the
|
||||
configured evals against the updated weights. The ``sft`` launcher writes this
|
||||
config; it can also be run standalone against any trainer that writes
|
||||
``weights/step_{n}`` HF checkpoints with ``STABLE`` markers."""
|
||||
|
||||
model: str = "Qwen/Qwen3-0.6B"
|
||||
"""Name the inference server serves the model under — the ``model`` field of every
|
||||
eval request and the startup model check. Auto-filled from ``model.name`` by the
|
||||
``sft`` launcher; the name stays fixed across checkpoint reloads (weights are
|
||||
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
|
||||
|
||||
eval: OnlineEvalConfig
|
||||
"""Eval sources, sampling, intervals, and the inference client."""
|
||||
|
||||
weights_dir: Path | None = None
|
||||
"""Directory to watch for ``step_{n}`` HF weight checkpoints. The ``sft`` launcher
|
||||
fills it from ``ckpt.output_dir`` when checkpoints are redirected to another volume;
|
||||
defaults to ``<output_dir>/weights``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — rollout traces and logs are written as
|
||||
subdirectories. Shared with the trainer."""
|
||||
|
||||
max_steps: int | None = None
|
||||
"""Trainer step at which the run ends. The final checkpoint always fires every
|
||||
eval env, and the evaluator exits after processing it. If None, the evaluator
|
||||
runs until terminated."""
|
||||
|
||||
resume_step: int | None = None
|
||||
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
|
||||
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
|
||||
this step."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_weights_dir(self):
|
||||
if self.weights_dir is None:
|
||||
self.weights_dir = self.output_dir / "weights"
|
||||
return self
|
||||
@@ -157,6 +157,77 @@ class EnvConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
|
||||
class StandardSamplerConfig(BaseConfig):
|
||||
type: Literal["standard"] = "standard"
|
||||
|
||||
|
||||
class DifficultyPoolConfig(BaseConfig):
|
||||
threshold: float
|
||||
"""Inclusive maximum reward assigned to this pool."""
|
||||
|
||||
weight: float = Field(ge=0)
|
||||
"""Relative per-task sampling weight."""
|
||||
|
||||
|
||||
def default_difficulty_pools() -> dict[str, DifficultyPoolConfig]:
|
||||
return {
|
||||
"hard": DifficultyPoolConfig(threshold=0.25, weight=0.2),
|
||||
"normal": DifficultyPoolConfig(threshold=0.75, weight=1.0),
|
||||
"easy": DifficultyPoolConfig(threshold=1.0, weight=0.2),
|
||||
}
|
||||
|
||||
|
||||
class DifficultyPoolSamplerConfig(BaseConfig):
|
||||
type: Literal["difficulty_pool"] = "difficulty_pool"
|
||||
|
||||
pools: dict[str, DifficultyPoolConfig] = Field(default_factory=default_difficulty_pools)
|
||||
"""Named pools ordered by their reward thresholds."""
|
||||
|
||||
seed: int = 42
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_pools(self):
|
||||
if not self.pools:
|
||||
raise ValueError("DifficultyPoolSampler requires at least one pool")
|
||||
thresholds = [pool.threshold for pool in self.pools.values()]
|
||||
if len(set(thresholds)) != len(thresholds):
|
||||
raise ValueError("Difficulty pool thresholds must be unique")
|
||||
if not any(pool.weight > 0 for pool in self.pools.values()):
|
||||
raise ValueError("At least one difficulty pool must have a positive weight")
|
||||
return self
|
||||
|
||||
|
||||
TaskSamplerConfig: TypeAlias = Annotated[
|
||||
StandardSamplerConfig | DifficultyPoolSamplerConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class AdvRangeGateConfig(BaseConfig):
|
||||
type: Literal["advantage_range"] = "advantage_range"
|
||||
|
||||
reject_min: float = 0.0
|
||||
reject_max: float = 0.0
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_range(self):
|
||||
if self.reject_min > self.reject_max:
|
||||
raise ValueError("reject_min must be less than or equal to reject_max")
|
||||
return self
|
||||
|
||||
|
||||
AdmissionGateConfig: TypeAlias = AdvRangeGateConfig
|
||||
|
||||
|
||||
class CurriculumConfig(BaseConfig):
|
||||
sampler: TaskSamplerConfig = Field(default_factory=StandardSamplerConfig)
|
||||
"""Task selection policy. The default cycles through the task iterator in source order."""
|
||||
|
||||
gates: dict[str, AdmissionGateConfig] = Field(default_factory=dict)
|
||||
"""Named admission policies. Every gate observes every finalized group,
|
||||
and a group trains only when every gate admits it."""
|
||||
|
||||
|
||||
class TrainSourceConfig(EnvConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
|
||||
@@ -170,6 +241,10 @@ class TrainSourceConfig(EnvConfig):
|
||||
``orchestrator.algo`` when unset; set ``type`` (and its params) to give
|
||||
this env its own algorithm."""
|
||||
|
||||
curriculum: CurriculumConfig | None = None
|
||||
"""User-authored task sampler and admission gates. The default cycles
|
||||
through the taskset and admits every finalized group."""
|
||||
|
||||
|
||||
class EvalSourceConfig(EnvConfig):
|
||||
sampling: EvalSamplingConfig = EvalSamplingConfig()
|
||||
@@ -192,6 +267,9 @@ class TrainConfig(BaseConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Shared training sampling configuration."""
|
||||
|
||||
filter_zero_advantages: bool = True
|
||||
"""Remove zero-advantage RL tokens after collecting a batch, before shipping it."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
|
||||
@@ -298,50 +376,6 @@ class CheckpointConfig(BaseConfig):
|
||||
"""Skip loading the progress from checkpoint."""
|
||||
|
||||
|
||||
# Flags rare tokens generated at high entropy (Section 5.2, https://arxiv.org/abs/2510.02387).
|
||||
class GibberishFilterConfig(BaseConfig):
|
||||
type: Literal["gibberish"] = "gibberish"
|
||||
|
||||
enforce: bool = False
|
||||
"""When True, skip detected rollouts entirely so they are not sent to the trainer. When False, only track detection metrics."""
|
||||
|
||||
token_id_threshold: int = 100_000
|
||||
"""Token IDs above this are candidates for gibberish. BPE tokens are sorted by merge order."""
|
||||
|
||||
logprob_offset: float = 2.0
|
||||
"""Offset from uniform-distribution logprob. Threshold = ``-log(vocab_size) - logprob_offset``."""
|
||||
|
||||
|
||||
# Flags rollouts stuck in a repetition loop: emits high-confidence tokens for an extended stretch.
|
||||
# Flagged when `window` consecutive tokens are each sampled with probability above `prob_threshold`.
|
||||
# (Section 3.2, https://arxiv.org/abs/2506.13585)
|
||||
class RepetitionFilterConfig(BaseConfig):
|
||||
type: Literal["repetition"] = "repetition"
|
||||
|
||||
enforce: bool = False
|
||||
"""When True, skip detected rollouts entirely so they are not sent to the trainer. When False, only track detection metrics."""
|
||||
|
||||
window: int = Field(3_000, ge=1)
|
||||
"""Consecutive high-probability steps required to flag the rollout."""
|
||||
|
||||
prob_threshold: float = Field(0.99, gt=0, le=1)
|
||||
"""Tokens sampled with probability above this are considered repetitive. Consecutive such tokens count toward the window."""
|
||||
|
||||
|
||||
# Flags rollouts with zero advantage.
|
||||
class ZeroAdvantageFilterConfig(BaseConfig):
|
||||
type: Literal["zero_advantage"] = "zero_advantage"
|
||||
|
||||
enforce: bool = True
|
||||
"""When True, skip detected rollouts entirely so they are not sent to the trainer. When False, only track detection metrics."""
|
||||
|
||||
|
||||
FilterConfig: TypeAlias = Annotated[
|
||||
GibberishFilterConfig | RepetitionFilterConfig | ZeroAdvantageFilterConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class FileSystemWeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
@@ -386,6 +420,30 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class ConcurrencyConfig(BaseConfig):
|
||||
"""Adaptive in-flight concurrency control. The orchestrator sizes the
|
||||
in-flight episode cap from engine KV capacity and learned per-env episode
|
||||
costs; these fields only bound and seed it."""
|
||||
|
||||
initial_inflight: int | None = Field(None, ge=1)
|
||||
"""Optional initial in-flight episodes to start from. Set it when a good value is known to skip the initial ramp; otherwise auto-derive a pessimistic bound at runtime."""
|
||||
|
||||
min_inflight: int = Field(1, ge=1)
|
||||
"""Minimum number of in-flight episodes. Set ``min_inflight = max_inflight`` to recover fixed concurrency."""
|
||||
|
||||
max_inflight: int | None = Field(1024, ge=1)
|
||||
"""Maximum number of in-flight episodes. Set it to avoid runaway concurrency, especially to limit other external resources (e.g. sandboxes). None removes the ceiling."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_bounds(self):
|
||||
if self.max_inflight is not None:
|
||||
if self.initial_inflight is not None and self.initial_inflight > self.max_inflight:
|
||||
raise ValueError("concurrency.initial_inflight must not exceed concurrency.max_inflight")
|
||||
if self.min_inflight > self.max_inflight:
|
||||
raise ValueError("concurrency.min_inflight must not exceed concurrency.max_inflight")
|
||||
return self
|
||||
|
||||
|
||||
class OrchestratorConfig(BaseConfig):
|
||||
algo: AlgoConfig = GRPOAlgoConfig()
|
||||
"""Training algorithm: sampling plus the per-token training signal (credit
|
||||
@@ -412,24 +470,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
eval: EvalConfig | None = None
|
||||
"""Evaluation configuration."""
|
||||
|
||||
pre_batch_filters: list[FilterConfig] = [
|
||||
GibberishFilterConfig(enforce=False),
|
||||
RepetitionFilterConfig(enforce=False),
|
||||
ZeroAdvantageFilterConfig(enforce=False),
|
||||
]
|
||||
"""Filters applied *before* a rollout enters the training batch buffer.
|
||||
All three filter types are registered in monitor mode by default; flip ``enforce=true`` per type
|
||||
to drop matching rollouts before they consume a slot in the batch (e.g. a zero-advantage group
|
||||
never makes it into a training batch)."""
|
||||
|
||||
post_batch_filters: list[FilterConfig] = [
|
||||
GibberishFilterConfig(),
|
||||
RepetitionFilterConfig(),
|
||||
ZeroAdvantageFilterConfig(),
|
||||
]
|
||||
"""Filters applied *after* a batch has been assembled. Each filter annotates each rollout;
|
||||
rollouts flagged by an enforcing filter are still recorded but not shipped to the trainer."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
env_vars: EnvVars = {}
|
||||
@@ -439,7 +479,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
|
||||
|
||||
collect_inference_metrics: bool = True
|
||||
"""Collect inference-server metrics (requires wandb)."""
|
||||
"""Mirror inference-server metrics to W&B (requires wandb). The ``/metrics`` poll itself always runs — it feeds the concurrency controller."""
|
||||
|
||||
inference_metrics_roles: list[Literal["prefill", "decode"]] | None = None
|
||||
"""Role for each policy admin client when collecting P/D inference metrics."""
|
||||
@@ -471,11 +511,8 @@ class OrchestratorConfig(BaseConfig):
|
||||
token_batch_size: int | None = Field(None, ge=1)
|
||||
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
|
||||
|
||||
oversampling_factor: float | None = Field(None, gt=0)
|
||||
"""Rollout-mode batching only. Multiplier used to derive ``max_inflight_episodes`` from ``batch_size`` when ``max_inflight_episodes`` is unset. Values below 1.0 intentionally cap in-flight episode capacity below ``batch_size``."""
|
||||
|
||||
max_inflight_episodes: int | None = Field(None, ge=1)
|
||||
"""Maximum number of episodes kept in-flight — one episode is one agent run at a time, whatever the env's agents are. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig()
|
||||
"""Adaptive in-flight concurrency control (``[orchestrator.concurrency]``)."""
|
||||
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Output sequences returned per example during training."""
|
||||
@@ -522,16 +559,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
self.monitors.prime.name = self.monitors.wandb.name
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_filter_types(self):
|
||||
for slot_name in ("pre_batch_filters", "post_batch_filters"):
|
||||
types = [f.type for f in getattr(self, slot_name)]
|
||||
if len(types) != len(set(types)):
|
||||
raise ValueError(
|
||||
f"Duplicate filter types in {slot_name}: {types}. Each filter type may only appear once per slot."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def inherit_env_algorithms(self):
|
||||
"""Envs without their own algorithm inherit the top-level one.
|
||||
@@ -599,29 +626,13 @@ class OrchestratorConfig(BaseConfig):
|
||||
if not has_rollout_batch and not has_token_batch:
|
||||
self.batch_size = 128
|
||||
|
||||
if has_token_batch:
|
||||
if self.oversampling_factor is not None:
|
||||
raise ValueError("oversampling_factor can only be set when batch_size is set")
|
||||
if self.max_inflight_episodes is None:
|
||||
raise ValueError("max_inflight_episodes must be set when token_batch_size is set")
|
||||
else:
|
||||
assert self.batch_size is not None
|
||||
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_episodes = max(
|
||||
self.group_size,
|
||||
int(self.batch_size * oversampling_factor),
|
||||
)
|
||||
if self.max_inflight_episodes is not None and self.oversampling_factor is not None:
|
||||
expected_max_inflight_episodes = resolved_max_inflight_episodes
|
||||
if self.max_inflight_episodes != expected_max_inflight_episodes:
|
||||
raise ValueError("max_inflight_episodes conflicts with oversampling_factor * batch_size")
|
||||
if self.max_inflight_episodes is None:
|
||||
self.max_inflight_episodes = resolved_max_inflight_episodes
|
||||
if self.batch_size is not None and self.batch_size % self.group_size != 0:
|
||||
raise ValueError("Batch size must be divisible by the number of samples per problem")
|
||||
|
||||
if self.max_inflight_episodes is not None and self.max_inflight_episodes < self.group_size:
|
||||
raise ValueError("max_inflight_episodes must be at least the number of rollouts per example")
|
||||
for field in ("max_inflight", "initial_inflight"):
|
||||
value = getattr(self.concurrency, field)
|
||||
if value is not None and value < self.group_size:
|
||||
raise ValueError(f"concurrency.{field} must be at least the number of rollouts per example")
|
||||
|
||||
# Propagate the top-level ``group_size`` into each train env that didn't set its own.
|
||||
for env_cfg in self.train.source:
|
||||
|
||||
@@ -2,11 +2,14 @@ import uuid
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic import AliasChoices, Field, model_validator
|
||||
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
from prime_rl.configs.evaluator import OnlineEvalConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
@@ -142,24 +145,33 @@ class BaseDeploymentConfig(BaseConfig):
|
||||
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
type: Literal["single_node"] = "single_node"
|
||||
|
||||
num_gpus: int = 1
|
||||
"""GPUs to use."""
|
||||
num_train_gpus: int = 1
|
||||
"""GPUs allocated to the trainer."""
|
||||
|
||||
num_infer_gpus: int = Field(1, validation_alias=AliasChoices("num_infer_gpus", "num_eval_gpus"))
|
||||
"""GPUs allocated to inference for online evals (alias: ``num_eval_gpus``). Only used when an ``[inference]`` block is configured."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_gpu_count(self):
|
||||
if self.num_gpus > self.gpus_per_node:
|
||||
raise ValueError(f"num_gpus ({self.num_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).")
|
||||
if self.num_train_gpus > self.gpus_per_node:
|
||||
raise ValueError(f"num_train_gpus ({self.num_train_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).")
|
||||
return self
|
||||
|
||||
|
||||
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
type: Literal["multi_node"] = "multi_node"
|
||||
|
||||
num_nodes: int = 2
|
||||
num_train_nodes: int = Field(2, ge=1)
|
||||
"""Training nodes."""
|
||||
|
||||
num_infer_nodes: int = Field(0, ge=0, validation_alias=AliasChoices("num_infer_nodes", "num_eval_nodes"))
|
||||
"""Inference nodes for online evals (alias: ``num_eval_nodes``). Submitted as a separate SLURM job, decoupled
|
||||
from the trainer job: the handoff is weight checkpoints on the shared filesystem,
|
||||
so the eval job can outlive the trainer job (evals drain after training ends) and
|
||||
exits after evaluating the final checkpoint."""
|
||||
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_nodes / nodes_per_fsdp_group``."""
|
||||
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
|
||||
|
||||
SFTDeploymentConfig: TypeAlias = Annotated[
|
||||
@@ -183,6 +195,15 @@ class SFTConfig(BaseConfig):
|
||||
val: SFTValConfig | None = None
|
||||
"""Validation configuration. If None, no validation runs."""
|
||||
|
||||
eval: OnlineEvalConfig | None = None
|
||||
"""Online evaluation configuration: rollout-based evals against a live inference
|
||||
server that reloads the trainer's HF weight checkpoints from disk. If None, no
|
||||
online evals run."""
|
||||
|
||||
inference: InferenceConfig | None = None
|
||||
"""Inference server for online evals. If None (with ``eval`` set), the launcher
|
||||
does not start a server and evals connect to ``eval.client.base_url``."""
|
||||
|
||||
optim: OptimizerConfig = AdamWConfig()
|
||||
|
||||
scheduler: SchedulerConfig = ConstantSchedulerConfig()
|
||||
@@ -264,10 +285,26 @@ class SFTConfig(BaseConfig):
|
||||
return data
|
||||
deployment = data.get("deployment")
|
||||
if isinstance(deployment, dict) and deployment.get("type") == "multi_node":
|
||||
for key in ("num_gpus",):
|
||||
for key in ("num_train_gpus", "num_infer_gpus"):
|
||||
deployment.pop(key, None)
|
||||
return data
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def propagate_model_to_inference(cls, data):
|
||||
"""Fill ``inference.vllm.model`` from ``model.name`` before InferenceConfig
|
||||
construction, so its parser auto-resolution sees the right model name."""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
inference = data.get("inference")
|
||||
model = data.get("model")
|
||||
name = model.get("name") if isinstance(model, dict) else None
|
||||
if isinstance(inference, dict) and name:
|
||||
vllm = inference.setdefault("vllm", {})
|
||||
if isinstance(vllm, dict):
|
||||
vllm.setdefault("model", name)
|
||||
return data
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -282,9 +319,9 @@ class SFTConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def full_optimizer_offload_requires_adamw(self):
|
||||
if self.model.full_offload and self.optim.type != "adamw":
|
||||
raise ValueError("Full optimizer offload only supports AdamW")
|
||||
def full_optimizer_offload_requires_supported_optimizer(self):
|
||||
if self.model.full_offload and self.optim.type not in ("adamw", "sign_sgd"):
|
||||
raise ValueError("Full optimizer offload only supports AdamW and SignSGD")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -304,6 +341,129 @@ class SFTConfig(BaseConfig):
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_online_eval(self):
|
||||
"""Wire online evals: require weight checkpoints (the disk handoff to
|
||||
inference) and connect the eval client to the launcher-managed server."""
|
||||
if self.eval is None:
|
||||
if self.inference is not None:
|
||||
raise ValueError("[inference] is only used for online evals — add an [eval] block or remove it.")
|
||||
return self
|
||||
|
||||
# The trainer's HF weight checkpoints are how inference picks up new policies.
|
||||
if self.ckpt is None:
|
||||
self.ckpt = CheckpointConfig()
|
||||
if self.ckpt.weights is None or self.ckpt.skip_gather_master_weights:
|
||||
raise ValueError(
|
||||
"Online evals require HF weight checkpoints. Enable ckpt.weights and "
|
||||
"disable ckpt.skip_gather_master_weights."
|
||||
)
|
||||
|
||||
if self.ckpt.keep_last is not None or self.ckpt.keep_interval is not None:
|
||||
warnings.warn(
|
||||
"ckpt.keep_last / ckpt.keep_interval can delete a weight checkpoint before the "
|
||||
"evaluator consumes it when evals run slower than training - such steps are "
|
||||
"skipped with a warning instead of evaluated.",
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
if self.deployment.type == "multi_node":
|
||||
# Decoupled deployment: the launcher submits a dedicated SLURM job running the
|
||||
# inference pool (one engine per DP rank behind a router) plus the evaluator.
|
||||
if self.inference is None:
|
||||
raise ValueError(
|
||||
"Multi-node online evals require an [inference] block - the launcher submits "
|
||||
"a dedicated SLURM job running the inference pool and the evaluator."
|
||||
)
|
||||
if self.deployment.num_infer_nodes < 1:
|
||||
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
|
||||
if self.inference.router is None:
|
||||
raise ValueError(
|
||||
"Multi-node online evals require an inference router - the eval job starts one "
|
||||
"router in front of the per-rank engines. Remove inference.router = 'None'."
|
||||
)
|
||||
if self.inference.vllm.model != self.model.name:
|
||||
raise ValueError(
|
||||
f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name "
|
||||
f"({self.model.name}). Remove inference.vllm.model to inherit it."
|
||||
)
|
||||
if self.deployment.gpus_per_node % self.inference.vllm.tensor_parallel_size != 0:
|
||||
raise ValueError(
|
||||
f"deployment.gpus_per_node ({self.deployment.gpus_per_node}) must be divisible by "
|
||||
f"inference.vllm.tensor_parallel_size ({self.inference.vllm.tensor_parallel_size})."
|
||||
)
|
||||
if self.inference.weight_broadcast.type != "filesystem":
|
||||
raise ValueError(
|
||||
"Online evals reload weights from disk — inference.weight_broadcast.type must be 'filesystem'."
|
||||
)
|
||||
if self.max_steps is None:
|
||||
warnings.warn(
|
||||
"Online evals without max_steps: the evaluator never sees a final checkpoint, "
|
||||
"so the eval SLURM job holds its allocation until its walltime.",
|
||||
stacklevel=2,
|
||||
)
|
||||
# The client is wired at runtime by the eval sbatch script (the router and
|
||||
# per-rank admin URLs are only known once SLURM assigns hosts).
|
||||
return self
|
||||
|
||||
if self.inference is None:
|
||||
warnings.warn(
|
||||
"Online evals are configured without an [inference] block - the launcher will not "
|
||||
f"start an inference server. Make sure one is running at eval.client.base_url "
|
||||
f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', "
|
||||
"otherwise the evaluator will hang waiting for it. If a router fronts the "
|
||||
"deployment, set eval.client.admin_base_url to the engine URLs - admin ops "
|
||||
"(pause/update_weights/resume) must bypass the router.",
|
||||
stacklevel=2,
|
||||
)
|
||||
return self
|
||||
|
||||
total_gpus = self.deployment.num_train_gpus + self.deployment.num_infer_gpus
|
||||
if total_gpus > self.deployment.gpus_per_node:
|
||||
raise ValueError(
|
||||
f"Total GPU count ({total_gpus} = {self.deployment.num_train_gpus} train + "
|
||||
f"{self.deployment.num_infer_gpus} infer) exceeds gpus_per_node "
|
||||
f"({self.deployment.gpus_per_node})."
|
||||
)
|
||||
|
||||
if self.inference.vllm.model != self.model.name:
|
||||
raise ValueError(
|
||||
f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name "
|
||||
f"({self.model.name}). Remove inference.vllm.model to inherit it."
|
||||
)
|
||||
|
||||
# Fill inference capacity with DP ranks (mirrors RLConfig.auto_setup_deployment).
|
||||
num_infer_gpus = self.deployment.num_infer_gpus
|
||||
vllm = self.inference.vllm
|
||||
if num_infer_gpus != vllm.data_parallel_size * vllm.tensor_parallel_size:
|
||||
if num_infer_gpus % vllm.tensor_parallel_size != 0:
|
||||
raise ValueError(
|
||||
f"deployment.num_infer_gpus ({num_infer_gpus}) must be divisible by "
|
||||
f"inference.vllm.tensor_parallel_size ({vllm.tensor_parallel_size})."
|
||||
)
|
||||
vllm.data_parallel_size = num_infer_gpus // vllm.tensor_parallel_size
|
||||
if vllm.api_server_count < vllm.data_parallel_size and not vllm.enable_lora:
|
||||
vllm.api_server_count = vllm.data_parallel_size
|
||||
if self.inference.weight_broadcast.type != "filesystem":
|
||||
raise ValueError(
|
||||
"Online evals reload weights from disk — inference.weight_broadcast.type must be 'filesystem'."
|
||||
)
|
||||
|
||||
host = self.inference.server.host or "localhost"
|
||||
client = self.eval.client
|
||||
if "base_url" not in client.model_fields_set:
|
||||
client.base_url = f"http://{host}:{self.inference.server.port}/v1"
|
||||
elif urlparse(client.base_url).port != self.inference.server.port:
|
||||
raise ValueError(
|
||||
f"eval.client.base_url port ({urlparse(client.base_url).port}) does not match "
|
||||
f"inference.server.port ({self.inference.server.port})."
|
||||
)
|
||||
if self.inference.router is not None and "admin_base_url" not in client.model_fields_set:
|
||||
# Admin ops (pause/update_weights/resume) must bypass the router and hit
|
||||
# the engine directly.
|
||||
client.admin_base_url = [f"http://{host}:{self.inference.backend_port}/v1"]
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_typed_renderer(self):
|
||||
"""Require a typed renderer whenever SFT renders real samples."""
|
||||
@@ -416,12 +576,12 @@ class SFTConfig(BaseConfig):
|
||||
def auto_setup_deployment(self):
|
||||
if self.deployment.type == "multi_node":
|
||||
if self.deployment.nodes_per_fsdp_group is not None:
|
||||
if self.deployment.num_nodes % self.deployment.nodes_per_fsdp_group != 0:
|
||||
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
|
||||
raise ValueError(
|
||||
f"deployment.num_nodes ({self.deployment.num_nodes}) must be divisible by "
|
||||
f"deployment.num_train_nodes ({self.deployment.num_train_nodes}) must be divisible by "
|
||||
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
|
||||
)
|
||||
self.model.dp_replicate = self.deployment.num_nodes // self.deployment.nodes_per_fsdp_group
|
||||
self.model.dp_replicate = self.deployment.num_train_nodes // self.deployment.nodes_per_fsdp_group
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -11,7 +11,16 @@ from prime_rl.utils.config import BaseConfig
|
||||
# and the single shared W&B run. The launcher always sets these last, so allowing them in
|
||||
# `env_vars` would be a silent no-op (or, on multi-node, a footgun) — reject them instead.
|
||||
PROTECTED_ENV_VARS = frozenset(
|
||||
{"CUDA_VISIBLE_DEVICES", "PRL_RUN_ID", "PRL_RUN_NAME", "WANDB_RUN_ID", "WANDB_SHARED_MODE", "WANDB_SHARED_LABEL"}
|
||||
{
|
||||
"CUDA_VISIBLE_DEVICES",
|
||||
"PRL_RUN_ID",
|
||||
"PRL_RUN_NAME",
|
||||
"WANDB_RUN_ID",
|
||||
"WANDB_SHARED_MODE",
|
||||
"WANDB_SHARED_LABEL",
|
||||
"WANDB_SHARED_PRIMARY",
|
||||
"WANDB_SHARED_FINISHER",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -55,19 +55,20 @@ class ActivationOffloadingConfig(BaseConfig):
|
||||
|
||||
|
||||
class OptimizerInBackwardOffloadConfig(BaseConfig):
|
||||
"""Full CPU optimizer offload: FP32 masters, moments, and accumulated gradients live in
|
||||
CPU RAM, each optimizer chunk runs on CPU as soon as its last gradient arrives, and the
|
||||
refreshed BF16 weights stream back while backward is still executing.
|
||||
"""Full CPU optimizer offload: FP32 masters, optimizer state (AdamW moments; SignSGD is
|
||||
stateless), and accumulated gradients live in CPU RAM, each optimizer chunk runs on CPU as
|
||||
soon as its last gradient arrives, and the refreshed BF16 weights stream back while backward
|
||||
is still executing.
|
||||
|
||||
Gradient numerics: gradients are reduced across ranks in FP32 (``reduce_dtype``) but FSDP2
|
||||
materializes them in the sharded parameter's dtype, which is BF16 for the offload compute
|
||||
model — so each gradient is rounded to BF16 once before the FP32 CPU update. Masters,
|
||||
moments, accumulation, and Adam arithmetic remain FP32. For gradient numerics bit-faithful
|
||||
to that path, disable offloading.
|
||||
moments, accumulation, and optimizer arithmetic remain FP32. For gradient numerics
|
||||
bit-faithful to that path, disable offloading.
|
||||
"""
|
||||
|
||||
cpu_optimizer_backend: Literal["native", "torch"] = "native"
|
||||
"""CPU AdamW implementation used by full offload. ``native`` is the production kernel; ``torch`` is a slower debugging and parity fallback."""
|
||||
"""CPU optimizer implementation used by full offload (AdamW or SignSGD). ``native`` is the production kernel; ``torch`` is a slower debugging and parity fallback."""
|
||||
|
||||
numa_bind: bool = True
|
||||
"""Pin each rank's CPUs to its GPU's NUMA node. Disable when the launcher already manages CPU affinity or GPU sysfs topology is unavailable."""
|
||||
@@ -673,9 +674,9 @@ class TrainerConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def full_optimizer_offload_requires_adamw(self):
|
||||
if self.model.full_offload and self.optim.type != "adamw":
|
||||
raise ValueError("Full optimizer offload only supports AdamW")
|
||||
def full_optimizer_offload_requires_supported_optimizer(self):
|
||||
if self.model.full_offload and self.optim.type not in ("adamw", "sign_sgd"):
|
||||
raise ValueError("Full optimizer offload only supports AdamW and SignSGD")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
+3
-2
@@ -6,7 +6,7 @@ readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"prime-rl-configs",
|
||||
"prime-pydantic-config",
|
||||
"prime-pydantic-config>=0.4.3",
|
||||
"beartype>=0.21.0",
|
||||
"datasets>=4.0.0",
|
||||
"jaxtyping>=0.3.2",
|
||||
@@ -33,7 +33,7 @@ dependencies = [
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers[harbor]>=0.3.1.dev14",
|
||||
"verifiers[harbor]>=0.3.1.dev33",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
@@ -53,6 +53,7 @@ sft = "prime_rl.entrypoints.sft:main"
|
||||
inference = "prime_rl.entrypoints.inference:main"
|
||||
trainer = "prime_rl.entrypoints.trainer:main"
|
||||
orchestrator = "prime_rl.entrypoints.orchestrator:main"
|
||||
evaluator = "prime_rl.entrypoints.evaluator:main"
|
||||
env-server = "prime_rl.entrypoints.env_server:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
|
||||
# Colors for output
|
||||
GREEN='\033[0;32m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
log_info() {
|
||||
echo -e "${GREEN}[INFO]${NC} $1"
|
||||
}
|
||||
|
||||
# Confirm destructive action
|
||||
confirm_cleanup() {
|
||||
echo "This will remove the following paths recursively:"
|
||||
echo " - **/logs"
|
||||
echo " - **/checkpoints"
|
||||
echo " - **/weights"
|
||||
echo " - **/rollouts"
|
||||
echo " - **/wandb"
|
||||
echo " - **/evals"
|
||||
echo " - .pydantic_config"
|
||||
while true; do
|
||||
read -r -p "Proceed? [y/N]: " response
|
||||
case "$response" in
|
||||
[yY]|[yY][eE][sS]) break ;;
|
||||
[nN]|[nN][oO]|"") echo "Aborted."; exit 1 ;;
|
||||
*) echo "Please answer y or n." ;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
# Remove logs, checkpoints, weights, rollouts, wandb
|
||||
confirm_cleanup
|
||||
rm -rf **/logs **/checkpoints **/weights **/rollouts **/wandb **/evals **/torchrun *.pydantic_config
|
||||
log_info "Cleaned up!"
|
||||
@@ -71,6 +71,8 @@ type = "subprocess"
|
||||
|
||||
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text` or `--orchestrator.eval.source.0.env.taskset.id reverse-text`.
|
||||
|
||||
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server), e.g. `--eval.source.0.env.taskset.id reverse-text`.
|
||||
|
||||
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
|
||||
|
||||
**vLLM pass-through** — `[inference.vllm]` uses vLLM's own argument names (`model`, `tensor_parallel_size`, `data_parallel_size`, `max_model_len`, ...) and forwards *any* key to the vLLM server, typed by prime-rl or not: `[inference.vllm] max_num_seqs = 256`, or `--inference.vllm.max-num-seqs 256` on the CLI. CLI values are JSON-coerced, so dict-valued vLLM args work as `--inference.vllm.compilation-config '{"cudagraph_mode": "NONE"}'`. Non-vLLM knobs (router, deployment, weight broadcast, kv-cache offload, env vars) stay on `[inference]` itself.
|
||||
|
||||
@@ -66,6 +66,7 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
{run_dir}/logs/latest/
|
||||
├── trainer.log # rank 0 stdout
|
||||
├── orchestrator.log # orchestrator stdout
|
||||
├── evaluator.log # SFT online-eval evaluator stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evaluator.log)
|
||||
├── inference.log # vLLM stdout
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node (multi-node only)
|
||||
@@ -81,7 +82,7 @@ Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough
|
||||
Scan for problems:
|
||||
|
||||
```bash
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,inference}.log
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evaluator,inference}.log
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
|
||||
```
|
||||
|
||||
@@ -92,9 +93,9 @@ All metrics print to the console log (and W&B when configured).
|
||||
**Progress** — orchestrator log. Rollout metrics mirror the episode/trace hierarchy, at two levels:
|
||||
|
||||
- `{scope}/{subset}/<metric>/<stat>` — episode-level facts only: the token/turn/branch counts, summed over an episode's traces.
|
||||
- `{scope}/{subset}/<agent>/<metric>/<stat>` — every trace-level metric (reward, truncation, errors, timing, env metrics, filter verdicts, eval scores), keyed by agent name so seats never mix. Flat over that agent's traces: one sample is one trace, so an in-episode fan-out like n solvers contributes n samples.
|
||||
- `{scope}/{subset}/<agent>/<metric>/<stat>` — every trace-level metric (reward, truncation, errors, timing, env metrics, curriculum admission, eval scores), keyed by agent name so seats never mix. Flat over that agent's traces: one sample is one trace, so an in-episode fan-out like n solvers contributes n samples.
|
||||
|
||||
`scope` is `train/agg` (all train envs) or `train/<env>` (`eval/<env>` for eval); `subset` is `all` (every rollout) or `effective` (post-filter). Single-agent envs have one agent — usually `agent` — and one trace per episode, so both levels agree; multi-agent envs name each seat (`proposer`, `solver`, `judge`, …).
|
||||
`scope` is `train/agg` (all train envs) or `train/<env>` (`eval/<env>` for eval); `subset` is `all` (every rollout) or `effective` (admitted, clean, and trainable). Single-agent envs have one agent — usually `agent` — and one trace per episode, so both levels agree; multi-agent envs name each seat (`proposer`, `solver`, `judge`, …).
|
||||
|
||||
| Metric | Description |
|
||||
|--------|-------------|
|
||||
@@ -104,7 +105,8 @@ All metrics print to the console log (and W&B when configured).
|
||||
| `train/<env>/effective/<agent>/num_turns/mean` | avg turns for that agent alone (also token counts, `num_branches`) |
|
||||
| `train/agg/effective/<agent>/is_truncated/mean` | fraction of that agent's rollouts truncated |
|
||||
| `train/agg/all/<agent>/has_error/mean` | fraction of that agent's rollouts errored (per-type under `train/agg/all/<agent>/error/<type>`; also `dispatcher/errored/{train,eval}`) |
|
||||
| `train/agg/all/<agent>/is_trainable/mean` | fraction carrying a training signal — 0.0 for a frozen seat like a judge (also `is_filtered`, `filters/<name>`) |
|
||||
| `train/agg/all/<agent>/is_trainable/mean` | fraction carrying a training signal — 0.0 for a frozen seat like a judge |
|
||||
| `train/agg/all/<agent>/is_admitted/mean` | fraction accepted by the source curriculum; per-source counters and custom policy metrics live under `curriculum/<env>/` |
|
||||
| `train/<env>/effective/<agent>/metrics/<name>/mean` | env-specific metrics for that agent (e.g. pass rate) |
|
||||
| `train/<env>/effective/<agent>/timing/agent/model/mean` | model vs harness share of that agent's phase |
|
||||
| `eval/<env>/effective/<agent>/{avg@k,pass@k}` | eval scores for that agent, when configured |
|
||||
@@ -128,7 +130,7 @@ All metrics print to the console log (and W&B when configured).
|
||||
| trainer | `perf/throughput`, `perf/mfu` | tokens/s and MFU % |
|
||||
| orchestrator | `time/step`, `time/save_ckpt` | phase timings |
|
||||
| orchestrator | `time/wait_for_policy` | **high → trainer is bottleneck** |
|
||||
| orchestrator | `dispatcher/off_policy_level_{mean,max}`, `dispatcher/inflight_{train,eval}`, `dispatcher/groups_in_flight`, `dispatcher/queued/eval` | dispatcher / async state |
|
||||
| orchestrator | `dispatcher/off_policy_level/{mean,max}`, `dispatcher/inflight/{train,eval}`, `dispatcher/queued/eval` | dispatcher / async state |
|
||||
| env server | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
|
||||
|
||||
For live vLLM stats, query Prometheus directly:
|
||||
@@ -147,7 +149,7 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
|
||||
|
||||
JSONL files of `vf.Trace` records (training tensors excluded), one line per trace — a
|
||||
multi-agent env's episode contributes several lines sharing one `info.episode_id`. `all`
|
||||
gets every completed rollout the moment it arrives — errored, filtered, and never-batched
|
||||
gets every completed rollout the moment it arrives — errored, curriculum-rejected, and never-batched
|
||||
ones included — so it's crash-durable; `effective` gets the clean trainable subset that went
|
||||
into the step's train batch (eval: the non-errored trainable epoch cohort; multiple eval envs
|
||||
share the step file) — untrainable traces (a frozen judge's) appear only in `all`. Each record carries `run` (`{type, id, step}`; for eval, `step` is the trigger step),
|
||||
|
||||
@@ -27,7 +27,8 @@ All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/t
|
||||
- State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`.
|
||||
- For gradients, FP32 masters, optimizer state, and optimizer-in-backward CPU execution, set
|
||||
`model.optim_cpu_offload = false` and `model.full_offload = true`. This mode uses the native
|
||||
CPU AdamW kernel, only supports AdamW, and disables gradient clipping. Use a
|
||||
CPU optimizer kernel, only supports AdamW and SignSGD (SignSGD is stateless and
|
||||
halves the host RAM footprint), and disables gradient clipping. Use a
|
||||
`[model.full_offload]` table only to select the Torch debugging backend or disable NUMA binding.
|
||||
|
||||
## `rl` — RL training
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Lightweight launcher for the online evaluator.
|
||||
|
||||
Defers heavy ML imports until after ``cli()`` parses CLI args, so
|
||||
``evaluator --help`` short-circuits in ``cli()``. The actual implementation
|
||||
lives in ``prime_rl.orchestrator.evaluator``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
from prime_rl.configs.evaluator import EvaluatorConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("Evaluator")
|
||||
config = cli(EvaluatorConfig)
|
||||
from prime_rl.orchestrator.evaluator import run_evaluator
|
||||
|
||||
asyncio.run(run_evaluator(config))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -10,8 +10,6 @@ from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import pynvml
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
from prime_rl.configs.inference import VllmRouterConfig
|
||||
from prime_rl.configs.orchestrator import EnvConfig
|
||||
@@ -35,6 +33,7 @@ from prime_rl.utils.process import (
|
||||
DEFAULT_TRAINER_ENV_VARS,
|
||||
cleanup_processes,
|
||||
cleanup_threads,
|
||||
get_physical_gpu_ids,
|
||||
monitor_process,
|
||||
set_proc_title,
|
||||
)
|
||||
@@ -68,15 +67,6 @@ def env_server_names(config: RLConfig, split: str) -> list[str]:
|
||||
return [source.resolved_name for source_split, source, _ in env_servers(config) if source_split == split]
|
||||
|
||||
|
||||
def get_physical_gpu_ids() -> list[int]:
|
||||
"""Return physical GPU IDs visible to the launcher."""
|
||||
raw_visible = os.environ.get("CUDA_VISIBLE_DEVICES")
|
||||
if raw_visible is None:
|
||||
pynvml.nvmlInit()
|
||||
return list(range(pynvml.nvmlDeviceGetCount()))
|
||||
return [int(token.strip()) for token in raw_visible.split(",") if token.strip()]
|
||||
|
||||
|
||||
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
|
||||
"""Write resolved config to disk, excluding launcher-only fields."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
+406
-51
@@ -1,5 +1,7 @@
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
@@ -7,27 +9,90 @@ from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
from prime_rl.configs.evaluator import EvaluatorConfig
|
||||
from prime_rl.configs.orchestrator import EvalSourceConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.utils.config import cli, dump_resolved_config, find_package_resource
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_log_dir,
|
||||
format_log_message,
|
||||
get_all_ckpt_steps,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_log_dir,
|
||||
get_step_path,
|
||||
get_weights_dir,
|
||||
latest_log_dir,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
DEFAULT_TRAINER_ENV_VARS,
|
||||
cleanup_processes,
|
||||
cleanup_threads,
|
||||
get_physical_gpu_ids,
|
||||
monitor_process,
|
||||
set_proc_title,
|
||||
)
|
||||
|
||||
SFT_CONFIG = "sft.json"
|
||||
SFT_SBATCH = "sft.sbatch"
|
||||
EVAL_SBATCH = "eval.sbatch"
|
||||
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
|
||||
|
||||
INFERENCE_CONFIG = "inference.json"
|
||||
EVALUATOR_CONFIG = "evaluator.json"
|
||||
|
||||
ENVS_DIR = "envs"
|
||||
|
||||
|
||||
def eval_env_servers(config: SFTConfig) -> list[tuple[EvalSourceConfig, str]]:
|
||||
"""``(source, address)`` for every launcher-managed eval source. A source with
|
||||
``serve.address`` set is externally managed — the launcher neither writes its
|
||||
config nor spawns a server for it."""
|
||||
if config.eval is None:
|
||||
return []
|
||||
addresses = config.eval.env_addresses
|
||||
return [
|
||||
(source, addresses[("eval", source.resolved_name)])
|
||||
for source in config.eval.source
|
||||
if source.serve.address is None
|
||||
]
|
||||
|
||||
|
||||
def get_ckpt_base(config: SFTConfig) -> Path:
|
||||
"""Where checkpoints and weights live: ``ckpt.output_dir`` when set, else the run dir."""
|
||||
return (config.ckpt.output_dir if config.ckpt else None) or config.run_dir
|
||||
|
||||
|
||||
def resolve_resume_step(config: SFTConfig) -> int | None:
|
||||
if config.resume is None:
|
||||
return None
|
||||
if config.resume.dir is not None:
|
||||
return config.resume.dir_step
|
||||
if config.resume.step is not None:
|
||||
return config.resume.step
|
||||
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
|
||||
|
||||
|
||||
def build_evaluator_config(config: SFTConfig) -> EvaluatorConfig:
|
||||
"""Derive the evaluator subconfig from the resolved SFT config."""
|
||||
assert config.eval is not None
|
||||
return EvaluatorConfig(
|
||||
model=config.model.name,
|
||||
eval=config.eval,
|
||||
weights_dir=get_weights_dir(get_ckpt_base(config)),
|
||||
output_dir=config.run_dir,
|
||||
max_steps=config.max_steps,
|
||||
resume_step=resolve_resume_step(config),
|
||||
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
|
||||
monitors=config.monitors,
|
||||
)
|
||||
|
||||
|
||||
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
|
||||
@@ -37,7 +102,39 @@ def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None
|
||||
json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2)
|
||||
|
||||
|
||||
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path) -> None:
|
||||
def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: bool = False) -> None:
|
||||
"""Write the inference, evaluator, and env-server configs for online evals."""
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if config.inference is not None:
|
||||
# Exclude launcher-only fields that are not needed by the vLLM server
|
||||
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
|
||||
inference_dict = dump_resolved_config(config.inference, exclude=exclude_inference)
|
||||
if strip_router:
|
||||
# Per-rank processes run bare engines; the sbatch starts the single global router.
|
||||
inference_dict["router"] = None
|
||||
with open(config_dir / INFERENCE_CONFIG, "w") as f:
|
||||
json.dump(inference_dict, f, indent=2)
|
||||
|
||||
with open(config_dir / EVALUATOR_CONFIG, "w") as f:
|
||||
json.dump(dump_resolved_config(build_evaluator_config(config)), f, indent=2)
|
||||
|
||||
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>`
|
||||
# binds at the source's deterministic address, where the evaluator connects.
|
||||
for source, address in eval_env_servers(config):
|
||||
env_dir = config_dir / ENVS_DIR / "eval"
|
||||
env_dir.mkdir(parents=True, exist_ok=True)
|
||||
source_dict = dump_resolved_config(source)
|
||||
env_server_dict = {
|
||||
"env": source_dict["env"],
|
||||
"serve": {**(source_dict.get("serve") or {}), "address": address},
|
||||
"log": {"level": config.log.vf_level, "json_logging": config.log.json_logging},
|
||||
}
|
||||
with open(env_dir / f"{source.resolved_name}.json", "w") as f:
|
||||
json.dump(env_server_dict, f, indent=2)
|
||||
|
||||
|
||||
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path, prl_run_id: str | None = None) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
@@ -66,21 +163,79 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path)
|
||||
config_path=config_path,
|
||||
output_dir=config.run_dir,
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
num_nodes=config.deployment.num_nodes,
|
||||
num_nodes=config.deployment.num_train_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
ranks_filter=",".join(map(str, config.log.ranks_filter)),
|
||||
prl_run_id=prl_run_id,
|
||||
run_name=config.run.name,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Path, prl_run_id: str | None) -> None:
|
||||
"""Write the SLURM script for the decoupled online-eval job (inference pool +
|
||||
env servers + evaluator) to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
assert config.slurm is not None
|
||||
assert config.slurm.template_path is not None
|
||||
assert config.deployment.type == "multi_node"
|
||||
assert config.inference is not None
|
||||
|
||||
# The eval template is bundled next to the trainer templates; a custom
|
||||
# slurm.template_path directory takes precedence so both can be overridden.
|
||||
template_dirs = [config.slurm.template_path.parent]
|
||||
bundled_templates = find_package_resource("templates")
|
||||
if bundled_templates is not None:
|
||||
template_dirs.append(bundled_templates)
|
||||
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
|
||||
template = env.get_template(EVAL_TEMPLATE)
|
||||
|
||||
inference_env_vars = {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
}
|
||||
evaluator_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
|
||||
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_dir=config_dir,
|
||||
output_dir=config.run_dir,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router=config.inference.router,
|
||||
router_port=config.inference.server.port,
|
||||
backend_port=config.inference.backend_port,
|
||||
data_parallel_rpc_port=config.inference.vllm.data_parallel_rpc_port,
|
||||
dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
|
||||
enable_expert_parallel=config.inference.vllm.enable_expert_parallel,
|
||||
inference_env_vars=inference_env_vars,
|
||||
evaluator_env_vars=evaluator_env_vars,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
prl_run_id=prl_run_id,
|
||||
run_name=config.run.name,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
def sft_slurm(config: SFTConfig):
|
||||
"""Run SFT training via SLURM."""
|
||||
"""Run SFT training via SLURM. With online evals on a multi-node deployment, the
|
||||
trainer and the eval deployment (inference pool + evaluator) are two independent
|
||||
SLURM jobs: the handoff is weight checkpoints on the shared filesystem, so the
|
||||
trainer job releases its allocation when training finishes while the eval job
|
||||
keeps draining evals and exits after the final checkpoint."""
|
||||
assert config.slurm is not None
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
decoupled_eval = config.deployment.type == "multi_node" and config.eval is not None
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
exclude = (
|
||||
@@ -88,28 +243,84 @@ def sft_slurm(config: SFTConfig):
|
||||
if config.deployment.type == "multi_node"
|
||||
else {"slurm", "dry_run", "clean"}
|
||||
)
|
||||
if decoupled_eval:
|
||||
# The trainer job only needs [eval] for the weight-checkpoint cadence; the
|
||||
# inference pool lives in the eval job.
|
||||
exclude = exclude | {"inference"}
|
||||
write_config(config, config_path, exclude=exclude)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
# Trainer and evaluator processes log to a single shared W&B run across both jobs,
|
||||
# keyed by the launcher's run id.
|
||||
prl_run_id: str | None = None
|
||||
if decoupled_eval and config.monitors.wandb is not None:
|
||||
prl_run_id = os.environ["PRL_RUN_ID"]
|
||||
|
||||
script_path = config.run_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, script_path)
|
||||
write_slurm_script(config, config_path, script_path, prl_run_id)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
log_dir = latest_log_dir(config.run_dir)
|
||||
num_nodes = config.deployment.num_nodes if config.deployment.type == "multi_node" else 1
|
||||
log_message = format_log_message(log_dir=log_dir, trainer=True, num_train_nodes=num_nodes)
|
||||
# The trainer job is submitted first and the eval job depends on it having started:
|
||||
# the trainer creates the shared W&B run, and the evaluator's joiner init only
|
||||
# retries for a bounded window — starting the evaluator while the trainer job pends
|
||||
# would crash it at wandb init.
|
||||
script_paths = [script_path]
|
||||
if decoupled_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(f"Wrote eval subconfigs to {config_dir}")
|
||||
eval_script_path = config.run_dir / EVAL_SBATCH
|
||||
write_eval_slurm_script(config, config_dir, eval_script_path, prl_run_id)
|
||||
logger.info(f"Wrote eval SLURM script to {eval_script_path}")
|
||||
script_paths = [script_path, eval_script_path]
|
||||
|
||||
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
|
||||
log_message = format_log_message(
|
||||
log_dir=latest_log_dir(config.run_dir),
|
||||
trainer=True,
|
||||
num_train_nodes=num_nodes,
|
||||
)
|
||||
if decoupled_eval:
|
||||
# The eval job logs at stable (non-attempt) paths under the run dir.
|
||||
log_message += "\n" + format_log_message(
|
||||
log_dir=get_log_dir(config.run_dir),
|
||||
evaluator=True,
|
||||
inference=True,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
).removeprefix("Logs:\n")
|
||||
|
||||
if config.dry_run:
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
submit = "\n".join(f" sbatch {path}" for path in script_paths)
|
||||
note = (
|
||||
"\n\nSubmit the trainer job first — the evaluator joins the W&B run the trainer creates."
|
||||
if decoupled_eval
|
||||
else ""
|
||||
)
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n{submit}{note}\n\n{log_message}")
|
||||
return
|
||||
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
sys.exit(1)
|
||||
submitted_job_ids: list[str] = []
|
||||
for path in script_paths:
|
||||
# --parsable prints ``<job_id>[;<cluster>]`` — the human-readable format varies
|
||||
# (e.g. multi-cluster sbatch appends "on cluster <name>").
|
||||
cmd = ["sbatch", "--parsable"]
|
||||
if submitted_job_ids:
|
||||
# Hold the eval job until the trainer job has started (not finished).
|
||||
cmd.append(f"--dependency=after:{submitted_job_ids[-1]}")
|
||||
cmd.append(str(path))
|
||||
logger.info(f"Submitting: {' '.join(cmd)}")
|
||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
for job_id in submitted_job_ids:
|
||||
logger.warning(f"Cancelling already-submitted job {job_id}")
|
||||
subprocess.run(["scancel", job_id], capture_output=True, text=True)
|
||||
sys.exit(1)
|
||||
job_id = result.stdout.strip().split(";")[0]
|
||||
submitted_job_ids.append(job_id)
|
||||
logger.success(f"Submitted batch job {job_id}")
|
||||
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
logger.success(log_message)
|
||||
|
||||
|
||||
def sft_local(config: SFTConfig):
|
||||
@@ -123,60 +334,151 @@ def sft_local(config: SFTConfig):
|
||||
write_config(config, config_path)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
if config.eval is not None:
|
||||
write_eval_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote eval subconfigs to {config_dir}")
|
||||
|
||||
if config.dry_run:
|
||||
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
log_dir = create_attempt_log_dir(config.run_dir)
|
||||
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
|
||||
# launcher must partition GPUs between processes; plain SFT leaves them to torchrun.
|
||||
infer_gpu_ids: list[int] = []
|
||||
trainer_gpu_ids: list[int] = []
|
||||
if config.inference is not None:
|
||||
num_infer_gpus = config.deployment.num_infer_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(
|
||||
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
|
||||
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
|
||||
)
|
||||
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
|
||||
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
|
||||
|
||||
trainer_cmd = [
|
||||
"torchrun",
|
||||
"--role=trainer",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
|
||||
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
f"--nproc-per-node={config.deployment.num_gpus}",
|
||||
"-m",
|
||||
"prime_rl.trainer.sft.train",
|
||||
"@",
|
||||
(config_dir / SFT_CONFIG).as_posix(),
|
||||
]
|
||||
|
||||
logger.info(f"Starting SFT trainer with {config.deployment.num_gpus} GPU(s)")
|
||||
logger.debug(f"Trainer command: {' '.join(trainer_cmd)}")
|
||||
# Trainer and evaluator log to a single shared W&B run whose id ($WANDB_RUN_ID)
|
||||
# equals $PRL_RUN_ID, one label per process.
|
||||
wandb_shared_env: dict[str, str] = {}
|
||||
if config.eval is not None:
|
||||
# The trainer creates the run; the evaluator (which drains its final evals
|
||||
# after the trainer exits) finalizes it.
|
||||
wandb_shared_env = {
|
||||
"WANDB_SHARED_MODE": "1",
|
||||
"WANDB_RUN_ID": os.environ["PRL_RUN_ID"],
|
||||
"WANDB_SHARED_PRIMARY": "trainer",
|
||||
"WANDB_SHARED_FINISHER": "evaluator",
|
||||
"WANDB_PROGRAM": "uv run sft",
|
||||
"WANDB_ARGS": json.dumps(sys.argv),
|
||||
}
|
||||
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
error_queue: list[Exception] = []
|
||||
stop_events: dict[str, Event] = {}
|
||||
|
||||
def sigterm_handler(signum, frame):
|
||||
logger.warning("Received SIGTERM, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
signal.signal(signal.SIGTERM, sigterm_handler)
|
||||
|
||||
def start_process(name: str, cmd: list[str], env: dict[str, str], log_path: Path) -> Popen:
|
||||
logger.debug(f"{name.capitalize()} command: {' '.join(cmd)}")
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(log_path, "w") as log_file:
|
||||
process = Popen(cmd, env=env, stdout=log_file, stderr=log_file)
|
||||
processes.append(process)
|
||||
stop_event = Event()
|
||||
stop_events[name] = stop_event
|
||||
monitor_thread = Thread(target=monitor_process, args=(process, stop_event, error_queue, name), daemon=True)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
return process
|
||||
|
||||
try:
|
||||
with open(log_dir / "trainer.log", "w") as log_file:
|
||||
trainer_process = Popen(
|
||||
trainer_cmd,
|
||||
# Optionally, start the inference server for online evals
|
||||
if config.inference is not None:
|
||||
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
|
||||
start_process(
|
||||
"inference",
|
||||
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
log_path=log_dir / "inference.log",
|
||||
)
|
||||
processes.append(trainer_process)
|
||||
|
||||
stop_event = Event()
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(trainer_process, stop_event, error_queue, "trainer"),
|
||||
daemon=True,
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
# Start one env server per eval source. The evaluator connects to each source's
|
||||
# deterministic address, polling until the server is up.
|
||||
for source, address in eval_env_servers(config):
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting eval env server {name} at {address}")
|
||||
start_process(
|
||||
f"env/eval/{name}",
|
||||
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars},
|
||||
log_path=log_dir / ENVS_DIR / "eval" / f"{name}.log",
|
||||
)
|
||||
|
||||
if config.eval is not None:
|
||||
logger.info("Starting evaluator process")
|
||||
start_process(
|
||||
"evaluator",
|
||||
["evaluator", "@", (config_dir / EVALUATOR_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "evaluator",
|
||||
},
|
||||
log_path=log_dir / "evaluator.log",
|
||||
)
|
||||
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
trainer_cmd = [
|
||||
"torchrun",
|
||||
"--role=trainer",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
|
||||
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
f"--nproc-per-node={config.deployment.num_train_gpus}",
|
||||
"-m",
|
||||
"prime_rl.trainer.sft.train",
|
||||
"@",
|
||||
config_path.as_posix(),
|
||||
]
|
||||
gpus_suffix = f" on GPU(s) {' '.join(map(str, trainer_gpu_ids))}" if trainer_gpu_ids else ""
|
||||
logger.info(f"Starting SFT trainer with {config.deployment.num_train_gpus} GPU(s){gpus_suffix}")
|
||||
trainer_env = {
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**wandb_shared_env,
|
||||
}
|
||||
if config.eval is not None:
|
||||
trainer_env["LOGURU_FORCE_COLORS"] = "1"
|
||||
trainer_env["WANDB_SHARED_LABEL"] = "trainer"
|
||||
if trainer_gpu_ids:
|
||||
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
|
||||
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
|
||||
|
||||
logger.success("Startup complete. Showing trainer logs...")
|
||||
tail_process = Popen(
|
||||
@@ -185,7 +487,22 @@ def sft_local(config: SFTConfig):
|
||||
)
|
||||
processes.append(tail_process)
|
||||
|
||||
stop_event.wait()
|
||||
# Wait for the trainer (and the evaluator, which drains its final evals after
|
||||
# the trainer's last checkpoint) while surfacing any process failure.
|
||||
terminal_events = [stop_events["trainer"]]
|
||||
if "evaluator" in stop_events:
|
||||
terminal_events.append(stop_events["evaluator"])
|
||||
while True:
|
||||
pending = [event for event in terminal_events if not event.is_set()]
|
||||
if error_queue:
|
||||
logger.error(f"Error: {error_queue[0]}")
|
||||
logger.error("Terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
if not pending:
|
||||
break
|
||||
pending[0].wait(timeout=1)
|
||||
|
||||
if trainer_process.returncode != 0:
|
||||
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
|
||||
@@ -209,11 +526,49 @@ def sft_local(config: SFTConfig):
|
||||
raise
|
||||
|
||||
|
||||
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
|
||||
"""Remove eval artifacts a previous run left behind: weight checkpoints and rollout
|
||||
trace dirs — everything on a fresh start, steps past the resume step on resume.
|
||||
Without this the evaluator would replay stale checkpoints (and then skip the
|
||||
re-trained ones at the same steps), and the append-only trace files would mix two
|
||||
policies' rollouts under one step."""
|
||||
logger = setup_logger(config.log.level or "info")
|
||||
if os.environ.get("NEVER_CLEAN"):
|
||||
logger.warning("NEVER_CLEAN is set - keeping stale weight checkpoints; the evaluator may replay them")
|
||||
return
|
||||
resume_step = resolve_resume_step(config)
|
||||
weights_dir = get_weights_dir(get_ckpt_base(config))
|
||||
stale_steps = [step for step in get_all_ckpt_steps(weights_dir) if resume_step is None or step > resume_step]
|
||||
if stale_steps:
|
||||
logger.info(
|
||||
f"Deleting {len(stale_steps)} stale weight checkpoint(s) in {weights_dir} "
|
||||
f"({','.join(map(str, stale_steps))})"
|
||||
)
|
||||
for step in stale_steps:
|
||||
shutil.rmtree(get_step_path(weights_dir, step), ignore_errors=True)
|
||||
clean_future_steps(config.run_dir, resume_step if resume_step is not None else -1)
|
||||
|
||||
|
||||
def sft(config: SFTConfig):
|
||||
# The run identity is runtime-only, never sub-config: $PRL_RUN_ID / $PRL_RUN_NAME are
|
||||
# the vehicle for runtime info between processes, and every spawned process inherits
|
||||
# them. Components launched standalone have no run identity.
|
||||
os.environ.setdefault("PRL_RUN_ID", uuid.uuid4().hex)
|
||||
assert config.run.name is not None # resolved at construction
|
||||
os.environ["PRL_RUN_NAME"] = config.run.name
|
||||
|
||||
resuming = config.resume is not None
|
||||
clean = config.clean and not os.environ.get("NEVER_CLEAN")
|
||||
validate_run_dir(config.run_dir, output_dir=config.output_dir, resuming=resuming, clean=clean)
|
||||
ckpt_output_dir = config.ckpt.output_dir if config.ckpt else None
|
||||
validate_run_dir(
|
||||
config.run_dir, output_dir=config.output_dir, resuming=resuming, clean=clean, ckpt_output_dir=ckpt_output_dir
|
||||
)
|
||||
config.run_dir.mkdir(parents=True, exist_ok=True)
|
||||
if ckpt_output_dir is not None:
|
||||
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if config.eval is not None and not config.dry_run:
|
||||
clean_stale_eval_artifacts(config)
|
||||
|
||||
if not config.dry_run:
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
|
||||
@@ -19,12 +19,12 @@ from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import update_mla_absorbed_weights
|
||||
from prime_rl.trainer.rl.broadcast.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
|
||||
from prime_rl.trainer.rl.broadcast.nixl.cuda_malloc_memory import (
|
||||
from prime_rl.transports.weights.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
|
||||
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
|
||||
size_cuda_buffers,
|
||||
use_cuda_malloc_pool,
|
||||
)
|
||||
from prime_rl.trainer.rl.broadcast.nixl.graph import (
|
||||
from prime_rl.transports.weights.nixl.graph import (
|
||||
Destination,
|
||||
OperationChain,
|
||||
RecordedCopy,
|
||||
@@ -34,9 +34,9 @@ from prime_rl.trainer.rl.broadcast.nixl.graph import (
|
||||
make_hf_lazy_weights,
|
||||
plan_tensor_replay,
|
||||
)
|
||||
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.trainer.rl.broadcast.nixl.tensor_routing import route_sharded_tensor
|
||||
from prime_rl.trainer.rl.broadcast.nixl.trainer_tensor_table import TrainerTensorTable
|
||||
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.transports.weights.nixl.tensor_routing import route_sharded_tensor
|
||||
from prime_rl.transports.weights.nixl.trainer_tensor_table import TrainerTensorTable
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.worker.gpu_worker import Worker
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, overload
|
||||
from typing import TYPE_CHECKING, Any, Literal, overload
|
||||
|
||||
from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig, WandbMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
@@ -47,6 +47,7 @@ async def setup(
|
||||
run_config: BaseConfig | None = None,
|
||||
train_env_names: list[str] | None = None,
|
||||
eval_env_names: list[str] | None = None,
|
||||
overview_flavor: Literal["rl", "sft"] = "rl",
|
||||
) -> None:
|
||||
"""Construct, initialize, and register one monitor per non-None config.
|
||||
|
||||
@@ -71,6 +72,7 @@ async def setup(
|
||||
config=run_config,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
overview_flavor=overview_flavor,
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -6,7 +6,7 @@ import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import TYPE_CHECKING, Any, Literal
|
||||
|
||||
import wandb
|
||||
from wandb.errors import CommError
|
||||
@@ -32,6 +32,7 @@ class WandbMonitor(Monitor):
|
||||
config: BaseConfig | None = None,
|
||||
train_env_names: list[str] | None = None,
|
||||
eval_env_names: list[str] | None = None,
|
||||
overview_flavor: Literal["rl", "sft"] = "rl",
|
||||
) -> None:
|
||||
# W&B reads the start command off sys.argv; the launcher passes the original
|
||||
# command to subprocesses via $WANDB_ARGS.
|
||||
@@ -50,14 +51,19 @@ class WandbMonitor(Monitor):
|
||||
# W&B's native run-id var, set by the launcher to $PRL_RUN_ID.
|
||||
run_id = os.environ.get("WANDB_RUN_ID")
|
||||
label = os.environ.get("WANDB_SHARED_LABEL")
|
||||
primary = label == "orchestrator"
|
||||
primary_label = os.environ.get("WANDB_SHARED_PRIMARY", "orchestrator")
|
||||
primary = label == primary_label
|
||||
# The primary creates the run; the finisher writes its final state. They can
|
||||
# differ when the run's creator is not its last-alive writer (e.g. the SFT
|
||||
# trainer creates the run, the evaluator outlives it and finalizes).
|
||||
finisher = label == os.environ.get("WANDB_SHARED_FINISHER", primary_label)
|
||||
settings = wandb.Settings(
|
||||
mode="shared",
|
||||
x_label=label,
|
||||
x_primary=primary,
|
||||
x_update_finish_state=primary,
|
||||
x_update_finish_state=finisher,
|
||||
)
|
||||
self.logger.info(f"Using shared W&B mode ({label=}, {primary=})")
|
||||
self.logger.info(f"Using shared W&B mode ({label=}, {primary=}, {finisher=})")
|
||||
is_online = True
|
||||
else:
|
||||
run_id = None
|
||||
@@ -117,6 +123,7 @@ class WandbMonitor(Monitor):
|
||||
self.wandb.project,
|
||||
train_envs=train_env_names or [],
|
||||
eval_envs=eval_env_names or [],
|
||||
flavor=overview_flavor,
|
||||
)
|
||||
if url:
|
||||
self.logger.info(f"Created W&B overview view - {url}")
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Sequence
|
||||
from typing import Literal
|
||||
|
||||
import wandb
|
||||
import wandb_workspaces.reports.v2 as wr
|
||||
@@ -70,6 +71,19 @@ INFERENCE_PANELS = [
|
||||
["inference/agg/prefix_cache_hit_rate/pooled", "inference/agg/prefix_cache_hit_rate/min"],
|
||||
["inference/agg/generation_tokens_total:rate/sum", "inference/agg/generation_tokens_total:rate/min"],
|
||||
["inference/agg/prompt_tokens_total:rate/sum", "inference/agg/prompt_tokens_total:rate/max"],
|
||||
["dispatcher/inflight/train", "dispatcher/inflight/eval"],
|
||||
]
|
||||
|
||||
# SFT flavor: no rollout-based train sections — the training signal is the loss curve.
|
||||
SFT_TRAIN_METRICS = ["loss/mean", "loss/perplexity", "val/loss", "val/perplexity", "progress/epoch"]
|
||||
SFT_STABILITY_METRICS = ["optim/grad_norm", "optim/lr", "loss/nan_count"]
|
||||
SFT_PERFORMANCE_METRICS = [
|
||||
"perf/mfu",
|
||||
"perf/throughput",
|
||||
"perf/peak_memory",
|
||||
"time/step",
|
||||
"time/forward_backward",
|
||||
"time/save_ckpt",
|
||||
]
|
||||
|
||||
# Dense grid: more, smaller panels per row and enough rows that sections don't paginate.
|
||||
@@ -129,7 +143,20 @@ def eval_section(name: str, env_pattern: str) -> ws.Section:
|
||||
)
|
||||
|
||||
|
||||
def build_sections(train_envs: Sequence[str] = (), eval_envs: Sequence[str] = ()) -> list[ws.Section]:
|
||||
def build_sections(
|
||||
train_envs: Sequence[str] = (), eval_envs: Sequence[str] = (), flavor: Literal["rl", "sft"] = "rl"
|
||||
) -> list[ws.Section]:
|
||||
# SFT trains on a dataset, not rollouts: the train section is the loss/perplexity
|
||||
# curves, eval sections are the same rollout-based ones as RL.
|
||||
if flavor == "sft":
|
||||
sections = [section("train", metrics=SFT_TRAIN_METRICS)]
|
||||
if eval_envs:
|
||||
sections += [eval_section(f"eval/{env}", re.escape(env)) for env in eval_envs]
|
||||
else:
|
||||
sections.append(eval_section("eval", ".*"))
|
||||
sections.append(section("stability", metrics=SFT_STABILITY_METRICS))
|
||||
sections.append(section("performance", metrics=SFT_PERFORMANCE_METRICS))
|
||||
return sections
|
||||
# With one env the aggregate == that env, so show only its section. With several, put the
|
||||
# cross-env aggregate on top followed by a section per env.
|
||||
if len(train_envs) == 1:
|
||||
@@ -193,11 +220,12 @@ def ensure_overview_view(
|
||||
name: str = OVERVIEW_NAME,
|
||||
train_envs: Sequence[str] = (),
|
||||
eval_envs: Sequence[str] = (),
|
||||
flavor: Literal["rl", "sft"] = "rl",
|
||||
) -> str | None:
|
||||
"""Ensure an overview saved view exists for this run's env set. Reuses an existing overview built
|
||||
for the same envs; when the env set is new, creates a fresh versioned view (``overview`` →
|
||||
``overview-v2`` → …). Returns the URL of a newly created view, else None."""
|
||||
sections = build_sections(train_envs, eval_envs)
|
||||
sections = build_sections(train_envs, eval_envs, flavor)
|
||||
target = view_signature(sections)
|
||||
overviews = [(dn, iname) for dn, iname in list_views(entity, project) if dn == name or dn.startswith(f"{name}-v")]
|
||||
for _, internal_name in overviews:
|
||||
|
||||
@@ -19,8 +19,8 @@ I/O); a hook that only does advantage math never awaits:
|
||||
I/O against another model — an inference pool the algorithm connected in
|
||||
``setup()`` (a frozen teacher) or the live policy (opsd's self-distillation),
|
||||
queried with bounded concurrency. No siblings.
|
||||
- ``score_group(group)`` — the cohort, on group completion, *before* filtering
|
||||
(filters read the streams): group-relative credit (GRPO/MaxRL baselines).
|
||||
- ``score_group(group)`` — the cohort, on group completion: group-relative
|
||||
credit (GRPO/MaxRL baselines).
|
||||
|
||||
How rollouts are *produced* is not the algorithm's concern: that is the env's
|
||||
:class:`~prime_rl.orchestrator.sampler.Sampler`, and sample construction
|
||||
@@ -95,21 +95,18 @@ class Algorithm:
|
||||
directly — read the trace, write credit via
|
||||
:meth:`Rollout.assign_advantages`. They are
|
||||
async so either stage may do I/O — e.g. a process-reward model or a
|
||||
teacher at arrival, or a judge at group time whose signal a pre-batch
|
||||
filter then reads; a hook that only does advantage math simply never
|
||||
awaits.
|
||||
teacher at arrival, or a judge at group time; a hook that only does
|
||||
advantage math simply never awaits.
|
||||
|
||||
- :meth:`score_rollout` — one rollout, on arrival: rollout-local credit,
|
||||
observation ce weights, or per-token results from a model the algorithm
|
||||
connected in :meth:`setup` (e.g. teacher reference logprobs). Default:
|
||||
nothing.
|
||||
- :meth:`score_group` — the cohort, *before* filtering (filters read the
|
||||
streams): group-relative credit. Default: nothing — rollouts keep
|
||||
``advantages=None``, so advantage-based filters skip them.
|
||||
- :meth:`score_group` — the cohort: group-relative credit. Default:
|
||||
nothing — rollouts keep ``advantages=None``.
|
||||
|
||||
Model I/O lives in :meth:`score_rollout`: it runs at arrival, *before* the
|
||||
pre-batch filters, so it pays compute on rollouts that may then be filtered
|
||||
out — accepted for the simpler one-rollout-at-a-time shape.
|
||||
Model I/O lives in :meth:`score_rollout`: it runs at arrival, so it pays
|
||||
compute on rollouts that the curriculum may later reject.
|
||||
|
||||
Constructed with the algorithm config it interprets plus the live policy
|
||||
pool (``self.policy_pool`` — always available, never closed by the
|
||||
@@ -145,8 +142,7 @@ class Algorithm:
|
||||
group stats."""
|
||||
|
||||
async def score_group(self, group: list[Rollout]) -> None:
|
||||
"""Group phase, the finalized cohort, before filtering: write
|
||||
group-relative credit."""
|
||||
"""Group phase over the finalized cohort: write group-relative credit."""
|
||||
|
||||
async def finalize_rollout(self, rollout: Rollout) -> None:
|
||||
"""Arrival phase (non-virtual): rollout-local scoring as each rollout is
|
||||
|
||||
@@ -20,8 +20,7 @@ class MaxRLAlgorithm(Algorithm):
|
||||
likelihood as it grows).
|
||||
|
||||
Assumes non-negative (canonically binary) rewards; a group with mean reward
|
||||
<= 0 carries no signal and gets zero advantages (the zero-advantage filter
|
||||
drops it, matching the paper's no-success convention)."""
|
||||
<= 0 carries no signal and gets zero advantages."""
|
||||
|
||||
async def score_group(self, group: list[Rollout]) -> None:
|
||||
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
|
||||
|
||||
@@ -8,7 +8,7 @@ from prime_rl.orchestrator.algo.base import Algorithm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.transports.rollouts import TrainingSample
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
|
||||
@@ -19,9 +19,8 @@ class OPDAlgorithm(Algorithm):
|
||||
The policy samples its own rollouts; at ship time each sample's full
|
||||
context is prefill-scored under the teacher (``ref_logprobs`` on the
|
||||
wire), and the trainer evaluates the KL against the live policy. No
|
||||
credit is assigned — rollouts keep ``advantages=None`` (advantage-based
|
||||
filters never fire) and samples ship no advantage stream; ``group_size``
|
||||
only fans out sampling."""
|
||||
credit is assigned — rollouts keep ``advantages=None`` and samples ship no
|
||||
advantage stream; ``group_size`` only fans out sampling."""
|
||||
|
||||
action_loss_type = "ref_kl"
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ if TYPE_CHECKING:
|
||||
from renderers.base import Renderer
|
||||
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.transports.rollouts import TrainingSample
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.configs.algorithm import ActionLossType
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.transports.rollouts import TrainingSample
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
@@ -8,7 +8,7 @@ class SFTDistillAlgorithm(Algorithm):
|
||||
rollouts (``sampling.source``); the policy trains with CE on its tokens.
|
||||
|
||||
Assigns no advantage — the ``ce`` loss ignores credit, and SFT trains on
|
||||
every sampled token. Reward-based filtering, if wanted, is an explicit
|
||||
filter, not smuggled through an unused advantage stream."""
|
||||
every sampled token. A curriculum can reject results using reward or any
|
||||
other finalized rollout data."""
|
||||
|
||||
action_loss_type = "ce"
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Checkpoint manager for the orchestrator state (``Progress`` counters +
|
||||
``TrainSource`` data position). Layout:
|
||||
"""Checkpoint manager for orchestrator progress and train-source state. Layout:
|
||||
``<output_dir>/checkpoints/step_N/orchestrator/progress.pt``."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -57,7 +56,7 @@ class CheckpointManager:
|
||||
get_logger().debug(f"Loading checkpoint from {state_file}")
|
||||
start = time.perf_counter()
|
||||
if self.config.skip_progress:
|
||||
get_logger().info("Skipping progress and data position loading from checkpoint")
|
||||
get_logger().info("Skipping progress and train source loading from checkpoint")
|
||||
else:
|
||||
with open(state_file, "rb") as f:
|
||||
state = torch.load(f, weights_only=False)
|
||||
@@ -66,15 +65,9 @@ class CheckpointManager:
|
||||
if hasattr(progress, key):
|
||||
setattr(progress, key, value)
|
||||
train_source.load_state_dict(state["train_source"])
|
||||
for name, position in state["train_source"]["envs"].items():
|
||||
if name not in train_source.base_rows:
|
||||
continue
|
||||
rows = train_source.base_rows[name]
|
||||
num_tasks = len(rows) if rows is not None else "infinite"
|
||||
get_logger().info(
|
||||
f"Resumed data position for env {name} - epoch={position['epoch']}, "
|
||||
f"cursor={position['cursor']}/{num_tasks}"
|
||||
)
|
||||
for name in state["train_source"]["envs"]:
|
||||
if name in train_source.curricula:
|
||||
get_logger().info(f"Resumed curriculum state for env {name}")
|
||||
get_logger().debug(f"Orchestrator checkpoint loaded in {format_time(time.perf_counter() - start)}")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
"""ConcurrencyController: adaptive cap on in-flight units of inference work.
|
||||
|
||||
A unit is whatever the dispatcher admits against one permit — the controller
|
||||
treats it as a black box. There is no cost model: the controller measures KV
|
||||
pressure off the engines and reacts at the pipeline's own pace (AIMD):
|
||||
|
||||
- **Grow** the cap multiplicatively per pipeline turnover (each completion
|
||||
advances the turnover by ``1/inflight``) while the engines are clear, KV
|
||||
usage is below ``KV_USAGE_GROW``, and the cap binds admission.
|
||||
- **Trim** above ``KV_USAGE_TRIGGER``: resize cap and pool to what the
|
||||
engines hold at ``KV_USAGE_TARGET`` and cancel the excess, youngest first.
|
||||
Cap moves alone cannot relieve pressure from units maturing in place.
|
||||
- **Cut** on overload: preemptions (single-shot loads) or a persistent
|
||||
capacity queue (agentic loads never preempt — admission control parks
|
||||
excess load in the waiting queue). Cut, cancel the excess, then freeze
|
||||
cuts until the pool drains below the new cap.
|
||||
|
||||
The cap starts at ``initial_inflight`` (else the pessimistic bound
|
||||
``KV capacity / max_model_len``) and is clamped to
|
||||
``[min_inflight, max_inflight]`` throughout.
|
||||
|
||||
The controller is a pure state machine — it owns no tasks or clients. The
|
||||
metrics collector pushes ``observe(samples)`` every poll; the dispatcher
|
||||
reports ``record_episode(...)`` per completed unit and consumes the cap via
|
||||
the hooks bound in :meth:`bind`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import format_num
|
||||
|
||||
TURNOVER_GROWTH = 1.25
|
||||
"""Cap growth per pipeline turnover while the engines are clear and the cap binds."""
|
||||
|
||||
BINDING_FRACTION = 0.9
|
||||
"""The cap counts as binding when inflight reaches this fraction of it."""
|
||||
|
||||
KV_USAGE_GROW = 0.6
|
||||
"""Grow only while every decode engine's KV usage is below this."""
|
||||
|
||||
KV_USAGE_TRIGGER = 0.8
|
||||
"""Above this usage, trim the cap and the in-flight pool."""
|
||||
|
||||
KV_USAGE_TARGET = 0.7
|
||||
"""A trim resizes to inflight * target / usage — below the trigger, so pool growth has headroom before the next trim."""
|
||||
|
||||
KV_TRIM_COOLDOWN_POLLS = 6
|
||||
"""Polls between kv-headroom trims, letting each trim propagate before the next is sized."""
|
||||
|
||||
QUEUE_RATIO = 0.5
|
||||
"""HARD once capacity-queued requests exceed this fraction of running requests for the persistence window."""
|
||||
|
||||
QUEUE_PERSISTENCE_POLLS = 6
|
||||
"""Consecutive polls of queue overload before the HARD cut; filters natural turn-completion bursts."""
|
||||
|
||||
QUEUE_CUT_FRACTION = 0.9
|
||||
"""A queue cut targets this fraction of the in-flight pool. Pool units, not
|
||||
engine requests: agentic episodes idle between turns, so engine ``running``
|
||||
undercounts the pool by the duty cycle and cutting to it over-cuts."""
|
||||
|
||||
PREEMPTION_CUT_FRACTION = 0.8
|
||||
"""A preemption cut targets this fraction of the in-flight pool."""
|
||||
|
||||
ESCALATED_CUT_FRACTION = 0.5
|
||||
"""Cut fraction when overload survives a full drain."""
|
||||
|
||||
ESCALATION_GRACE_POLLS = 6
|
||||
"""Polls after a drain completes during which a repeat overload cuts at the
|
||||
escalated fraction; past the grace window the system is considered recovered
|
||||
and escalation resets."""
|
||||
|
||||
GROWTH_GATE_TTL_S = 15.0
|
||||
"""The growth gate expires this long after the poll that set it — if the
|
||||
metrics path stalls (an API server too loaded to answer is exactly the state
|
||||
runaway growth creates), growth freezes instead of compounding blind."""
|
||||
|
||||
|
||||
Signal = Literal["clear", "soft", "hard"]
|
||||
"""Engine pressure, in increasing severity."""
|
||||
|
||||
SEVERITY: dict[Signal, int] = {"clear": 0, "soft": 1, "hard": 2}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EngineLoadSample:
|
||||
"""Per-engine load facts for one ``/metrics`` poll. Raw values only —
|
||||
thresholds and verdicts live in the controller."""
|
||||
|
||||
engine_id: str
|
||||
role: str | None
|
||||
kv_capacity_tokens: int | None
|
||||
max_model_len: int | None
|
||||
kv_usage: float
|
||||
running: int
|
||||
waiting: int
|
||||
# Requests queued specifically for KV capacity (None if the engine does
|
||||
# not report the by-reason breakdown; fall back to ``waiting``)
|
||||
waiting_capacity: int | None
|
||||
preemptions_delta: int
|
||||
|
||||
|
||||
class ConcurrencyController:
|
||||
def __init__(self, config: ConcurrencyConfig, *, fallback_cost: int) -> None:
|
||||
self.config = config
|
||||
self.floor = config.min_inflight
|
||||
self.fallback_cost = fallback_cost
|
||||
"""Pessimistic per-unit cost for the starting cap when the engine reports no max context."""
|
||||
|
||||
self.cap = float(config.initial_inflight or self.floor)
|
||||
self.max_inflight = self.clamp(self.cap)
|
||||
self.bootstrapped = config.initial_inflight is not None
|
||||
self.engine_max_len: int | None = None
|
||||
self.capacity_by_engine: dict[str, int] = {}
|
||||
|
||||
self.turnover = 0.0
|
||||
self.signal: Signal = "clear"
|
||||
# Growth gate from the last poll, consumed by per-completion growth
|
||||
self.can_grow = False
|
||||
self.can_grow_until = 0.0
|
||||
self.prev_waiting: dict[str, int] = {}
|
||||
self.queue_overload_polls = 0
|
||||
self.trim_cooldown = 0
|
||||
self.escalation_grace = 0
|
||||
# After a cut, ignore further cuts until inflight has drained below
|
||||
# the new cap — the overload during drain is stale
|
||||
self.draining = False
|
||||
self.escalated = False
|
||||
|
||||
self.set_limit: Callable[[int], None] | None = None
|
||||
self.get_inflight: Callable[[], int] | None = None
|
||||
self.on_overload: Callable[[int], None] | None = None
|
||||
|
||||
def bind(
|
||||
self,
|
||||
*,
|
||||
set_limit: Callable[[int], None],
|
||||
get_inflight: Callable[[], int],
|
||||
on_overload: Callable[[int], None] | None = None,
|
||||
) -> None:
|
||||
"""Attach the outbound hooks. The dispatcher is constructed with this
|
||||
controller's initial cap, so no ``set_limit`` fires here.
|
||||
``on_overload`` receives the unit excess on a downward resize so the
|
||||
dispatcher can cancel in-flight work instead of just blocking
|
||||
admission."""
|
||||
self.set_limit = set_limit
|
||||
self.get_inflight = get_inflight
|
||||
self.on_overload = on_overload
|
||||
|
||||
# ── inbound hooks ────────────────────────────────────────────────────────
|
||||
|
||||
def record_episode(self, env_name: str, kind: str, tokens: int, duration: float) -> None:
|
||||
"""One completed unit (from the dispatcher). Advances the turnover
|
||||
clock and, while the last poll was green, grows the cap — so growth
|
||||
is paced by the pipeline itself at any concurrency scale."""
|
||||
# The dispatcher releases the permit before this hook fires, so the
|
||||
# completing episode is already off the count — add it back, or the
|
||||
# binding check is unsatisfiable for caps below 10 (0.9 * cap > cap - 1)
|
||||
inflight = (self.get_inflight() if self.get_inflight is not None else 0) + 1
|
||||
fraction = 1 / inflight
|
||||
self.turnover += fraction
|
||||
if tokens <= 0:
|
||||
# Error markers consumed no engine capacity: a slow-failing error
|
||||
# storm keeps the pool binding while idle engines read CLEAR, and
|
||||
# growing on it floods the engines once the environment recovers
|
||||
return
|
||||
if (
|
||||
self.can_grow
|
||||
and time.monotonic() < self.can_grow_until
|
||||
and inflight >= BINDING_FRACTION * self.max_inflight
|
||||
):
|
||||
self.cap = self.clamp(self.cap * TURNOVER_GROWTH**fraction)
|
||||
self.apply_limit(int(self.cap), reason=None)
|
||||
|
||||
def observe(self, samples: list[EngineLoadSample]) -> None:
|
||||
"""Per-poll engine load push from the metrics collector: classify the
|
||||
signal, gate growth, and apply trims and cuts."""
|
||||
if not samples:
|
||||
return
|
||||
for sample in samples:
|
||||
if sample.kv_capacity_tokens and sample.role != "prefill":
|
||||
self.capacity_by_engine[sample.engine_id] = sample.kv_capacity_tokens
|
||||
if sample.max_model_len:
|
||||
self.engine_max_len = max(self.engine_max_len or 0, sample.max_model_len)
|
||||
# Overload signals read decode engines only: in P/D deployments a
|
||||
# prefill queue or prefill preemption is normal flow, not KV pressure
|
||||
samples = [sample for sample in samples if sample.role != "prefill"]
|
||||
if not samples:
|
||||
return
|
||||
|
||||
worst: Signal = "clear"
|
||||
max_usage = 0.0
|
||||
total_running = 0
|
||||
total_queued = 0
|
||||
preempted = False
|
||||
for sample in samples:
|
||||
if sample.preemptions_delta > 0:
|
||||
preempted = True
|
||||
worst = "hard"
|
||||
if sample.waiting > 0 and self.prev_waiting.get(sample.engine_id, 0) > 0:
|
||||
worst = max(worst, "soft", key=SEVERITY.__getitem__)
|
||||
max_usage = max(max_usage, sample.kv_usage)
|
||||
total_running += sample.running
|
||||
total_queued += sample.waiting_capacity if sample.waiting_capacity is not None else sample.waiting
|
||||
self.prev_waiting = {sample.engine_id: sample.waiting for sample in samples}
|
||||
|
||||
if total_running > 0 and total_queued > QUEUE_RATIO * total_running:
|
||||
self.queue_overload_polls += 1
|
||||
else:
|
||||
self.queue_overload_polls = 0
|
||||
queue_overload = self.queue_overload_polls >= QUEUE_PERSISTENCE_POLLS
|
||||
if queue_overload or max_usage > KV_USAGE_GROW:
|
||||
worst = max(worst, "hard" if queue_overload else "soft", key=SEVERITY.__getitem__)
|
||||
self.signal = worst
|
||||
|
||||
inflight = self.get_inflight() if self.get_inflight is not None else 0
|
||||
# Release the drain only once the engines have settled too: cuts
|
||||
# cancel episodes, so dispatcher inflight drops below the cap almost
|
||||
# immediately while the engines are still churning through their own
|
||||
# backlog — preemption deltas from that stale churn must not trigger
|
||||
# follow-up cuts (observed: an escalated-cut cascade 1024 -> 8, one
|
||||
# halving per poll).
|
||||
if self.draining and inflight <= self.max_inflight and not preempted and not queue_overload:
|
||||
self.draining = False
|
||||
self.escalation_grace = ESCALATION_GRACE_POLLS
|
||||
if not self.draining and self.escalated:
|
||||
# Escalation persists only through the grace window after a
|
||||
# drain: a repeat overload inside it cuts harder, anything later
|
||||
# means the system recovered (steady state post-cut is SOFT, so
|
||||
# gating the reset on a CLEAR poll would latch escalation forever)
|
||||
self.escalation_grace -= 1
|
||||
if self.escalation_grace <= 0:
|
||||
self.escalated = False
|
||||
self.trim_cooldown = max(0, self.trim_cooldown - 1)
|
||||
self.can_grow = worst == "clear" and total_queued == 0 and not self.draining
|
||||
self.can_grow_until = time.monotonic() + GROWTH_GATE_TTL_S
|
||||
|
||||
# First capacity observation without a user-set start: derive the
|
||||
# pessimistic starting cap, once
|
||||
if not self.bootstrapped and self.capacity is not None:
|
||||
self.bootstrapped = True
|
||||
cost = float(self.engine_max_len or self.fallback_cost)
|
||||
self.cap = self.clamp(self.capacity / cost)
|
||||
get_logger().info(
|
||||
f"Derived initial max inflight {int(self.cap)} - {format_num(self.capacity, precision=1)} "
|
||||
f"KV cache tokens / {format_num(cost, precision=1)} tokens per episode"
|
||||
)
|
||||
self.apply_limit(int(self.cap), reason=None)
|
||||
|
||||
if self.draining:
|
||||
return
|
||||
|
||||
if preempted or queue_overload:
|
||||
fraction = ESCALATED_CUT_FRACTION if self.escalated else None
|
||||
if queue_overload:
|
||||
self.queue_overload_polls = 0
|
||||
target = int(self.clamp(inflight * (fraction or QUEUE_CUT_FRACTION)))
|
||||
reason = "queue overload"
|
||||
else:
|
||||
target = int(self.clamp(inflight * (fraction or PREEMPTION_CUT_FRACTION)))
|
||||
reason = "preemptions"
|
||||
self.resize_down(target, inflight, reason=reason)
|
||||
self.draining = True
|
||||
self.escalated = True
|
||||
return
|
||||
|
||||
if max_usage > KV_USAGE_TRIGGER and inflight > 0 and self.trim_cooldown == 0:
|
||||
target = int(self.clamp(inflight * KV_USAGE_TARGET / max_usage))
|
||||
self.resize_down(target, inflight, reason=f"kv headroom (usage {max_usage:.2f})")
|
||||
self.trim_cooldown = KV_TRIM_COOLDOWN_POLLS
|
||||
|
||||
# ── internals ────────────────────────────────────────────────────────────
|
||||
|
||||
def resize_down(self, target: int, inflight: int, *, reason: str) -> None:
|
||||
"""Lower the cap (never raise) and cancel the in-flight excess."""
|
||||
target = min(target, self.max_inflight)
|
||||
self.cap = float(target)
|
||||
self.apply_limit(target, reason=reason)
|
||||
if self.on_overload is not None and inflight > target:
|
||||
self.on_overload(inflight - target)
|
||||
|
||||
def apply_limit(self, n_max: int, *, reason: str | None) -> None:
|
||||
if n_max == self.max_inflight:
|
||||
return
|
||||
if reason is not None:
|
||||
verb = "Increased" if n_max > self.max_inflight else "Decreased"
|
||||
get_logger().info(
|
||||
f"{verb} concurrency {self.max_inflight} -> {n_max} ({reason}) - "
|
||||
f"turnover={self.turnover:.1f} signal={self.signal}"
|
||||
)
|
||||
self.max_inflight = n_max
|
||||
if self.set_limit is not None:
|
||||
self.set_limit(n_max)
|
||||
|
||||
def clamp(self, n_max: float) -> float:
|
||||
ceiling = self.config.max_inflight or math.inf
|
||||
return min(max(n_max, float(self.floor)), float(ceiling))
|
||||
|
||||
@property
|
||||
def capacity(self) -> int | None:
|
||||
"""Total KV tokens across decode engines; None until the first poll."""
|
||||
return sum(self.capacity_by_engine.values()) or None
|
||||
|
||||
# ── observability ────────────────────────────────────────────────────────
|
||||
|
||||
def gauges(self) -> dict[str, float]:
|
||||
return {
|
||||
"concurrency/max_inflight": float(self.max_inflight),
|
||||
"concurrency/turnover": self.turnover,
|
||||
"concurrency/capacity": float(self.capacity or 0),
|
||||
"concurrency/signal": float(SEVERITY[self.signal]),
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Task selection and finalized-sample admission for training environments."""
|
||||
|
||||
from prime_rl.orchestrator.curriculum.base import Curriculum
|
||||
from prime_rl.orchestrator.curriculum.gates import AdmissionGate, AdvRangeGate
|
||||
from prime_rl.orchestrator.curriculum.samplers import DifficultyPoolSampler, StandardSampler, TaskSampler
|
||||
|
||||
__all__ = [
|
||||
"AdmissionGate",
|
||||
"AdvRangeGate",
|
||||
"Curriculum",
|
||||
"DifficultyPoolSampler",
|
||||
"StandardSampler",
|
||||
"TaskSampler",
|
||||
]
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Curriculum composition and lifecycle."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator, Sequence
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.curriculum.gates import AdmissionGate
|
||||
from prime_rl.orchestrator.curriculum.samplers import TaskSampler
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.configs.orchestrator import CurriculumConfig
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
class Curriculum:
|
||||
"""One task sampler composed with zero or more admission gates."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: CurriculumConfig | None,
|
||||
tasks: Sequence[vf.Task] | Iterator[vf.Task],
|
||||
) -> None:
|
||||
from prime_rl.configs.orchestrator import (
|
||||
AdvRangeGateConfig,
|
||||
CurriculumConfig,
|
||||
DifficultyPoolSamplerConfig,
|
||||
StandardSamplerConfig,
|
||||
)
|
||||
from prime_rl.orchestrator.curriculum.gates import AdvRangeGate
|
||||
from prime_rl.orchestrator.curriculum.samplers import DifficultyPoolSampler, StandardSampler
|
||||
|
||||
config = CurriculumConfig() if config is None else config
|
||||
if isinstance(config.sampler, StandardSamplerConfig):
|
||||
self.sampler: TaskSampler = StandardSampler(tasks)
|
||||
elif isinstance(config.sampler, DifficultyPoolSamplerConfig):
|
||||
self.sampler = DifficultyPoolSampler(config.sampler, tasks)
|
||||
else:
|
||||
raise TypeError(f"Unsupported task sampler config: {type(config.sampler).__name__}")
|
||||
|
||||
self.gates: dict[str, AdmissionGate] = {}
|
||||
for name, gate_config in config.gates.items():
|
||||
if isinstance(gate_config, AdvRangeGateConfig):
|
||||
gate: AdmissionGate = AdvRangeGate(gate_config)
|
||||
else:
|
||||
raise TypeError(f"Unsupported admission gate config: {type(gate_config).__name__}")
|
||||
self.gates[name] = gate
|
||||
|
||||
def on_result(self, group: list[Rollout]) -> bool:
|
||||
"""Observe every result, evaluate every gate, and combine with AND."""
|
||||
if not group:
|
||||
raise ValueError("Cannot report an empty rollout group")
|
||||
task_keys = {rollout.task.key for rollout in group}
|
||||
if None in task_keys:
|
||||
raise ValueError("A finalized group is missing Task.key")
|
||||
if len(task_keys) != 1:
|
||||
raise ValueError(f"A finalized group contains multiple task keys: {task_keys}")
|
||||
self.sampler.observe(group)
|
||||
decisions: list[bool] = []
|
||||
for name, gate in self.gates.items():
|
||||
decision = gate.admit(group)
|
||||
if not isinstance(decision, bool):
|
||||
raise TypeError(f"AdmissionGate {name!r}.admit() must return bool, got {type(decision).__name__}")
|
||||
decisions.append(decision)
|
||||
return all(decisions)
|
||||
|
||||
def state_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"sampler": self.sampler.state_dict(),
|
||||
"gates": {name: gate.state_dict() for name, gate in self.gates.items()},
|
||||
}
|
||||
|
||||
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
|
||||
if "sampler" not in state_dict:
|
||||
self.sampler.load_state_dict(state_dict)
|
||||
return
|
||||
self.sampler.load_state_dict(state_dict["sampler"])
|
||||
for name, gate_state in state_dict["gates"].items():
|
||||
gate = self.gates.get(name)
|
||||
if gate is not None:
|
||||
gate.load_state_dict(gate_state)
|
||||
|
||||
def metrics(self) -> dict[str, float]:
|
||||
metrics = {f"sampler/{name}": float(value) for name, value in self.sampler.metrics().items()}
|
||||
for gate_name, gate in self.gates.items():
|
||||
metrics |= {f"gate/{gate_name}/{name}": float(value) for name, value in gate.metrics().items()}
|
||||
return metrics
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Admission gate interfaces and implementations."""
|
||||
|
||||
from prime_rl.orchestrator.curriculum.gates.adv import AdvRangeGate
|
||||
from prime_rl.orchestrator.curriculum.gates.base import AdmissionGate
|
||||
|
||||
__all__ = ["AdmissionGate", "AdvRangeGate"]
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Advantage-based training-sample admission."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.orchestrator.curriculum.gates.base import AdmissionGate
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.configs.orchestrator import AdvRangeGateConfig
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
class AdvRangeGate(AdmissionGate):
|
||||
"""Reject groups whose trainable-token advantages all fall inside a range.
|
||||
|
||||
The default ``[0, 0]`` interval filters groups with no online learning
|
||||
signal. Groups without an advantage stream are admitted.
|
||||
"""
|
||||
|
||||
def __init__(self, config: AdvRangeGateConfig) -> None:
|
||||
self.config = config
|
||||
|
||||
def admit(self, group: list[Rollout]) -> bool:
|
||||
advantages: list[float] = []
|
||||
for rollout in group:
|
||||
if rollout.advantages is None:
|
||||
continue
|
||||
trainable = [value for sample in rollout.samples for value in sample.mask]
|
||||
advantages.extend(advantage for advantage, keep in zip(rollout.advantages, trainable, strict=True) if keep)
|
||||
if not advantages:
|
||||
return True
|
||||
return not all(self.config.reject_min <= advantage <= self.config.reject_max for advantage in advantages)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Admission gate interface."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
class AdmissionGate:
|
||||
"""Base class for user-authored training-sample admission policies."""
|
||||
|
||||
def admit(self, group: list[Rollout]) -> bool:
|
||||
"""Return whether a finalized group should enter the training batch."""
|
||||
return True
|
||||
|
||||
def state_dict(self) -> dict[str, Any]:
|
||||
"""Return checkpoint state owned by this gate."""
|
||||
return {}
|
||||
|
||||
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
|
||||
"""Restore checkpoint state before results resume."""
|
||||
|
||||
def metrics(self) -> dict[str, float]:
|
||||
"""Return metrics relative to this gate's namespace."""
|
||||
return {}
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Task sampler interfaces and implementations."""
|
||||
|
||||
from prime_rl.orchestrator.curriculum.samplers.base import TaskSampler
|
||||
from prime_rl.orchestrator.curriculum.samplers.pool import DifficultyPoolSampler
|
||||
from prime_rl.orchestrator.curriculum.samplers.standard import StandardSampler
|
||||
|
||||
__all__ = ["DifficultyPoolSampler", "StandardSampler", "TaskSampler"]
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Task sampler interface."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Iterator
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
class TaskSampler(Iterator[vf.Task], ABC):
|
||||
"""Base class for user-authored task selection policies."""
|
||||
|
||||
@abstractmethod
|
||||
def __next__(self) -> vf.Task:
|
||||
"""Choose the next task."""
|
||||
raise NotImplementedError
|
||||
|
||||
def observe(self, group: list[Rollout]) -> None:
|
||||
"""Update sampling state from a finalized group."""
|
||||
|
||||
def state_dict(self) -> dict[str, Any]:
|
||||
"""Return checkpoint state owned by this sampler."""
|
||||
return {}
|
||||
|
||||
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
|
||||
"""Restore checkpoint state before sampling resumes."""
|
||||
|
||||
def metrics(self) -> dict[str, float]:
|
||||
"""Return metrics relative to this sampler's namespace."""
|
||||
return {}
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Difficulty-pool task sampling."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from collections import Counter
|
||||
from collections.abc import Iterator, Sequence
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.curriculum.samplers.base import TaskSampler
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.configs.orchestrator import DifficultyPoolSamplerConfig
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
class DifficultyPoolSampler(TaskSampler):
|
||||
"""Weight finite tasks by a pool derived from their latest group mean.
|
||||
|
||||
Each pool's threshold is its inclusive maximum reward; the final pool is
|
||||
the catch-all. Unseen tasks have neutral weight, so observations affect
|
||||
sampling immediately without requiring a full taskset pass.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: DifficultyPoolSamplerConfig,
|
||||
tasks: Sequence[vf.Task] | Iterator[vf.Task],
|
||||
) -> None:
|
||||
if not isinstance(tasks, Sequence):
|
||||
raise ValueError("DifficultyPoolSampler requires a finite taskset")
|
||||
self.tasks = tuple(tasks)
|
||||
if not self.tasks:
|
||||
raise ValueError("DifficultyPoolSampler requires at least one task")
|
||||
keys = [task.key for task in self.tasks]
|
||||
duplicates = {key for key, count in Counter(keys).items() if count > 1}
|
||||
if duplicates:
|
||||
raise ValueError(f"Task keys must be unique within a taskset: {sorted(duplicates)}")
|
||||
self.tasks_by_key = dict(zip(keys, self.tasks))
|
||||
self.rng = random.Random(config.seed)
|
||||
self.pools = config.pools
|
||||
ordered = sorted(self.pools.items(), key=lambda item: item[1].threshold)
|
||||
self._ordered_pools = tuple(ordered)
|
||||
self.task_rewards: dict[str, float] = {}
|
||||
|
||||
def task_pool(self, task_key: str) -> str | None:
|
||||
"""Return the task's current pool, or ``None`` until it has a score."""
|
||||
score = self.task_rewards.get(task_key)
|
||||
if score is None:
|
||||
return None
|
||||
for name, pool in self._ordered_pools:
|
||||
if score <= pool.threshold:
|
||||
return name
|
||||
return self._ordered_pools[-1][0]
|
||||
|
||||
def __next__(self) -> vf.Task:
|
||||
weights = []
|
||||
for task in self.tasks:
|
||||
pool = self.task_pool(task.key)
|
||||
weights.append(1.0 if pool is None else self.pools[pool].weight)
|
||||
if not any(weights):
|
||||
raise RuntimeError("DifficultyPoolSampler has no tasks in a pool with positive weight")
|
||||
return self.rng.choices(self.tasks, weights=weights, k=1)[0]
|
||||
|
||||
def observe(self, group: list[Rollout]) -> None:
|
||||
rewards = [rollout.reward for rollout in group if not rollout.has_error and rollout.agent.trainable]
|
||||
if not rewards:
|
||||
return
|
||||
task_key = group[0].task.key
|
||||
if task_key is None:
|
||||
raise ValueError("A finalized group is missing Task.key")
|
||||
self.task_rewards[task_key] = sum(rewards) / len(rewards)
|
||||
|
||||
def state_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"rng": self.rng.getstate(),
|
||||
"task_rewards": dict(self.task_rewards),
|
||||
}
|
||||
|
||||
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
|
||||
self.rng.setstate(state_dict["rng"])
|
||||
self.task_rewards = dict(state_dict["task_rewards"])
|
||||
|
||||
def metrics(self) -> dict[str, float]:
|
||||
occupancy = dict.fromkeys(self.pools, 0)
|
||||
for task_key in self.task_rewards:
|
||||
pool = self.task_pool(task_key)
|
||||
if pool is not None:
|
||||
occupancy[pool] += 1
|
||||
return {
|
||||
"pool/unseen": float(len(self.tasks_by_key) - len(self.task_rewards)),
|
||||
**{f"pool/{name}": float(count) for name, count in occupancy.items()},
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Standard task iteration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
from collections import Counter
|
||||
from collections.abc import Iterator, Sequence
|
||||
from typing import Any
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.curriculum.samplers.base import TaskSampler
|
||||
|
||||
|
||||
class StandardSampler(TaskSampler):
|
||||
"""Advance the task iterator, cycling finite tasksets in source order."""
|
||||
|
||||
def __init__(self, tasks: Sequence[vf.Task] | Iterator[vf.Task]) -> None:
|
||||
self.tasks = tuple(tasks) if isinstance(tasks, Sequence) else None
|
||||
if self.tasks is not None:
|
||||
if not self.tasks:
|
||||
raise ValueError("A finite curriculum needs at least one task")
|
||||
keys = [task.key for task in self.tasks]
|
||||
duplicates = {key for key, count in Counter(keys).items() if count > 1}
|
||||
if duplicates:
|
||||
raise ValueError(f"Task keys must be unique within a taskset: {sorted(duplicates)}")
|
||||
self.task_iterator = itertools.cycle(self.tasks)
|
||||
else:
|
||||
self.task_iterator = tasks
|
||||
self.cursor = 0
|
||||
|
||||
def __next__(self) -> vf.Task:
|
||||
task = next(self.task_iterator)
|
||||
self.cursor += 1
|
||||
return task
|
||||
|
||||
def state_dict(self) -> dict[str, Any]:
|
||||
return {"cursor": self.cursor}
|
||||
|
||||
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
|
||||
cursor = state_dict["cursor"]
|
||||
if self.tasks is not None:
|
||||
self.task_iterator = itertools.cycle(self.tasks)
|
||||
offset = cursor % len(self.tasks)
|
||||
else:
|
||||
offset = cursor
|
||||
for _ in range(offset):
|
||||
next(self.task_iterator)
|
||||
self.cursor = cursor
|
||||
@@ -1,7 +1,10 @@
|
||||
"""RolloutDispatcher: schedules rollouts under a shared permit counter.
|
||||
"""Dispatcher: schedules rollouts under a shared permit counter.
|
||||
|
||||
- Capacity (``max_inflight_episodes``) is shared across train + eval. One permit is
|
||||
one episode: one ``run`` request against an env server.
|
||||
- Capacity (``max_inflight``) is shared across train + eval. One permit is
|
||||
one episode: one ``run`` request against an env server. The cap is dynamic —
|
||||
the concurrency controller moves it via ``set_limit``; refills are
|
||||
burst-capped so a raised (or drained) cap never lands all its prefills at
|
||||
once.
|
||||
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
|
||||
- Emit-everything invariant: every dispatched episode eventually reaches
|
||||
``out_q`` exactly once, as a ``list[Rollout]``. Failures
|
||||
@@ -9,10 +12,10 @@
|
||||
``trace.last_error`` set; sinks decide drop / partial-train policy.
|
||||
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
|
||||
schedule next. Transitions are level-triggered (driven by the eval
|
||||
source's emptiness), so in-flight rollouts of the opposite kind drain
|
||||
source's emptiness), so in-flight episodes of the opposite kind drain
|
||||
naturally on either side of an eval boundary.
|
||||
- ``on_version_pending`` (called by the watcher before the engines pause for
|
||||
the weight update) bumps ``off_policy_steps`` on in-flight train rollouts and
|
||||
the weight update) bumps ``off_policy_steps`` on in-flight train episodes and
|
||||
drops groups past ``max_off_policy_steps``.
|
||||
Eval rollouts are measurements for the policy version they started with,
|
||||
so they are allowed to finish even if training advances. Train rollouts
|
||||
@@ -25,8 +28,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum, auto
|
||||
from typing import Literal
|
||||
@@ -39,7 +44,7 @@ from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import (
|
||||
GroupState,
|
||||
InflightRollout,
|
||||
InflightEpisode,
|
||||
Policy,
|
||||
Rollout,
|
||||
RolloutKind,
|
||||
@@ -60,7 +65,7 @@ class DispatcherMode(Enum):
|
||||
class DispatcherMetrics:
|
||||
"""Per-tick drain counters for the orchestrator's periodic log.
|
||||
``drained()`` returns the current values and clears them; point-in-time
|
||||
gauges live on ``RolloutDispatcher.gauges`` instead."""
|
||||
gauges live on ``Dispatcher.gauges`` instead."""
|
||||
|
||||
cancelled_by_kind_env: dict[tuple[Literal["train", "eval"], str], int] = field(
|
||||
default_factory=lambda: defaultdict(int)
|
||||
@@ -113,7 +118,19 @@ class DispatcherMetrics:
|
||||
return keys
|
||||
|
||||
|
||||
class RolloutDispatcher:
|
||||
def error_trace_task(group: GroupState | None) -> vf.TraceTask:
|
||||
"""Preserve task identity on a synthetic error trace."""
|
||||
if group is None:
|
||||
return vf.TraceTask(type="Task", data=vf.TaskData(idx=-1, prompt=None))
|
||||
return vf.TraceTask(
|
||||
type=type(group.task).__name__,
|
||||
data=vf.TaskData(idx=group.task.data.idx, prompt=None),
|
||||
key=group.task.key,
|
||||
hash=group.task.hash,
|
||||
)
|
||||
|
||||
|
||||
class Dispatcher:
|
||||
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
|
||||
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules
|
||||
rollouts under shared capacity, and emits ``Rollout``\\ s to
|
||||
@@ -129,9 +146,11 @@ class RolloutDispatcher:
|
||||
eval_source: EvalSource | None,
|
||||
policy_pool: InferencePool,
|
||||
policy: Policy,
|
||||
max_inflight_episodes: int,
|
||||
initial_max_inflight: int,
|
||||
max_inflight_ceiling: int | None,
|
||||
tasks_per_minute: float | None,
|
||||
max_off_policy_steps: int,
|
||||
on_episode_complete: Callable[[str, str, int, float], None] | None = None,
|
||||
) -> None:
|
||||
self.policy = policy
|
||||
self.train_envs = train_envs
|
||||
@@ -142,19 +161,37 @@ class RolloutDispatcher:
|
||||
self.train_source = train_source
|
||||
self.eval_source = eval_source
|
||||
self.max_off_policy_steps = max_off_policy_steps
|
||||
# ``(env_name, kind, total_tokens, duration_s)`` per completed episode
|
||||
self.on_episode_complete = on_episode_complete
|
||||
|
||||
self.max_inflight = max_inflight_episodes
|
||||
self.inflight_permits = 0
|
||||
# Starting value of the dynamic cap (the concurrency controller moves
|
||||
# it); ``max_inflight_ceiling`` is the configured hard maximum, used to
|
||||
# bound ``out_q``
|
||||
self.max_inflight = initial_max_inflight
|
||||
self.current_inflight = 0
|
||||
self.rate_limiter: AsyncLimiter | None = (
|
||||
AsyncLimiter(tasks_per_minute, time_period=60) if tasks_per_minute else None
|
||||
)
|
||||
# Admission smoothing: the pool may only GROW by ``burst_cap`` per
|
||||
# window. Replacing a completed episode is always free (each natural
|
||||
# completion refunds one admission); only net expansion is metered.
|
||||
# This keeps a raised cap or post-drain refill from landing a wall of
|
||||
# prefills at once, without rate-limiting fast-turning workloads at
|
||||
# steady state.
|
||||
self.admission_window_s = 5.0
|
||||
self.admission_window_start = time.monotonic()
|
||||
self.admissions_in_window = 0
|
||||
self.min_burst = max((env.config.group_size for env in train_envs), default=8)
|
||||
|
||||
self.inflight: dict[asyncio.Task, InflightRollout] = {}
|
||||
self.inflight: dict[asyncio.Task, InflightEpisode] = {}
|
||||
self.groups: dict[uuid.UUID, GroupState] = {}
|
||||
|
||||
# Bounded so the dispatcher backpressures on a slow sink. One entry per
|
||||
# episode — the sinks count episodes, never loose traces.
|
||||
self.out_q: asyncio.Queue[list[Rollout]] = asyncio.Queue(maxsize=max(8, self.max_inflight))
|
||||
# Bounded so the dispatcher backpressures on a slow sink (unbounded
|
||||
# when no hard ceiling is configured — the dynamic cap still bounds
|
||||
# in-flight work). One entry per episode — the sinks count episodes,
|
||||
# never loose traces.
|
||||
maxsize = max(8, max_inflight_ceiling) if max_inflight_ceiling is not None else 0
|
||||
self.out_q: asyncio.Queue[list[Rollout]] = asyncio.Queue(maxsize=maxsize)
|
||||
|
||||
self.mode: DispatcherMode = DispatcherMode.PREFER_TRAIN
|
||||
# Set by the orchestrator after the final train step; pipeline then
|
||||
@@ -189,7 +226,51 @@ class RolloutDispatcher:
|
||||
|
||||
@property
|
||||
def available_permits(self) -> int:
|
||||
return self.max_inflight - self.inflight_permits
|
||||
return self.max_inflight - self.current_inflight
|
||||
|
||||
def set_limit(self, max_inflight: int) -> None:
|
||||
"""Move the in-flight cap (concurrency controller hook). A cap below
|
||||
the current in-flight count sheds nothing — admissions just stay
|
||||
blocked until enough episodes finish."""
|
||||
self.max_inflight = max_inflight
|
||||
|
||||
def cancel_inflight(self, n: int) -> None:
|
||||
"""Cancel roughly ``n`` in-flight train episodes, youngest groups
|
||||
first (least inference spend so far). Called on an overload cut so
|
||||
the working set shrinks immediately instead of waiting for the
|
||||
over-admitted episodes to finish at thrashed throughput."""
|
||||
asyncio.create_task(self._cancel_inflight(n))
|
||||
|
||||
async def _cancel_inflight(self, n: int) -> None:
|
||||
# A group's age is its OLDEST member's start: max() would make a
|
||||
# long-running group look young the moment it schedules another
|
||||
# member, cancelling the most sunk cost instead of the least
|
||||
group_age: dict[uuid.UUID, float] = {}
|
||||
for meta in self.inflight.values():
|
||||
if meta.kind != "train":
|
||||
continue
|
||||
age = group_age.get(meta.group_id)
|
||||
group_age[meta.group_id] = meta.started_at if age is None else min(age, meta.started_at)
|
||||
shed = 0
|
||||
for group_id in sorted(group_age, key=lambda gid: group_age[gid], reverse=True):
|
||||
if shed >= n:
|
||||
break
|
||||
# Count only live cancellations toward the excess: drop_group's
|
||||
# return includes never-dispatched markers, which free no permits
|
||||
live = sum(1 for meta in self.inflight.values() if meta.group_id == group_id)
|
||||
await self.drop_group(group_id)
|
||||
shed += live
|
||||
if shed:
|
||||
get_logger().warning(f"Cancelled {shed} youngest in-flight episodes after overload cut")
|
||||
|
||||
def admission_budget(self) -> int:
|
||||
"""Admissions still allowed in the current burst window."""
|
||||
now = time.monotonic()
|
||||
if now - self.admission_window_start >= self.admission_window_s:
|
||||
self.admission_window_start = now
|
||||
self.admissions_in_window = 0
|
||||
burst_cap = max(self.min_burst, self.max_inflight // 10)
|
||||
return burst_cap - self.admissions_in_window
|
||||
|
||||
@property
|
||||
def inflight_by_env(self) -> dict[tuple[RolloutKind, str], int]:
|
||||
@@ -262,7 +343,7 @@ class RolloutDispatcher:
|
||||
|
||||
async def stop(self) -> None:
|
||||
self.stopped.set()
|
||||
await self.cancel_inflight_rollouts()
|
||||
await self.cancel_inflight_episodes()
|
||||
if self.task is not None:
|
||||
await safe_cancel(self.task)
|
||||
self.task = None
|
||||
@@ -296,7 +377,7 @@ class RolloutDispatcher:
|
||||
|
||||
if cancelled:
|
||||
get_logger().warning(
|
||||
f"Cancelled {cancelled} train rollouts past max_off_policy_steps={self.max_off_policy_steps}. "
|
||||
f"Cancelled {cancelled} train episodes past max_off_policy_steps={self.max_off_policy_steps}. "
|
||||
"Consider increasing it to avoid this."
|
||||
)
|
||||
|
||||
@@ -310,7 +391,7 @@ class RolloutDispatcher:
|
||||
respects it. When ``PREFER_EVAL``'s source exhausts we flip back to
|
||||
``PREFER_TRAIN`` so the eval tail drains alongside fresh train."""
|
||||
while True:
|
||||
if self.available_permits <= 0:
|
||||
if self.available_permits <= 0 or self.admission_budget() <= 0:
|
||||
return
|
||||
|
||||
if self.mode == DispatcherMode.PREFER_EVAL:
|
||||
@@ -337,7 +418,7 @@ class RolloutDispatcher:
|
||||
if new_mode == self.mode:
|
||||
return
|
||||
prefer = "eval" if new_mode == DispatcherMode.PREFER_EVAL else "train"
|
||||
get_logger().info(f"Switching dispatcher mode to prefer {prefer} rollouts because {reason}")
|
||||
get_logger().info(f"Switching dispatcher mode to prefer {prefer} episodes because {reason}")
|
||||
self.mode = new_mode
|
||||
|
||||
async def try_schedule(self, kind: RolloutKind) -> bool:
|
||||
@@ -424,6 +505,7 @@ class RolloutDispatcher:
|
||||
|
||||
group.rollouts_to_schedule -= 1
|
||||
await self.acquire()
|
||||
self.admissions_in_window += 1
|
||||
task = asyncio.create_task(
|
||||
env.run(
|
||||
client=client,
|
||||
@@ -433,13 +515,14 @@ class RolloutDispatcher:
|
||||
)
|
||||
)
|
||||
|
||||
self.inflight[task] = InflightRollout(
|
||||
self.inflight[task] = InflightEpisode(
|
||||
kind=group.kind,
|
||||
env_name=group.env_name,
|
||||
group_id=group_id,
|
||||
policy_version=group.policy_version_at_start,
|
||||
client_config=client,
|
||||
eval_step=group.eval_step,
|
||||
started_at=time.monotonic(),
|
||||
)
|
||||
return True
|
||||
|
||||
@@ -448,10 +531,15 @@ class RolloutDispatcher:
|
||||
``available_permits >= 1``; this is not a blocking acquire."""
|
||||
if self.rate_limiter is not None:
|
||||
await self.rate_limiter.acquire()
|
||||
self.inflight_permits += 1
|
||||
self.current_inflight += 1
|
||||
|
||||
def release(self) -> None:
|
||||
self.inflight_permits -= 1
|
||||
def release(self, *, refund_admission: bool = False) -> None:
|
||||
"""Free one permit. ``refund_admission`` only on natural completions:
|
||||
refunding cancelled episodes would hand a mass shed's worth of burst
|
||||
budget to the refill while the overload is still draining."""
|
||||
self.current_inflight -= 1
|
||||
if refund_admission:
|
||||
self.admissions_in_window = max(0, self.admissions_in_window - 1)
|
||||
|
||||
async def handle_completed_rollout(self, task: asyncio.Task) -> None:
|
||||
"""Emit every dispatched episode exactly once to ``out_q``. Task
|
||||
@@ -462,8 +550,8 @@ class RolloutDispatcher:
|
||||
"""
|
||||
meta = self.inflight.pop(task, None)
|
||||
if meta is None:
|
||||
return # already handled by drop_group / cancel_inflight_rollouts
|
||||
self.release()
|
||||
return # already handled by drop_group / cancel_inflight_episodes
|
||||
self.release(refund_admission=True)
|
||||
group = self.groups.get(meta.group_id)
|
||||
|
||||
is_synth_exception = False
|
||||
@@ -476,10 +564,9 @@ class RolloutDispatcher:
|
||||
return
|
||||
except Exception as exc:
|
||||
get_logger().warning(f"Rollout task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
|
||||
task_idx = group.task.data.idx if group is not None else -1
|
||||
rollouts = [
|
||||
Rollout(
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
|
||||
task=error_trace_task(group),
|
||||
agent=vf.AgentInfo(config=vf.AgentConfig()),
|
||||
)
|
||||
]
|
||||
@@ -500,9 +587,12 @@ class RolloutDispatcher:
|
||||
get_logger().warning(
|
||||
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — {r.last_error.type}: {r.last_error.message}"
|
||||
)
|
||||
if not is_synth_exception and self.on_episode_complete is not None and meta.started_at > 0:
|
||||
total_tokens = sum(r.num_total_tokens for r in rollouts)
|
||||
self.on_episode_complete(meta.env_name, meta.kind, total_tokens, time.monotonic() - meta.started_at)
|
||||
await self.emit_episode(meta, group, rollouts)
|
||||
|
||||
async def emit_episode(self, meta: InflightRollout, group: GroupState | None, rollouts: list[Rollout]) -> None:
|
||||
async def emit_episode(self, meta: InflightEpisode, group: GroupState | None, rollouts: list[Rollout]) -> None:
|
||||
"""Stamp prime-rl metadata onto one completed episode and put it on
|
||||
``out_q``. Pops the group from ``self.groups`` once every owed episode
|
||||
has been emitted."""
|
||||
@@ -532,14 +622,12 @@ class RolloutDispatcher:
|
||||
(both in-flight and not-yet-scheduled). Returns the count for
|
||||
off-policy metrics."""
|
||||
group = self.groups.pop(group_id, None)
|
||||
task_idx = group.task.data.idx if group is not None else -1
|
||||
|
||||
# Sync claim phase: pop matching tasks from ``self.inflight`` and
|
||||
# release their permits in one non-yielding sweep. After this loop
|
||||
# the dropped tasks are no longer reachable from ``self.inflight``,
|
||||
# so ``handle_completed_rollout``'s existing None-guard makes the
|
||||
# subsequent async emit phase race-free.
|
||||
claimed: list[tuple[asyncio.Task, InflightRollout]] = []
|
||||
claimed: list[tuple[asyncio.Task, InflightEpisode]] = []
|
||||
for task, meta in list(self.inflight.items()):
|
||||
if meta.group_id != group_id:
|
||||
continue
|
||||
@@ -549,10 +637,10 @@ class RolloutDispatcher:
|
||||
|
||||
tasks_to_cancel = [task for task, _ in claimed]
|
||||
inflight_cancelled = len(claimed)
|
||||
last_meta: InflightRollout | None = claimed[-1][1] if claimed else None
|
||||
last_meta: InflightEpisode | None = claimed[-1][1] if claimed else None
|
||||
for _, meta in claimed:
|
||||
trace = Rollout(
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
|
||||
task=error_trace_task(group),
|
||||
agent=vf.AgentInfo(config=vf.AgentConfig()),
|
||||
ok=False,
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
@@ -569,7 +657,7 @@ class RolloutDispatcher:
|
||||
# and us reaching it — synthesize a stand-in from the group state
|
||||
unscheduled_cancelled = 0
|
||||
if group is not None and group.rollouts_to_schedule > 0:
|
||||
fallback_meta = last_meta or InflightRollout(
|
||||
fallback_meta = last_meta or InflightEpisode(
|
||||
kind=group.kind,
|
||||
env_name=group.env_name,
|
||||
group_id=group_id,
|
||||
@@ -579,7 +667,7 @@ class RolloutDispatcher:
|
||||
unscheduled_cancelled = group.rollouts_to_schedule
|
||||
for _ in range(unscheduled_cancelled):
|
||||
trace = Rollout(
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
|
||||
task=error_trace_task(group),
|
||||
agent=vf.AgentInfo(config=vf.AgentConfig()),
|
||||
ok=False,
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
@@ -590,7 +678,7 @@ class RolloutDispatcher:
|
||||
cancelled = inflight_cancelled + unscheduled_cancelled
|
||||
if cancelled > 0:
|
||||
meta_for_log = last_meta or (
|
||||
InflightRollout(
|
||||
InflightEpisode(
|
||||
kind=group.kind,
|
||||
env_name=group.env_name,
|
||||
group_id=group_id,
|
||||
@@ -611,8 +699,8 @@ class RolloutDispatcher:
|
||||
await safe_cancel_all(tasks_to_cancel)
|
||||
return cancelled
|
||||
|
||||
async def cancel_inflight_rollouts(self) -> None:
|
||||
"""Cancel all in-flight rollouts. Used on shutdown — doesn't emit
|
||||
async def cancel_inflight_episodes(self) -> None:
|
||||
"""Cancel all in-flight episodes. Used on shutdown — doesn't emit
|
||||
markers since the sinks are being torn down anyway."""
|
||||
for meta in self.inflight.values():
|
||||
self.metrics.record_cancellation(kind=meta.kind, env_name=meta.env_name)
|
||||
@@ -623,8 +711,8 @@ class RolloutDispatcher:
|
||||
if tasks:
|
||||
await safe_cancel_all(tasks)
|
||||
|
||||
async def cancel_inflight_train_rollouts(self) -> int:
|
||||
"""Cancel in-flight train rollouts, leaving eval alone. Used by the
|
||||
async def cancel_inflight_train_episodes(self) -> int:
|
||||
"""Cancel in-flight train episodes, leaving eval alone. Used by the
|
||||
orchestrator at ``max_steps`` so triggered eval can still complete
|
||||
through the pipeline while wasted train inference is short-circuited."""
|
||||
train_tasks: list[asyncio.Task] = []
|
||||
@@ -650,11 +738,10 @@ class RolloutDispatcher:
|
||||
def gauges(self) -> dict[str, float]:
|
||||
"""Instantaneous, read-only gauges sampled by the periodic logger."""
|
||||
return {
|
||||
"dispatcher/inflight_train": float(self.inflight_train_count),
|
||||
"dispatcher/inflight_eval": float(self.inflight_eval_count),
|
||||
"dispatcher/inflight/train": float(self.inflight_train_count),
|
||||
"dispatcher/inflight/eval": float(self.inflight_eval_count),
|
||||
"dispatcher/queued/eval": float(self.queued_eval_examples),
|
||||
"dispatcher/mode": float(self.mode == DispatcherMode.PREFER_EVAL),
|
||||
"dispatcher/groups_in_flight": float(len(self.groups)),
|
||||
"dispatcher/off_policy_level_max": float(self.max_off_policy_level),
|
||||
"dispatcher/off_policy_level_mean": self.mean_off_policy_level,
|
||||
"dispatcher/off_policy_level/max": float(self.max_off_policy_level),
|
||||
"dispatcher/off_policy_level/mean": self.mean_off_policy_level,
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ once, and each dispatched episode ships its task's data on the request
|
||||
(``task_data``); the server pydantic-validates it into the taskset's declared
|
||||
``TaskData`` type and runs it. That keeps the server (and every worker in its
|
||||
pool) stateless about data — no per-worker dataset loads, no idx-addressed task
|
||||
cache — and gives the orchestrator real tasks to cycle, shuffle, and filter.
|
||||
cache — and gives the orchestrator real tasks to sample.
|
||||
|
||||
The server answers one ``Episode`` per run request, whose traces we validate into
|
||||
``Trace[WireTaskData]`` — real ``vf.Trace``\\ s (never loose dicts) whose task
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""EvalSink: three-level rollout sink for eval epochs.
|
||||
|
||||
Same shape as ``TrainSink``, but no tokenization / advantages / filters:
|
||||
Same shape as ``TrainSink``, but no tokenization, advantages, or admission:
|
||||
|
||||
1. ``process_rollout`` — no-op.
|
||||
2. ``process_group`` — at ``group_size`` episodes, move the rollouts
|
||||
|
||||
@@ -43,15 +43,17 @@ class EvalSource:
|
||||
# trigger fires every env (subject to ``skip_first_step``)
|
||||
self.first_trigger = not is_resumed
|
||||
|
||||
def trigger(self, step: int) -> list[str]:
|
||||
def trigger(self, step: int, *, force: bool = False) -> list[str]:
|
||||
"""Fire eligible envs for ``step`` and return their names. On resume
|
||||
``first_trigger`` is False, so the startup/base eval doesn't re-run."""
|
||||
``first_trigger`` is False, so the startup/base eval doesn't re-run.
|
||||
``force`` fires every env regardless of interval (e.g. the evaluator's
|
||||
final-checkpoint eval)."""
|
||||
is_first, self.first_trigger = self.first_trigger, False
|
||||
if is_first and self.eval_config.skip_first_step:
|
||||
return []
|
||||
fired: list[str] = []
|
||||
for name, interval in self.intervals.items():
|
||||
if is_first or step % interval == 0:
|
||||
if is_first or force or step % interval == 0:
|
||||
fired.append(name)
|
||||
# Round-robin across fired envs (A₁, B₁, A₂, B₂, …) so the
|
||||
# dispatcher rotates at example granularity. ``try_schedule``'s
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
"""Online evaluator: disk-checkpoint-driven evals against a live inference server.
|
||||
|
||||
The trainer writes HF weight checkpoints to ``weights/step_{n}`` (``STABLE``
|
||||
marker on completion) — that is its signal that a new policy is ready. The
|
||||
evaluator watches the directory, tells the inference server to reload each
|
||||
eligible checkpoint from disk (``/update_weights``, no NCCL rendezvous), and
|
||||
runs the configured evals against the updated weights, sequentially per
|
||||
checkpoint so every epoch measures exactly one policy version.
|
||||
|
||||
Reuses the orchestrator's eval components — ``EvalEnvs`` / ``EvalSource`` /
|
||||
``EvalSink`` / ``EvalRollouts`` — and logs metrics and episodes through the same
|
||||
monitors (``eval/{env}/...`` metrics, episode traces via the file monitor).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.evaluator import EvaluatorConfig
|
||||
from prime_rl.orchestrator.envs import EvalEnv, EvalEnvs
|
||||
from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
monkey_patch_oai_iterable_types,
|
||||
)
|
||||
from prime_rl.orchestrator.types import EvalBatch, Rollout
|
||||
from prime_rl.orchestrator.utils import group_episodes, intercept_vf_logging, set_default_executor
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_step_path
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
monkey_patch_oai_iterable_types()
|
||||
monkey_patch_chat_completion_logprobs()
|
||||
|
||||
# How often to re-scan the weights directory for new checkpoints.
|
||||
POLL_INTERVAL_S = 2.0
|
||||
|
||||
|
||||
class Evaluator:
|
||||
def __init__(self, config: EvaluatorConfig) -> None:
|
||||
self.config = config
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
get_logger().info(f"Starting evaluator (weights_dir={config.weights_dir})")
|
||||
|
||||
# The last weight-checkpoint step already handled (evaluated or skipped).
|
||||
self.last_step = config.resume_step or 0
|
||||
self.eval_triggered_at: dict[tuple[str, int], float] = {}
|
||||
|
||||
async def setup(self) -> None:
|
||||
config = self.config
|
||||
set_default_executor()
|
||||
|
||||
get_logger().info(f"Initializing monitors ({config.monitors})")
|
||||
await monitors.setup(
|
||||
wandb=config.monitors.wandb,
|
||||
file=config.monitors.file,
|
||||
output_dir=config.output_dir,
|
||||
run_config=config,
|
||||
eval_env_names=[source.resolved_name for source in config.eval.source],
|
||||
overview_flavor="sft",
|
||||
)
|
||||
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
|
||||
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
|
||||
self.run_name = os.environ.get("PRL_RUN_NAME")
|
||||
|
||||
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
|
||||
self.pool = InferencePool(config.eval.client, model_name=config.model)
|
||||
|
||||
get_logger().info("Loading eval environment(s)")
|
||||
self.eval_envs = EvalEnvs(config.eval.source, config.eval.env_addresses)
|
||||
await self.eval_envs.start()
|
||||
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
|
||||
|
||||
get_logger().info("Waiting for inference pool to be ready")
|
||||
await self.pool.wait_for_ready(config.model)
|
||||
get_logger().success("Inference pool ready")
|
||||
|
||||
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=config.resume_step is not None)
|
||||
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
|
||||
|
||||
async def run(self) -> None:
|
||||
await self.setup()
|
||||
config = self.config
|
||||
|
||||
if config.resume_step is None:
|
||||
# Base-model eval: the inference server starts with the untrained weights,
|
||||
# so no reload is needed. The first trigger fires every env (policy v0)
|
||||
# unless ``skip_first_step``.
|
||||
await self.maybe_run_evals(step=0)
|
||||
elif config.eval.retrigger_on_resume:
|
||||
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
|
||||
# evals). Requires the resume step's weights on disk. The final checkpoint
|
||||
# force-fires every env, exactly like the watch loop below.
|
||||
is_final = config.max_steps is not None and config.resume_step >= config.max_steps
|
||||
await self.maybe_run_evals(step=config.resume_step, reload_weights=True, force=is_final)
|
||||
|
||||
get_logger().info(f"Watching {config.weights_dir} for new weight checkpoints (max_steps={config.max_steps})")
|
||||
while True:
|
||||
assert config.weights_dir is not None # resolved by the config validator
|
||||
steps = get_all_ckpt_steps(config.weights_dir)
|
||||
stable = {step: (get_step_path(config.weights_dir, step) / "STABLE").exists() for step in steps}
|
||||
newest_stable = max((step for step in steps if stable[step]), default=None)
|
||||
# Also walk eval-due steps that are no longer on disk: checkpoint cleaning
|
||||
# (ckpt.keep_last / keep_interval) can delete a step before this scan sees
|
||||
# it, and a vanished step would otherwise be skipped without a trace.
|
||||
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_stable)):
|
||||
if step <= self.last_step:
|
||||
continue
|
||||
if step not in stable:
|
||||
get_logger().warning(
|
||||
f"Weight checkpoint for eval step {step} was deleted before it could be "
|
||||
"evaluated (checkpoint cleaning outpaced the evaluator) - skipping its evals"
|
||||
)
|
||||
self.last_step = max(self.last_step, step)
|
||||
continue
|
||||
if not stable[step]:
|
||||
# The trainer writes checkpoints in ascending order, so a marker-less
|
||||
# step below a stable one is an abandoned partial write (e.g. a crash
|
||||
# mid-save), not one in progress — skip it instead of wedging on it.
|
||||
if newest_stable is None or newest_stable < step:
|
||||
break # still being written — later steps can't be ready either
|
||||
get_logger().warning(
|
||||
f"Weight checkpoint step {step} has no STABLE marker but newer stable "
|
||||
"checkpoints exist - treating it as abandoned and skipping its evals"
|
||||
)
|
||||
self.last_step = max(self.last_step, step)
|
||||
continue
|
||||
is_final = config.max_steps is not None and step >= config.max_steps
|
||||
await self.maybe_run_evals(step=step, reload_weights=True, force=is_final)
|
||||
if config.max_steps is not None and self.last_step >= config.max_steps:
|
||||
break
|
||||
await asyncio.sleep(POLL_INTERVAL_S)
|
||||
|
||||
get_logger().success("Evaluator finished!")
|
||||
|
||||
def deleted_due_steps(self, steps: list[int], newest_stable: int | None) -> set[int]:
|
||||
"""Eval-due steps up to the newest stable checkpoint that are missing from the
|
||||
weights dir — the trainer wrote them (it saves at every due step), so their
|
||||
absence means checkpoint cleaning removed them before they were evaluated."""
|
||||
if newest_stable is None:
|
||||
return set()
|
||||
due = {
|
||||
step
|
||||
for interval in self.eval_source.intervals.values()
|
||||
for step in range(interval, newest_stable + 1, interval)
|
||||
}
|
||||
return due - set(steps)
|
||||
|
||||
async def maybe_run_evals(self, step: int, *, reload_weights: bool = False, force: bool = False) -> None:
|
||||
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
|
||||
reloading the inference weights first. No-op when no env is due."""
|
||||
assert self.config.weights_dir is not None # resolved by the config validator
|
||||
weight_dir = get_step_path(self.config.weights_dir, step)
|
||||
if reload_weights and not (weight_dir / "STABLE").exists():
|
||||
get_logger().warning(f"No stable weight checkpoint for step {step} ({weight_dir}) - skipping eval")
|
||||
self.last_step = max(self.last_step, step)
|
||||
return
|
||||
|
||||
fired = self.eval_source.trigger(step, force=force)
|
||||
self.last_step = max(self.last_step, step)
|
||||
if not fired:
|
||||
return
|
||||
|
||||
now = time.perf_counter()
|
||||
for env_name in fired:
|
||||
self.eval_triggered_at[(env_name, step)] = now
|
||||
total_rollouts = sum(
|
||||
self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
|
||||
for env_name in fired
|
||||
)
|
||||
|
||||
if reload_weights:
|
||||
get_logger().info(f"Updating inference weights to checkpoint step {step} ({weight_dir})")
|
||||
try:
|
||||
await self.pool.update_weights(weight_dir, step=step)
|
||||
except Exception as exc:
|
||||
# Skip this step instead of killing the run; drain the queued examples
|
||||
# so they don't leak into a later epoch with the wrong eval_step.
|
||||
while self.eval_source.next_example() is not None:
|
||||
pass
|
||||
get_logger().error(f"Failed to update inference weights to step {step} - skipping evals: {exc!r}")
|
||||
return
|
||||
|
||||
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
|
||||
await self.run_evals(step)
|
||||
|
||||
async def run_evals(self, step: int) -> None:
|
||||
"""Drain the eval queue for one step under bounded concurrency, routing
|
||||
finished episodes through the sink and finalizing each env's epoch."""
|
||||
semaphore = asyncio.Semaphore(self.config.eval.max_inflight_episodes)
|
||||
tasks: list[asyncio.Task] = []
|
||||
while (example := self.eval_source.next_example()) is not None:
|
||||
env = self.eval_envs.get(example["env_name"])
|
||||
group_id = uuid.uuid4()
|
||||
for _ in range(env.config.group_size):
|
||||
tasks.append(asyncio.create_task(self.run_episode(env, example, group_id, step, semaphore)))
|
||||
|
||||
for future in asyncio.as_completed(tasks):
|
||||
episode = await future
|
||||
run = vf.EvalRunInfo(id=self.run_id, name=self.run_name, step=step)
|
||||
for rollout in episode:
|
||||
rollout.record_run(
|
||||
run,
|
||||
env_name=rollout.env_name,
|
||||
group_id=str(rollout.group_id),
|
||||
episode_id=rollout.episode_id,
|
||||
policy_version=rollout.policy_version,
|
||||
)
|
||||
await monitors.log(group_episodes(episode), step, "eval", "all")
|
||||
eval_batch = self.eval_sink.add(episode)
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
|
||||
async def run_episode(
|
||||
self,
|
||||
env: EvalEnv,
|
||||
example: dict,
|
||||
group_id: uuid.UUID,
|
||||
step: int,
|
||||
semaphore: asyncio.Semaphore,
|
||||
) -> list[Rollout]:
|
||||
"""Run one episode against the env server; failures synthesize an
|
||||
error-marker rollout so the sink's count-based finalization still fires."""
|
||||
async with semaphore:
|
||||
try:
|
||||
rollouts = await env.run(
|
||||
client=self.pool.eval_client,
|
||||
model_name=self.pool.model_name,
|
||||
cache_salt=str(step),
|
||||
task_data=example["task"].data.model_dump(mode="json"),
|
||||
)
|
||||
except Exception as exc:
|
||||
get_logger().warning(f"Rollout task failed in group {group_id} ({env.name}): {exc!r}")
|
||||
rollout = Rollout(
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=example["task"].data.idx, prompt=None)),
|
||||
agent=vf.AgentInfo(config=vf.AgentConfig()),
|
||||
)
|
||||
rollout.record_error(exc)
|
||||
rollouts = [rollout]
|
||||
|
||||
for rollout in rollouts:
|
||||
if not rollout.has_error and rollout.num_turns == 0:
|
||||
rollout.errors.append(
|
||||
vf.Error(type="EmptyTrajectory", message="Rollout returned with no trajectory steps")
|
||||
)
|
||||
rollout.ok = False
|
||||
get_logger().warning(f"Empty trajectory in group {group_id} ({env.name})")
|
||||
rollout.kind = "eval"
|
||||
rollout.env_name = env.name
|
||||
rollout.group_id = group_id
|
||||
# For SFT-driven evals the policy version *is* the checkpoint step.
|
||||
rollout.policy_version = step
|
||||
rollout.eval_step = step
|
||||
return rollouts
|
||||
|
||||
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
|
||||
"""Persist + log one completed eval epoch through the monitors, mirroring the
|
||||
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
|
||||
if not batch.rollouts:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
|
||||
return
|
||||
|
||||
await monitors.log(group_episodes(batch.rollouts.effective.rollouts), batch.step, "eval", "effective")
|
||||
|
||||
rollouts = batch.rollouts
|
||||
effective = rollouts.effective
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", rollouts), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
|
||||
metrics["step"] = float(batch.step)
|
||||
await monitors.log(metrics, step=batch.step)
|
||||
|
||||
eff, full = effective.metrics, rollouts.metrics
|
||||
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
|
||||
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
|
||||
pool = getattr(self, "pool", None)
|
||||
if pool is not None:
|
||||
await pool.stop()
|
||||
|
||||
|
||||
@clean_exit
|
||||
async def run_evaluator(config: EvaluatorConfig) -> None:
|
||||
evaluator = Evaluator(config)
|
||||
try:
|
||||
await evaluator.run()
|
||||
# Finalize only on a clean exit — a crashed evaluator must not mark the run completed.
|
||||
await monitors.finalize()
|
||||
finally:
|
||||
await evaluator.stop()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
set_proc_title("Evaluator")
|
||||
asyncio.run(run_evaluator(cli(EvaluatorConfig)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,172 +0,0 @@
|
||||
"""Orchestrator-side rollout filters for detecting degenerate generations.
|
||||
|
||||
Filters run after rollouts complete, inspecting token IDs and logprobs to
|
||||
detect gibberish or repetition. Detection metrics are always tracked.
|
||||
When enforce=True, detected rollouts are skipped entirely during training and
|
||||
are not sent to the trainer. Reward is kept as-is for baseline calculation.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Protocol
|
||||
|
||||
from prime_rl.configs.orchestrator import FilterConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
@dataclass
|
||||
class FilterResult:
|
||||
detected: bool
|
||||
|
||||
|
||||
class RolloutFilter(Protocol):
|
||||
name: str
|
||||
enforce: bool
|
||||
|
||||
def check(self, rollout: Rollout) -> FilterResult: ...
|
||||
|
||||
|
||||
@dataclass
|
||||
class GibberishFilter:
|
||||
"""Flags rollouts containing rare tokens generated at high entropy.
|
||||
|
||||
A token is flagged when both:
|
||||
- id(token) > token_id_threshold (rare BPE token)
|
||||
- logprob(token) < -log(vocab_size) - logprob_offset (high entropy)
|
||||
|
||||
References:
|
||||
Section 5.2, https://arxiv.org/abs/2510.02387
|
||||
"""
|
||||
|
||||
name: str
|
||||
token_id_threshold: int
|
||||
logprob_threshold: float
|
||||
enforce: bool = False
|
||||
|
||||
def check(self, rollout: Rollout) -> FilterResult:
|
||||
for branch in rollout.branches:
|
||||
# branch.{token_ids,logprobs,sampled_mask} are flat and mutually aligned; the raw
|
||||
# node arrays are not (node.logprobs covers only the sampled suffix, not the
|
||||
# generation-prompt scaffold that token_ids/mask also span).
|
||||
for token_id, logprob, sampled in zip(branch.token_ids, branch.logprobs, branch.sampled_mask):
|
||||
if not sampled:
|
||||
continue
|
||||
if token_id > self.token_id_threshold and logprob < self.logprob_threshold:
|
||||
return FilterResult(detected=True)
|
||||
return FilterResult(detected=False)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RepetitionFilter:
|
||||
"""Flags rollouts with pathological repetition loops.
|
||||
|
||||
Counts consecutive tokens where logprob > log(prob_threshold), indicating
|
||||
the model is generating with very high confidence. When the streak reaches
|
||||
the window size, the rollout is flagged.
|
||||
|
||||
References:
|
||||
Section 3.2, https://arxiv.org/abs/2506.13585
|
||||
"""
|
||||
|
||||
name: str
|
||||
window: int
|
||||
logprob_threshold: float
|
||||
enforce: bool = False
|
||||
|
||||
def check(self, rollout: Rollout) -> FilterResult:
|
||||
for branch in rollout.branches:
|
||||
# Aligned branch streams (see GibberishFilter), and reset the streak per branch:
|
||||
# flat rollout.nodes interleaves distinct root->leaf paths (compaction/subagents),
|
||||
# so a per-node walk would run a streak across a branch boundary.
|
||||
consecutive = 0
|
||||
for logprob, sampled in zip(branch.logprobs, branch.sampled_mask):
|
||||
if not sampled:
|
||||
continue
|
||||
if logprob > self.logprob_threshold:
|
||||
consecutive += 1
|
||||
else:
|
||||
consecutive = 0
|
||||
if consecutive >= self.window:
|
||||
return FilterResult(detected=True)
|
||||
return FilterResult(detected=False)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZeroAdvantageFilter:
|
||||
"""Flags rollouts whose advantage stream is all zero (e.g. all rollouts in
|
||||
a GRPO group earned the same reward, so the centered advantage collapses)."""
|
||||
|
||||
name: str
|
||||
enforce: bool = True
|
||||
|
||||
def check(self, rollout: Rollout) -> FilterResult:
|
||||
if rollout.advantages is not None and all(a == 0.0 for a in rollout.advantages):
|
||||
return FilterResult(detected=True)
|
||||
return FilterResult(detected=False)
|
||||
|
||||
|
||||
def setup_filter(config: FilterConfig, vocab_size: int) -> RolloutFilter:
|
||||
"""Create a RolloutFilter from a filter config."""
|
||||
if config.type == "gibberish":
|
||||
return GibberishFilter(
|
||||
name="gibberish",
|
||||
token_id_threshold=config.token_id_threshold,
|
||||
logprob_threshold=-math.log(vocab_size) - config.logprob_offset,
|
||||
enforce=config.enforce,
|
||||
)
|
||||
elif config.type == "repetition":
|
||||
return RepetitionFilter(
|
||||
name="repetition",
|
||||
window=config.window,
|
||||
logprob_threshold=math.log(config.prob_threshold),
|
||||
enforce=config.enforce,
|
||||
)
|
||||
elif config.type == "zero_advantage":
|
||||
return ZeroAdvantageFilter(
|
||||
name="zero_advantage",
|
||||
enforce=config.enforce,
|
||||
)
|
||||
raise ValueError(f"Unknown filter type: {config.type}")
|
||||
|
||||
|
||||
def setup_filters(configs: list[FilterConfig], vocab_size: int, *, kind: str) -> list[RolloutFilter]:
|
||||
"""Create RolloutFilters from a list of filter configs."""
|
||||
filters = [setup_filter(config, vocab_size) for config in configs]
|
||||
if filters:
|
||||
get_logger().info(f"Configured {len(filters)} {kind} rollout filter(s):")
|
||||
for config, filt in zip(configs, filters):
|
||||
mode = "Enforcing" if filt.enforce else "Monitoring"
|
||||
params = ", ".join(f"{k}={v}" for k, v in config.model_dump().items())
|
||||
get_logger().info(f" {mode} {filt.name} filter ({params})")
|
||||
return filters
|
||||
|
||||
|
||||
def apply_filters(filters: list[RolloutFilter], rollouts: list[Rollout]) -> None:
|
||||
"""Flag ``Rollout``\\ s in place with per-filter detection + drop decision.
|
||||
|
||||
Each rollout's ``filter_results`` dict records per-filter detection bools;
|
||||
``is_filtered`` is True iff an enforcing filter detected it. First matching
|
||||
filter wins per rollout (no double-counting). Reward and trajectory tokens
|
||||
are left untouched so the rollout can still contribute to baseline
|
||||
calculations and metric aggregation.
|
||||
"""
|
||||
for rollout in rollouts:
|
||||
rollout.filter_results = {f.name: False for f in filters}
|
||||
rollout.is_filtered = False
|
||||
|
||||
if not filters:
|
||||
return
|
||||
|
||||
for rollout in rollouts:
|
||||
for filt in filters:
|
||||
result = filt.check(rollout)
|
||||
if result.detected:
|
||||
rollout.filter_results[filt.name] = True
|
||||
if filt.enforce:
|
||||
rollout.is_filtered = True
|
||||
break
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import math
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from statistics import mean, median
|
||||
|
||||
@@ -10,16 +11,16 @@ import wandb
|
||||
from httpx import AsyncClient
|
||||
from prometheus_client.parser import text_string_to_metric_families
|
||||
|
||||
from prime_rl.orchestrator.concurrency import EngineLoadSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
POLL_INTERVAL = 5.0
|
||||
FETCH_TIMEOUT = 5.0
|
||||
METRIC_PREFIX = "vllm:"
|
||||
CACHE_CONFIG_FAMILY = "vllm:cache_config_info"
|
||||
PD_ROLES = {"prefill", "decode"}
|
||||
QUANTILES = {"p50": 0.5, "p90": 0.9, "p99": 0.99}
|
||||
AGGREGATIONS = {"min": min, "max": max, "sum": sum, "mean": mean, "median": median}
|
||||
OVERLOAD_WAITING_FRACTION = 0.2
|
||||
OVERLOAD_WARN_INTERVAL = 60.0
|
||||
|
||||
# Scope-level ratios derived from counter deltas; each operand lists legacy and
|
||||
# OpenMetrics sample names, whichever the running vLLM version emits.
|
||||
@@ -50,6 +51,8 @@ class EngineSnapshot:
|
||||
gauges: dict[str, float] = field(default_factory=dict)
|
||||
counters: dict[str, float] = field(default_factory=dict)
|
||||
histograms: dict[str, HistogramSnapshot] = field(default_factory=dict)
|
||||
cache_config: dict[str, str] = field(default_factory=dict)
|
||||
"""Labels of ``vllm:cache_config_info`` (e.g. ``num_gpu_blocks``, ``block_size``)."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -92,7 +95,14 @@ def parse_prometheus_text(text: str) -> dict[str, EngineSnapshot]:
|
||||
if sample.name.endswith("_created") or not math.isfinite(sample.value):
|
||||
continue
|
||||
engine = engines.setdefault(sample.labels.get("engine", "0"), EngineSnapshot())
|
||||
if family.name == CACHE_CONFIG_FAMILY:
|
||||
engine.cache_config.update(sample.labels)
|
||||
continue
|
||||
name = sample.name.removeprefix(METRIC_PREFIX)
|
||||
# Keep the queue-reason breakdown instead of summing it away — the
|
||||
# concurrency controller keys on capacity-queued requests
|
||||
if name == "num_requests_waiting_by_reason":
|
||||
name = f"num_requests_waiting_reason_{sample.labels.get('reason', 'unknown')}"
|
||||
if family.type == "gauge":
|
||||
engine.gauges[name] = engine.gauges.get(name, 0.0) + sample.value
|
||||
elif family.type == "counter":
|
||||
@@ -268,28 +278,31 @@ class InferenceMetricsCollector:
|
||||
self,
|
||||
admin_clients: list[AsyncClient],
|
||||
roles: list[str | None] | None = None,
|
||||
max_inflight_episodes: int | None = None,
|
||||
on_load: Callable[[list[EngineLoadSample]], None] | None = None,
|
||||
log_to_wandb: bool = True,
|
||||
):
|
||||
self.endpoints = build_metrics_endpoints(admin_clients, roles=roles)
|
||||
self.previous: dict[tuple[str, str], TimedSnapshot] = {}
|
||||
self.max_model_len_by_endpoint: dict[str, int] = {}
|
||||
self.task: asyncio.Task | None = None
|
||||
self.has_pd_roles = {endpoint.role for endpoint in self.endpoints if endpoint.role is not None} == PD_ROLES
|
||||
self.max_inflight_episodes = max_inflight_episodes
|
||||
self.last_overload_warning = float("-inf")
|
||||
self.on_load = on_load
|
||||
self.log_to_wandb = log_to_wandb
|
||||
get_logger().info(
|
||||
"Collecting inference metrics from "
|
||||
+ ", ".join(f"{endpoint.name}={endpoint.key}" for endpoint in self.endpoints)
|
||||
)
|
||||
|
||||
async def start(self):
|
||||
wandb.define_metric("inference/*", step_metric="_timestamp")
|
||||
if self.log_to_wandb:
|
||||
wandb.define_metric("inference/*", step_metric="_timestamp")
|
||||
|
||||
async def poll_loop():
|
||||
while True:
|
||||
try:
|
||||
await self.collect_and_log()
|
||||
except Exception as e:
|
||||
get_logger().debug(f"Inference metrics poll failed: {e!r}")
|
||||
get_logger().warning(f"Inference metrics poll failed: {e!r}")
|
||||
await asyncio.sleep(POLL_INTERVAL)
|
||||
|
||||
self.task = asyncio.create_task(poll_loop())
|
||||
@@ -316,28 +329,74 @@ class InferenceMetricsCollector:
|
||||
if not samples:
|
||||
return
|
||||
|
||||
metrics = self.build_metrics(samples)
|
||||
await asyncio.gather(*[self.fetch_max_model_len(endpoint) for endpoint in self.endpoints])
|
||||
metrics = self.build_metrics(samples) if self.log_to_wandb else {}
|
||||
load_samples = [self.build_load_sample(sample) for sample in samples]
|
||||
for sample in samples:
|
||||
self.previous[sample.key] = TimedSnapshot(timestamp=sample.timestamp, snapshot=sample.snapshot)
|
||||
|
||||
waiting_requests = metrics.get("inference/agg/num_requests_waiting/sum", 0.0)
|
||||
if (
|
||||
self.max_inflight_episodes is not None
|
||||
and waiting_requests > OVERLOAD_WAITING_FRACTION * self.max_inflight_episodes
|
||||
and now - self.last_overload_warning >= OVERLOAD_WARN_INTERVAL
|
||||
):
|
||||
self.last_overload_warning = now
|
||||
get_logger().warning(
|
||||
f"Inference is overloaded: {waiting_requests:.0f} waiting request(s), more than "
|
||||
f"{OVERLOAD_WAITING_FRACTION:.0%} of max_inflight_episodes={self.max_inflight_episodes} - "
|
||||
"training is slowed by queued requests. If intermittent, wait it out - if persistent, "
|
||||
"lower concurrency by decreasing max_inflight_episodes"
|
||||
)
|
||||
if self.on_load is not None:
|
||||
self.on_load(load_samples)
|
||||
|
||||
if metrics:
|
||||
metrics["_timestamp"] = time.time()
|
||||
wandb.log(metrics)
|
||||
|
||||
async def fetch_max_model_len(self, endpoint: MetricsEndpoint) -> None:
|
||||
"""Cache the engine's max context length from ``/v1/models`` (set
|
||||
explicitly or derived from the model config). Static per engine
|
||||
lifetime; retried next poll on failure."""
|
||||
if endpoint.key in self.max_model_len_by_endpoint:
|
||||
return
|
||||
try:
|
||||
response = await endpoint.client.get("/v1/models", timeout=FETCH_TIMEOUT)
|
||||
response.raise_for_status()
|
||||
lengths = [card.get("max_model_len") for card in response.json().get("data", [])]
|
||||
lengths = [length for length in lengths if length]
|
||||
if lengths:
|
||||
self.max_model_len_by_endpoint[endpoint.key] = max(lengths)
|
||||
except Exception as e:
|
||||
get_logger().debug(f"Failed to fetch max_model_len from {endpoint.client.base_url}: {e!r}")
|
||||
|
||||
def build_load_sample(self, sample: EngineSample) -> EngineLoadSample:
|
||||
"""Raw per-engine load facts for the concurrency controller."""
|
||||
cache_config = sample.snapshot.cache_config
|
||||
kv_capacity_tokens: int | None = None
|
||||
# ``kv_cache_size_tokens`` is authoritative; the ``num_gpu_blocks``
|
||||
# label does not reflect ``num_gpu_blocks_override`` (observed 4x off)
|
||||
size_tokens = cache_config.get("kv_cache_size_tokens", "")
|
||||
num_gpu_blocks, block_size = cache_config.get("num_gpu_blocks", ""), cache_config.get("block_size", "")
|
||||
if size_tokens.isdigit():
|
||||
kv_capacity_tokens = int(size_tokens)
|
||||
elif num_gpu_blocks.isdigit() and block_size.isdigit():
|
||||
kv_capacity_tokens = int(num_gpu_blocks) * int(block_size)
|
||||
|
||||
# First poll has no baseline — a nonzero cumulative counter (e.g. after
|
||||
# an orchestrator restart) is not a fresh preemption
|
||||
previous = self.previous.get(sample.key)
|
||||
preemptions_delta = 0
|
||||
if previous is not None:
|
||||
for name in ("num_preemptions", "num_preemptions_total"):
|
||||
if name in sample.snapshot.counters:
|
||||
delta = sample.snapshot.counters[name] - previous.snapshot.counters.get(name, 0.0)
|
||||
preemptions_delta = max(preemptions_delta, int(delta))
|
||||
|
||||
return EngineLoadSample(
|
||||
engine_id=sample.engine_id,
|
||||
role=sample.endpoint.role,
|
||||
kv_capacity_tokens=kv_capacity_tokens,
|
||||
max_model_len=self.max_model_len_by_endpoint.get(sample.endpoint.key),
|
||||
kv_usage=sample.snapshot.gauges.get("kv_cache_usage_perc", 0.0),
|
||||
running=int(sample.snapshot.gauges.get("num_requests_running", 0.0)),
|
||||
waiting=int(sample.snapshot.gauges.get("num_requests_waiting", 0.0)),
|
||||
waiting_capacity=(
|
||||
int(capacity_waiting)
|
||||
if (capacity_waiting := sample.snapshot.gauges.get("num_requests_waiting_reason_capacity")) is not None
|
||||
else None
|
||||
),
|
||||
preemptions_delta=preemptions_delta,
|
||||
)
|
||||
|
||||
def build_metrics(self, samples: list[EngineSample]) -> dict[str, float]:
|
||||
values_per_engine = [engine_values(sample, self.previous.get(sample.key)) for sample in samples]
|
||||
bucket_deltas_per_engine = [bucket_deltas(sample, self.previous.get(sample.key)) for sample in samples]
|
||||
|
||||
@@ -333,7 +333,7 @@ class EpisodeMetrics:
|
||||
|
||||
|
||||
class TrainMetrics(EpisodeMetrics):
|
||||
"""Common metrics plus the per-agent filter-pipeline rates. ``reward`` (flat over all traces)
|
||||
"""Common metrics plus per-agent pipeline rates. ``reward`` (flat over all traces)
|
||||
serves the console log lines; the wandb reward stats are per-agent."""
|
||||
|
||||
@property
|
||||
@@ -342,18 +342,12 @@ class TrainMetrics(EpisodeMetrics):
|
||||
|
||||
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
|
||||
out = super().to_wandb(prefix=prefix, subset=subset)
|
||||
# The pipeline verdicts are per-trace (an untrainable seat is 0.0 throughout, and filters
|
||||
# only ever run on trainable survivors), so they read per agent like the rest.
|
||||
# Pipeline verdicts are per-trace, so they read per agent like the rest.
|
||||
for agent, traces in self.by_agent().items():
|
||||
p = f"{prefix}/{subset}/{agent}"
|
||||
rollouts = traces.rollouts
|
||||
out[f"{p}/is_trainable/mean"] = sum(float(r.is_trainable) for r in rollouts) / len(rollouts)
|
||||
out[f"{p}/is_filtered/mean"] = sum(float(r.is_filtered) for r in rollouts) / len(rollouts)
|
||||
names = sorted({name for r in rollouts for name in r.filter_results})
|
||||
out |= {
|
||||
f"{p}/filters/{name}/mean": sum(1 for r in rollouts if r.filter_results.get(name)) / len(rollouts)
|
||||
for name in names
|
||||
}
|
||||
out[f"{p}/is_admitted/mean"] = sum(float(r.is_admitted) for r in rollouts) / len(rollouts)
|
||||
return out
|
||||
|
||||
|
||||
@@ -396,8 +390,8 @@ class EvalMetrics(EpisodeMetrics):
|
||||
|
||||
|
||||
class TrainRollouts:
|
||||
"""A list of train rollouts (everything that came back, errored + filtered + untrainable
|
||||
included). ``effective`` is the clean trainable subset (a view of the same traces);
|
||||
"""A list of train rollouts (everything that came back, including rejected,
|
||||
errored and untrainable traces). ``effective`` is the clean trainable subset;
|
||||
``metrics`` builds ``TrainMetrics`` over them."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout] | None = None) -> None:
|
||||
@@ -414,7 +408,7 @@ class TrainRollouts:
|
||||
|
||||
@property
|
||||
def effective(self) -> TrainRollouts:
|
||||
return TrainRollouts([r for r in self.rollouts if not r.has_error and not r.is_filtered and r.agent.trainable])
|
||||
return TrainRollouts([r for r in self.rollouts if r.is_admitted and not r.has_error and r.agent.trainable])
|
||||
|
||||
def by_env(self) -> dict[str, TrainRollouts]:
|
||||
grouped: dict[str, list[Rollout]] = {}
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
``Orchestrator`` owns the shared state (policy, progress, ckpt, monitor)
|
||||
and drives the pipeline. Components are single-purpose:
|
||||
|
||||
- ``RolloutDispatcher`` schedules rollouts; emits ``Rollout`` (train/eval
|
||||
- ``Dispatcher`` schedules rollouts; emits ``Rollout`` (train/eval
|
||||
discriminated by ``kind``) on its queue.
|
||||
- ``TrainSink`` ingests train rollouts (tokenize → advantages → filters)
|
||||
- ``TrainSink`` ingests train rollouts (tokenize → advantages → admission)
|
||||
and returns a ``TrainBatch`` when the threshold is met.
|
||||
- ``EvalSink`` ingests eval rollouts and returns an ``EvalBatch`` (the full
|
||||
returned cohort) on epoch completion.
|
||||
@@ -37,17 +37,17 @@ if TYPE_CHECKING:
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.orchestrator.ckpt import CheckpointManager
|
||||
from prime_rl.transport.base import MicroBatchSender
|
||||
from prime_rl.transports.rollouts.base import MicroBatchSender
|
||||
from prime_rl.utils.client import InferencePool
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
|
||||
from prime_rl.orchestrator.dispatcher import DispatcherMetrics, DispatcherMode, RolloutDispatcher
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
|
||||
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
|
||||
from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.filters import setup_filters
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.packing import BatchPacker
|
||||
from prime_rl.orchestrator.patches import (
|
||||
@@ -74,8 +74,8 @@ from prime_rl.orchestrator.utils import (
|
||||
)
|
||||
from prime_rl.orchestrator.watcher import WeightWatcher
|
||||
from prime_rl.trainer.model import setup_tokenizer
|
||||
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.transport import setup_micro_batch_sender
|
||||
from prime_rl.transports.rollouts import setup_micro_batch_sender
|
||||
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
|
||||
from prime_rl.utils.client import init_nccl_broadcast, init_nixl_broadcast
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
@@ -93,9 +93,7 @@ monkey_patch_chat_completion_logprobs()
|
||||
# shutdown wedges (env-server ZMQ recv, vLLM admin aclose, etc)
|
||||
SHUTDOWN_TIMEOUT_S = 300
|
||||
|
||||
# Abort after this many consecutive train batches drop all rollouts to
|
||||
# post-batch filters — usually a misconfigured filter or homogeneous-reward
|
||||
# dataset; fail loudly instead of spinning
|
||||
# Abort after this many consecutive train batches contain no samples.
|
||||
MAX_CONSECUTIVE_EMPTY_BATCHES = 10
|
||||
|
||||
# Maximum batches the orchestrator may run ahead of the trainer. The
|
||||
@@ -130,7 +128,8 @@ class Orchestrator:
|
||||
train_envs: TrainEnvs
|
||||
train_source: TrainSource
|
||||
train_sink: TrainSink
|
||||
dispatcher: RolloutDispatcher
|
||||
dispatcher: Dispatcher
|
||||
concurrency: ConcurrencyController
|
||||
watcher: WeightWatcher
|
||||
lag_monitor: EventLoopLagMonitor
|
||||
periodic_logger: PeriodicLogger
|
||||
@@ -236,10 +235,6 @@ class Orchestrator:
|
||||
if config.heartbeat is not None:
|
||||
self.heart = Heartbeat(config.heartbeat.url)
|
||||
|
||||
# Filters apply to train rollouts only
|
||||
pre_filters = setup_filters(config.pre_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="pre-batch")
|
||||
post_filters = setup_filters(config.post_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="post-batch")
|
||||
|
||||
get_logger().info("Loading training environments")
|
||||
self.train_envs = TrainEnvs(
|
||||
config.train.source,
|
||||
@@ -281,16 +276,6 @@ class Orchestrator:
|
||||
*(env.algorithm.setup() for env in self.train_envs),
|
||||
)
|
||||
|
||||
# Gate on the registered monitor, not the config - the collector logs to the global
|
||||
# W&B session, which only exists when the monitor's init succeeded.
|
||||
if monitors.get(monitors.WandbMonitor) is not None and config.collect_inference_metrics:
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.policy_inference.admin_clients,
|
||||
roles=config.inference_metrics_roles,
|
||||
max_inflight_episodes=config.max_inflight_episodes,
|
||||
)
|
||||
await self.inference_metrics.start()
|
||||
|
||||
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
if config.weight_broadcast.type == "nccl":
|
||||
await init_nccl_broadcast(
|
||||
@@ -386,20 +371,38 @@ class Orchestrator:
|
||||
else None
|
||||
)
|
||||
|
||||
assert config.max_inflight_episodes is not None, "max_inflight_episodes must be resolved before dispatcher init"
|
||||
log_interval = config.log.interval
|
||||
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
|
||||
self.dispatcher = RolloutDispatcher(
|
||||
|
||||
self.concurrency = ConcurrencyController(config.concurrency, fallback_cost=config.seq_len)
|
||||
self.dispatcher = Dispatcher(
|
||||
train_envs=self.train_envs,
|
||||
eval_envs=self.eval_envs,
|
||||
train_source=self.train_source,
|
||||
eval_source=self.eval_source,
|
||||
policy_pool=self.policy_inference,
|
||||
policy=self.policy,
|
||||
max_inflight_episodes=config.max_inflight_episodes,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
max_inflight_ceiling=config.concurrency.max_inflight,
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
max_off_policy_steps=config.max_off_policy_steps,
|
||||
on_episode_complete=self.concurrency.record_episode,
|
||||
)
|
||||
self.concurrency.bind(
|
||||
set_limit=self.dispatcher.set_limit,
|
||||
get_inflight=lambda: self.dispatcher.current_inflight,
|
||||
on_overload=self.dispatcher.cancel_inflight,
|
||||
)
|
||||
# The collector always polls — it feeds the concurrency controller;
|
||||
# W&B mirroring is gated on the registered monitor (the collector logs
|
||||
# to the global W&B session, which only exists when init succeeded).
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.policy_inference.admin_clients,
|
||||
roles=config.inference_metrics_roles,
|
||||
on_load=self.concurrency.observe,
|
||||
log_to_wandb=wandb_enabled and config.collect_inference_metrics,
|
||||
)
|
||||
await self.inference_metrics.start()
|
||||
self.train_sink = TrainSink(
|
||||
config,
|
||||
tokenizer=self.tokenizer,
|
||||
@@ -407,8 +410,7 @@ class Orchestrator:
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
batch_size=config.batch_size,
|
||||
token_batch_size=config.token_batch_size,
|
||||
pre_filters=pre_filters,
|
||||
post_filters=post_filters,
|
||||
on_result=self.train_source.on_result,
|
||||
)
|
||||
self.eval_sink = EvalSink(eval_envs=self.eval_envs) if self.eval_envs is not None else None
|
||||
self.watcher = WeightWatcher(
|
||||
@@ -428,6 +430,7 @@ class Orchestrator:
|
||||
collect=self.collect_pipeline_view,
|
||||
metric_keys=[
|
||||
*list(self.dispatcher.gauges().keys()),
|
||||
*list(self.concurrency.gauges().keys()),
|
||||
*DispatcherMetrics.drain_keys(
|
||||
train_envs={e.name for e in self.train_envs},
|
||||
eval_envs={e.name for e in self.eval_envs} if self.eval_envs is not None else set(),
|
||||
@@ -486,6 +489,10 @@ class Orchestrator:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
if clean_exit:
|
||||
get_logger().success(f"Orchestrator step loop done in {elapsed}")
|
||||
# The collector logs to the W&B run, so it must stop before
|
||||
# finalize marks the run finished
|
||||
if self.inference_metrics is not None:
|
||||
await self.inference_metrics.stop()
|
||||
# Finalize only on a clean exit — a crashed run must not be marked
|
||||
# completed; the platform run's atexit hook marks it failed instead.
|
||||
await monitors.finalize()
|
||||
@@ -520,7 +527,7 @@ class Orchestrator:
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
|
||||
# Every completed rollout — errored, filtered, or never batched — lands in the
|
||||
# Every completed rollout — errored, rejected, or never batched — lands in the
|
||||
# ``all`` trace file the moment it arrives, so it survives crashes and drains.
|
||||
# Train rollouts belong to the batch window currently collecting (``progress.step``),
|
||||
# eval rollouts to the step whose eval triggered them.
|
||||
@@ -573,9 +580,9 @@ class Orchestrator:
|
||||
if config.max_steps is not None and step > config.max_steps:
|
||||
self.draining = True
|
||||
self.dispatcher.disable_train_scheduling()
|
||||
n_cancelled = await self.dispatcher.cancel_inflight_train_rollouts()
|
||||
n_cancelled = await self.dispatcher.cancel_inflight_train_episodes()
|
||||
get_logger().info(
|
||||
f"Draining pipeline (cancelled {n_cancelled} in-flight train rollout(s); "
|
||||
f"Draining pipeline (cancelled {n_cancelled} in-flight train episode(s); "
|
||||
f"any in-flight evals will complete)"
|
||||
)
|
||||
return
|
||||
@@ -583,14 +590,14 @@ class Orchestrator:
|
||||
if not batch.samples:
|
||||
self.consecutive_empty_batches += 1
|
||||
get_logger().warning(
|
||||
f"Step {step}: empty train batch (0 of {len(batch.rollouts)} generated rollouts shipped — "
|
||||
f"all errored or filtered out) "
|
||||
f"(consecutive empty batches: {self.consecutive_empty_batches}/{MAX_CONSECUTIVE_EMPTY_BATCHES})"
|
||||
f"Step {step}: empty train batch after {len(batch.rollouts)} finalized rollouts "
|
||||
f"(consecutive empty batches: "
|
||||
f"{self.consecutive_empty_batches}/{MAX_CONSECUTIVE_EMPTY_BATCHES})"
|
||||
)
|
||||
if self.consecutive_empty_batches >= MAX_CONSECUTIVE_EMPTY_BATCHES:
|
||||
raise RuntimeError(
|
||||
f"{self.consecutive_empty_batches} consecutive empty train batches — "
|
||||
"check filter config (pre_batch_filters / post_batch_filters) or task difficulty."
|
||||
"check algorithm credit and task difficulty."
|
||||
)
|
||||
return
|
||||
self.consecutive_empty_batches = 0
|
||||
@@ -599,7 +606,7 @@ class Orchestrator:
|
||||
if effective and n_trainable / len(effective) <= 0.1:
|
||||
get_logger().warning(
|
||||
f"Only {n_trainable}/{len(effective)} effective rollouts are trainable "
|
||||
f"({n_trainable / len(effective):.1%}) — consider reviewing task difficulty / filter config"
|
||||
f"({n_trainable / len(effective):.1%}) — consider reviewing task difficulty"
|
||||
)
|
||||
|
||||
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
|
||||
@@ -646,14 +653,14 @@ class Orchestrator:
|
||||
trim_process_memory()
|
||||
|
||||
# Rollout metrics over the {agg,<env>} × {all,effective} matrix. ``batch.rollouts`` is the
|
||||
# full arrival window (errored + filtered included); ``.effective`` is the clean subset.
|
||||
# full arrival window (errored + rejected included); ``.effective`` is the clean subset.
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", batch.rollouts), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
|
||||
for env_name, env_pool in pool.by_env().items():
|
||||
metrics |= env_pool.metrics.to_wandb(prefix=f"train/{env_name}", subset=subset)
|
||||
|
||||
# Progress / timing / env-share / pre-filter accounting (assembled here, not in the metrics
|
||||
# Progress / timing / env-share accounting (assembled here, not in the metrics
|
||||
# objects). ``num_tokens`` is over the full arrival window; the input/output breakdown is over
|
||||
# the effective (shipped) subset, summing the same ``vf.Trace`` token properties the metric
|
||||
# matrix reports.
|
||||
@@ -679,12 +686,7 @@ class Orchestrator:
|
||||
}
|
||||
for env_name, env_pool in batch.rollouts.by_env().items():
|
||||
metrics[f"batch/{env_name}"] = len(env_pool) / len(batch.rollouts)
|
||||
if self.train_sink.pre_filter_seen > 0:
|
||||
metrics["pre_filters/all/dropped_rate"] = (
|
||||
self.train_sink.pre_filter_dropped / self.train_sink.pre_filter_seen
|
||||
)
|
||||
for name, count in self.train_sink.pre_filter_dropped_by_name.items():
|
||||
metrics[f"pre_filters/all/{name}/rate"] = count / self.train_sink.pre_filter_seen
|
||||
metrics |= self.train_source.metrics()
|
||||
await monitors.log(metrics, step=step)
|
||||
self.wait_for_policy_time = 0.0
|
||||
|
||||
@@ -697,7 +699,6 @@ class Orchestrator:
|
||||
|
||||
self.log_train_batch(batch, step=step, step_time=step_time)
|
||||
|
||||
self.train_sink.reset_pre_filter_stats()
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
trim_process_memory()
|
||||
|
||||
@@ -715,11 +716,11 @@ class Orchestrator:
|
||||
for env_name in fired:
|
||||
self.eval_triggered_at[(env_name, step)] = now
|
||||
assert self.eval_envs is not None
|
||||
total_rollouts = sum(
|
||||
self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
|
||||
census = {
|
||||
env_name: self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
|
||||
for env_name in fired
|
||||
)
|
||||
get_logger().info(f"Starting evals in {', '.join(fired)} ({total_rollouts} total rollouts)")
|
||||
}
|
||||
get_logger().info(f"Starting evals in {', '.join(fired)} ({sum(census.values())} total rollouts)")
|
||||
|
||||
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
|
||||
"""Pipeline view for the orchestrator's ``PeriodicLogger``. Returns
|
||||
@@ -762,7 +763,7 @@ class Orchestrator:
|
||||
# Unified inflight tail: total, then train/eval split, then per-env
|
||||
# (only when more than one env of a kind makes the split ambiguous)
|
||||
inflight_part = (
|
||||
f"{inflight_train + inflight_eval} inflight rollouts (train={inflight_train}, eval={inflight_eval}"
|
||||
f"{inflight_train + inflight_eval} inflight episodes (train={inflight_train}, eval={inflight_eval}"
|
||||
)
|
||||
if multi_train or multi_eval:
|
||||
env_pairs = [(e.name, inflight_by_env.get(("train", e.name), 0)) for e in self.train_envs]
|
||||
@@ -773,7 +774,7 @@ class Orchestrator:
|
||||
|
||||
body = train_batch_part + eval_batch_part + "; " + inflight_part
|
||||
|
||||
payload: dict[str, float] = {**disp_gauges, **disp_drain, **watcher_gauges}
|
||||
payload: dict[str, float] = {**disp_gauges, **disp_drain, **watcher_gauges, **self.concurrency.gauges()}
|
||||
if lag_stats.n > 0:
|
||||
payload["event_loop_lag/min"] = lag_stats.min
|
||||
payload["event_loop_lag/mean"] = lag_stats.mean
|
||||
|
||||
@@ -2,7 +2,7 @@ from transformers import AutoConfig
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
|
||||
from prime_rl.transport.types import MicroBatch, TrainingSample
|
||||
from prime_rl.transports.rollouts.types import MicroBatch, TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
dispatcher producing more rollouts), then the env algorithm's
|
||||
``finalize_rollout`` (rollout-local scoring + any reference I/O). Errored
|
||||
and untrainable rollouts skip this.
|
||||
2. ``process_group`` — filters errored rollouts, hands the trainable
|
||||
2. ``process_group`` — removes errored rollouts, hands the trainable
|
||||
survivors to the env algorithm's ``finalize_group`` (advantages +
|
||||
per-sample wire stamping), runs the pre-batch filter pass.
|
||||
3. ``process_batch`` — applies post-batch filter annotations and assembles
|
||||
the trainer-bound ``TrainingSample`` list. Returns a ``TrainBatch``.
|
||||
per-sample wire stamping), then asks the source curriculum whether the
|
||||
result should train.
|
||||
3. ``process_batch`` — assembles the trainer-bound ``TrainingSample`` list
|
||||
and optionally removes zero-advantage RL payload.
|
||||
|
||||
``add()`` takes one episode (``list[Rollout]``) and returns
|
||||
``TrainBatch | None``; group accounting counts episodes, never loose traces.
|
||||
@@ -21,16 +22,18 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.envs import TrainEnvs
|
||||
from prime_rl.orchestrator.filters import RolloutFilter, apply_filters
|
||||
from prime_rl.orchestrator.metrics import TrainRollouts
|
||||
from prime_rl.orchestrator.trajectories import trace_to_samples
|
||||
from prime_rl.orchestrator.types import Rollout, TrainBatch
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.transports.rollouts import TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS = 10
|
||||
|
||||
|
||||
def payload_tokens(rollout: Rollout) -> int:
|
||||
"""Token cost of the rollout's trainer-bound payload — the samples built by
|
||||
@@ -45,6 +48,38 @@ def payload_tokens(rollout: Rollout) -> int:
|
||||
return sum(len(sample.token_ids) for sample in rollout.samples) or rollout.num_total_tokens
|
||||
|
||||
|
||||
def _prune_zero_advantages(sample: TrainingSample) -> bool:
|
||||
"""Remove zero-advantage tokens from the RL component.
|
||||
|
||||
Return whether the sample still carries any RL, CE, or reference-KL
|
||||
component and therefore needs to be shipped.
|
||||
"""
|
||||
if sample.advantages is None:
|
||||
return True
|
||||
|
||||
if sample.rl_weights is None:
|
||||
rl_weights = [1.0 if trainable else 0.0 for trainable in sample.mask]
|
||||
else:
|
||||
rl_weights = list(sample.rl_weights)
|
||||
|
||||
changed = False
|
||||
for index, (trainable, advantage, weight) in enumerate(
|
||||
zip(sample.mask, sample.advantages, rl_weights, strict=True)
|
||||
):
|
||||
if trainable and advantage == 0.0 and weight != 0.0:
|
||||
rl_weights[index] = 0.0
|
||||
changed = True
|
||||
|
||||
if not changed:
|
||||
return True
|
||||
|
||||
sample.rl_weights = rl_weights
|
||||
has_rl = any(trainable and weight != 0.0 for trainable, weight in zip(sample.mask, rl_weights, strict=True))
|
||||
has_ce = sample.ce_weights is not None and any(weight != 0.0 for weight in sample.ce_weights)
|
||||
has_ref_kl = sample.ref_kl_weights is not None and any(weight != 0.0 for weight in sample.ref_kl_weights)
|
||||
return has_rl or has_ce or has_ref_kl
|
||||
|
||||
|
||||
class TrainSink:
|
||||
"""Three-level train sink. Constructed once, fed via ``add(rollout)``."""
|
||||
|
||||
@@ -57,8 +92,7 @@ class TrainSink:
|
||||
mm_token_type_ids_mapping: dict[int, int] | None,
|
||||
batch_size: int | None,
|
||||
token_batch_size: int | None,
|
||||
pre_filters: list[RolloutFilter],
|
||||
post_filters: list[RolloutFilter],
|
||||
on_result: Callable[[list[Rollout]], bool] | None = None,
|
||||
) -> None:
|
||||
assert (batch_size is None) != (token_batch_size is None), (
|
||||
"Exactly one of batch_size / token_batch_size must be set"
|
||||
@@ -69,11 +103,10 @@ class TrainSink:
|
||||
self.mm_token_type_ids_mapping = mm_token_type_ids_mapping
|
||||
self.batch_size = batch_size
|
||||
self.token_batch_size = token_batch_size
|
||||
self.pre_filters = pre_filters
|
||||
self.post_filters = post_filters
|
||||
self.on_result = on_result
|
||||
|
||||
# Observation window for the next shipped batch: rollouts of groups
|
||||
# finalized since the last ship (errored + filtered + survivors).
|
||||
# finalized since the last ship (errored + rejected + admitted).
|
||||
# In-progress groups stay out until they finalize.
|
||||
self.pending_rollouts: TrainRollouts = TrainRollouts()
|
||||
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
|
||||
@@ -88,11 +121,10 @@ class TrainSink:
|
||||
# runs), kept in sync on append/pop so the readiness check never
|
||||
# re-sums per arrival.
|
||||
self.pending_tokens: int = 0
|
||||
|
||||
# Reset by the orchestrator after each ship via ``reset_pre_filter_stats``
|
||||
self.pre_filter_seen = 0
|
||||
self.pre_filter_dropped = 0
|
||||
self.pre_filter_dropped_by_name: dict[str, int] = {}
|
||||
# Finalized work since the most recent positive contribution, measured
|
||||
# in the active batch unit.
|
||||
self.zero_output_units: int = 0
|
||||
self.reported_zero_output_windows: int = 0
|
||||
|
||||
def group_size_for(self, env_name: str) -> int:
|
||||
return self.train_envs.get(env_name).config.group_size
|
||||
@@ -166,8 +198,7 @@ class TrainSink:
|
||||
await self.train_envs.get(rollout.env_name).algorithm.finalize_rollout(rollout)
|
||||
|
||||
async def process_group(self, group_id: uuid.UUID) -> None:
|
||||
"""Finalize one GRPO group: drop errored rollouts, assign advantages,
|
||||
run pre-batch filters, append survivors to ``pending_batch``."""
|
||||
"""Finalize one group, ask its curriculum for admission, and queue it."""
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
self.pending_group_episodes.pop(group_id, None)
|
||||
if not group:
|
||||
@@ -187,6 +218,8 @@ class TrainSink:
|
||||
# Untrainable traces carry no samples and must not skew the group baseline.
|
||||
survivors = [r for r in survivors if r.agent.trainable]
|
||||
if not survivors:
|
||||
self._admit(group)
|
||||
self._record_zero_output(group)
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
f"rollouts={len(group)} (errored={num_errored}) | dropped: no trainable survivors"
|
||||
@@ -205,44 +238,65 @@ class TrainSink:
|
||||
for sample in r.samples:
|
||||
sample.temperatures = [temperature] * len(sample.token_ids)
|
||||
|
||||
if self.pre_filters:
|
||||
apply_filters(self.pre_filters, survivors)
|
||||
filtered_by_name: dict[str, int] = {}
|
||||
num_filtered = 0
|
||||
if not self._admit(group):
|
||||
self._record_zero_output(group)
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
f"rollouts={len(group)} (errored={num_errored}) | rejected by curriculum"
|
||||
)
|
||||
return
|
||||
|
||||
for r in survivors:
|
||||
self.pre_filter_seen += 1
|
||||
if r.is_filtered:
|
||||
self.pre_filter_dropped += 1
|
||||
num_filtered += 1
|
||||
for name, hit in r.filter_results.items():
|
||||
if hit:
|
||||
self.pre_filter_dropped_by_name[name] = self.pre_filter_dropped_by_name.get(name, 0) + 1
|
||||
filtered_by_name[name] = filtered_by_name.get(name, 0) + 1
|
||||
continue
|
||||
# Reset annotations so the post-batch filter pass starts clean
|
||||
r.filter_results = {}
|
||||
r.is_filtered = False
|
||||
self.pending_batch.append(r)
|
||||
if self.token_batch_size is not None:
|
||||
self.pending_tokens += payload_tokens(r)
|
||||
self.zero_output_units = 0
|
||||
self.reported_zero_output_windows = 0
|
||||
|
||||
# Per-group summary. One line per finalized group; per-filter
|
||||
# detection breakdown lives at debug level in ``apply_filters``
|
||||
rewards = [r.reward for r in survivors]
|
||||
avg_reward = sum(rewards) / len(rewards) if rewards else 0.0
|
||||
filter_str = ", ".join(f"{n}={c}" for n, c in filtered_by_name.items()) if filtered_by_name else "—"
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
f"rollouts={len(group)} (errored={num_errored}, filtered={num_filtered}) | "
|
||||
f"reward={avg_reward:.4f} | filters: {filter_str}"
|
||||
f"rollouts={len(group)} (errored={num_errored}) | reward={avg_reward:.4f}"
|
||||
)
|
||||
|
||||
def _admit(self, group: list[Rollout]) -> bool:
|
||||
admitted = self.on_result(group) if self.on_result is not None else True
|
||||
for rollout in group:
|
||||
rollout.is_admitted = admitted
|
||||
return admitted
|
||||
|
||||
def _record_zero_output(self, group: list[Rollout]) -> None:
|
||||
if self.batch_size is not None:
|
||||
self.zero_output_units += len(group)
|
||||
else:
|
||||
payload = sum(payload_tokens(rollout) for rollout in group)
|
||||
self.zero_output_units += payload or self.config.seq_len * len(group)
|
||||
self._check_zero_output_budget()
|
||||
|
||||
def _check_zero_output_budget(self) -> None:
|
||||
target = self.batch_size if self.batch_size is not None else self.token_batch_size
|
||||
assert target is not None
|
||||
windows = self.zero_output_units // target
|
||||
if windows <= self.reported_zero_output_windows:
|
||||
return
|
||||
self.reported_zero_output_windows = windows
|
||||
get_logger().warning(
|
||||
f"No admitted train payload after {self.zero_output_units} finalized units "
|
||||
f"(consecutive zero-output batch equivalents: "
|
||||
f"{windows}/{MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS})"
|
||||
)
|
||||
if windows >= MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS:
|
||||
raise RuntimeError(
|
||||
f"{windows} consecutive zero-output batch equivalents — "
|
||||
"check the curriculum admission policy and task difficulty."
|
||||
)
|
||||
|
||||
def process_batch(self) -> TrainBatch:
|
||||
"""Pop a cohort off ``pending_batch`` (by rollout count when
|
||||
``batch_size`` is set, by token count when ``token_batch_size`` is
|
||||
set), apply post-batch filter annotations, and assemble the
|
||||
trainer-bound ``TrainingSample`` list. Overflow stays for the next
|
||||
batch."""
|
||||
set), and assemble the trainer-bound ``TrainingSample`` list. Overflow
|
||||
stays for the next batch."""
|
||||
if self.batch_size is not None:
|
||||
cohort = self.pending_batch[: self.batch_size]
|
||||
self.pending_batch = self.pending_batch[self.batch_size :]
|
||||
@@ -259,15 +313,13 @@ class TrainSink:
|
||||
self.pending_batch = self.pending_batch[cut:]
|
||||
self.pending_tokens -= running
|
||||
|
||||
if self.post_filters:
|
||||
apply_filters(self.post_filters, cohort)
|
||||
|
||||
# Samples are pre-built by ``process_rollout``; ``process_group`` already stamped the
|
||||
# advantage stream and loss routing on each sample. Filtered rollouts don't ship.
|
||||
samples: list[TrainingSample] = [sample for r in cohort if not r.is_filtered for sample in r.samples]
|
||||
if self.config.train.filter_zero_advantages:
|
||||
for rollout in cohort:
|
||||
rollout.samples = [sample for sample in rollout.samples if _prune_zero_advantages(sample)]
|
||||
samples: list[TrainingSample] = [sample for rollout in cohort for sample in rollout.samples]
|
||||
|
||||
# ``rollouts`` is the observation window — every rollout of every group finalized since the
|
||||
# last ship (errored + filtered + survivors) — while ``samples`` is the shipped cohort's
|
||||
# last ship (errored + rejected + admitted) — while ``samples`` is the shipped cohort's
|
||||
# trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive the clean subset +
|
||||
# metric views on demand. Reset the window only when the batch actually ships (non-empty
|
||||
# samples) — an empty batch is dropped unlogged by the orchestrator, so keep accumulating its
|
||||
@@ -276,8 +328,3 @@ class TrainSink:
|
||||
if samples:
|
||||
self.pending_rollouts = TrainRollouts()
|
||||
return TrainBatch(rollouts=rollouts, samples=samples)
|
||||
|
||||
def reset_pre_filter_stats(self) -> None:
|
||||
self.pre_filter_seen = 0
|
||||
self.pre_filter_dropped = 0
|
||||
self.pre_filter_dropped_by_name.clear()
|
||||
|
||||
@@ -1,35 +1,20 @@
|
||||
"""TrainSource: weighted round-robin across train envs, infinite pull.
|
||||
|
||||
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
|
||||
per env). An env serves the tasks the orchestrator loaded client-side: a
|
||||
finite one as a shuffled table (reshuffled with ``seed=epoch`` on cursor
|
||||
exhaustion), an infinite one (``num_tasks is None``) straight off its
|
||||
generator — every pull is a fresh task and there are no epochs to shuffle."""
|
||||
"""Training source selection and curriculum lifecycle."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from collections.abc import Iterator
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from collections import defaultdict
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from prime_rl.orchestrator.curriculum import Curriculum
|
||||
from prime_rl.orchestrator.envs import TrainEnvs
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
class TrainSource:
|
||||
"""``next_example()`` picks a weighted-RR env and returns its next
|
||||
example. Returned dicts carry ``env_name`` + ``task``, whose data is
|
||||
shipped to the env server at dispatch.
|
||||
|
||||
The data position round-trips through a checkpoint via ``state_dict()``
|
||||
/ ``load_state_dict()``: per-env ``{epoch, cursor}`` plus the env-choice
|
||||
RNG state, making the dispatch sequence reproducible across resumes. For
|
||||
a finite env, epochs are 1-indexed and seed that epoch's shuffle; for an
|
||||
infinite env the epoch stays 1 and the cursor counts generator pulls,
|
||||
replayed on restore by fast-forwarding the generator (exact iff it's
|
||||
deterministic). Cursors advance at dispatch time (ahead of shipped
|
||||
batches), so a resume skips the tasks that were in flight at checkpoint
|
||||
time."""
|
||||
"""Mix train envs and host one user-authored curriculum per env."""
|
||||
|
||||
def __init__(self, train_envs: TrainEnvs) -> None:
|
||||
self.rng = random.Random(42)
|
||||
@@ -37,73 +22,59 @@ class TrainSource:
|
||||
if not self.envs:
|
||||
raise ValueError("TrainSource needs at least one train env")
|
||||
|
||||
# A finite env's example table in canonical order (each epoch's shuffle
|
||||
# starts from this); ``None`` for an infinite env, whose generator
|
||||
# (``self.iters``) is pulled per example.
|
||||
self.base_rows: dict[str, list[dict] | None] = {}
|
||||
self.examples: dict[str, list[dict] | None] = {}
|
||||
self.iters: dict[str, Iterator[vf.Task]] = {}
|
||||
self.epochs: dict[str, int] = {}
|
||||
self.cursors: dict[str, int] = {}
|
||||
self.curricula: dict[str, Curriculum] = {}
|
||||
for env in self.envs:
|
||||
assert env.tasks is not None, f"env {env.name} not started"
|
||||
if env.num_tasks is None: # infinite: pull the generator per example
|
||||
rows: list[dict] | None = None
|
||||
self.iters[env.name] = env.tasks
|
||||
else:
|
||||
rows = [{"task": task, "env_name": env.name} for task in env.tasks]
|
||||
self.base_rows[env.name] = rows
|
||||
self.epochs[env.name] = 1
|
||||
self.cursors[env.name] = 0
|
||||
self.examples[env.name] = self._shuffle(env.name)
|
||||
if env.tasks is None:
|
||||
raise RuntimeError(f"env {env.name} not started")
|
||||
tasks = env.tasks if env.num_tasks is None else list(env.tasks)
|
||||
self.curricula[env.name] = Curriculum(env.config.curriculum, tasks)
|
||||
|
||||
self.env_names = [e.name for e in self.envs]
|
||||
self.weights: list[float] = [float(e.config.ratio) for e in self.envs]
|
||||
self.env_names = [env.name for env in self.envs]
|
||||
self.weights = [float(env.config.ratio) for env in self.envs]
|
||||
self._admitted: dict[str, int] = defaultdict(int)
|
||||
self._rejected: dict[str, int] = defaultdict(int)
|
||||
|
||||
def _shuffle(self, env_name: str) -> list[dict] | None:
|
||||
"""The env's example table shuffled for its current epoch — a pure
|
||||
function of (canonical order, epoch), so a restored position replays
|
||||
the exact epoch permutation."""
|
||||
rows = self.base_rows[env_name]
|
||||
if rows is None:
|
||||
return None
|
||||
rows = rows.copy()
|
||||
random.Random(self.epochs[env_name]).shuffle(rows)
|
||||
return rows
|
||||
|
||||
def state_dict(self) -> dict:
|
||||
"""Env-choice RNG state + per-env ``{epoch, cursor}``."""
|
||||
def next_example(self) -> dict[str, Any]:
|
||||
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
|
||||
return {
|
||||
"rng": self.rng.getstate(),
|
||||
"envs": {name: {"epoch": self.epochs[name], "cursor": self.cursors[name]} for name in self.epochs},
|
||||
"env_name": env_name,
|
||||
"task": next(self.curricula[env_name].sampler),
|
||||
}
|
||||
|
||||
def load_state_dict(self, state_dict: dict) -> None:
|
||||
self.rng.setstate(state_dict["rng"])
|
||||
for name, position in state_dict["envs"].items():
|
||||
if name not in self.base_rows:
|
||||
continue
|
||||
self.epochs[name] = position["epoch"]
|
||||
self.cursors[name] = position["cursor"]
|
||||
if self.base_rows[name] is None:
|
||||
for _ in range(position["cursor"]):
|
||||
next(self.iters[name])
|
||||
else:
|
||||
self.examples[name] = self._shuffle(name)
|
||||
def on_result(self, group: list[Rollout]) -> bool:
|
||||
"""Report a finalized group and return whether it should train."""
|
||||
if not group:
|
||||
raise ValueError("Cannot report an empty rollout group")
|
||||
env_name = group[0].env_name
|
||||
admitted = self.curricula[env_name].on_result(group)
|
||||
if not isinstance(admitted, bool):
|
||||
raise TypeError(f"Curriculum.on_result() must return bool, got {type(admitted).__name__}")
|
||||
if admitted:
|
||||
self._admitted[env_name] += 1
|
||||
else:
|
||||
self._rejected[env_name] += 1
|
||||
return admitted
|
||||
|
||||
def next_example(self) -> dict | None:
|
||||
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
|
||||
rows = self.examples[env_name]
|
||||
cursor = self.cursors[env_name]
|
||||
if rows is None: # infinite env: pull the next generated task
|
||||
task = next(self.iters[env_name])
|
||||
self.cursors[env_name] = cursor + 1
|
||||
return {"task": task, "env_name": env_name}
|
||||
if cursor >= len(rows):
|
||||
self.epochs[env_name] += 1
|
||||
rows = self._shuffle(env_name)
|
||||
self.examples[env_name] = rows
|
||||
cursor = 0
|
||||
example = rows[cursor]
|
||||
self.cursors[env_name] = cursor + 1
|
||||
return example
|
||||
def metrics(self) -> dict[str, float]:
|
||||
metrics: dict[str, float] = {}
|
||||
for env_name, curriculum in self.curricula.items():
|
||||
admitted = self._admitted.pop(env_name, 0)
|
||||
rejected = self._rejected.pop(env_name, 0)
|
||||
total = admitted + rejected
|
||||
if total:
|
||||
metrics[f"curriculum/{env_name}/admission_rate"] = admitted / total
|
||||
metrics |= {f"curriculum/{env_name}/{name}": float(value) for name, value in curriculum.metrics().items()}
|
||||
return metrics
|
||||
|
||||
def state_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"rng": self.rng.getstate(),
|
||||
"envs": {name: curriculum.state_dict() for name, curriculum in self.curricula.items()},
|
||||
}
|
||||
|
||||
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
|
||||
self.rng.setstate(state_dict["rng"])
|
||||
for name, curriculum_state in state_dict["envs"].items():
|
||||
curriculum = self.curricula.get(name)
|
||||
if curriculum is not None:
|
||||
curriculum.load_state_dict(curriculum_state)
|
||||
|
||||
@@ -20,8 +20,8 @@ from collections.abc import Iterator
|
||||
import numpy as np
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.transport.types import EncodedTensor, RoutedExperts
|
||||
from prime_rl.transports.rollouts import TrainingSample
|
||||
from prime_rl.transports.rollouts.types import EncodedTensor, RoutedExperts
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import verifiers.v1 as vf
|
||||
from pydantic import ConfigDict, Field
|
||||
from verifiers.v1.task import DataT
|
||||
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.transports.rollouts import TrainingSample
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.metrics import EvalRollouts, TrainRollouts
|
||||
@@ -39,7 +39,7 @@ RolloutKind = Literal["train", "eval"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class InflightRollout:
|
||||
class InflightEpisode:
|
||||
"""Per-task scheduling state in the dispatcher; one entry per in-flight
|
||||
``run`` task."""
|
||||
|
||||
@@ -50,6 +50,8 @@ class InflightRollout:
|
||||
client_config: vf.ClientConfig | None = None
|
||||
off_policy_steps: int = 0
|
||||
eval_step: int | None = None
|
||||
started_at: float = 0.0
|
||||
"""``time.monotonic()`` at dispatch; feeds episode-duration estimates."""
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -96,11 +98,9 @@ class Rollout(vf.Trace[DataT], Generic[DataT]):
|
||||
samples: list[TrainingSample] = Field(default_factory=list, exclude=True)
|
||||
# Per-token rl advantage stream, full-length-N (= len(token_ids)) per
|
||||
# sample, concatenated across the rollout's samples in order; 0.0 on
|
||||
# non-trainable positions. None = no credit assigned (advantage-based
|
||||
# filters skip it; the wire ships no advantage stream).
|
||||
# non-trainable positions. None means no credit was assigned.
|
||||
advantages: list[float] | None = Field(default=None, exclude=True)
|
||||
is_filtered: bool = Field(default=False, exclude=True)
|
||||
filter_results: dict[str, bool] = Field(default_factory=dict, exclude=True)
|
||||
is_admitted: bool = Field(default=True, exclude=True)
|
||||
eval_step: int | None = Field(default=None, exclude=True)
|
||||
|
||||
def assign_advantages(self, values: float | list[float]) -> None:
|
||||
@@ -140,9 +140,9 @@ class Rollout(vf.Trace[DataT], Generic[DataT]):
|
||||
@dataclass
|
||||
class TrainBatch:
|
||||
"""``rollouts`` is the observation window since the last ship — every rollout of every group
|
||||
finalized in that span (errored + filtered included; rollouts of still-incomplete groups wait
|
||||
finalized in that span (errored + rejected included; rollouts of still-incomplete groups wait
|
||||
for a later window). Its ``.effective`` / ``.metrics`` views drive logging. ``samples`` is the
|
||||
trainer-bound payload (the shipped cohort's post-filter survivors) — an empty list means nothing
|
||||
trainer-bound payload from the admitted cohort — an empty list means nothing
|
||||
ships, which would stall the trainer. Trainable counts derive from ``rollouts.effective``
|
||||
(``r.is_trainable``) and token totals from ``samples``, so neither is carried as a field."""
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ from modelexpress import p2p_pb2
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.types import Policy, VersionObserver
|
||||
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.utils.async_utils import safe_cancel
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
|
||||
@@ -41,6 +41,19 @@ mkdir -p $LOG_DIR/trainer
|
||||
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
|
||||
|
||||
{% if prl_run_id %}
|
||||
# Trainer and evaluator (separate SLURM job) log to a single shared W&B run whose id
|
||||
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evaluator (which
|
||||
# outlives the trainer) finalizes it.
|
||||
export PRL_RUN_ID={{ prl_run_id }}
|
||||
export PRL_RUN_NAME={{ run_name }}
|
||||
export WANDB_RUN_ID=$PRL_RUN_ID
|
||||
export WANDB_SHARED_MODE=1
|
||||
export WANDB_SHARED_PRIMARY=trainer
|
||||
export WANDB_SHARED_FINISHER=evaluator
|
||||
export WANDB_SHARED_LABEL=trainer
|
||||
export WANDB_PROGRAM="uv run sft"
|
||||
{% endif %}
|
||||
# Networking
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
echo "HOSTNAMES=${HOSTNAMES[@]}"
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user