Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
991b925e6e | ||
|
|
03cdc51575 | ||
|
|
cb5f1e72bb | ||
|
|
52eebada92 | ||
|
|
5d0fc8ba2e | ||
|
|
c2a25f0622 | ||
|
|
bc9e186963 | ||
|
|
bfb0fe346e | ||
|
|
2acb19eccd | ||
|
|
69308b88cb | ||
|
|
0630b7bff7 | ||
|
|
5ed05cf6ac | ||
|
|
1c0720d975 | ||
|
|
61f2448d1d | ||
|
|
c7a6573de5 | ||
|
|
8b2819b4c7 | ||
|
|
1fd4fefd4a |
+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/
|
||||
|
||||
@@ -19,6 +19,9 @@ lr = 1e-5
|
||||
batch_size = 128
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 128
|
||||
|
||||
[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 = 128
|
||||
|
||||
[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 = 128
|
||||
|
||||
[orchestrator.model.lora]
|
||||
name = "r8-1e-4"
|
||||
|
||||
|
||||
@@ -22,6 +22,9 @@ impl = "custom"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 128
|
||||
|
||||
[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 = 128
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "opd"
|
||||
|
||||
|
||||
@@ -24,6 +24,9 @@ name = "ci-rl-sft"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 128
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "sft"
|
||||
|
||||
|
||||
@@ -22,6 +22,9 @@ lr = 3e-6
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 128
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
|
||||
@@ -19,6 +19,9 @@ lr = 3e-6
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 128
|
||||
|
||||
[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 = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@ batch_size = 512
|
||||
group_size = 8
|
||||
seq_len = 8192
|
||||
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 128
|
||||
|
||||
[[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 = 128
|
||||
|
||||
[[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 = 128
|
||||
max_inflight = 128
|
||||
|
||||
[[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 = 128
|
||||
|
||||
[[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 = 128
|
||||
|
||||
[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"
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
# Concurrency-controller debug run: GLM-4.5-Air on the v1 `scaleswe` SWE taskset,
|
||||
# bash harness on a prime sandbox runtime, 1 train + 1 infer node, eval on 100
|
||||
# SWE-Bench Verified instances. Concurrency is fully default: the controller
|
||||
# derives its start from the measured KV budget and adapts from there — watch
|
||||
# the concurrency/* gauges in W&B or the "Concurrency ..." lines in the
|
||||
# orchestrator log.
|
||||
#
|
||||
# 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: LM-head token chunking, activation checkpointing
|
||||
# (freq=1) + activation offloading (max_inflight=1), and skip-gather /
|
||||
# skip-optimizer checkpointing. Router replay is enabled — GLM-4.5-Air is a
|
||||
# glm4_moe model, which supports routed_experts.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the input-token and turns
|
||||
# coefficients set to 0.1.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "debug-concurrency"
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "debug-concurrency" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 1
|
||||
|
||||
[monitors.wandb]
|
||||
project = "swe-ablations"
|
||||
name = "debug-concurrency"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
|
||||
[resume]
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "sign_sgd"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 8
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "scaleswe"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["debug-concurrency"]
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
num_examples = 100
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["debug-concurrency"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
quantization = "fp8"
|
||||
enable_return_routed_experts = true
|
||||
Vendored
+1
-1
Submodule deps/verifiers updated: 02cc940d8f...4bcb48e55a
+53
-38
@@ -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)
|
||||
@@ -158,20 +158,20 @@ At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_r
|
||||
| `algo.type` | Class | hook(s) — stage |
|
||||
|---|---|---|
|
||||
| `grpo` | `GRPOAlgorithm` | `score_group`: group-norm credit (optional length penalty) |
|
||||
| `echo` | `EchoAlgorithm` | `score_rollout`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
|
||||
| `echo` | `EchoAlgorithm` | `score_episode`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
|
||||
| `max_rl` | `MaxRLAlgorithm` | `score_group`: mean-normalized group credit |
|
||||
| `rae` | `RAEAlgorithm` | `score_group`: per-agent EMA-baseline credit |
|
||||
| `hierarchical_grpo` | `HierarchicalGRPOAlgorithm` | `score_group`: GRPO baseline per episode for solvers, per group for the proposer |
|
||||
| `opd` | `OPDAlgorithm` | `score_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) |
|
||||
| `opd` | `OPDAlgorithm` | `score_episode`: own-context prefill under the teacher |
|
||||
| `opsd` | `OPSDAlgorithm` | `score_episode`: demo-conditioned prefill under the live policy |
|
||||
| `sft` | `SFTDistillAlgorithm` | no credit assignment; CE on sampled tokens |
|
||||
|
||||
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:
|
||||
Algorithms operate on native verifier artifacts and annotate their message graphs directly:
|
||||
|
||||
- `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_episode(episode)` — rollout-local scoring as one episode arrives.
|
||||
- `async score_group(episodes)` — group-relative scoring after the cohort completes.
|
||||
|
||||
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.
|
||||
The pipeline drives these through `finalize_episode` and `finalize_group`. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
|
||||
|
||||
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy pool (`self.policy_pool`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -420,30 +420,32 @@ Both of `kuhn-poker`'s agents late-bind to the run's own model — shared-policy
|
||||
|
||||
### Authoring an Algorithm
|
||||
|
||||
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class. The hook receives the group's `Rollout`s (each the env's typed `verifiers.Trace` — turns, tool calls, metadata in `info` — with `samples` attached) and writes credit via `assign_advantages`:
|
||||
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class:
|
||||
|
||||
```python
|
||||
# src/prime_rl/orchestrator/algo/my_algo.py
|
||||
import torch
|
||||
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
|
||||
|
||||
class MyAlgorithm(Algorithm):
|
||||
async def score_group(self, group):
|
||||
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
|
||||
advantages = ... # one value per rollout
|
||||
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
|
||||
rollout.assign_advantages(advantage)
|
||||
async def score_group(self, episodes):
|
||||
traces = [trace for episode in episodes for trace in episode.traces]
|
||||
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
|
||||
advantages = ... # one value per trace
|
||||
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
|
||||
assign_advantages(trace, advantage)
|
||||
```
|
||||
|
||||
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).
|
||||
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick `score_episode` for rollout-local work or model calls, and `score_group` for group-relative credit. `assign_advantages` takes a scalar or a list aligned to the trace graph's sampled tokens.
|
||||
|
||||
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.
|
||||
Curriculum admission and metrics can inspect the resulting graph-native streams after group scoring.
|
||||
|
||||
### Reference Scoring
|
||||
|
||||
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_rollout`: as each rollout arrives they query a reference (the sample's own context for `opd`, the demo-conditioned context for `opsd`) and attach per-token reference logprobs to each sample. Rollouts are consumed serially by the orchestrator's main loop and each carries only a handful of samples, so the in-flight request count is naturally bounded — no explicit concurrency cap:
|
||||
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_episode`: as each episode arrives they query a reference and attach sampled-token reference logprobs to its graph nodes:
|
||||
|
||||
- `opd` — score each sample's own context under the `teacher` (a frozen [model reference](#model-references)) via prefill; fills `ref_logprobs` for the `ref_kl` loss component (on-policy distillation). The `teacher` is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero).
|
||||
- `opsd` — SDFT: prepend an expert demonstration as a leading system message (`template`, with a `{demonstration}` placeholder) and score the sample under that demo-conditioned context. The sample is scored verbatim (`hint_block + token_ids`, slicing the hint's logprobs back off), so the join is BPE-clean and it's robust to tool/multimodal prompts and any number of turns. The scoring reference *is* the live policy — self-distillation names no teacher. opsd builds its own renderer to tokenize the hint block: the tokenizer is always the live policy's (not configurable — there is no separate model), and only the `renderer` family is settable (defaults to `"auto"`, resolved from the policy tokenizer; set it to match a non-auto policy renderer). The demonstration is read from the example's `info[demo_key]`, falling back to a top-level rollout field of the same name (e.g. `answer`).
|
||||
@@ -454,31 +456,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 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 `list[vf.Episode]`; each gate inspects the same native episodes. The group trains only if every gate admits it. Rejected groups remain observable while the orchestrator samples again to fill the batch.
|
||||
|
||||
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 first lowers the cap and lets completions drain the pool naturally (soft — no work lost); only if usage keeps climbing despite the closed gate does it also cancel the youngest episodes (hard — least work lost).
|
||||
- **Cut**: when the engines are demonstrably overloaded — requests being preempted, or piling up in the waiting queue — cut the pool hard, cancel the excess, and hold further cuts until the system settles.
|
||||
|
||||
The cap starts from a safe bound derived from the engines (KV capacity divided by the maximum context length), or from `initial_inflight` when a good value is known, and always stays within `[min_inflight, max_inflight]`.
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### KV Cache Offload
|
||||
|
||||
+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
|
||||
|
||||
|
||||
+4
-4
@@ -204,17 +204,17 @@ 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.
|
||||
The launcher starts the inference server, one env server per eval source, and an `evals` 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 evals process 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. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
|
||||
#### Multi-Node (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:
|
||||
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 evals process:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2 # trainer job
|
||||
num_infer_nodes = 1 # eval job (inference pool + evaluator)
|
||||
num_infer_nodes = 1 # eval job (inference pool + evals)
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
@@ -223,7 +223,7 @@ tensor_parallel_size = 8
|
||||
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.
|
||||
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 evals log to a single shared W&B run across both jobs — the trainer creates it, the evals process finalizes it. Any train × inference layout works: `num_nodes` and `num_infer_nodes` are fully independent.
|
||||
|
||||
### SFT-Specific Knobs
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# Standalone SWE evals: SWE-bench Verified + Terminal-Bench 2, one epoch each,
|
||||
# against DeepSeek V4 Flash on Prime Inference.
|
||||
#
|
||||
# export PRIME_API_KEY=<your Prime Inference key>
|
||||
# uv run evals @ examples/evals/swe.toml
|
||||
#
|
||||
# The tasksets run in prime sandboxes (the default runtime), so the key also
|
||||
# authenticates sandbox creation. External API endpoints expose no vLLM
|
||||
# /metrics, so adaptive concurrency has no load signal - the band must be
|
||||
# pinned (min_inflight = max_inflight) or the evals process refuses to start.
|
||||
|
||||
model = "deepseek/deepseek-v4-flash"
|
||||
|
||||
[eval.client]
|
||||
base_url = "https://api.pinference.ai/api/v1"
|
||||
api_key_var = "PRIME_API_KEY"
|
||||
|
||||
[eval.concurrency]
|
||||
min_inflight = 32
|
||||
max_inflight = 32
|
||||
|
||||
[[eval.source]]
|
||||
name = "swebench-verified"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
|
||||
[[eval.source]]
|
||||
name = "terminal-bench-2"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "terminal-bench-2"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
@@ -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,109 @@
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, LogConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class EvalsEvalConfig(EvalConfig):
|
||||
"""Evals against a live inference server. Extends the orchestrator ``EvalConfig``
|
||||
(sources, sampling, intervals) with the client of the inference deployment and
|
||||
evals-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."""
|
||||
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig()
|
||||
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
|
||||
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
|
||||
|
||||
@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``: sources with an explicit
|
||||
``serve.address`` are externally managed; the evals process spawns an env server at
|
||||
the derived address for every other source."""
|
||||
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 OnlineConfig(BaseConfig):
|
||||
"""Checkpoint-driven online evals: watch a weights directory for new HF checkpoints
|
||||
and evaluate each eligible one. Without this block the evals process runs every eval
|
||||
source once against the weights the inference server currently serves, then exits."""
|
||||
|
||||
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``."""
|
||||
|
||||
max_steps: int | None = None
|
||||
"""Trainer step at which the run ends. The final checkpoint always fires every
|
||||
eval env, and the evals process exits after processing it. If None, the evals process
|
||||
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."""
|
||||
|
||||
|
||||
class EvalsConfig(BaseConfig):
|
||||
"""``uv run evals``: run the configured evals against a live inference server.
|
||||
Standalone (no ``[online]``), one epoch of every eval source runs against the
|
||||
served weights and the evals process exits. With ``[online]``, the evals process watches a
|
||||
weights directory for new HF checkpoints, points the inference server at each one
|
||||
(``/update_weights`` from disk), and runs the configured evals against the updated
|
||||
weights — the ``sft`` launcher writes this config; it also works 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: EvalsEvalConfig
|
||||
"""Eval sources, sampling, intervals, concurrency, and the inference client."""
|
||||
|
||||
online: OnlineConfig | None = None
|
||||
"""Checkpoint watching (``[online]``). None runs the evals once and exits."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — rollout traces and logs are written as
|
||||
subdirectories. Shared with the trainer for online evals."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_weights_dir(self):
|
||||
if self.online is not None and self.online.weights_dir is None:
|
||||
self.online.weights_dir = self.output_dir / "weights"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_skip_first_step_is_online_only(self):
|
||||
"""``skip_first_step`` gates the base-model eval between checkpoints; a
|
||||
standalone run has only that one epoch, so skipping it would exit
|
||||
successfully without evaluating anything."""
|
||||
if self.online is None and self.eval.skip_first_step:
|
||||
raise ValueError(
|
||||
"eval.skip_first_step only applies to online evals - a standalone run "
|
||||
"would skip its only eval epoch. Remove it or add an [online] block."
|
||||
)
|
||||
return self
|
||||
@@ -1,84 +0,0 @@
|
||||
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:
|
||||
|
||||
@@ -8,7 +8,7 @@ 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.evals import EvalsEvalConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
@@ -28,6 +28,7 @@ from prime_rl.configs.trainer import (
|
||||
OptimizerConfig,
|
||||
SchedulerConfig,
|
||||
TokenizerConfig,
|
||||
validate_scheduler,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
|
||||
@@ -42,6 +43,9 @@ class BaseDataConfig(BaseConfig):
|
||||
micro_batch_size: int = Field(1, ge=1)
|
||||
"""Per-step micro batch size. ``batch_size`` must be divisible by this."""
|
||||
|
||||
num_workers: int = Field(1, ge=0)
|
||||
"""Number of dataloader worker processes. With ``>= 1``, batches are prepared and pinned in the background so tokenization/packing overlaps with training. ``0`` loads inline on the main process."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_batch_size(self):
|
||||
if self.batch_size % self.micro_batch_size != 0:
|
||||
@@ -60,6 +64,9 @@ class FakeDataConfig(BaseDataConfig):
|
||||
input_ids: Literal["increasing", "random"] = "increasing"
|
||||
"""Token id generator: ``increasing`` for deterministic sequences, ``random`` for random ids."""
|
||||
|
||||
seed: int = 0
|
||||
"""Seed for the per-rank packing/token generator, combined with the data rank."""
|
||||
|
||||
|
||||
class LossMaskConfig(BaseConfig):
|
||||
system: bool = False
|
||||
@@ -195,7 +202,7 @@ class SFTConfig(BaseConfig):
|
||||
val: SFTValConfig | None = None
|
||||
"""Validation configuration. If None, no validation runs."""
|
||||
|
||||
eval: OnlineEvalConfig | None = None
|
||||
eval: EvalsEvalConfig | 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."""
|
||||
@@ -319,9 +326,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")
|
||||
@@ -362,18 +369,18 @@ class SFTConfig(BaseConfig):
|
||||
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 "
|
||||
"evals 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.
|
||||
# inference pool (one engine per DP rank behind a router) plus the evals process.
|
||||
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."
|
||||
"a dedicated SLURM job running the inference pool and the evals process."
|
||||
)
|
||||
if self.deployment.num_infer_nodes < 1:
|
||||
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
|
||||
@@ -398,7 +405,7 @@ class SFTConfig(BaseConfig):
|
||||
)
|
||||
if self.max_steps is None:
|
||||
warnings.warn(
|
||||
"Online evals without max_steps: the evaluator never sees a final checkpoint, "
|
||||
"Online evals without max_steps: the evals process never sees a final checkpoint, "
|
||||
"so the eval SLURM job holds its allocation until its walltime.",
|
||||
stacklevel=2,
|
||||
)
|
||||
@@ -411,7 +418,7 @@ class SFTConfig(BaseConfig):
|
||||
"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 "
|
||||
"otherwise the evals process 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,
|
||||
@@ -538,6 +545,11 @@ class SFTConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_scheduler_steps(self):
|
||||
validate_scheduler(self.scheduler, self.max_steps)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_adapter_saving(self):
|
||||
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
|
||||
|
||||
@@ -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."""
|
||||
@@ -255,7 +256,7 @@ class ModelConfig(BaseModelConfig):
|
||||
debug: DebugModelConfig = DebugModelConfig()
|
||||
"""Debugging knobs for the model and distributed training."""
|
||||
|
||||
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 1024
|
||||
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 8192
|
||||
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -386,6 +387,28 @@ SchedulerConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
def validate_scheduler(scheduler: SchedulerConfig, max_steps: int | None) -> None:
|
||||
"""Check scheduler phases against max_steps so misconfigurations fail at config time."""
|
||||
if isinstance(scheduler, LinearSchedulerConfig):
|
||||
if scheduler.warmup_steps == 0 and scheduler.decay_steps == 0:
|
||||
raise ValueError(
|
||||
"Linear scheduler requires warmup_steps > 0 or decay_steps > 0 (use the constant scheduler instead)"
|
||||
)
|
||||
if scheduler.decay_steps > 0:
|
||||
if max_steps is None:
|
||||
raise ValueError("Must specify max_steps when using a linear scheduler with decay_steps > 0")
|
||||
if scheduler.warmup_steps + scheduler.decay_steps > max_steps:
|
||||
raise ValueError(
|
||||
f"warmup_steps ({scheduler.warmup_steps}) + decay_steps ({scheduler.decay_steps}) "
|
||||
f"must not exceed max_steps ({max_steps})"
|
||||
)
|
||||
if isinstance(scheduler, CosineSchedulerConfig):
|
||||
if max_steps is None:
|
||||
raise ValueError("Must specify max_steps when using a cosine scheduler")
|
||||
if scheduler.warmup_steps >= max_steps:
|
||||
raise ValueError(f"warmup_steps ({scheduler.warmup_steps}) must be less than max_steps ({max_steps})")
|
||||
|
||||
|
||||
class BaseOptimizerConfig(BaseConfig):
|
||||
lr: float = Field(1e-6, ge=0)
|
||||
"""Peak learning rate."""
|
||||
@@ -673,9 +696,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")
|
||||
@@ -719,6 +742,11 @@ class TrainerConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_scheduler_steps(self):
|
||||
validate_scheduler(self.scheduler, self.max_steps)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_adapter_saving(self):
|
||||
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
|
||||
|
||||
+2
-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.dev59",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
@@ -53,7 +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"
|
||||
evals = "prime_rl.entrypoints.evals: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!"
|
||||
@@ -66,7 +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)
|
||||
├── evals.log # SFT online-eval evals stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evals.log)
|
||||
├── inference.log # vLLM stdout
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node (multi-node only)
|
||||
@@ -82,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,evaluator,inference}.log
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evals,inference}.log
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
|
||||
```
|
||||
|
||||
@@ -93,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 |
|
||||
|--------|-------------|
|
||||
@@ -105,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 |
|
||||
@@ -129,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:
|
||||
@@ -139,31 +140,30 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
|
||||
# vllm:num_requests_running, vllm:num_requests_waiting, vllm:gpu_cache_usage_perc (→1.0 = KV cache saturated)
|
||||
```
|
||||
|
||||
### Traces
|
||||
### Episodes
|
||||
|
||||
```
|
||||
{run_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per rollout as it completes
|
||||
{run_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per episode as it completes
|
||||
{run_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
```
|
||||
|
||||
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
|
||||
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),
|
||||
`verifiers` (producing build), `agent` (model, sampling, harness, `name`, `trainable`), `ok`
|
||||
(the success sentinel — `errors` alone keeps retry history even after a recovery), and
|
||||
`runtime` (config + provisioned resource id, e.g. the sandbox id), plus `env_name`,
|
||||
`group_id`, `episode_id`, and `policy_version` under `info`.
|
||||
JSONL files of native `vf.Episode` records (training tensors excluded), one line per episode.
|
||||
`all` gets every completed episode as it arrives — including trace-less failures,
|
||||
curriculum-rejected work, and work that never enters a batch — so it is crash-durable.
|
||||
`effective` contains the admitted clean trainable traces grouped into their original episodes
|
||||
(eval: the non-errored trainable epoch cohort). Each record carries its provenance at the
|
||||
episode level: `env` (`id` plus the orchestrator's `name`), full `task`, `group_id`,
|
||||
and `run`. Training-run records discriminate train/eval work and include dispatch
|
||||
step plus an optional live-policy version span. Traces retain their own task,
|
||||
verifiers, agent, and runtime fields.
|
||||
|
||||
```bash
|
||||
wc -l {run_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
|
||||
jq '.rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.ok | not) | {id, env: .info.env_name, runtime}' {run_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
jq '.traces[].rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.ok | not) | {id, env: .env.id, errors}' {run_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
```
|
||||
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the trace subtrees.
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
|
||||
|
||||
### Common failure modes
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: start-run
|
||||
description: How to launch prime-rl training runs — the `rl`, `sft`, and `inference` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
|
||||
description: How to launch prime-rl training runs — the `rl`, `sft`, `inference`, and `evals` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
|
||||
---
|
||||
|
||||
# Start a run
|
||||
@@ -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
|
||||
@@ -47,8 +48,10 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
|
||||
If a local env exists under `deps/prime-envs/environments/` or
|
||||
`deps/verifiers/environments/` but does not import, install the env workspace
|
||||
members with `uv sync --all-packages` (all) or `uv sync --package prime-rl
|
||||
--package <env>` (one) — they're auto-discovered, no `pyproject.toml` edit needed.
|
||||
members with `uv sync --all-extras --all-packages` (all) or `uv sync --all-extras
|
||||
--package prime-rl --package <env>` (one) — they're auto-discovered, no
|
||||
`pyproject.toml` edit needed. Keep `--all-extras` for training so a targeted
|
||||
package sync does not prune accelerator dependencies from the environment.
|
||||
|
||||
## `sft` — SFT training
|
||||
|
||||
@@ -87,6 +90,46 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
- Entrypoint: `src/prime_rl/entrypoints/inference.py`
|
||||
- SLURM: single-node, multi-node, and disaggregated deployments
|
||||
|
||||
## `evals` — multi-env evals
|
||||
|
||||
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`weights_dir`, `max_steps`, `resume_step`): watch the weights dir for stable `step_{n}` HF checkpoints and evaluate each — the `sft` launcher writes this config for online evals.
|
||||
|
||||
```bash
|
||||
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
|
||||
uv run evals @ eval.toml
|
||||
```
|
||||
|
||||
Minimal standalone `eval.toml`:
|
||||
|
||||
```toml
|
||||
model = "Qwen/Qwen3-4B"
|
||||
|
||||
[eval.client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[eval.concurrency] # adaptive; same controller as [orchestrator.concurrency]
|
||||
min_inflight = 8
|
||||
max_inflight = 128
|
||||
|
||||
[[eval.source]]
|
||||
num_examples = 32 # always cap eval size for smokes
|
||||
group_size = 4
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "aime25"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
```
|
||||
|
||||
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/envs/eval/{name}.log`.
|
||||
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
|
||||
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
|
||||
|
||||
## Summary
|
||||
|
||||
| Command | Purpose | Typical use |
|
||||
@@ -94,6 +137,7 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
| `rl` | Full RL pipeline | Production RL training |
|
||||
| `sft` | Supervised fine-tuning | SFT and hard-distill |
|
||||
| `inference` | vLLM server | Standalone serving / debugging |
|
||||
| `evals` | Multi-env evals | Standalone evals / SFT online evals |
|
||||
|
||||
## Key paths
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Lightweight launcher for the online evals.
|
||||
|
||||
Defers heavy ML imports until after ``cli()`` parses CLI args, so
|
||||
``evals --help`` short-circuits in ``cli()``. The actual implementation
|
||||
lives in ``prime_rl.evals.evals``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("Evals")
|
||||
config = cli(EvalsConfig)
|
||||
from prime_rl.evals.evals import run_evals
|
||||
|
||||
asyncio.run(run_evals(config))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,24 +0,0 @@
|
||||
"""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()
|
||||
@@ -9,7 +9,7 @@ from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
from prime_rl.configs.evaluator import EvaluatorConfig
|
||||
from prime_rl.configs.evals import EvalsConfig, OnlineConfig
|
||||
from prime_rl.configs.orchestrator import EvalSourceConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
@@ -46,7 +46,7 @@ EVAL_SBATCH = "eval.sbatch"
|
||||
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
|
||||
|
||||
INFERENCE_CONFIG = "inference.json"
|
||||
EVALUATOR_CONFIG = "evaluator.json"
|
||||
EVALS_CONFIG = "evals.json"
|
||||
|
||||
ENVS_DIR = "envs"
|
||||
|
||||
@@ -80,16 +80,24 @@ def resolve_resume_step(config: SFTConfig) -> int | None:
|
||||
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."""
|
||||
def build_evals_config(config: SFTConfig) -> EvalsConfig:
|
||||
"""Derive the evals subconfig from the resolved SFT config. The launcher
|
||||
spawns the env servers itself, so each source's derived address is stamped in,
|
||||
marking it externally managed for the evals process."""
|
||||
assert config.eval is not None
|
||||
return EvaluatorConfig(
|
||||
eval_config = config.eval.model_copy(deep=True)
|
||||
addresses = config.eval.env_addresses
|
||||
for source in eval_config.source:
|
||||
source.serve.address = addresses[("eval", source.resolved_name)]
|
||||
return EvalsConfig(
|
||||
model=config.model.name,
|
||||
eval=config.eval,
|
||||
weights_dir=get_weights_dir(get_ckpt_base(config)),
|
||||
eval=eval_config,
|
||||
online=OnlineConfig(
|
||||
weights_dir=get_weights_dir(get_ckpt_base(config)),
|
||||
max_steps=config.max_steps,
|
||||
resume_step=resolve_resume_step(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,
|
||||
)
|
||||
@@ -103,7 +111,7 @@ def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | 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."""
|
||||
"""Write the inference, evals, and env-server configs for online evals."""
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if config.inference is not None:
|
||||
@@ -116,11 +124,11 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
|
||||
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)
|
||||
with open(config_dir / EVALS_CONFIG, "w") as f:
|
||||
json.dump(dump_resolved_config(build_evals_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.
|
||||
# binds at the source's deterministic address, where the evals process connects.
|
||||
for source, address in eval_env_servers(config):
|
||||
env_dir = config_dir / ENVS_DIR / "eval"
|
||||
env_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -176,7 +184,7 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
|
||||
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."""
|
||||
env servers + evals) to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
assert config.slurm is not None
|
||||
@@ -199,7 +207,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
}
|
||||
evaluator_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
|
||||
evals_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
|
||||
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
@@ -214,7 +222,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
|
||||
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,
|
||||
evals_env_vars=evals_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,
|
||||
@@ -226,7 +234,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
|
||||
|
||||
def sft_slurm(config: SFTConfig):
|
||||
"""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
|
||||
trainer and the eval deployment (inference pool + evals) 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."""
|
||||
@@ -250,7 +258,7 @@ def sft_slurm(config: SFTConfig):
|
||||
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,
|
||||
# Trainer and evals 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:
|
||||
@@ -261,8 +269,8 @@ def sft_slurm(config: SFTConfig):
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
# 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
|
||||
# the trainer creates the shared W&B run, and the evals process's joiner init only
|
||||
# retries for a bounded window — starting the evals process while the trainer job pends
|
||||
# would crash it at wandb init.
|
||||
script_paths = [script_path]
|
||||
if decoupled_eval:
|
||||
@@ -283,7 +291,7 @@ def sft_slurm(config: SFTConfig):
|
||||
# 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,
|
||||
evals=True,
|
||||
inference=True,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
@@ -292,7 +300,7 @@ def sft_slurm(config: SFTConfig):
|
||||
if config.dry_run:
|
||||
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."
|
||||
"\n\nSubmit the trainer job first — the evals process joins the W&B run the trainer creates."
|
||||
if decoupled_eval
|
||||
else ""
|
||||
)
|
||||
@@ -360,17 +368,17 @@ def sft_local(config: SFTConfig):
|
||||
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
|
||||
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
|
||||
|
||||
# Trainer and evaluator log to a single shared W&B run whose id ($WANDB_RUN_ID)
|
||||
# Trainer and evals 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
|
||||
# The trainer creates the run; the evals process (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_SHARED_FINISHER": "evals",
|
||||
"WANDB_PROGRAM": "uv run sft",
|
||||
"WANDB_ARGS": json.dumps(sys.argv),
|
||||
}
|
||||
@@ -419,7 +427,7 @@ def sft_local(config: SFTConfig):
|
||||
log_path=log_dir / "inference.log",
|
||||
)
|
||||
|
||||
# Start one env server per eval source. The evaluator connects to each source's
|
||||
# Start one env server per eval source. The evals process 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
|
||||
@@ -432,19 +440,19 @@ def sft_local(config: SFTConfig):
|
||||
)
|
||||
|
||||
if config.eval is not None:
|
||||
logger.info("Starting evaluator process")
|
||||
logger.info("Starting evals process")
|
||||
start_process(
|
||||
"evaluator",
|
||||
["evaluator", "@", (config_dir / EVALUATOR_CONFIG).as_posix()],
|
||||
"evals",
|
||||
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "evaluator",
|
||||
"WANDB_SHARED_LABEL": "evals",
|
||||
},
|
||||
log_path=log_dir / "evaluator.log",
|
||||
log_path=log_dir / "evals.log",
|
||||
)
|
||||
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
@@ -487,11 +495,11 @@ def sft_local(config: SFTConfig):
|
||||
)
|
||||
processes.append(tail_process)
|
||||
|
||||
# Wait for the trainer (and the evaluator, which drains its final evals after
|
||||
# Wait for the trainer (and the evals process, 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"])
|
||||
if "evals" in stop_events:
|
||||
terminal_events.append(stop_events["evals"])
|
||||
while True:
|
||||
pending = [event for event in terminal_events if not event.is_set()]
|
||||
if error_queue:
|
||||
@@ -529,12 +537,12 @@ def sft_local(config: SFTConfig):
|
||||
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
|
||||
Without this the evals process 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")
|
||||
logger.warning("NEVER_CLEAN is set - keeping stale weight checkpoints; the evals process may replay them")
|
||||
return
|
||||
resume_step = resolve_resume_step(config)
|
||||
weights_dir = get_weights_dir(get_ckpt_base(config))
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
"""Evals: multi-env evals against a live inference server.
|
||||
|
||||
Standalone (no ``[online]``), it runs one epoch of every configured eval
|
||||
source against the weights the inference server currently serves, then exits.
|
||||
With ``[online]``, it watches a weights directory for new HF checkpoints —
|
||||
the trainer writes ``weights/step_{n}`` with a ``STABLE`` marker on
|
||||
completion — 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.
|
||||
|
||||
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
|
||||
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
|
||||
fed by the ``InferenceMetricsCollector``'s ``/metrics`` polls. Eval episodes
|
||||
are version-pinned measurements, so an overload cut only blocks admission and
|
||||
the in-flight pool drains through natural completions.
|
||||
|
||||
Env servers: sources without an explicit ``serve.address`` get an env server
|
||||
spawned by the evals process at their derived address; sources with one are
|
||||
externally managed (e.g. spawned by the ``sft`` launcher, which stamps the
|
||||
derived addresses into this config)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from subprocess import Popen
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
monkey_patch_oai_iterable_types,
|
||||
)
|
||||
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.types import EvalBatch, Policy
|
||||
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.config import dump_resolved_config
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir, get_step_path
|
||||
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
|
||||
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 Evals:
|
||||
def __init__(self, config: EvalsConfig) -> None:
|
||||
self.config = config
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
mode = f"online (weights_dir={config.online.weights_dir})" if config.online is not None else "standalone"
|
||||
get_logger().info(f"Starting evals ({mode})")
|
||||
|
||||
# The last weight-checkpoint step already handled (evaluated or skipped).
|
||||
self.last_step = (config.online.resume_step if config.online is not None else None) or 0
|
||||
self.eval_triggered_at: dict[tuple[str, int], float] = {}
|
||||
self.env_server_procs: list[Popen] = []
|
||||
self.dispatcher_task: asyncio.Task | None = None
|
||||
|
||||
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")
|
||||
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
|
||||
|
||||
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)
|
||||
|
||||
self.spawn_env_servers()
|
||||
|
||||
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")
|
||||
|
||||
is_resumed = config.online is not None and config.online.resume_step is not None
|
||||
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=is_resumed)
|
||||
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
|
||||
self.policy = Policy(version=0, model_name=config.model)
|
||||
|
||||
# Pessimistic per-episode token cost for the controller's starting cap,
|
||||
# only used when the engine doesn't report its max context length.
|
||||
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.eval.source) or 8192
|
||||
self.concurrency = ConcurrencyController(config.eval.concurrency, fallback_cost=fallback_cost)
|
||||
self.dispatcher = Dispatcher(
|
||||
train_envs=None,
|
||||
eval_envs=self.eval_envs,
|
||||
train_source=None,
|
||||
eval_source=self.eval_source,
|
||||
policy_pool=self.pool,
|
||||
policy=self.policy,
|
||||
progress=None,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
max_inflight_ceiling=config.eval.concurrency.max_inflight,
|
||||
tasks_per_minute=None,
|
||||
max_off_policy_steps=0,
|
||||
run_id=self.run_id,
|
||||
run_name=self.run_name,
|
||||
on_episode_complete=self.concurrency.record_episode,
|
||||
)
|
||||
# No ``on_overload``: eval episodes are measurements and are never
|
||||
# cancelled — a cut only blocks admission until the pool drains.
|
||||
self.concurrency.bind(
|
||||
set_limit=self.dispatcher.set_limit,
|
||||
get_inflight=lambda: self.dispatcher.current_inflight,
|
||||
)
|
||||
# The collector always polls — it feeds the concurrency controller;
|
||||
# W&B mirroring is gated on the registered monitor.
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.pool.admin_clients,
|
||||
on_load=self.concurrency.observe,
|
||||
log_to_wandb=wandb_enabled,
|
||||
)
|
||||
# Fail fast when adaptivity has no signal: external API endpoints
|
||||
# (e.g. Prime Inference) expose no vLLM /metrics, so without a probe
|
||||
# hit the cap would silently sit at min_inflight forever. A pinned
|
||||
# band (min_inflight = max_inflight) makes the controller inert and
|
||||
# is the supported way to run against such endpoints.
|
||||
if not await self.inference_metrics.probe():
|
||||
concurrency = config.eval.concurrency
|
||||
if concurrency.min_inflight != concurrency.max_inflight:
|
||||
urls = ", ".join(str(client.base_url) for client in self.pool.admin_clients)
|
||||
raise ValueError(
|
||||
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
|
||||
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
|
||||
"pin the concurrency by setting eval.concurrency.min_inflight = max_inflight."
|
||||
)
|
||||
get_logger().warning(f"No engine metrics - running with concurrency pinned at {concurrency.min_inflight}")
|
||||
await self.inference_metrics.start()
|
||||
|
||||
self.periodic_logger = PeriodicLogger(
|
||||
name="Evals",
|
||||
collect=self.collect_pipeline_view,
|
||||
metric_keys=[
|
||||
*list(self.dispatcher.gauges().keys()),
|
||||
*list(self.concurrency.gauges().keys()),
|
||||
*DispatcherMetrics.drain_keys(train_envs=set(), eval_envs={env.name for env in self.eval_envs}),
|
||||
],
|
||||
interval=config.log.interval,
|
||||
wandb_enabled=wandb_enabled,
|
||||
)
|
||||
|
||||
def spawn_env_servers(self) -> None:
|
||||
"""Spawn one env server per source without an explicit ``serve.address``,
|
||||
at the source's derived address."""
|
||||
config = self.config
|
||||
addresses = config.eval.env_addresses
|
||||
config_dir = get_config_dir(config.output_dir) / "envs" / "eval"
|
||||
log_dir = get_log_dir(config.output_dir) / "envs" / "eval"
|
||||
for source in config.eval.source:
|
||||
if source.serve.address is not None:
|
||||
continue
|
||||
name = source.resolved_name
|
||||
address = addresses[("eval", name)]
|
||||
source_dict = dump_resolved_config(source)
|
||||
server_config = {
|
||||
"env": source_dict["env"],
|
||||
"serve": {**(source_dict.get("serve") or {}), "address": address},
|
||||
"log": {"level": config.log.vf_level, "json_logging": config.log.json_logging},
|
||||
}
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_path = config_dir / f"{name}.json"
|
||||
config_path.write_text(json.dumps(server_config, indent=2))
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
log_path = log_dir / f"{name}.log"
|
||||
get_logger().info(f"Starting env server {name} at {address} (logs: {log_path})")
|
||||
with open(log_path, "w") as log_file:
|
||||
process = Popen(
|
||||
["env-server", "@", config_path.as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
self.env_server_procs.append(process)
|
||||
|
||||
async def run(self) -> None:
|
||||
await self.setup()
|
||||
self.dispatcher_task = asyncio.create_task(self.dispatcher.start(), name="dispatcher")
|
||||
await self.periodic_logger.start()
|
||||
|
||||
if self.config.online is None:
|
||||
await self.maybe_run_evals(step=0)
|
||||
else:
|
||||
await self.watch()
|
||||
|
||||
# The periodic logger and the collector log to the W&B run, so they
|
||||
# must stop before finalize marks the run finished.
|
||||
await self.periodic_logger.stop()
|
||||
await self.inference_metrics.stop()
|
||||
get_logger().success("Evals finished!")
|
||||
|
||||
async def watch(self) -> None:
|
||||
"""Online mode: evaluate each eligible weight checkpoint as it appears."""
|
||||
config = self.config
|
||||
assert config.online is not None
|
||||
online = config.online
|
||||
|
||||
if online.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 = online.max_steps is not None and online.resume_step >= online.max_steps
|
||||
await self.maybe_run_evals(step=online.resume_step, reload_weights=True, force=is_final)
|
||||
|
||||
get_logger().info(f"Watching {online.weights_dir} for new weight checkpoints (max_steps={online.max_steps})")
|
||||
while True:
|
||||
assert online.weights_dir is not None # resolved by the config validator
|
||||
steps = get_all_ckpt_steps(online.weights_dir)
|
||||
stable = {step: (get_step_path(online.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 evals process) - 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 = online.max_steps is not None and step >= online.max_steps
|
||||
await self.maybe_run_evals(step=step, reload_weights=True, force=is_final)
|
||||
if online.max_steps is not None and self.last_step >= online.max_steps:
|
||||
break
|
||||
await asyncio.sleep(POLL_INTERVAL_S)
|
||||
|
||||
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."""
|
||||
if reload_weights:
|
||||
assert self.config.online is not None and self.config.online.weights_dir is not None
|
||||
weight_dir = get_step_path(self.config.online.weights_dir, step)
|
||||
if 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
|
||||
|
||||
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
|
||||
# between the trigger above and the weight reload completing.
|
||||
self.policy.version = step
|
||||
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
|
||||
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=f"eval was triggered at step {step}")
|
||||
await self.consume_epoch(fired)
|
||||
|
||||
async def consume_epoch(self, fired: list[str]) -> None:
|
||||
"""Consume dispatcher episodes until every fired env's epoch finalizes,
|
||||
routing them through the sink and monitors."""
|
||||
# An env with no examples emits no episodes, so its epoch can never finalize.
|
||||
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
|
||||
while pending:
|
||||
episode = await self.dispatcher.out_q.get()
|
||||
step = eval_work(episode).step
|
||||
await monitors.log([episode], step, "eval", "all")
|
||||
eval_batch = self.eval_sink.add(episode)
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
pending.discard(eval_batch.env_name)
|
||||
|
||||
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.episodes:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no episodes returned, skipping log")
|
||||
return
|
||||
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
|
||||
episodes = batch.episodes
|
||||
effective = episodes.effective
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", episodes), ("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, episodes.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%}"
|
||||
)
|
||||
|
||||
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
|
||||
"""Pipeline view for the ``PeriodicLogger``: per-env epoch progress plus the
|
||||
in-flight pool against the controller's current cap."""
|
||||
disp_gauges = self.dispatcher.gauges()
|
||||
disp_drain = self.dispatcher.metrics.drained(train_envs=set(), eval_envs={env.name for env in self.eval_envs})
|
||||
|
||||
parts = []
|
||||
for env_name, _step, arrived, expected, buffered in sorted(self.eval_sink.batch_progress()):
|
||||
part = f"{env_name} {arrived}/{expected} ({arrived / expected:.1%})" if expected else env_name
|
||||
if buffered:
|
||||
part += f" (+{buffered} buffered)"
|
||||
parts.append(part)
|
||||
progress_part = " | ".join(parts) if parts else "Idle"
|
||||
|
||||
body = (
|
||||
f"{progress_part}; {self.dispatcher.inflight_eval_count} inflight episodes "
|
||||
f"(cap {self.dispatcher.max_inflight}, signal {self.concurrency.signal})"
|
||||
)
|
||||
payload = {**disp_gauges, **disp_drain, **self.concurrency.gauges()}
|
||||
return body, payload
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
|
||||
periodic_logger: PeriodicLogger | None = getattr(self, "periodic_logger", None)
|
||||
if periodic_logger is not None:
|
||||
await periodic_logger.stop()
|
||||
inference_metrics: InferenceMetricsCollector | None = getattr(self, "inference_metrics", None)
|
||||
if inference_metrics is not None:
|
||||
await inference_metrics.stop()
|
||||
dispatcher: Dispatcher | None = getattr(self, "dispatcher", None)
|
||||
if dispatcher is not None:
|
||||
await dispatcher.stop()
|
||||
pool: InferencePool | None = getattr(self, "pool", None)
|
||||
if pool is not None:
|
||||
await pool.stop()
|
||||
cleanup_processes(self.env_server_procs)
|
||||
|
||||
|
||||
@clean_exit
|
||||
async def run_evals(config: EvalsConfig) -> None:
|
||||
evals = Evals(config)
|
||||
try:
|
||||
await evals.run()
|
||||
# Finalize only on a clean exit — a crashed evals must not mark the run completed.
|
||||
await monitors.finalize()
|
||||
finally:
|
||||
await evals.stop()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
set_proc_title("Evals")
|
||||
asyncio.run(run_evals(cli(EvalsConfig)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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
|
||||
|
||||
@@ -28,7 +28,7 @@ class FileMonitor(Monitor):
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Line-buffered append so a concurrently-running dashboard can tail the file.
|
||||
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
|
||||
self.logger.info(f"Logging metrics to {self.path} and traces to {output_dir / 'rollouts'}")
|
||||
self.logger.info(f"Logging metrics to {self.path} and episodes to {output_dir / 'rollouts'}")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
sanitized, dropped = sanitize(metrics)
|
||||
@@ -41,9 +41,10 @@ class FileMonitor(Monitor):
|
||||
self.file.write(json.dumps(row) + "\n")
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
"""Append the cohort's traces to its per-step trace file. ``all`` grows one
|
||||
"""Append the cohort to its per-step episode file. ``all`` grows one
|
||||
episode at a time as they complete, ``effective`` one batch at a time on finalize,
|
||||
so an in-progress run's traces can be inspected live."""
|
||||
so an in-progress run can be inspected live. Episode-level failures are
|
||||
preserved even when no trace was produced."""
|
||||
|
||||
def write() -> None:
|
||||
path = self.output_dir / "rollouts" / f"step_{step}" / kind / subset / "traces.jsonl"
|
||||
@@ -51,8 +52,7 @@ class FileMonitor(Monitor):
|
||||
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
|
||||
with open(path, "ab") as f:
|
||||
for episode in episodes:
|
||||
for trace in episode.traces:
|
||||
f.write(orjson.dumps(trace.to_record(), default=str, option=opts))
|
||||
f.write(orjson.dumps(episode.to_record(), default=str, option=opts))
|
||||
|
||||
# Record serialization is heavy pure-Python work; keep it off the event loop.
|
||||
# Awaited (not fire-and-forget) so appends to one file never interleave.
|
||||
|
||||
@@ -277,7 +277,7 @@ def episodes_to_parquet_bytes(episodes: list[vf.Episode], run_id: str | None, st
|
||||
env_names: dict[str, str] = {}
|
||||
for episode in episodes:
|
||||
summary_trace = next((trace for trace in episode.traces if trace.agent.trainable), episode.traces[0])
|
||||
advantages[episode.id] = summary_trace.scalar_advantage()
|
||||
advantages[episode.id] = summary_trace.info.get("advantage")
|
||||
env_names[episode.id] = episode.env.id
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
@@ -55,7 +55,7 @@ class WandbMonitor(Monitor):
|
||||
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).
|
||||
# trainer creates the run, the evals process outlives it and finalizes).
|
||||
finisher = label == os.environ.get("WANDB_SHARED_FINISHER", primary_label)
|
||||
settings = wandb.Settings(
|
||||
mode="shared",
|
||||
|
||||
@@ -71,6 +71,7 @@ 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.
|
||||
|
||||
@@ -8,21 +8,14 @@ turns the signal half into runtime objects (the sampling half is the env's
|
||||
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
|
||||
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``) — each named class owns
|
||||
its scoring hooks
|
||||
(``score_rollout`` / ``score_group``) and declares what it needs (loss
|
||||
(``score_episode`` / ``score_group``) and declares what it needs (loss
|
||||
component, a "teacher", ...). One instance per env, built by
|
||||
:func:`build_algorithm`. A new credit-assignment scheme is a new named class:
|
||||
subclass :class:`Algorithm`, assign advantages in the hook whose timing fits,
|
||||
and register it below.
|
||||
- ``base`` — the :class:`Algorithm` base class, whose non-virtual
|
||||
``finalize_rollout`` / ``finalize_group`` methods the pipeline drives.
|
||||
Advantages are per-token everywhere they are stored or shipped — there is no
|
||||
scalar advantage in the pipeline. An algorithm assigns credit in its scoring
|
||||
hook via ``Rollout.assign_advantages``: a scalar that is *broadcast* over the
|
||||
rollout's completion tokens (uniform credit, the common case), or an explicit
|
||||
full-length-N per-token list aligned to the concatenated sample token_ids
|
||||
(0.0 off-mask).
|
||||
- ``routing`` — wire-field stamping: per-token component weight streams
|
||||
(rl / ce / ref_kl) and the per-token advantage stream.
|
||||
- ``base`` — the :class:`Algorithm` base class. Algorithms annotate native
|
||||
verifier graphs; transport samples are compiled only after admission.
|
||||
- ``routing`` — graph annotation and final transport loss routing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,9 +30,8 @@ from prime_rl.orchestrator.algo.max_rl import MaxRLAlgorithm
|
||||
from prime_rl.orchestrator.algo.opd import OPDAlgorithm
|
||||
from prime_rl.orchestrator.algo.opsd import OPSDAlgorithm
|
||||
from prime_rl.orchestrator.algo.rae import RAEAlgorithm
|
||||
from prime_rl.orchestrator.algo.routing import stamp_advantages, stamp_loss_routing
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages, stamp_loss_routing
|
||||
from prime_rl.orchestrator.algo.sft import SFTDistillAlgorithm
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.configs.algorithm import AlgoConfig
|
||||
@@ -79,10 +71,9 @@ __all__ = [
|
||||
"OPDAlgorithm",
|
||||
"OPSDAlgorithm",
|
||||
"RAEAlgorithm",
|
||||
"Rollout",
|
||||
"SFTDistillAlgorithm",
|
||||
"build_algorithm",
|
||||
"connect_frozen_pool",
|
||||
"stamp_advantages",
|
||||
"assign_advantages",
|
||||
"stamp_loss_routing",
|
||||
]
|
||||
|
||||
@@ -1,70 +1,24 @@
|
||||
"""The per-env algorithm runtime: the :class:`Algorithm` base class.
|
||||
|
||||
Each named class in this package *is* one training algorithm, one module per
|
||||
algorithm: it owns the algorithm's two scoring hooks directly —
|
||||
``score_rollout`` (per arrival) and ``score_group`` (per group) — and declares
|
||||
which loss component its action tokens feed (``action_loss_type``). Reading a
|
||||
module top to bottom reads the algorithm; writing your own is subclassing
|
||||
:class:`Algorithm` and overriding the hooks its signal needs. Shared math (group
|
||||
normalization, prefill alignment) lives as plain functions in ``advantage.py``;
|
||||
duplication of orchestration between similar algorithms (e.g. OPD and OPSD) is
|
||||
accepted so each module stays self-contained.
|
||||
|
||||
The two hooks are one scope-and-timing ladder — the wider scope is unlocked by
|
||||
a later barrier, so the two axes coincide. Both are ``async`` (either may do
|
||||
I/O); a hook that only does advantage math never awaits:
|
||||
|
||||
- ``score_rollout(rollout)`` — one rollout, on arrival: rollout-local signals
|
||||
(raw reward, process rewards, echo's observation weighting) *and* per-rollout
|
||||
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).
|
||||
|
||||
How rollouts are *produced* is not the algorithm's concern: that is the env's
|
||||
:class:`~prime_rl.orchestrator.sampler.Sampler`, and sample construction
|
||||
(interleaving, with observation-token provenance via structural node
|
||||
attribution) is pure pipeline.
|
||||
|
||||
The pipeline (train sink) drives each algorithm through its non-virtual
|
||||
:meth:`Algorithm.finalize_rollout` / :meth:`Algorithm.finalize_group` methods
|
||||
and reads the class declarations; it never branches on algorithm config fields
|
||||
or model roles — liveness of a reference is the only runtime distinction.
|
||||
prime-rl hosts exactly one model — the trainable policy, whose pool every
|
||||
algorithm is handed (``self.policy_pool``): use it for anything that scores
|
||||
against the live model (opsd's self-distillation teacher, an LLM judge, ...).
|
||||
Every *frozen* model an algorithm needs is an external endpoint it *connects to*
|
||||
(never launches) and owns, in :meth:`Algorithm.setup`.
|
||||
"""
|
||||
"""Episode-native algorithm hooks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import ActionLossType, AlgoConfig, FrozenModelConfig
|
||||
from prime_rl.orchestrator.algo.routing import stamp_advantages, stamp_loss_routing
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from renderers import RendererConfig
|
||||
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
|
||||
async def connect_frozen_pool(
|
||||
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
|
||||
) -> InferencePool:
|
||||
"""Connect a client pool to an inline frozen model and wait for it to be
|
||||
ready. The endpoint is externally hosted — prime-rl connects and waits,
|
||||
never launches.
|
||||
|
||||
When ``renderer_config`` is set, the pool's train client is the renderer
|
||||
(token-in/out) client — required when the frozen model *generates* rollouts
|
||||
(sft), so the rollout carries tokens. Left as plain chat-completions
|
||||
otherwise (opd/opsd read teacher logprobs via prefill, where the train
|
||||
client type is moot)."""
|
||||
"""Connect to an externally hosted frozen model and wait for it."""
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
|
||||
@@ -78,88 +32,50 @@ async def connect_frozen_pool(
|
||||
return pool
|
||||
|
||||
|
||||
def iter_trainable_traces(episodes: list[vf.Episode]):
|
||||
"""Yield clean trainable traces that contain sampled tokens."""
|
||||
for episode in episodes:
|
||||
for trace in episode.traces:
|
||||
if trace.has_error or not trace.agent.trainable:
|
||||
continue
|
||||
if any(any(node.mask) for node in trace.nodes):
|
||||
yield episode, trace
|
||||
|
||||
|
||||
class Algorithm:
|
||||
"""Base class for one env's training algorithm — the runtime of the
|
||||
algorithm config's per-token training signal (its sibling :class:`Sampler`
|
||||
interprets the ``sampling`` half).
|
||||
"""Assign training annotations directly to verifier episodes.
|
||||
|
||||
Everything on this class is yours to override; the pipeline drives the
|
||||
compilation through the non-virtual :meth:`finalize_rollout` /
|
||||
:meth:`finalize_group` methods and never calls anything else. The surface is:
|
||||
|
||||
- declarations — which loss component the action tokens feed
|
||||
(``action_loss_type``);
|
||||
- lifecycle — :meth:`setup` connects client pools to the frozen models
|
||||
the algorithm declares, resolving each reference via :meth:`connect`;
|
||||
- the two scoring hooks, each ``async`` and given the :class:`Rollout`
|
||||
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.
|
||||
|
||||
- :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.
|
||||
|
||||
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.
|
||||
|
||||
Constructed with the algorithm config it interprets plus the live policy
|
||||
pool (``self.policy_pool`` — always available, never closed by the
|
||||
algorithm). An algorithm that needs to tokenize (e.g. opsd's demonstration
|
||||
hint) builds its own renderer in :meth:`setup` from its config; the policy's
|
||||
renderer is not threaded in."""
|
||||
Override :meth:`score_episode` for rollout-local work and
|
||||
:meth:`score_group` for cohort-relative work. The train sink compiles the
|
||||
annotated traces into transport samples only after admission.
|
||||
"""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
def __init__(self, config: AlgoConfig, policy_pool: InferencePool):
|
||||
self.policy_pool = policy_pool
|
||||
self.connected_pools: list[InferencePool] = [] # frozen pools connected in setup(); closed at shutdown
|
||||
self.connected_pools: list[InferencePool] = []
|
||||
|
||||
async def setup(self) -> None:
|
||||
"""Connect client pools to the algorithm's frozen models — override
|
||||
and resolve each reference via :meth:`connect`. The base has nothing
|
||||
to connect."""
|
||||
"""Connect resources owned by the algorithm."""
|
||||
|
||||
async def connect(self, reference: FrozenModelConfig) -> InferencePool:
|
||||
"""Connect a client pool to a frozen model endpoint and track it in
|
||||
``connected_pools`` — the host closes what the algorithm opened, at
|
||||
shutdown. The live policy is never connected here; opsd receives the
|
||||
policy pool directly."""
|
||||
"""Connect and track a frozen model pool owned by this algorithm."""
|
||||
pool = await connect_frozen_pool(reference)
|
||||
self.connected_pools.append(pool)
|
||||
return pool
|
||||
|
||||
async def score_rollout(self, rollout: Rollout) -> None:
|
||||
"""Arrival phase, one rollout, before its group is complete: write
|
||||
rollout-local credit (``rollout.assign_advantages``), observation ce
|
||||
weights (echo), or per-token results from a model — an inference pool
|
||||
connected in :meth:`setup`, or the live policy (opsd). No siblings, no
|
||||
group stats."""
|
||||
async def score_episode(self, episode: vf.Episode) -> None:
|
||||
"""Assign rollout-local annotations to one finalized episode."""
|
||||
|
||||
async def score_group(self, group: list[Rollout]) -> None:
|
||||
"""Group phase, the finalized cohort, before filtering: write
|
||||
group-relative credit."""
|
||||
async def score_group(self, episodes: list[vf.Episode]) -> None:
|
||||
"""Assign group-relative annotations to a finalized cohort."""
|
||||
|
||||
async def finalize_rollout(self, rollout: Rollout) -> None:
|
||||
"""Arrival phase (non-virtual): rollout-local scoring as each rollout is
|
||||
tokenized."""
|
||||
if rollout.samples:
|
||||
await self.score_rollout(rollout)
|
||||
async def finalize_episode(self, episode: vf.Episode) -> None:
|
||||
"""Run rollout-local scoring when the episode has trainable traces."""
|
||||
if any(True for _ in iter_trainable_traces([episode])):
|
||||
await self.score_episode(episode)
|
||||
|
||||
async def finalize_group(self, rollouts: list[Rollout]) -> None:
|
||||
"""Group phase (non-virtual): group-relative scoring, then stamp each
|
||||
sample's wire fields (the advantage stream + loss routing). After this
|
||||
the records are frozen — groups die at stamping."""
|
||||
await self.score_group(rollouts)
|
||||
for rollout in rollouts:
|
||||
stamp_advantages(rollout)
|
||||
for sample in rollout.samples:
|
||||
stamp_loss_routing(sample, self.action_loss_type)
|
||||
async def finalize_group(self, episodes: list[vf.Episode]) -> None:
|
||||
"""Run group-relative scoring over the native episodes."""
|
||||
await self.score_group(episodes)
|
||||
|
||||
@@ -11,7 +11,6 @@ from prime_rl.utils.utils import import_object
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
|
||||
@@ -34,13 +33,13 @@ class EchoAlgorithm(GRPOAlgorithm):
|
||||
if config.filter is not None:
|
||||
self.filter_fn = partial(import_object(config.filter.import_path), **config.filter.kwargs)
|
||||
|
||||
async def score_rollout(self, rollout: Rollout) -> None:
|
||||
# Observation weighting is rollout-local; the group-relative GRPO
|
||||
# baseline is inherited unchanged as ``score_group``.
|
||||
self._weight_observations(rollout)
|
||||
async def score_episode(self, episode: vf.Episode) -> None:
|
||||
for trace in episode.traces:
|
||||
if not trace.has_error and trace.agent.trainable:
|
||||
self._weight_observations(trace)
|
||||
|
||||
def _weight_observations(self, rollout: Rollout) -> None:
|
||||
"""Write each sample's ``ce_weights`` stream over the env-provided
|
||||
def _weight_observations(self, trace: vf.Trace) -> None:
|
||||
"""Write graph-native ``ce`` weights over the env-provided
|
||||
observation tokens of later turns. Provenance is structural under v1:
|
||||
within a branch, the non-sampled nodes that follow the first model
|
||||
response (tool output, user feedback) are the env-provided
|
||||
@@ -56,12 +55,10 @@ class EchoAlgorithm(GRPOAlgorithm):
|
||||
(role tags, separators, tool-response wraps) is excluded. Nodes without
|
||||
attribution (the default renderer, or relay turns with no token ids)
|
||||
fall back to weighting the whole non-sampled span."""
|
||||
# Same branch selection as ``trace_to_samples``, so the zip with ``rollout.samples``
|
||||
# stays aligned when fork dedup drops a branch.
|
||||
trainable_branches = [branch for branch, _ in iter_trainable_branches(rollout)]
|
||||
filter_masks = self._filter_masks(rollout, trainable_branches) if self.filter_fn is not None else None
|
||||
for sample_idx, (sample, branch) in enumerate(zip(rollout.samples, trainable_branches)):
|
||||
weights = [0.0] * len(sample.token_ids)
|
||||
trainable_branches = [branch for branch, _ in iter_trainable_branches(trace)]
|
||||
filter_masks = self._filter_masks(trace, trainable_branches) if self.filter_fn is not None else None
|
||||
for branch_idx, branch in enumerate(trainable_branches):
|
||||
weights = [0.0] * len(branch.token_ids)
|
||||
offset = 0
|
||||
seen_response = False
|
||||
for node in branch.nodes:
|
||||
@@ -69,7 +66,7 @@ class EchoAlgorithm(GRPOAlgorithm):
|
||||
role = node.message.role
|
||||
if seen_response and not node.sampled and role in self.role_weights:
|
||||
weight = self.role_weights[role]
|
||||
keep_mask = filter_masks[sample_idx] if filter_masks is not None else None
|
||||
keep_mask = filter_masks[branch_idx] if filter_masks is not None else None
|
||||
# Per-token content granularity when the renderer attributed it; otherwise
|
||||
# the whole node span (is_content empty -> fall back to current behavior).
|
||||
has_content = len(node.is_content) == span
|
||||
@@ -81,8 +78,16 @@ class EchoAlgorithm(GRPOAlgorithm):
|
||||
if node.sampled:
|
||||
seen_response = True
|
||||
offset += span
|
||||
if any(weights):
|
||||
sample.ce_weights = weights
|
||||
offset = 0
|
||||
for node in branch.nodes:
|
||||
end = offset + len(node.token_ids)
|
||||
node_weights = weights[offset:end]
|
||||
if any(node_weights):
|
||||
streams = dict(node.loss_weights or {})
|
||||
current = streams.get("ce", [0.0] * len(node.token_ids))
|
||||
streams["ce"] = [max(old, new) for old, new in zip(current, node_weights, strict=True)]
|
||||
node.loss_weights = streams
|
||||
offset = end
|
||||
|
||||
def _filter_masks(self, trace: vf.Trace, trainable_branches: list) -> list[list[bool]]:
|
||||
"""Invoke the user echo filter and validate its shape: one keep-mask
|
||||
|
||||
@@ -3,12 +3,13 @@ from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import GRPOAlgoConfig
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
|
||||
@@ -21,15 +22,16 @@ class GRPOAlgorithm(Algorithm):
|
||||
super().__init__(config, policy_pool)
|
||||
self.length_penalty = config.length_penalty
|
||||
|
||||
async def score_group(self, group: list[Rollout]) -> None:
|
||||
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
|
||||
async def score_group(self, episodes: list[vf.Episode]) -> None:
|
||||
traces = [trace for _, trace in iter_trainable_traces(episodes)]
|
||||
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
|
||||
length_penalty = self.length_penalty
|
||||
if length_penalty is None:
|
||||
advantages = rewards - rewards.mean()
|
||||
else:
|
||||
output = torch.tensor([rollout.num_output_tokens for rollout in group], dtype=rewards.dtype)
|
||||
total = torch.tensor([rollout.num_total_tokens for rollout in group], dtype=rewards.dtype)
|
||||
turns = torch.tensor([rollout.num_turns for rollout in group], dtype=rewards.dtype)
|
||||
output = torch.tensor([trace.num_output_tokens for trace in traces], dtype=rewards.dtype)
|
||||
total = torch.tensor([trace.num_total_tokens for trace in traces], dtype=rewards.dtype)
|
||||
turns = torch.tensor([trace.num_turns for trace in traces], dtype=rewards.dtype)
|
||||
input = total - output
|
||||
penalty_frac = (
|
||||
length_penalty.num_output_tokens_weight * (output / output.max().clamp(min=1))
|
||||
@@ -39,5 +41,5 @@ class GRPOAlgorithm(Algorithm):
|
||||
penalty = rewards.mean() * penalty_frac
|
||||
shaped_rewards = rewards - penalty
|
||||
advantages = shaped_rewards - shaped_rewards.mean()
|
||||
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
|
||||
rollout.assign_advantages(advantage)
|
||||
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
|
||||
assign_advantages(trace, advantage)
|
||||
|
||||
@@ -3,11 +3,13 @@ from __future__ import annotations
|
||||
from collections import defaultdict
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import HierarchicalGRPOAlgoConfig
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
|
||||
@@ -28,13 +30,13 @@ class HierarchicalGRPOAlgorithm(Algorithm):
|
||||
super().__init__(config, policy_pool)
|
||||
self.episode_agents = set(config.episode_agents)
|
||||
|
||||
async def score_group(self, group: list[Rollout]) -> None:
|
||||
peers: dict[tuple[str, str | None], list[Rollout]] = defaultdict(list)
|
||||
for rollout in group:
|
||||
episode_scoped = rollout.agent.name in self.episode_agents
|
||||
key = (rollout.agent.name, rollout.episode_id if episode_scoped else None)
|
||||
peers[key].append(rollout)
|
||||
async def score_group(self, episodes: list[vf.Episode]) -> None:
|
||||
peers: dict[tuple[str, str | None], list[vf.Trace]] = defaultdict(list)
|
||||
for episode, trace in iter_trainable_traces(episodes):
|
||||
episode_scoped = trace.agent.name in self.episode_agents
|
||||
key = (trace.agent.name, episode.id if episode_scoped else None)
|
||||
peers[key].append(trace)
|
||||
for members in peers.values():
|
||||
baseline = sum(rollout.reward for rollout in members) / len(members)
|
||||
for rollout in members:
|
||||
rollout.assign_advantages(rollout.reward - baseline)
|
||||
baseline = sum(trace.reward for trace in members) / len(members)
|
||||
for trace in members:
|
||||
assign_advantages(trace, trace.reward - baseline)
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
|
||||
|
||||
class MaxRLAlgorithm(Algorithm):
|
||||
@@ -20,12 +17,12 @@ 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)
|
||||
async def score_group(self, episodes: list[vf.Episode]) -> None:
|
||||
traces = [trace for _, trace in iter_trainable_traces(episodes)]
|
||||
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
|
||||
mean = rewards.mean()
|
||||
advantages = torch.zeros_like(rewards) if mean <= 0 else (rewards - mean) / mean
|
||||
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
|
||||
rollout.assign_advantages(advantage)
|
||||
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
|
||||
assign_advantages(trace, advantage)
|
||||
|
||||
@@ -3,12 +3,14 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import OPDAlgoConfig
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_reference_logprobs
|
||||
from prime_rl.orchestrator.trajectories import iter_trainable_branches
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
|
||||
@@ -19,9 +21,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"
|
||||
|
||||
@@ -33,11 +34,12 @@ class OPDAlgorithm(Algorithm):
|
||||
async def setup(self) -> None:
|
||||
self.teacher_pool = await self.connect(self.teacher)
|
||||
|
||||
async def score_rollout(self, rollout: Rollout) -> None:
|
||||
async def score_episode(self, episode: vf.Episode) -> None:
|
||||
pool = self.teacher_pool
|
||||
assert pool is not None, "teacher pool not connected — Algorithm.setup() must run first"
|
||||
|
||||
async def score_sample(sample: TrainingSample) -> None:
|
||||
sample.ref_logprobs = await pool.score(list(sample.token_ids))
|
||||
|
||||
await asyncio.gather(*(score_sample(sample) for sample in rollout.samples))
|
||||
branches = [
|
||||
branch for _, trace in iter_trainable_traces([episode]) for branch, _ in iter_trainable_branches(trace)
|
||||
]
|
||||
scores = await asyncio.gather(*(pool.score(branch.token_ids) for branch in branches))
|
||||
for branch, logprobs in zip(branches, scores, strict=True):
|
||||
assign_reference_logprobs(branch, logprobs)
|
||||
|
||||
@@ -3,14 +3,17 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import OPSDAlgoConfig
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_reference_logprobs
|
||||
from prime_rl.orchestrator.trajectories import iter_trainable_branches
|
||||
from prime_rl.orchestrator.utils import episode_env_name
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from renderers.base import Renderer
|
||||
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
|
||||
@@ -50,28 +53,26 @@ class OPSDAlgorithm(Algorithm):
|
||||
|
||||
self.renderer = create_renderer(load_tokenizer(self.policy_pool.model_name), self.renderer_config)
|
||||
|
||||
def _demonstration(self, rollout: Rollout) -> str:
|
||||
demonstration = rollout.info.get(self.demo_key)
|
||||
def _demonstration(self, episode: vf.Episode, trace: vf.Trace) -> str:
|
||||
demonstration = trace.info.get(self.demo_key)
|
||||
if demonstration is None:
|
||||
demonstration = getattr(rollout.task.data, self.demo_key, None)
|
||||
demonstration = getattr(trace.task.data, self.demo_key, None)
|
||||
if demonstration is None:
|
||||
env_name = episode_env_name(episode)
|
||||
raise ValueError(
|
||||
f"opsd requires '{self.demo_key}' in the trace info dict or on the task "
|
||||
f"(env '{rollout.env_name}', task {rollout.task.data.idx})."
|
||||
f"(env '{env_name}', task {trace.task.data.idx})."
|
||||
)
|
||||
return demonstration
|
||||
|
||||
async def score_rollout(self, rollout: Rollout) -> None:
|
||||
async def score_episode(self, episode: vf.Episode) -> None:
|
||||
pool = self.teacher_pool
|
||||
renderer = self.renderer
|
||||
assert renderer is not None, "renderer not built — Algorithm.setup() must run first"
|
||||
hint = self.template.format(demonstration=self._demonstration(rollout))
|
||||
hint_block = renderer.render_ids([{"role": "system", "content": hint}], add_generation_prompt=False)
|
||||
|
||||
async def score_sample(sample: TrainingSample) -> None:
|
||||
full_logprobs = await pool.score(hint_block + list(sample.token_ids))
|
||||
# Drop the hint's own logprobs; the tail aligns full-length to
|
||||
# sample.token_ids (demo-conditioned, the trainer's ref_kl target).
|
||||
sample.ref_logprobs = full_logprobs[len(hint_block) :]
|
||||
|
||||
await asyncio.gather(*(score_sample(sample) for sample in rollout.samples))
|
||||
for _, trace in iter_trainable_traces([episode]):
|
||||
hint = self.template.format(demonstration=self._demonstration(episode, trace))
|
||||
hint_block = renderer.render_ids([{"role": "system", "content": hint}], add_generation_prompt=False)
|
||||
branches = [branch for branch, _ in iter_trainable_branches(trace)]
|
||||
scores = await asyncio.gather(*(pool.score(hint_block + branch.token_ids) for branch in branches))
|
||||
for branch, full_logprobs in zip(branches, scores, strict=True):
|
||||
assign_reference_logprobs(branch, full_logprobs[len(hint_block) :])
|
||||
|
||||
@@ -3,11 +3,13 @@ from __future__ import annotations
|
||||
from collections import defaultdict
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import RAEAlgoConfig
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
|
||||
@@ -34,8 +36,8 @@ class RAEAlgorithm(Algorithm):
|
||||
self.decay = config.decay
|
||||
self.baselines: dict[str, float] = defaultdict(float)
|
||||
|
||||
async def score_group(self, group: list[Rollout]) -> None:
|
||||
for rollout in group:
|
||||
baseline = self.baselines[rollout.agent.name]
|
||||
rollout.assign_advantages(rollout.reward - baseline)
|
||||
self.baselines[rollout.agent.name] = self.decay * baseline + (1.0 - self.decay) * rollout.reward
|
||||
async def score_group(self, episodes: list[vf.Episode]) -> None:
|
||||
for _, trace in iter_trainable_traces(episodes):
|
||||
baseline = self.baselines[trace.agent.name]
|
||||
assign_advantages(trace, trace.reward - baseline)
|
||||
self.baselines[trace.agent.name] = self.decay * baseline + (1.0 - self.decay) * trace.reward
|
||||
|
||||
@@ -1,38 +1,71 @@
|
||||
"""Wire-field stamping for the per-token streams.
|
||||
|
||||
The training loss is a sum of three components — ``rl`` (importance-weighted
|
||||
PG + KL), ``ce`` (masked NLL), and ``ref_kl`` (reverse KL to a reference model
|
||||
as the PG signal) — each normalized by its own global token count in the
|
||||
trainer. The algorithm decides which component the action tokens feed
|
||||
and the per-token advantages the rl component consumes; these helpers write
|
||||
the component weight streams and the advantage stream onto the
|
||||
``TrainingSample`` wire fields at group finalization.
|
||||
"""
|
||||
"""Training annotations and transport loss routing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
import verifiers.v1 as vf
|
||||
|
||||
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
|
||||
|
||||
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
|
||||
"""Assign credit in compact sampled-token order across the trace graph."""
|
||||
nodes = [node for node in trace.nodes if any(node.mask)]
|
||||
for node in nodes:
|
||||
if len(node.mask) != len(node.token_ids):
|
||||
raise ValueError(
|
||||
f"node masks must align with token ids in trace {trace.id!r}: "
|
||||
f"got {len(node.mask)}, expected {len(node.token_ids)}"
|
||||
)
|
||||
total = sum(sum(node.mask) for node in nodes)
|
||||
if isinstance(values, (int, float)):
|
||||
advantages = [float(values)] * total
|
||||
else:
|
||||
if len(values) != total:
|
||||
raise ValueError(
|
||||
f"advantages must align with trace {trace.id!r}'s sampled tokens: got {len(values)}, expected {total}"
|
||||
)
|
||||
advantages = [float(value) for value in values]
|
||||
|
||||
offset = 0
|
||||
for node in nodes:
|
||||
end = offset + sum(node.mask)
|
||||
node.advantages = advantages[offset:end]
|
||||
offset = end
|
||||
|
||||
|
||||
def assign_reference_logprobs(branch: vf.Branch, values: list[float]) -> None:
|
||||
"""Project branch-aligned reference logprobs onto sampled graph nodes."""
|
||||
if len(values) != len(branch.token_ids):
|
||||
raise ValueError(
|
||||
f"reference logprobs must align with branch tokens: got {len(values)}, expected {len(branch.token_ids)}"
|
||||
)
|
||||
offset = 0
|
||||
for node in branch.nodes:
|
||||
end = offset + len(node.token_ids)
|
||||
if any(node.mask) and node.reference_logprobs is None:
|
||||
node.reference_logprobs = [
|
||||
float(value) for value, sampled in zip(values[offset:end], node.mask, strict=True) if sampled
|
||||
]
|
||||
offset = end
|
||||
|
||||
|
||||
def scalar_advantage(trace: vf.Trace) -> float | None:
|
||||
"""Mean nonzero token advantage, or zero for an assigned-zero trace."""
|
||||
advantages = [value for node in trace.nodes for value in node.advantages or []]
|
||||
if not advantages:
|
||||
return None
|
||||
nonzero = [value for value in advantages if value != 0.0]
|
||||
return sum(nonzero) / len(nonzero) if nonzero else 0.0
|
||||
|
||||
|
||||
def is_trainable(trace: vf.Trace) -> bool:
|
||||
"""Whether any sampled token carries nonzero RL credit."""
|
||||
return any(value != 0.0 for node in trace.nodes for value in node.advantages or [])
|
||||
|
||||
|
||||
def stamp_loss_routing(sample: TrainingSample, action_loss_type: ActionLossType) -> None:
|
||||
"""Stamp the algorithm's loss routing onto one sample's component weight
|
||||
streams: action tokens (the trainable completion tokens, per the loss
|
||||
mask) feed the algorithm's declared component.
|
||||
|
||||
``rl`` is the default and ships nothing (absent streams mean rl weight
|
||||
1.0 on the loss mask — the hot path); ``ce``/``ref_kl`` weight the action
|
||||
tokens into that component's stream and zero the rl stream. Streams an
|
||||
algorithm wrote directly (echo's observation ce weights) are merged, not
|
||||
clobbered — env-provided tokens stay out of the loss ``mask``, so the
|
||||
component an algorithm weights them into is the only one that trains
|
||||
them.
|
||||
"""
|
||||
"""Route action tokens into the algorithm's declared loss component."""
|
||||
if action_loss_type == "rl":
|
||||
return
|
||||
|
||||
@@ -49,26 +82,3 @@ def stamp_loss_routing(sample: TrainingSample, action_loss_type: ActionLossType)
|
||||
else:
|
||||
assert action_loss_type == "ref_kl"
|
||||
sample.ref_kl_weights = action_weights
|
||||
|
||||
|
||||
def stamp_advantages(rollout: Rollout) -> None:
|
||||
"""Stamp the rollout's per-token advantage stream onto its samples' wire
|
||||
fields. The stream is full-length-N — aligned to the samples' ``token_ids``
|
||||
concatenated in order, 0.0 on non-trainable positions — and sliced across
|
||||
them. Rollouts with no credit assigned (``advantages=None``, e.g. opd/opsd)
|
||||
ship no advantage stream.
|
||||
"""
|
||||
advantages = rollout.advantages
|
||||
if advantages is None:
|
||||
return
|
||||
total = sum(len(sample.token_ids) for sample in rollout.samples)
|
||||
if len(advantages) != total:
|
||||
raise ValueError(
|
||||
f"advantage stream must align with the rollout's tokens: "
|
||||
f"got {len(advantages)}, expected {total} (env '{rollout.env_name}')."
|
||||
)
|
||||
offset = 0
|
||||
for sample in rollout.samples:
|
||||
num_tokens = len(sample.token_ids)
|
||||
sample.advantages = list(advantages[offset : offset + num_tokens])
|
||||
offset += num_tokens
|
||||
|
||||
@@ -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,334 @@
|
||||
"""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_SOFT_CAP``: lower the cap to what the engines
|
||||
hold at ``KV_USAGE_TARGET`` and let completions drain the pool (soft). If
|
||||
usage still climbs past ``KV_USAGE_HARD_CAP`` — units maturing in place
|
||||
outpace completions — also cancel the excess, youngest first (hard).
|
||||
- **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_SOFT_CAP = 0.8
|
||||
"""Above this usage, soft-trim: lower the cap and let completions drain the
|
||||
pool naturally — no work is cancelled."""
|
||||
|
||||
KV_USAGE_HARD_CAP = 0.9
|
||||
"""Above this usage, hard-trim: in-place context growth is outpacing
|
||||
completions despite the closed gate, so also cancel the pool excess before
|
||||
thrash onset (a cliff, not a slope)."""
|
||||
|
||||
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_SOFT_CAP and inflight > 0 and self.trim_cooldown == 0:
|
||||
hard = max_usage > KV_USAGE_HARD_CAP
|
||||
target = int(self.clamp(inflight * KV_USAGE_TARGET / max_usage))
|
||||
self.resize_down(
|
||||
target,
|
||||
inflight,
|
||||
reason=f"kv headroom (usage {max_usage:.2f}, {'hard' if hard else 'soft'} trim)",
|
||||
cancel=hard,
|
||||
)
|
||||
self.trim_cooldown = KV_TRIM_COOLDOWN_POLLS
|
||||
|
||||
# ── internals ────────────────────────────────────────────────────────────
|
||||
|
||||
def resize_down(self, target: int, inflight: int, *, reason: str, cancel: bool = True) -> None:
|
||||
"""Lower the cap (never raise) and, with ``cancel``, shed the
|
||||
in-flight excess; without it, admission stays blocked until the pool
|
||||
drains below the new cap on its own."""
|
||||
target = min(target, self.max_inflight)
|
||||
self.cap = float(target)
|
||||
self.apply_limit(target, reason=reason)
|
||||
if cancel and 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,91 @@
|
||||
"""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
|
||||
|
||||
|
||||
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[vf.Episode]) -> bool:
|
||||
"""Observe every result, evaluate every gate, and combine with AND."""
|
||||
if not group:
|
||||
raise ValueError("Cannot report an empty rollout group")
|
||||
task_keys = {episode.task.key for episode 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:
|
||||
expected_fields = {"sampler", "gates"}
|
||||
if set(state_dict) != expected_fields:
|
||||
raise ValueError(f"Curriculum checkpoint fields must be {sorted(expected_fields)}")
|
||||
gate_states = state_dict["gates"]
|
||||
if set(gate_states) != set(self.gates):
|
||||
raise ValueError(
|
||||
f"Curriculum checkpoint gates {sorted(gate_states)} do not match configured gates {sorted(self.gates)}"
|
||||
)
|
||||
self.sampler.load_state_dict(state_dict["sampler"])
|
||||
for name, gate in self.gates.items():
|
||||
gate.load_state_dict(gate_states[name])
|
||||
|
||||
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,36 @@
|
||||
"""Advantage-based training-sample admission."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.curriculum.gates.base import AdmissionGate
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.configs.orchestrator import AdvRangeGateConfig
|
||||
|
||||
|
||||
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[vf.Episode]) -> bool:
|
||||
advantages = [
|
||||
advantage
|
||||
for episode in group
|
||||
for trace in episode.traces
|
||||
if not trace.has_error and trace.agent.trainable
|
||||
for node in trace.nodes
|
||||
for advantage in node.advantages or []
|
||||
]
|
||||
if not advantages:
|
||||
return True
|
||||
return not all(self.config.reject_min <= advantage <= self.config.reject_max for advantage in advantages)
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Admission gate interface."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
|
||||
class AdmissionGate:
|
||||
"""Base class for user-authored training-sample admission policies."""
|
||||
|
||||
def admit(self, group: list[vf.Episode]) -> 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,32 @@
|
||||
"""Task sampler interface."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Iterator
|
||||
from typing import Any
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
|
||||
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[vf.Episode]) -> 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,99 @@
|
||||
"""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
|
||||
|
||||
|
||||
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[vf.Episode]) -> None:
|
||||
rewards = [
|
||||
trace.reward
|
||||
for episode in group
|
||||
for trace in episode.traces
|
||||
if not trace.has_error and trace.agent.trainable
|
||||
]
|
||||
if not rewards:
|
||||
return
|
||||
task = group[0].task
|
||||
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,18 +1,20 @@
|
||||
"""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
|
||||
(env error, empty trajectory, task exception, off-policy cancel) carry
|
||||
``trace.last_error`` set; sinks decide drop / partial-train policy.
|
||||
``out_q`` exactly once. Failures remain episode errors;
|
||||
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,11 +27,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
import traceback
|
||||
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
|
||||
from typing import Any, Literal
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from aiolimiter import AsyncLimiter
|
||||
@@ -39,10 +44,10 @@ 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,
|
||||
Progress,
|
||||
WorkKind,
|
||||
)
|
||||
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
|
||||
from prime_rl.utils.client import InferencePool
|
||||
@@ -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,27 +118,49 @@ class DispatcherMetrics:
|
||||
return keys
|
||||
|
||||
|
||||
class RolloutDispatcher:
|
||||
def _trace_task(task: vf.Task) -> vf.TraceTask:
|
||||
return vf.TraceTask(
|
||||
type=type(task).__name__,
|
||||
data=task.data,
|
||||
key=task.key,
|
||||
hash=task.hash,
|
||||
)
|
||||
|
||||
|
||||
def _validate_episode_task(episode: vf.Episode[Any, Any, Any], task: vf.Task) -> None:
|
||||
expected = (task.key, task.hash)
|
||||
actual = (episode.task.key, episode.task.hash)
|
||||
if actual != expected:
|
||||
raise ValueError(f"Episode task provenance {actual} does not match dispatched task {expected}")
|
||||
|
||||
|
||||
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
|
||||
``out_q``. The watcher drives ``on_version_pending`` for off-policy
|
||||
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules episodes
|
||||
under shared capacity, and emits native verifier episodes to ``out_q``.
|
||||
The watcher drives ``on_version_pending`` for off-policy
|
||||
cancellation; the orchestrator triggers eval epochs."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
train_envs: TrainEnvs,
|
||||
train_envs: TrainEnvs | None,
|
||||
eval_envs: EvalEnvs | None,
|
||||
train_source: TrainSource,
|
||||
train_source: TrainSource | None,
|
||||
eval_source: EvalSource | None,
|
||||
policy_pool: InferencePool,
|
||||
policy: Policy,
|
||||
max_inflight_episodes: int,
|
||||
progress: Progress | None,
|
||||
initial_max_inflight: int,
|
||||
max_inflight_ceiling: int | None,
|
||||
tasks_per_minute: float | None,
|
||||
max_off_policy_steps: int,
|
||||
run_id: str,
|
||||
run_name: str | None,
|
||||
on_episode_complete: Callable[[str, str, int, float], None] | None = None,
|
||||
) -> None:
|
||||
self.policy = policy
|
||||
self.progress = progress
|
||||
self.train_envs = train_envs
|
||||
self.eval_envs = eval_envs
|
||||
# Train rollouts go to the env sampler's pool; eval always
|
||||
@@ -142,19 +169,39 @@ class RolloutDispatcher:
|
||||
self.train_source = train_source
|
||||
self.eval_source = eval_source
|
||||
self.max_off_policy_steps = max_off_policy_steps
|
||||
self.run_id = run_id
|
||||
self.run_name = run_name
|
||||
# ``(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 or ()), 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[vf.Episode[Any, Any, Any]] = asyncio.Queue(maxsize=maxsize)
|
||||
|
||||
self.mode: DispatcherMode = DispatcherMode.PREFER_TRAIN
|
||||
# Set by the orchestrator after the final train step; pipeline then
|
||||
@@ -174,6 +221,7 @@ class RolloutDispatcher:
|
||||
def _train_pool_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
|
||||
"""``(pool, model_name, is_live)`` for *train* rollouts of this env —
|
||||
the env sampler's pool. (Eval always uses the policy.)"""
|
||||
assert self.train_envs is not None # train groups only exist when train is configured
|
||||
sampler = self.train_envs.get(env_name).sampler
|
||||
if sampler.samples_from_live_policy:
|
||||
return sampler.pool, self.policy.model_name, True
|
||||
@@ -189,11 +237,55 @@ 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]:
|
||||
counts: dict[tuple[RolloutKind, str], int] = defaultdict(int)
|
||||
def inflight_by_env(self) -> dict[tuple[WorkKind, str], int]:
|
||||
counts: dict[tuple[WorkKind, str], int] = defaultdict(int)
|
||||
for meta in self.inflight.values():
|
||||
counts[(meta.kind, meta.env_name)] += 1
|
||||
return dict(counts)
|
||||
@@ -209,7 +301,7 @@ class RolloutDispatcher:
|
||||
(``next_fresh_group``), but its ``group_size`` rollouts dispatch one at a time across
|
||||
``fill_inflight`` passes — so the queue can be empty while a group is still mid-schedule."""
|
||||
return bool(self.eval_source) or any(
|
||||
g.kind == "eval" and g.rollouts_to_schedule > 0 for g in self.groups.values()
|
||||
g.kind == "eval" and g.episodes_to_schedule > 0 for g in self.groups.values()
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -256,13 +348,13 @@ class RolloutDispatcher:
|
||||
timeout=0.5, # wake periodically to re-check fill (mode flips)
|
||||
)
|
||||
for task in done:
|
||||
await self.handle_completed_rollout(task)
|
||||
await self.handle_completed_episode(task)
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
|
||||
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
|
||||
@@ -284,6 +376,7 @@ class RolloutDispatcher:
|
||||
continue
|
||||
# Frozen-sourced rollouts never go stale — their sampler doesn't
|
||||
# change with policy updates.
|
||||
assert self.train_envs is not None
|
||||
if not self.train_envs.get(meta.env_name).sampler.samples_from_live_policy:
|
||||
continue
|
||||
meta.off_policy_steps += 1
|
||||
@@ -296,7 +389,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 +403,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,10 +430,10 @@ 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:
|
||||
async def try_schedule(self, kind: WorkKind) -> bool:
|
||||
"""Schedule one rollout of ``kind``: prefer continuing an existing
|
||||
group (keeps prefix-cache hits); otherwise open a fresh group from
|
||||
the corresponding source. Returns False if nothing could be
|
||||
@@ -352,21 +445,22 @@ class RolloutDispatcher:
|
||||
return False
|
||||
|
||||
for gid, group in list(self.groups.items()):
|
||||
if group.kind != kind or group.rollouts_to_schedule <= 0:
|
||||
if group.kind != kind or group.episodes_to_schedule <= 0:
|
||||
continue
|
||||
return await self.schedule_group_rollout(gid, group)
|
||||
return await self.schedule_group_episode(gid, group)
|
||||
|
||||
fresh = self.next_fresh_group(kind, envs)
|
||||
if fresh is None:
|
||||
return False
|
||||
gid = uuid.uuid4()
|
||||
self.groups[gid] = fresh
|
||||
return await self.schedule_group_rollout(gid, fresh)
|
||||
return await self.schedule_group_episode(gid, fresh)
|
||||
|
||||
def next_fresh_group(self, kind: RolloutKind, envs) -> GroupState | None:
|
||||
def next_fresh_group(self, kind: WorkKind, envs) -> GroupState | None:
|
||||
"""Pop the next example from the corresponding source and wrap it in
|
||||
a ``GroupState``. Returns ``None`` if the source is empty."""
|
||||
if kind == "train":
|
||||
assert self.train_source is not None
|
||||
source = self.train_source
|
||||
else:
|
||||
assert self.eval_source is not None
|
||||
@@ -383,13 +477,13 @@ class RolloutDispatcher:
|
||||
kind=kind,
|
||||
env_name=env_name,
|
||||
task=example["task"],
|
||||
rollouts_to_schedule=group_size,
|
||||
target_rollouts=group_size,
|
||||
episodes_to_schedule=group_size,
|
||||
target_episodes=group_size,
|
||||
eval_step=eval_step,
|
||||
policy_version_at_start=self.policy.version,
|
||||
)
|
||||
|
||||
async def schedule_group_rollout(self, group_id: uuid.UUID, group: GroupState) -> bool:
|
||||
async def schedule_group_episode(self, group_id: uuid.UUID, group: GroupState) -> bool:
|
||||
"""Dispatch one ``run`` task for this group.
|
||||
|
||||
Returns False only if we couldn't even schedule one rollout (no clients
|
||||
@@ -422,8 +516,9 @@ class RolloutDispatcher:
|
||||
else:
|
||||
cache_salt = None
|
||||
|
||||
group.rollouts_to_schedule -= 1
|
||||
group.episodes_to_schedule -= 1
|
||||
await self.acquire()
|
||||
self.admissions_in_window += 1
|
||||
task = asyncio.create_task(
|
||||
env.run(
|
||||
client=client,
|
||||
@@ -433,98 +528,132 @@ class RolloutDispatcher:
|
||||
)
|
||||
)
|
||||
|
||||
self.inflight[task] = InflightRollout(
|
||||
self.inflight[task] = InflightEpisode(
|
||||
kind=group.kind,
|
||||
env_name=group.env_name,
|
||||
group_id=group_id,
|
||||
task=group.task,
|
||||
policy_version=group.policy_version_at_start,
|
||||
step=self._work_step(group.kind, group.eval_step),
|
||||
client_config=client,
|
||||
eval_step=group.eval_step,
|
||||
started_at=time.monotonic(),
|
||||
)
|
||||
return True
|
||||
|
||||
def _work_step(self, kind: WorkKind, eval_step: int | None) -> int:
|
||||
if kind == "eval":
|
||||
assert eval_step is not None
|
||||
return eval_step
|
||||
if self.progress is None:
|
||||
raise RuntimeError("Train dispatch requires progress state")
|
||||
return self.progress.step
|
||||
|
||||
async def acquire(self) -> None:
|
||||
"""Reserve one permit + rate-limit it. Caller must precheck
|
||||
``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
|
||||
exceptions synthesize an error-marker episode so the sink's
|
||||
count-to-``group_size`` finalization still triggers. Cancelled tasks
|
||||
(popped by ``drop_group``) raise ``CancelledError`` and are discarded —
|
||||
``drop_group`` already emitted their markers.
|
||||
"""
|
||||
async def handle_completed_episode(self, task: asyncio.Task) -> None:
|
||||
"""Emit every dispatched episode exactly once to ``out_q``."""
|
||||
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
|
||||
try:
|
||||
result = task.result()
|
||||
rollouts: list[Rollout] = result if isinstance(result, list) else [result]
|
||||
if not rollouts:
|
||||
raise RuntimeError("env run returned an empty episode (no traces)")
|
||||
episode: vf.Episode[Any, Any, Any] = task.result()
|
||||
except asyncio.CancelledError:
|
||||
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)),
|
||||
agent=vf.AgentInfo(config=vf.AgentConfig()),
|
||||
)
|
||||
]
|
||||
for r in rollouts:
|
||||
r.record_error(exc)
|
||||
get_logger().warning(f"Episode task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
|
||||
episode = vf.WireEpisode(
|
||||
env=vf.EnvInfo(id=meta.env_name),
|
||||
task=_trace_task(meta.task),
|
||||
ok=False,
|
||||
errors=[
|
||||
vf.Error(
|
||||
type=type(exc).__name__,
|
||||
message=str(exc),
|
||||
traceback="".join(traceback.format_exception(exc)),
|
||||
)
|
||||
],
|
||||
)
|
||||
is_synth_exception = True
|
||||
|
||||
for r in rollouts:
|
||||
if not r.has_error and r.num_turns == 0:
|
||||
if not episode.traces and episode.ok:
|
||||
episode.ok = False
|
||||
episode.errors.append(vf.Error(type="EmptyEpisode", message="Episode returned with no traces"))
|
||||
|
||||
for trace in episode.traces:
|
||||
if not trace.has_error and trace.num_turns == 0:
|
||||
# Empty trajectory: promote to an explicit error so the sink
|
||||
# treats it like any other failure (``has_error`` reads ``ok``)
|
||||
r.errors.append(vf.Error(type="EmptyTrajectory", message="Rollout returned with no trajectory steps"))
|
||||
r.ok = False
|
||||
trace.errors.append(vf.Error(type="EmptyTrajectory", message="Trace returned with no trajectory steps"))
|
||||
trace.ok = False
|
||||
episode.ok = False
|
||||
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
|
||||
if r.has_error:
|
||||
if trace.has_error:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if not is_synth_exception and r.last_error is not None:
|
||||
if not is_synth_exception and trace.last_error is not None:
|
||||
get_logger().warning(
|
||||
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — {r.last_error.type}: {r.last_error.message}"
|
||||
f"Trace failed in group {meta.group_id} ({meta.env_name}) — "
|
||||
f"{trace.last_error.type}: {trace.last_error.message}"
|
||||
)
|
||||
await self.emit_episode(meta, group, rollouts)
|
||||
if not episode.ok and not episode.traces:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if not is_synth_exception and self.on_episode_complete is not None and meta.started_at > 0:
|
||||
self.on_episode_complete(
|
||||
meta.env_name, meta.kind, episode.num_total_tokens, time.monotonic() - meta.started_at
|
||||
)
|
||||
await self.emit_episode(meta, group, episode)
|
||||
|
||||
async def emit_episode(self, meta: InflightRollout, 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."""
|
||||
async def emit_episode(
|
||||
self,
|
||||
meta: InflightEpisode,
|
||||
group: GroupState | None,
|
||||
episode: vf.Episode[Any, Any, Any],
|
||||
) -> None:
|
||||
"""Stamp one completed episode with its dispatch provenance and emit it."""
|
||||
_validate_episode_task(episode, meta.task)
|
||||
eval_step = meta.eval_step
|
||||
policy_version = meta.policy_version
|
||||
if group is not None:
|
||||
eval_step = group.eval_step
|
||||
policy_version = group.policy_version_at_start
|
||||
group.emitted += 1
|
||||
if group.emitted >= group.target_rollouts:
|
||||
if group.emitted >= group.target_episodes:
|
||||
self.groups.pop(meta.group_id, None)
|
||||
|
||||
for rollout in rollouts:
|
||||
rollout.kind = meta.kind
|
||||
rollout.env_name = meta.env_name
|
||||
rollout.group_id = meta.group_id
|
||||
rollout.policy_version = policy_version
|
||||
rollout.off_policy_steps = meta.off_policy_steps
|
||||
if meta.kind == "eval":
|
||||
assert eval_step is not None, "eval rollout missing eval_step"
|
||||
rollout.eval_step = eval_step
|
||||
await self.out_q.put(rollouts)
|
||||
if meta.kind == "eval":
|
||||
assert eval_step is not None, "eval episode missing eval_step"
|
||||
episode.env.name = meta.env_name
|
||||
episode.group = vf.GroupInfo(id=str(meta.group_id))
|
||||
live_policy = meta.kind == "eval"
|
||||
if meta.kind == "train":
|
||||
assert self.train_envs is not None
|
||||
live_policy = self.train_envs.get(meta.env_name).sampler.samples_from_live_policy
|
||||
policy = vf.PolicySpan(start=policy_version, end=self.policy.version) if live_policy else None
|
||||
work: vf.WorkInfo = (
|
||||
vf.EvalWorkInfo(step=meta.step, policy=policy)
|
||||
if meta.kind == "eval"
|
||||
else vf.TrainWorkInfo(step=meta.step, policy=policy)
|
||||
)
|
||||
run = vf.TrainRunInfo(id=self.run_id, name=self.run_name, work=work)
|
||||
episode.record_run(run)
|
||||
await self.out_q.put(episode)
|
||||
|
||||
async def drop_group(self, group_id: uuid.UUID) -> int:
|
||||
"""Cancel remaining in-flight tasks for this group and emit a
|
||||
@@ -532,14 +661,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
|
||||
# so ``handle_completed_episode``'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,52 +676,53 @@ 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)),
|
||||
agent=vf.AgentInfo(config=vf.AgentConfig()),
|
||||
episode = vf.WireEpisode(
|
||||
env=vf.EnvInfo(id=meta.env_name),
|
||||
task=_trace_task(meta.task),
|
||||
ok=False,
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
stop_condition="error",
|
||||
)
|
||||
await self.emit_episode(meta, group, [trace])
|
||||
await self.emit_episode(meta, group, episode)
|
||||
|
||||
# The group may have rollouts that were never dispatched
|
||||
# (``rollouts_to_schedule > 0``). Emit markers for those too so the
|
||||
# sink hits ``target_rollouts``
|
||||
# The group may have episodes that were never dispatched. Emit markers
|
||||
# for those too so the sink reaches ``target_episodes``.
|
||||
#
|
||||
# ``last_meta`` can be ``None`` if the only inflight task for this
|
||||
# group completed naturally between ``on_version_pending``'s snapshot
|
||||
# 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(
|
||||
if group is not None and group.episodes_to_schedule > 0:
|
||||
fallback_meta = last_meta or InflightEpisode(
|
||||
kind=group.kind,
|
||||
env_name=group.env_name,
|
||||
group_id=group_id,
|
||||
task=group.task,
|
||||
policy_version=group.policy_version_at_start,
|
||||
step=self._work_step(group.kind, group.eval_step),
|
||||
eval_step=group.eval_step,
|
||||
)
|
||||
unscheduled_cancelled = group.rollouts_to_schedule
|
||||
unscheduled_cancelled = group.episodes_to_schedule
|
||||
for _ in range(unscheduled_cancelled):
|
||||
trace = Rollout(
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
|
||||
agent=vf.AgentInfo(config=vf.AgentConfig()),
|
||||
episode = vf.WireEpisode(
|
||||
env=vf.EnvInfo(id=group.env_name),
|
||||
task=_trace_task(group.task),
|
||||
ok=False,
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
stop_condition="error",
|
||||
)
|
||||
await self.emit_episode(fallback_meta, group, [trace])
|
||||
await self.emit_episode(fallback_meta, group, episode)
|
||||
|
||||
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,
|
||||
task=group.task,
|
||||
policy_version=group.policy_version_at_start if group else 0,
|
||||
step=self._work_step(group.kind, group.eval_step),
|
||||
eval_step=group.eval_step,
|
||||
)
|
||||
if group is not None
|
||||
@@ -611,8 +739,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 +751,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 +778,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
|
||||
@@ -30,14 +30,8 @@ from verifiers.v1.serve import EnvClient
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
|
||||
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
|
||||
from prime_rl.orchestrator.sampler import Sampler
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# Every wire trace validates into this type. WireTaskData (extra="allow") keeps the env's task
|
||||
# fields without importing the env package — the orchestrator never reads them typed (only
|
||||
# task.idx + task.model_dump).
|
||||
ROLLOUT_TYPE = Rollout[vf.WireTaskData]
|
||||
|
||||
# Max wait for the env server to answer health. Generous because the launcher spawns
|
||||
# servers concurrently with the orchestrator, and a server imports its env package
|
||||
# before serving.
|
||||
@@ -102,30 +96,23 @@ class Env:
|
||||
model_name: str,
|
||||
cache_salt: str | None,
|
||||
task_data: dict,
|
||||
) -> list[Rollout]:
|
||||
"""Run one episode; return its typed Traces. A zero-trace episode raises (the
|
||||
dispatcher synthesizes the error marker); a not-``ok`` episode marks its clean
|
||||
traces failed so partial episodes never train."""
|
||||
) -> vf.WireEpisode:
|
||||
"""Run and return one typed episode. A failed multi-trace episode marks
|
||||
its otherwise-clean traces failed so partial episodes never train."""
|
||||
episode = await self.env_client.run(
|
||||
task_data=task_data,
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling=self._sampling(cache_salt),
|
||||
)
|
||||
if not episode.traces:
|
||||
error = episode.last_error
|
||||
detail = f"{error.type}: {error.message}" if error is not None else "no traces and no error recorded"
|
||||
raise RuntimeError(f"episode failed before any trace was produced — {detail}")
|
||||
rollouts = [ROLLOUT_TYPE.model_construct(**dict(wire)) for wire in episode.traces]
|
||||
for rollout in rollouts:
|
||||
rollout.episode_id = episode.id
|
||||
if not episode.ok and rollout.ok:
|
||||
for trace in episode.traces:
|
||||
if not episode.ok and trace.ok:
|
||||
error = episode.last_error or vf.Error(
|
||||
type="EpisodeFailed", message="A sibling trace in this episode failed"
|
||||
)
|
||||
rollout.errors = [*rollout.errors, error]
|
||||
rollout.ok = False
|
||||
return rollouts
|
||||
trace.errors = [*trace.errors, error]
|
||||
trace.ok = False
|
||||
return episode
|
||||
|
||||
|
||||
class TrainEnv(Env):
|
||||
|
||||
@@ -1,52 +1,36 @@
|
||||
"""EvalSink: three-level rollout sink for eval epochs.
|
||||
|
||||
Same shape as ``TrainSink``, but no tokenization / advantages / filters:
|
||||
|
||||
1. ``process_rollout`` — no-op.
|
||||
2. ``process_group`` — at ``group_size`` episodes, move the rollouts
|
||||
(errored ones included) into the ``(env, eval_step)`` bucket.
|
||||
3. ``process_batch`` — at ``num_examples × group_size`` episodes, return an
|
||||
``EvalBatch`` with the full returned cohort (metrics are computed downstream).
|
||||
|
||||
``add()`` takes one episode (``list[Rollout]``) and returns ``EvalBatch | None``;
|
||||
all accounting counts episodes, never loose traces.
|
||||
"""
|
||||
"""Evaluation-side episode, group, and epoch assembly."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.metrics import EvalRollouts
|
||||
from prime_rl.orchestrator.types import EvalBatch, Rollout
|
||||
from prime_rl.orchestrator.metrics import EvalEpisodes
|
||||
from prime_rl.orchestrator.types import EvalBatch
|
||||
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, eval_work
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class EvalSink:
|
||||
"""Constructed only when eval is configured."""
|
||||
"""Collect completed evaluation episodes into per-environment epochs."""
|
||||
|
||||
def __init__(self, *, eval_envs: EvalEnvs) -> None:
|
||||
self.eval_envs = eval_envs
|
||||
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
|
||||
# Episodes arrived per group / per batch bucket — the finalization counts.
|
||||
self.pending_group_episodes: dict[uuid.UUID, int] = defaultdict(int)
|
||||
self.pending_batches: dict[tuple[str, int], list[Rollout]] = defaultdict(list)
|
||||
self.pending_batch_episodes: dict[tuple[str, int], int] = defaultdict(int)
|
||||
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
|
||||
self.pending_batches: dict[tuple[str, int], list[vf.Episode]] = defaultdict(list)
|
||||
|
||||
def add(self, episode: list[Rollout]) -> EvalBatch | None:
|
||||
"""Process one episode arrival; finalize the group on the ``group_size``-th
|
||||
episode and the per-env epoch on the ``num_examples × group_size``-th."""
|
||||
env_name = episode[0].env_name
|
||||
group_id = episode[0].group_id
|
||||
for rollout in episode:
|
||||
self.process_rollout(rollout)
|
||||
bkey = (env_name, episode[0].eval_step)
|
||||
self.pending_groups[group_id].extend(episode)
|
||||
self.pending_group_episodes[group_id] += 1
|
||||
if self.pending_group_episodes[group_id] >= self.group_size_for(env_name):
|
||||
def add(self, episode: vf.Episode) -> EvalBatch | None:
|
||||
env_name = episode_env_name(episode)
|
||||
group_id = episode_group_id(episode)
|
||||
eval_step = eval_work(episode).step
|
||||
bkey = (env_name, eval_step)
|
||||
group = self.pending_groups[group_id]
|
||||
group.append(episode)
|
||||
if len(group) >= self.group_size_for(env_name):
|
||||
self.process_group(group_id)
|
||||
if self.pending_batch_episodes[bkey] >= self.batch_size_for(env_name):
|
||||
if len(self.pending_batches[bkey]) >= self.batch_size_for(env_name):
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
@@ -54,24 +38,19 @@ class EvalSink:
|
||||
return self.eval_envs.get(env_name).config.group_size
|
||||
|
||||
def batch_size_for(self, env_name: str) -> int:
|
||||
"""``num_examples × group_size`` — total episodes expected for one
|
||||
epoch of ``env_name``."""
|
||||
env = self.eval_envs.get(env_name)
|
||||
return len(env.examples) * env.config.group_size
|
||||
|
||||
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
|
||||
"""One entry per accumulating ``(env, eval_step)`` batch:
|
||||
``(env_name, eval_step, batch_count, expected, buffered)``.
|
||||
``batch_count`` is finalized-group episodes in ``pending_batches``;
|
||||
``buffered`` is partial-group episode arrivals."""
|
||||
batch_counts: dict[tuple[str, int], int] = dict(self.pending_batch_episodes)
|
||||
batch_counts = {key: len(runs) for key, runs in self.pending_batches.items()}
|
||||
buffered: dict[tuple[str, int], int] = {}
|
||||
for group_id, rollouts in self.pending_groups.items():
|
||||
if not rollouts:
|
||||
for group in self.pending_groups.values():
|
||||
if not group:
|
||||
continue
|
||||
env_name = rollouts[0].env_name
|
||||
bkey = (env_name, rollouts[0].eval_step)
|
||||
buffered[bkey] = buffered.get(bkey, 0) + self.pending_group_episodes.get(group_id, 0)
|
||||
episode = group[0]
|
||||
eval_step = eval_work(episode).step
|
||||
key = (episode_env_name(episode), eval_step)
|
||||
buffered[key] = buffered.get(key, 0) + len(group)
|
||||
return [
|
||||
(
|
||||
env_name,
|
||||
@@ -80,47 +59,31 @@ class EvalSink:
|
||||
self.batch_size_for(env_name),
|
||||
buffered.get((env_name, eval_step), 0),
|
||||
)
|
||||
for (env_name, eval_step) in set(batch_counts) | set(buffered)
|
||||
for env_name, eval_step in set(batch_counts) | set(buffered)
|
||||
]
|
||||
|
||||
# ── level 1: per-rollout (no-op for eval) ─────────────────────────────
|
||||
|
||||
def process_rollout(self, rollout: Rollout) -> None:
|
||||
"""No-op. Eval rollouts don't need trainer-bound tokenization; the
|
||||
method exists to keep the three-level structure uniform with
|
||||
``TrainSink``.
|
||||
"""
|
||||
return None
|
||||
|
||||
# ── level 2: per-group (move into batch bucket) ───────────────────────
|
||||
|
||||
def process_group(self, group_id: uuid.UUID) -> None:
|
||||
def process_group(self, group_id: str) -> None:
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
episodes = self.pending_group_episodes.pop(group_id, 0)
|
||||
if not group:
|
||||
return
|
||||
env_name = group[0].env_name
|
||||
task_idx = group[0].task.data.idx
|
||||
eval_step = group[0].eval_step
|
||||
bucket = self.pending_batches[(env_name, eval_step)]
|
||||
bucket.extend(group)
|
||||
self.pending_batch_episodes[(env_name, eval_step)] += episodes
|
||||
episode = group[0]
|
||||
env_name = episode_env_name(episode)
|
||||
eval_step = eval_work(episode).step
|
||||
self.pending_batches[(env_name, eval_step)].extend(group)
|
||||
|
||||
survivors = [r for r in group if not r.has_error]
|
||||
num_errored = len(group) - len(survivors)
|
||||
rewards = [r.reward for r in survivors]
|
||||
traces = [trace for episode in group for trace in episode.traces]
|
||||
survivors = [trace for trace in traces if not trace.has_error]
|
||||
num_errored = len(traces) - len(survivors) + sum(not episode.ok for episode in group if not episode.traces)
|
||||
rewards = [trace.reward for trace in survivors]
|
||||
avg_reward = sum(rewards) / len(rewards) if rewards else 0.0
|
||||
task_idx = next((trace.task.data.idx for trace in traces), None)
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} eval_step={eval_step} | "
|
||||
f"rollouts={len(group)} (errored={num_errored}) | reward={avg_reward:.4f}"
|
||||
f"Finished group | env={env_name} task_idx={task_idx} "
|
||||
f"eval_step={eval_step} | episodes={len(group)} traces={len(traces)} "
|
||||
f"(errored={num_errored}) | reward={avg_reward:.4f}"
|
||||
)
|
||||
|
||||
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
|
||||
"""Pop the finished ``(env, eval_step)`` epoch and return the ``EvalBatch`` with its full
|
||||
returned cohort (errored rollouts included — the ``all`` set). Metrics are computed
|
||||
downstream via ``EvalBatch.rollouts.metrics`` over the all/effective subsets, so the sink
|
||||
does no aggregation."""
|
||||
env_name, step = key
|
||||
rollouts = self.pending_batches.pop(key, [])
|
||||
self.pending_batch_episodes.pop(key, None)
|
||||
return EvalBatch(env_name=env_name, step=step, rollouts=EvalRollouts(rollouts))
|
||||
episodes = self.pending_batches.pop(key, [])
|
||||
return EvalBatch(env_name=env_name, step=step, episodes=EvalEpisodes(episodes))
|
||||
|
||||
@@ -46,7 +46,7 @@ class EvalSource:
|
||||
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.
|
||||
``force`` fires every env regardless of interval (e.g. the evaluator's
|
||||
``force`` fires every env regardless of interval (e.g. the evals process's
|
||||
final-checkpoint eval)."""
|
||||
is_first, self.first_trigger = self.first_trigger, False
|
||||
if is_first and self.eval_config.skip_first_step:
|
||||
|
||||
@@ -1,320 +0,0 @@
|
||||
"""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,32 +278,51 @@ 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())
|
||||
|
||||
async def probe(self, attempts: int = 3, interval: float = 2.0) -> bool:
|
||||
"""Scrape once, outside the poll loop, and report whether any engine
|
||||
answered with metrics. External API endpoints (no vLLM ``/metrics``)
|
||||
fail every attempt immediately; the retries only cover a real engine
|
||||
racing its first exposition."""
|
||||
for attempt in range(attempts):
|
||||
if attempt > 0:
|
||||
await asyncio.sleep(interval)
|
||||
try:
|
||||
await self.collect_and_log()
|
||||
except Exception as e:
|
||||
get_logger().warning(f"Inference metrics probe failed: {e!r}")
|
||||
if self.previous:
|
||||
return True
|
||||
return False
|
||||
|
||||
async def collect_and_log(self):
|
||||
now = time.monotonic()
|
||||
|
||||
@@ -316,28 +345,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]
|
||||
|
||||
@@ -1,38 +1,48 @@
|
||||
"""Train and eval rollout metrics.
|
||||
|
||||
A rollout container (``TrainRollouts`` / ``EvalRollouts``) owns the rollout list and exposes
|
||||
``.effective`` (the clean subset, as the same container type) and ``.metrics`` (``TrainMetrics`` /
|
||||
``EvalMetrics``). The metrics object exposes each distributional / rate metric as a ``Stat`` — so
|
||||
``rollouts.metrics.num_input_tokens.mean()`` works — and assembles the full
|
||||
``{prefix}/{subset}/<metric>/<stat>`` wandb dict via ``.to_wandb(...)``.
|
||||
|
||||
The wandb layout mirrors the episode/trace hierarchy, one aggregation per level:
|
||||
|
||||
- ``{prefix}/{subset}/<metric>/<stat>`` — episode level, one value per episode summing its traces
|
||||
(matching ``vf.Episode``'s aggregates). Only the count metrics live here.
|
||||
- ``{prefix}/{subset}/<agent>/<metric>/<stat>`` — agent level, one value per trace, grouped by agent
|
||||
name (``vf.Episode.by_agent``) so agents never mix into one distribution. Everything trace-scoped
|
||||
lives here: reward, rates, timing, custom metrics, the pipeline verdicts, the eval scores.
|
||||
|
||||
A single-agent env has one trace per episode, so the count metrics coincide across levels.
|
||||
|
||||
No I/O, no pandas — plain Python over the ``vf.Trace`` properties each rollout exposes.
|
||||
"""
|
||||
"""Episode-native train and evaluation metrics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any, Callable, Iterator, Literal
|
||||
from collections.abc import Callable, Iterator
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal
|
||||
|
||||
from prime_rl.orchestrator.utils import compute_pass_metrics
|
||||
import verifiers.v1 as vf
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.orchestrator.algo.routing import is_trainable, scalar_advantage
|
||||
from prime_rl.orchestrator.utils import compute_pass_metrics, episode_env_name, episode_group_id
|
||||
|
||||
Subset = Literal["all", "effective"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TraceRecord:
|
||||
"""A trace joined with its episode and training selection state."""
|
||||
|
||||
episode: vf.Episode
|
||||
trace: vf.Trace
|
||||
sampled: bool
|
||||
admitted: bool
|
||||
|
||||
|
||||
def _records(
|
||||
episodes: list[vf.Episode],
|
||||
sampled_trace_ids: set[str],
|
||||
admitted: set[str],
|
||||
) -> list[TraceRecord]:
|
||||
return [
|
||||
TraceRecord(
|
||||
episode=episode,
|
||||
trace=trace,
|
||||
sampled=trace.id in sampled_trace_ids,
|
||||
admitted=episode.id in admitted,
|
||||
)
|
||||
for episode in episodes
|
||||
for trace in episode.traces
|
||||
]
|
||||
|
||||
|
||||
class Stat:
|
||||
"""A distribution of per-rollout values with mean/max/min and p10/p90 accessors."""
|
||||
"""A distribution with mean, extrema, and percentile accessors."""
|
||||
|
||||
def __init__(self, values: list[float]) -> None:
|
||||
self.values = values
|
||||
@@ -47,14 +57,13 @@ class Stat:
|
||||
return float(min(self.values)) if self.values else 0.0
|
||||
|
||||
def percentile(self, q: float) -> float:
|
||||
"""Linear-interpolated ``q``-th percentile (numpy's default method); 0.0 if empty."""
|
||||
if not self.values:
|
||||
return 0.0
|
||||
s = sorted(self.values)
|
||||
rank = q / 100 * (len(s) - 1)
|
||||
lo = int(rank)
|
||||
hi = min(lo + 1, len(s) - 1)
|
||||
return float(s[lo] + (s[hi] - s[lo]) * (rank - lo))
|
||||
values = sorted(self.values)
|
||||
rank = q / 100 * (len(values) - 1)
|
||||
low = int(rank)
|
||||
high = min(low + 1, len(values) - 1)
|
||||
return float(values[low] + (values[high] - values[low]) * (rank - low))
|
||||
|
||||
def p10(self) -> float:
|
||||
return self.percentile(10)
|
||||
@@ -63,7 +72,6 @@ class Stat:
|
||||
return self.percentile(90)
|
||||
|
||||
def to_dict(self, prefix: str) -> dict[str, float]:
|
||||
"""``{prefix}/mean,max,min,p10,p90``; ``{}`` for an empty distribution."""
|
||||
if not self.values:
|
||||
return {}
|
||||
return {
|
||||
@@ -76,11 +84,12 @@ class Stat:
|
||||
|
||||
|
||||
class StatGroup:
|
||||
"""A nested group of named ``Stat``s. ``to_dict`` emits ``{prefix}/<name>/<stat>`` for each
|
||||
distribution and ``group[name]`` returns one; subclasses supply the names via ``stats()``."""
|
||||
def __init__(self, records: list[TraceRecord]) -> None:
|
||||
self.records = records
|
||||
|
||||
def __init__(self, rollouts: list[Rollout]) -> None:
|
||||
self.rollouts = rollouts
|
||||
@property
|
||||
def traces(self) -> list[vf.Trace]:
|
||||
return [record.trace for record in self.records]
|
||||
|
||||
def stats(self) -> dict[str, Stat]:
|
||||
raise NotImplementedError
|
||||
@@ -96,41 +105,35 @@ class StatGroup:
|
||||
|
||||
|
||||
class TimingMetrics(StatGroup):
|
||||
"""Per-phase rollout durations, nested so ``metrics.timing.setup.mean()`` reads naturally.
|
||||
``total`` is the per-rollout sum across all phases."""
|
||||
|
||||
PHASES = ("setup", "agent", "finalize", "scoring")
|
||||
|
||||
@property
|
||||
def setup(self) -> Stat:
|
||||
return Stat([r.timing.setup.duration for r in self.rollouts])
|
||||
return Stat([trace.timing.setup.duration for trace in self.traces])
|
||||
|
||||
@property
|
||||
def agent(self) -> Stat:
|
||||
return Stat([r.timing.agent.duration for r in self.rollouts])
|
||||
return Stat([trace.timing.agent.duration for trace in self.traces])
|
||||
|
||||
@property
|
||||
def agent_model(self) -> Stat:
|
||||
"""The share of the agent phase spent inside model calls (inference)."""
|
||||
return Stat([r.timing.agent.model.duration for r in self.rollouts])
|
||||
return Stat([trace.timing.agent.model.duration for trace in self.traces])
|
||||
|
||||
@property
|
||||
def agent_harness(self) -> Stat:
|
||||
"""The share of the agent phase spent outside model calls (harness, tools,
|
||||
user simulation)."""
|
||||
return Stat([r.timing.agent.harness.duration for r in self.rollouts])
|
||||
return Stat([trace.timing.agent.harness.duration for trace in self.traces])
|
||||
|
||||
@property
|
||||
def finalize(self) -> Stat:
|
||||
return Stat([r.timing.finalize.duration for r in self.rollouts])
|
||||
return Stat([trace.timing.finalize.duration for trace in self.traces])
|
||||
|
||||
@property
|
||||
def scoring(self) -> Stat:
|
||||
return Stat([r.timing.scoring.duration for r in self.rollouts])
|
||||
return Stat([trace.timing.scoring.duration for trace in self.traces])
|
||||
|
||||
@property
|
||||
def total(self) -> Stat:
|
||||
return Stat([sum(getattr(r.timing, p).duration for p in self.PHASES) for r in self.rollouts])
|
||||
return Stat([sum(getattr(trace.timing, phase).duration for phase in self.PHASES) for trace in self.traces])
|
||||
|
||||
def stats(self) -> dict[str, Stat]:
|
||||
return {
|
||||
@@ -142,26 +145,24 @@ class TimingMetrics(StatGroup):
|
||||
|
||||
|
||||
class CustomMetrics(StatGroup):
|
||||
"""Per-key ``Stat``s over a dynamic per-rollout dict attribute (env ``@metric``s or reward
|
||||
components), each over the rollouts that carry the key. Scoring seeds every expected key
|
||||
with ``None`` before invoking it, so a ``None`` value means the signal never produced a
|
||||
score and counts as 0.0 — the ``effective`` subset excludes errored rollouts and gives the
|
||||
clean means. ``value`` extracts the float from each scored entry (rewards are ``vf.Reward``
|
||||
records; metrics are plain floats)."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout], attr: str, value: Callable[[Any], float] = float) -> None:
|
||||
super().__init__(rollouts)
|
||||
def __init__(
|
||||
self,
|
||||
records: list[TraceRecord],
|
||||
attr: str,
|
||||
value: Callable[[Any], float] = float,
|
||||
) -> None:
|
||||
super().__init__(records)
|
||||
self.attr = attr
|
||||
self.value = value
|
||||
|
||||
def stats(self) -> dict[str, Stat]:
|
||||
names = sorted({name for r in self.rollouts for name in getattr(r, self.attr)})
|
||||
names = sorted({name for trace in self.traces for name in getattr(trace, self.attr)})
|
||||
return {
|
||||
name: Stat(
|
||||
[
|
||||
self.value(scores[name]) if scores[name] is not None else 0.0
|
||||
for r in self.rollouts
|
||||
if name in (scores := getattr(r, self.attr))
|
||||
for trace in self.traces
|
||||
if name in (scores := getattr(trace, self.attr))
|
||||
]
|
||||
)
|
||||
for name in names
|
||||
@@ -169,78 +170,68 @@ class CustomMetrics(StatGroup):
|
||||
|
||||
|
||||
class TraceMetrics(StatGroup):
|
||||
"""Trace-level metrics for one agent, every one of them flat over that agent's traces: one
|
||||
sample is one trace, so a fan-out (n same-agent traces in one episode, e.g. n solvers) simply
|
||||
contributes n samples. Weighing whole episodes against each other is the episode level's job;
|
||||
inside a seat the trace is the unit, which is also what the advantage computation samples."""
|
||||
|
||||
DISTRIBUTIONS = ("reward", "num_total_tokens", "num_input_tokens", "num_output_tokens", "num_turns", "num_branches")
|
||||
DISTRIBUTIONS = (
|
||||
"reward",
|
||||
"num_total_tokens",
|
||||
"num_input_tokens",
|
||||
"num_output_tokens",
|
||||
"num_turns",
|
||||
"num_branches",
|
||||
)
|
||||
RATES = ("is_truncated", "is_completed")
|
||||
|
||||
def stats(self) -> dict[str, Stat]:
|
||||
return {
|
||||
name: Stat([float(getattr(r, name)) for r in self.rollouts]) for name in (*self.DISTRIBUTIONS, *self.RATES)
|
||||
name: Stat([float(getattr(trace, name)) for trace in self.traces])
|
||||
for name in (*self.DISTRIBUTIONS, *self.RATES)
|
||||
}
|
||||
|
||||
@property
|
||||
def timing(self) -> TimingMetrics:
|
||||
return TimingMetrics(self.rollouts)
|
||||
return TimingMetrics(self.records)
|
||||
|
||||
@property
|
||||
def metrics(self) -> CustomMetrics:
|
||||
"""Env custom ``@metric`` outputs, keyed by name."""
|
||||
return CustomMetrics(self.rollouts, "metrics")
|
||||
return CustomMetrics(self.records, "metrics")
|
||||
|
||||
@property
|
||||
def rewards(self) -> CustomMetrics:
|
||||
"""Per-component reward breakdown, keyed by name (each entry's weighted ``value``,
|
||||
summed into the scalar ``reward``)."""
|
||||
return CustomMetrics(self.rollouts, "rewards", value=lambda reward: reward.value)
|
||||
return CustomMetrics(self.records, "rewards", value=lambda reward: reward.value)
|
||||
|
||||
@property
|
||||
def has_error(self) -> Stat:
|
||||
return Stat([float(r.has_error) for r in self.rollouts])
|
||||
return Stat([float(trace.has_error) for trace in self.traces])
|
||||
|
||||
def stop_conditions(self) -> dict[str, float]:
|
||||
"""``generation_truncated`` over the agent's traces, then each recorded
|
||||
``stop_condition``'s rate over the traces that recorded one."""
|
||||
out = {
|
||||
"generation_truncated": sum(
|
||||
1 for r in self.rollouts if r.is_truncated and r.stop_condition != "prompt_too_long"
|
||||
trace.is_truncated and trace.stop_condition != "prompt_too_long" for trace in self.traces
|
||||
)
|
||||
/ len(self.rollouts)
|
||||
/ len(self.traces)
|
||||
}
|
||||
conditions = [r.stop_condition for r in self.rollouts if r.stop_condition is not None]
|
||||
conditions = [trace.stop_condition for trace in self.traces if trace.stop_condition is not None]
|
||||
for condition in sorted(set(conditions)):
|
||||
out[condition] = conditions.count(condition) / len(conditions)
|
||||
return out
|
||||
|
||||
def error_types(self) -> dict[str, int]:
|
||||
"""Count of errored traces by error type (the trace's last error — e.g. ``Cancelled``,
|
||||
``ProviderError``)."""
|
||||
types = [r.last_error.type for r in self.rollouts if r.has_error and r.last_error is not None]
|
||||
return {t: types.count(t) for t in sorted(set(types))}
|
||||
types = [trace.last_error.type for trace in self.traces if trace.has_error and trace.last_error is not None]
|
||||
return {error_type: types.count(error_type) for error_type in sorted(set(types))}
|
||||
|
||||
def solve_rates(self) -> dict[str, float]:
|
||||
"""Per-group solve rates over the agent's traces, assuming binary 0/1 rewards (unspecified
|
||||
for other reward ranges): ``solved_none`` (the group earned no reward), ``solved_all``
|
||||
(every trace scored 1.0), and ``solved_some`` (the mixed remainder — the GRPO-signal
|
||||
groups)."""
|
||||
groups: dict = {}
|
||||
for r in self.rollouts:
|
||||
groups.setdefault(r.group_id, []).append(r)
|
||||
n_groups = len(groups)
|
||||
solved_none = sum(1 for g in groups.values() if sum(r.reward for r in g) == 0)
|
||||
solved_all = sum(1 for g in groups.values() if all(r.reward == 1.0 for r in g))
|
||||
for record in self.records:
|
||||
groups.setdefault(episode_group_id(record.episode), []).append(record.trace)
|
||||
num_groups = len(groups)
|
||||
solved_none = sum(sum(trace.reward for trace in group) == 0 for group in groups.values())
|
||||
solved_all = sum(all(trace.reward == 1.0 for trace in group) for group in groups.values())
|
||||
return {
|
||||
"solved_none": solved_none / n_groups,
|
||||
"solved_all": solved_all / n_groups,
|
||||
"solved_some": 1 - (solved_none + solved_all) / n_groups,
|
||||
"solved_none": solved_none / num_groups,
|
||||
"solved_all": solved_all / num_groups,
|
||||
"solved_some": 1 - (solved_none + solved_all) / num_groups,
|
||||
}
|
||||
|
||||
def to_dict(self, prefix: str, *, subset: Subset) -> dict[str, float]:
|
||||
"""Full ``<stat>`` fan-out for the distributions; ``/mean`` only for the 0/1 rates.
|
||||
Errors live only on the ``all`` subset (``effective`` drops them by construction)."""
|
||||
stats = self.stats()
|
||||
out: dict[str, float] = {}
|
||||
for name in self.DISTRIBUTIONS:
|
||||
@@ -252,217 +243,263 @@ class TraceMetrics(StatGroup):
|
||||
out |= self.rewards.to_dict(f"{prefix}/rewards")
|
||||
if subset == "all":
|
||||
out[f"{prefix}/has_error/mean"] = self.has_error.mean()
|
||||
out |= {f"{prefix}/error/{t}": float(count) for t, count in self.error_types().items()}
|
||||
out |= {f"{prefix}/stop_condition/{k}": v for k, v in self.stop_conditions().items()}
|
||||
out |= {f"{prefix}/{k}": v for k, v in self.solve_rates().items()}
|
||||
out |= {f"{prefix}/error/{key}": float(value) for key, value in self.error_types().items()}
|
||||
out |= {f"{prefix}/{key}": value for key, value in self.solve_rates().items()}
|
||||
out |= {f"{prefix}/stop_condition/{key}": value for key, value in self.stop_conditions().items()}
|
||||
return out
|
||||
|
||||
|
||||
class EpisodeMetrics:
|
||||
"""Metrics shared by train and eval over a rollout list. The count metrics (tokens/turns/
|
||||
branches) are episode-level — one value per episode, summing its traces — and are the only
|
||||
per-metric keys ``to_wandb`` emits at the env level; every trace-level metric is emitted per
|
||||
agent via ``by_agent()``. The boolean ``Stat`` properties (0/1 distributions, ``.mean()`` is
|
||||
the rate) serve the console log lines. ``TrainMetrics`` / ``EvalMetrics`` extend ``to_wandb``
|
||||
with the train pipeline rates and the eval scores."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout]) -> None:
|
||||
self.rollouts = rollouts
|
||||
|
||||
def episodes(self) -> list[list[Rollout]]:
|
||||
"""The subset's rollouts grouped into their episodes. A rollout without an
|
||||
``episode_id`` (synthesized error markers) is its own episode."""
|
||||
grouped: dict[str, list[Rollout]] = {}
|
||||
for r in self.rollouts:
|
||||
grouped.setdefault(r.episode_id or r.id, []).append(r)
|
||||
return list(grouped.values())
|
||||
def __init__(self, episodes: list[vf.Episode], records: list[TraceRecord]) -> None:
|
||||
self.episodes = episodes
|
||||
self.records = records
|
||||
|
||||
def by_agent(self) -> dict[str, TraceMetrics]:
|
||||
"""Per-agent metric views (``vf.Episode.by_agent`` over the subset's rollouts)."""
|
||||
per_agent: dict[str, list[Rollout]] = {}
|
||||
for r in self.rollouts:
|
||||
per_agent.setdefault(r.agent.name, []).append(r)
|
||||
return {name: TraceMetrics(rollouts) for name, rollouts in sorted(per_agent.items())}
|
||||
per_agent: dict[str, list[TraceRecord]] = {}
|
||||
for record in self.records:
|
||||
per_agent.setdefault(record.trace.agent.name, []).append(record)
|
||||
return {name: TraceMetrics(records) for name, records in sorted(per_agent.items())}
|
||||
|
||||
def _episode_stat(self, attr: str) -> Stat:
|
||||
by_episode = {id(episode): 0.0 for episode in self.episodes}
|
||||
for record in self.records:
|
||||
by_episode[id(record.episode)] += float(getattr(record.trace, attr))
|
||||
return Stat(list(by_episode.values()))
|
||||
|
||||
# Episode-level count metrics: one value per episode, summing its traces — the same
|
||||
# aggregation as ``vf.Episode.num_turns`` / ``num_*_tokens``.
|
||||
@property
|
||||
def num_total_tokens(self) -> Stat:
|
||||
return Stat([float(sum(r.num_total_tokens for r in episode)) for episode in self.episodes()])
|
||||
return self._episode_stat("num_total_tokens")
|
||||
|
||||
@property
|
||||
def num_input_tokens(self) -> Stat:
|
||||
return Stat([float(sum(r.num_input_tokens for r in episode)) for episode in self.episodes()])
|
||||
return self._episode_stat("num_input_tokens")
|
||||
|
||||
@property
|
||||
def num_output_tokens(self) -> Stat:
|
||||
return Stat([float(sum(r.num_output_tokens for r in episode)) for episode in self.episodes()])
|
||||
return self._episode_stat("num_output_tokens")
|
||||
|
||||
@property
|
||||
def num_turns(self) -> Stat:
|
||||
return Stat([float(sum(r.num_turns for r in episode)) for episode in self.episodes()])
|
||||
return self._episode_stat("num_turns")
|
||||
|
||||
@property
|
||||
def num_branches(self) -> Stat:
|
||||
return Stat([float(sum(r.num_branches for r in episode)) for episode in self.episodes()])
|
||||
return self._episode_stat("num_branches")
|
||||
|
||||
# Boolean rate metrics for the console log lines (0/1 distributions — ``.mean()`` is the
|
||||
# rate); to_wandb emits their per-agent counterparts instead.
|
||||
@property
|
||||
def is_truncated(self) -> Stat:
|
||||
return Stat([float(r.is_truncated) for r in self.rollouts])
|
||||
return Stat([float(record.trace.is_truncated) for record in self.records])
|
||||
|
||||
@property
|
||||
def has_error(self) -> Stat:
|
||||
return Stat([float(r.has_error) for r in self.rollouts])
|
||||
return Stat(
|
||||
[float(not episode.ok or any(trace.has_error for trace in episode.traces)) for episode in self.episodes]
|
||||
)
|
||||
|
||||
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
|
||||
"""The common metric dict for one ``{prefix}/{subset}`` slice. Empty input → ``{}``."""
|
||||
if not self.rollouts:
|
||||
if not self.episodes:
|
||||
return {}
|
||||
p = f"{prefix}/{subset}"
|
||||
metric_prefix = f"{prefix}/{subset}"
|
||||
out: dict[str, float] = {}
|
||||
out |= self.num_total_tokens.to_dict(f"{p}/num_total_tokens")
|
||||
out |= self.num_input_tokens.to_dict(f"{p}/num_input_tokens")
|
||||
out |= self.num_output_tokens.to_dict(f"{p}/num_output_tokens")
|
||||
out |= self.num_turns.to_dict(f"{p}/num_turns")
|
||||
out |= self.num_branches.to_dict(f"{p}/num_branches")
|
||||
for agent, agent_metrics in self.by_agent().items():
|
||||
out |= agent_metrics.to_dict(f"{p}/{agent}", subset=subset)
|
||||
for name in ("num_total_tokens", "num_input_tokens", "num_output_tokens", "num_turns", "num_branches"):
|
||||
out |= getattr(self, name).to_dict(f"{metric_prefix}/{name}")
|
||||
if subset == "all":
|
||||
out[f"{metric_prefix}/has_error/mean"] = self.has_error.mean()
|
||||
for agent, metrics in self.by_agent().items():
|
||||
out |= metrics.to_dict(f"{metric_prefix}/{agent}", subset=subset)
|
||||
return out
|
||||
|
||||
|
||||
class TrainMetrics(EpisodeMetrics):
|
||||
"""Common metrics plus the per-agent filter-pipeline rates. ``reward`` (flat over all traces)
|
||||
serves the console log lines; the wandb reward stats are per-agent."""
|
||||
|
||||
@property
|
||||
def reward(self) -> Stat:
|
||||
return Stat([float(r.reward) for r in self.rollouts])
|
||||
return Stat([float(record.trace.reward) for record in self.records])
|
||||
|
||||
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.
|
||||
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
|
||||
}
|
||||
metric_prefix = f"{prefix}/{subset}/{agent}"
|
||||
out[f"{metric_prefix}/is_trainable/mean"] = sum(
|
||||
float(is_trainable(record.trace)) for record in traces.records
|
||||
) / len(traces.records)
|
||||
out[f"{metric_prefix}/is_admitted/mean"] = sum(float(record.admitted) for record in traces.records) / len(
|
||||
traces.records
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def pass_at_k(rollouts: list[Rollout]) -> dict[str, float]:
|
||||
"""pass@k / pass^k averaged over examples; ``{}`` for non-binary rewards."""
|
||||
rewards = [r.reward for r in rollouts]
|
||||
def pass_at_k(records: list[TraceRecord]) -> dict[str, float]:
|
||||
rewards = [record.trace.reward for record in records]
|
||||
if not set(rewards).issubset({0.0, 1.0}):
|
||||
return {}
|
||||
by_example: dict = {}
|
||||
for r in rollouts:
|
||||
by_example.setdefault(r.group_id, []).append(r.reward)
|
||||
per_example = [compute_pass_metrics(rs) for rs in by_example.values()]
|
||||
keys = sorted({k for d in per_example for k in d})
|
||||
return {k: sum(d[k] for d in per_example if k in d) / sum(1 for d in per_example if k in d) for k in keys}
|
||||
for record in records:
|
||||
by_example.setdefault(episode_group_id(record.episode), []).append(record.trace.reward)
|
||||
per_example = [compute_pass_metrics(group) for group in by_example.values()]
|
||||
keys = sorted({key for result in per_example for key in result})
|
||||
return {
|
||||
key: sum(result[key] for result in per_example if key in result) / sum(key in result for result in per_example)
|
||||
for key in keys
|
||||
}
|
||||
|
||||
|
||||
class EvalMetrics(EpisodeMetrics):
|
||||
"""Common metrics plus the per-agent ``avg@<group_size>`` score and (on the effective subset,
|
||||
for binary-reward tasks) pass@k / pass^k. Both score an agent's own traces, so they live in its
|
||||
subtree like every other trace-level metric. ``group_size`` (the ``avg@k`` k, the run's rollouts
|
||||
per example) is supplied by the container so the ``all`` and ``effective`` subsets — and every
|
||||
agent — share one stable key."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout], group_size: int) -> None:
|
||||
super().__init__(rollouts)
|
||||
def __init__(self, episodes: list[vf.Episode], records: list[TraceRecord], group_size: int) -> None:
|
||||
super().__init__(episodes, records)
|
||||
self.group_size = group_size
|
||||
|
||||
@property
|
||||
def reward(self) -> Stat:
|
||||
return Stat([float(r.reward) for r in self.rollouts])
|
||||
return Stat([float(record.trace.reward) for record in self.records])
|
||||
|
||||
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
|
||||
out = super().to_wandb(prefix=prefix, subset=subset)
|
||||
for agent, traces in self.by_agent().items():
|
||||
p = f"{prefix}/{subset}/{agent}"
|
||||
out[f"{p}/avg@{self.group_size}"] = traces.stats()["reward"].mean()
|
||||
metric_prefix = f"{prefix}/{subset}/{agent}"
|
||||
out[f"{metric_prefix}/avg@{self.group_size}"] = traces.stats()["reward"].mean()
|
||||
if subset == "effective":
|
||||
out |= {f"{p}/{k}": v for k, v in pass_at_k(traces.rollouts).items()}
|
||||
out |= {f"{metric_prefix}/{key}": value for key, value in pass_at_k(traces.records).items()}
|
||||
return out
|
||||
|
||||
|
||||
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);
|
||||
``metrics`` builds ``TrainMetrics`` over them."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout] | None = None) -> None:
|
||||
self.rollouts = rollouts if rollouts is not None else []
|
||||
|
||||
def append(self, rollout: Rollout) -> None:
|
||||
self.rollouts.append(rollout)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.rollouts)
|
||||
|
||||
def __iter__(self) -> Iterator[Rollout]:
|
||||
return iter(self.rollouts)
|
||||
class EpisodeCollection:
|
||||
def __init__(
|
||||
self,
|
||||
episodes: list[vf.Episode] | None = None,
|
||||
sampled_trace_ids: set[str] | None = None,
|
||||
admitted: set[str] | None = None,
|
||||
predicate: Callable[[TraceRecord], bool] | None = None,
|
||||
) -> None:
|
||||
self.episodes = episodes if episodes is not None else []
|
||||
self.sampled_trace_ids = sampled_trace_ids if sampled_trace_ids is not None else set()
|
||||
self.admitted = admitted if admitted is not None else {episode.id for episode in self.episodes}
|
||||
self._predicate = predicate
|
||||
|
||||
@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])
|
||||
def records(self) -> list[TraceRecord]:
|
||||
records = _records(self.episodes, self.sampled_trace_ids, self.admitted)
|
||||
if self._predicate is None:
|
||||
return records
|
||||
return [record for record in records if self._predicate(record)]
|
||||
|
||||
def by_env(self) -> dict[str, TrainRollouts]:
|
||||
grouped: dict[str, list[Rollout]] = {}
|
||||
for r in self.rollouts:
|
||||
grouped.setdefault(r.env_name, []).append(r)
|
||||
return {env: TrainRollouts(rs) for env, rs in grouped.items()}
|
||||
@property
|
||||
def selected_episodes(self) -> list[vf.Episode]:
|
||||
if self._predicate is None:
|
||||
return self.episodes
|
||||
selected = {id(record.episode) for record in self.records}
|
||||
return [episode for episode in self.episodes if id(episode) in selected]
|
||||
|
||||
@property
|
||||
def num_traces(self) -> int:
|
||||
return len(self.records)
|
||||
|
||||
@property
|
||||
def num_total_tokens(self) -> int:
|
||||
return sum(record.trace.num_total_tokens for record in self.records)
|
||||
|
||||
@property
|
||||
def vf_episodes(self) -> list[vf.Episode]:
|
||||
if self._predicate is None:
|
||||
return self.selected_episodes
|
||||
by_episode: dict[int, list[vf.Trace]] = {}
|
||||
for record in self.records:
|
||||
trace = record.trace
|
||||
advantage = scalar_advantage(trace)
|
||||
if advantage is not None:
|
||||
trace = trace.model_copy(update={"info": {**trace.info, "advantage": advantage}})
|
||||
by_episode.setdefault(id(record.episode), []).append(trace)
|
||||
return [
|
||||
episode.model_copy(update={"traces": by_episode[id(episode)]})
|
||||
for episode in self.selected_episodes
|
||||
if id(episode) in by_episode
|
||||
]
|
||||
|
||||
def append(
|
||||
self,
|
||||
episode: vf.Episode,
|
||||
*,
|
||||
sampled_trace_ids: set[str] | None = None,
|
||||
admitted: bool = True,
|
||||
) -> None:
|
||||
self.episodes.append(episode)
|
||||
self.sampled_trace_ids.update(sampled_trace_ids or set())
|
||||
if admitted:
|
||||
self.admitted.add(episode.id)
|
||||
|
||||
def extend(
|
||||
self,
|
||||
episodes: list[vf.Episode],
|
||||
*,
|
||||
sampled_trace_ids: set[str] | None = None,
|
||||
admitted: bool = True,
|
||||
) -> None:
|
||||
self.episodes.extend(episodes)
|
||||
self.sampled_trace_ids.update(sampled_trace_ids or set())
|
||||
if admitted:
|
||||
self.admitted.update(episode.id for episode in episodes)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.selected_episodes)
|
||||
|
||||
def __iter__(self) -> Iterator[vf.Episode]:
|
||||
return iter(self.selected_episodes)
|
||||
|
||||
|
||||
class TrainEpisodes(EpisodeCollection):
|
||||
@property
|
||||
def effective(self) -> TrainEpisodes:
|
||||
return TrainEpisodes(
|
||||
self.episodes,
|
||||
self.sampled_trace_ids,
|
||||
self.admitted,
|
||||
predicate=lambda record: (
|
||||
record.admitted and record.sampled and not record.trace.has_error and record.trace.agent.trainable
|
||||
),
|
||||
)
|
||||
|
||||
def by_env(self) -> dict[str, TrainEpisodes]:
|
||||
grouped: dict[str, list[vf.Episode]] = {}
|
||||
for episode in self.selected_episodes:
|
||||
grouped.setdefault(episode_env_name(episode), []).append(episode)
|
||||
return {
|
||||
env_name: TrainEpisodes(episodes, self.sampled_trace_ids, self.admitted, self._predicate)
|
||||
for env_name, episodes in grouped.items()
|
||||
}
|
||||
|
||||
@property
|
||||
def metrics(self) -> TrainMetrics:
|
||||
return TrainMetrics(self.rollouts)
|
||||
return TrainMetrics(self.selected_episodes, self.records)
|
||||
|
||||
|
||||
class EvalRollouts:
|
||||
"""A list of eval rollouts (errored + untrainable included). ``effective`` is the
|
||||
non-errored trainable subset (a view).
|
||||
``group_size`` (rollouts per example, the ``avg@k`` k) is derived from the full epoch and carried
|
||||
onto ``effective`` so both subsets share one stable key; ``metrics`` builds ``EvalMetrics``."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout] | None = None, group_size: int | None = None) -> None:
|
||||
self.rollouts = rollouts if rollouts is not None else []
|
||||
class EvalEpisodes(EpisodeCollection):
|
||||
def __init__(
|
||||
self,
|
||||
episodes: list[vf.Episode] | None = None,
|
||||
predicate: Callable[[TraceRecord], bool] | None = None,
|
||||
group_size: int | None = None,
|
||||
) -> None:
|
||||
super().__init__(episodes, predicate=predicate)
|
||||
self._group_size = group_size
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.rollouts)
|
||||
|
||||
def __iter__(self) -> Iterator[Rollout]:
|
||||
return iter(self.rollouts)
|
||||
|
||||
@property
|
||||
def group_size(self) -> int:
|
||||
"""The largest group in trainable (policy) traces — equals the configured group size
|
||||
whenever one example kept all its rollouts; untrainable traces don't count, so a
|
||||
multi-agent episode doesn't inflate ``k``. A subview carries its parent's value so
|
||||
``avg@k`` doesn't drift across subsets."""
|
||||
if self._group_size is not None:
|
||||
return self._group_size
|
||||
counts: dict = {}
|
||||
for r in self.rollouts:
|
||||
if r.agent.trainable:
|
||||
counts[r.group_id] = counts.get(r.group_id, 0) + 1
|
||||
for record in self.records:
|
||||
if record.trace.agent.trainable:
|
||||
group_id = episode_group_id(record.episode)
|
||||
counts[group_id] = counts.get(group_id, 0) + 1
|
||||
return max(counts.values(), default=0)
|
||||
|
||||
@property
|
||||
def effective(self) -> EvalRollouts:
|
||||
return EvalRollouts(
|
||||
[r for r in self.rollouts if not r.has_error and r.agent.trainable], group_size=self.group_size
|
||||
def effective(self) -> EvalEpisodes:
|
||||
return EvalEpisodes(
|
||||
self.episodes,
|
||||
predicate=lambda record: not record.trace.has_error and record.trace.agent.trainable,
|
||||
group_size=self.group_size,
|
||||
)
|
||||
|
||||
@property
|
||||
def metrics(self) -> EvalMetrics:
|
||||
return EvalMetrics(self.rollouts, self.group_size)
|
||||
return EvalMetrics(self.selected_episodes, self.records, self.group_size)
|
||||
|
||||
@@ -3,14 +3,12 @@
|
||||
``Orchestrator`` owns the shared state (policy, progress, ckpt, monitor)
|
||||
and drives the pipeline. Components are single-purpose:
|
||||
|
||||
- ``RolloutDispatcher`` schedules rollouts; emits ``Rollout`` (train/eval
|
||||
discriminated by ``kind``) on its queue.
|
||||
- ``TrainSink`` ingests train rollouts (tokenize → advantages → filters)
|
||||
- ``Dispatcher`` schedules environment runs and emits completed episodes.
|
||||
- ``TrainSink`` ingests train rollouts (score → admission → sample compilation)
|
||||
and returns a ``TrainBatch`` when the threshold is met.
|
||||
- ``EvalSink`` ingests eval rollouts and returns an ``EvalBatch`` (the full
|
||||
returned cohort) on epoch completion.
|
||||
- ``TrainRollouts`` / ``EvalRollouts`` carry the rollouts and build the per-step W&B metrics
|
||||
(``batch.rollouts.metrics`` / ``.effective.metrics``).
|
||||
- ``TrainEpisodes`` / ``EvalEpisodes`` preserve episode boundaries and build per-step metrics.
|
||||
- ``WeightWatcher`` advances ``Policy`` and notifies observers.
|
||||
- ``PeriodicLogger`` polls the components on a shared interval for the
|
||||
``_timestamp``-axis pipeline log.
|
||||
@@ -37,18 +35,20 @@ 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.algo.routing import is_trainable
|
||||
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.metrics import TrainEpisodes
|
||||
from prime_rl.orchestrator.packing import BatchPacker
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
@@ -61,21 +61,22 @@ from prime_rl.orchestrator.types import (
|
||||
EvalBatch,
|
||||
Policy,
|
||||
Progress,
|
||||
Rollout,
|
||||
TrainBatch,
|
||||
)
|
||||
from prime_rl.orchestrator.utils import (
|
||||
episode_group_id,
|
||||
eval_work,
|
||||
get_weight_dir,
|
||||
group_episodes,
|
||||
intercept_vf_logging,
|
||||
set_default_executor,
|
||||
setup_policy_inference_pool,
|
||||
train_work,
|
||||
trim_process_memory,
|
||||
)
|
||||
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 +94,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 +129,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 +236,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 +277,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 +372,41 @@ 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,
|
||||
progress=self.progress,
|
||||
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,
|
||||
run_id=self.run_id,
|
||||
run_name=self.run_name,
|
||||
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,9 +414,9 @@ 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(
|
||||
config,
|
||||
@@ -428,6 +435,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(),
|
||||
@@ -445,6 +453,13 @@ class Orchestrator:
|
||||
wandb_enabled=wandb_enabled,
|
||||
)
|
||||
|
||||
def off_policy_steps(self, episode: vf.Episode, training_step: int) -> int:
|
||||
"""Policy updates between generation and the batch that trains on it."""
|
||||
work = train_work(episode)
|
||||
if work.policy is None:
|
||||
return 0
|
||||
return max(0, (training_step - 1) - work.policy.start)
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Run the orchestrator until shutdown. Drives setup, spawns the
|
||||
background tasks, runs the main loop in this task, then cleans up."""
|
||||
@@ -486,6 +501,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()
|
||||
@@ -506,41 +525,33 @@ class Orchestrator:
|
||||
trim_process_memory()
|
||||
|
||||
async def main_loop(self) -> None:
|
||||
"""Consume episodes (``list[Rollout]``) from the dispatcher and route them
|
||||
"""Consume completed episodes from the dispatcher and route them
|
||||
to the train / eval sink. Both sinks return a finalized batch (or
|
||||
``None``) from ``add()``; we just dispatch on the result."""
|
||||
while not self.stopped.is_set():
|
||||
self._raise_if_component_stopped()
|
||||
if self.draining and self.dispatcher.is_idle:
|
||||
get_logger().info("Pipeline drained, exiting main loop")
|
||||
self.stopped.set()
|
||||
break
|
||||
|
||||
try:
|
||||
episode: list[Rollout] = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
|
||||
episode = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
|
||||
except asyncio.TimeoutError:
|
||||
self._raise_if_component_stopped()
|
||||
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.
|
||||
kind = episode[0].kind
|
||||
step = episode[0].eval_step if kind == "eval" else self.progress.step
|
||||
assert step is not None
|
||||
run: vf.RunInfo = (
|
||||
vf.EvalRunInfo(id=self.run_id, name=self.run_name, step=step)
|
||||
if kind == "eval"
|
||||
else vf.TrainRunInfo(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, kind, "all")
|
||||
if episode.run is None:
|
||||
raise ValueError("Dispatched episode is missing run identity")
|
||||
if not isinstance(episode.run, vf.TrainRunInfo):
|
||||
raise ValueError("Orchestrated episode is missing training-run provenance")
|
||||
kind = episode.run.work.type
|
||||
step = episode.run.work.step if kind == "eval" else self.progress.step
|
||||
await monitors.log([episode], step, kind, "all")
|
||||
|
||||
if kind == "eval":
|
||||
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
|
||||
@@ -555,6 +566,18 @@ class Orchestrator:
|
||||
if train_batch is not None and not self.draining and not self.stopped.is_set():
|
||||
await self.finalize_train_batch(train_batch)
|
||||
|
||||
def _raise_if_component_stopped(self) -> None:
|
||||
"""Propagate unexpected background-component termination to the run."""
|
||||
for task in self.component_tasks:
|
||||
if not task.done():
|
||||
continue
|
||||
if task.cancelled():
|
||||
raise RuntimeError(f"{task.get_name()} stopped unexpectedly")
|
||||
error = task.exception()
|
||||
if error is not None:
|
||||
raise error
|
||||
raise RuntimeError(f"{task.get_name()} exited unexpectedly")
|
||||
|
||||
async def finalize_train_batch(self, batch: TrainBatch) -> None:
|
||||
"""Ship one ``TrainBatch`` out to the trainer and handle the I/O
|
||||
side-effects (ckpt, monitors.log, reference scoring, sender.send,
|
||||
@@ -573,7 +596,7 @@ 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"any in-flight evals will complete)"
|
||||
@@ -583,23 +606,23 @@ 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.episodes)} finalized episodes "
|
||||
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
|
||||
effective = batch.rollouts.effective
|
||||
n_trainable = sum(1 for r in effective if r.is_trainable)
|
||||
if effective and n_trainable / len(effective) <= 0.1:
|
||||
effective = batch.cohort.effective
|
||||
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
|
||||
if effective.num_traces and n_trainable / effective.num_traces <= 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"Only {n_trainable}/{effective.num_traces} effective traces are trainable "
|
||||
f"({n_trainable / effective.num_traces:.1%}) — consider reviewing task difficulty"
|
||||
)
|
||||
|
||||
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
|
||||
@@ -622,18 +645,9 @@ class Orchestrator:
|
||||
await self.version_advanced.wait()
|
||||
self.wait_for_policy_time += time.perf_counter() - hold_start
|
||||
|
||||
# Stamp each rollout's true staleness: batch ``step`` trains on policy
|
||||
# v{step-1}, so a rollout generated from v{k} is (step-1)-k versions
|
||||
# off-policy — queue time included, unlike the dispatcher's in-flight
|
||||
# counter, which only sees weight updates during generation. Frozen-
|
||||
# sourced rollouts stay 0 (their sampler doesn't follow the policy).
|
||||
for r in batch.rollouts:
|
||||
if self.train_envs.get(r.env_name).sampler.samples_from_live_policy:
|
||||
r.off_policy_steps = (step - 1) - r.policy_version
|
||||
|
||||
# The effective (clean, trained-on) subset is logged at ship time; the full arrival
|
||||
# window already streamed into the ``all`` cohort on arrival.
|
||||
await monitors.log(group_episodes(effective.rollouts), step, "train", "effective")
|
||||
await monitors.log(effective.vf_episodes, step, "train", "effective")
|
||||
|
||||
pack_start_time = time.perf_counter()
|
||||
micro_batch_grid = await asyncio.to_thread(self.packer.pack, batch.samples)
|
||||
@@ -645,23 +659,23 @@ class Orchestrator:
|
||||
save_ckpt_time = await self.maybe_save_ckpt(step)
|
||||
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.
|
||||
# Episode metrics over the {agg,<env>} × {all,effective} matrix. ``all`` is the
|
||||
# full arrival window; ``effective`` is the exact shipped cohort.
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", batch.rollouts), ("effective", effective)):
|
||||
for subset, pool in (("all", batch.episodes), ("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.
|
||||
num_tokens = sum(r.num_total_tokens for r in batch.rollouts)
|
||||
num_input = sum(r.num_input_tokens for r in effective)
|
||||
num_output = sum(r.num_output_tokens for r in effective)
|
||||
num_rollouts = len(batch.rollouts)
|
||||
num_unique_examples = len({r.group_id for r in batch.rollouts})
|
||||
num_tokens = batch.episodes.num_total_tokens
|
||||
num_input = sum(record.trace.num_input_tokens for record in effective.records)
|
||||
num_output = sum(record.trace.num_output_tokens for record in effective.records)
|
||||
num_rollouts = batch.episodes.num_traces
|
||||
num_unique_examples = len({episode_group_id(episode) for episode in batch.episodes})
|
||||
metrics |= {
|
||||
"progress/tokens": num_tokens,
|
||||
"progress/input_tokens": num_input,
|
||||
@@ -677,14 +691,9 @@ class Orchestrator:
|
||||
"time/wait_for_policy": self.wait_for_policy_time,
|
||||
"step": step,
|
||||
}
|
||||
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
|
||||
for env_name, env_pool in batch.episodes.by_env().items():
|
||||
metrics[f"batch/{env_name}"] = env_pool.num_traces / batch.episodes.num_traces
|
||||
metrics |= self.train_source.metrics()
|
||||
await monitors.log(metrics, step=step)
|
||||
self.wait_for_policy_time = 0.0
|
||||
|
||||
@@ -697,7 +706,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 +723,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 +770,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 +781,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
|
||||
@@ -788,64 +796,69 @@ class Orchestrator:
|
||||
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
|
||||
``Error`` is the sink-level rate (errored arrivals / total arrivals, over the full window);
|
||||
the quality metrics are over the effective (clean, trained-on) subset, as is ``Trainable``."""
|
||||
rollouts = batch.rollouts
|
||||
effective = rollouts.effective
|
||||
episodes = batch.episodes
|
||||
effective = batch.cohort.effective
|
||||
eff = effective.metrics
|
||||
n_generated = len(rollouts)
|
||||
n_effective = len(effective)
|
||||
n_trainable = sum(1 for r in effective if r.is_trainable)
|
||||
n_generated = episodes.num_traces
|
||||
n_effective = effective.num_traces
|
||||
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
|
||||
trainable_rate = (n_trainable / n_effective) if n_effective else 0.0
|
||||
max_off_policy = max((r.off_policy_steps for r in effective), default=0)
|
||||
max_off_policy = max((self.off_policy_steps(episode, step) for episode in effective), default=0)
|
||||
|
||||
head = (
|
||||
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Trainable {n_trainable}/{n_effective} ({trainable_rate:.1%}) | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max_off_policy} | "
|
||||
f"Error {rollouts.metrics.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
f"Error {episodes.metrics.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
if len(self.train_envs) <= 1:
|
||||
get_logger().success(head)
|
||||
return
|
||||
|
||||
by_env = rollouts.by_env()
|
||||
name_width = max((len(n) for n in by_env), default=0)
|
||||
window_by_env = episodes.by_env()
|
||||
shipped_by_env = effective.by_env()
|
||||
env_names = sorted(set(window_by_env) | set(shipped_by_env))
|
||||
name_width = max((len(name) for name in env_names), default=0)
|
||||
lines = [head]
|
||||
for env_name in sorted(by_env):
|
||||
pool = by_env[env_name]
|
||||
env_eff_pool = pool.effective
|
||||
for env_name in env_names:
|
||||
pool = window_by_env.get(env_name, TrainEpisodes())
|
||||
env_eff_pool = shipped_by_env.get(env_name, TrainEpisodes())
|
||||
env_eff = env_eff_pool.metrics
|
||||
ratio = (len(pool) / n_generated) if n_generated else 0.0
|
||||
ratio = (pool.num_traces / n_generated) if n_generated else 0.0
|
||||
lines.append(
|
||||
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_eff.reward.mean():.4f} | "
|
||||
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max((r.off_policy_steps for r in env_eff_pool), default=0)} | "
|
||||
f"Max Off-Policy {max((self.off_policy_steps(episode, step) for episode in env_eff_pool), default=0)} | "
|
||||
f"Error {pool.metrics.has_error.mean():.1%} | Truncation {env_eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
get_logger().success("\n\t\t ".join(lines))
|
||||
|
||||
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
|
||||
"""Persist + log one completed eval epoch through the monitors."""
|
||||
if not batch.rollouts:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
|
||||
if not batch.episodes:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no episodes returned, skipping log")
|
||||
return
|
||||
|
||||
# The non-errored subset is logged on epoch completion (multiple eval envs share the
|
||||
# step's trace file — each epoch appends its cohort once, and every record carries
|
||||
# ``env_name``); the full returned cohort already streamed into ``all`` on arrival.
|
||||
await monitors.log(group_episodes(batch.rollouts.effective.rollouts), batch.step, "eval", "effective")
|
||||
policy_versions = {r.policy_version for r in batch.rollouts}
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
policy_spans = [eval_work(episode).policy for episode in batch.episodes]
|
||||
if any(span is None for span in policy_spans):
|
||||
raise ValueError(f"Eval {batch.env_name} step {batch.step} is missing policy provenance")
|
||||
policy_versions = {span.start for span in policy_spans if span is not None}
|
||||
policy_version = min(policy_versions)
|
||||
if len(policy_versions) > 1:
|
||||
get_logger().warning(
|
||||
f"Eval {batch.env_name} step {batch.step} had mixed policy versions: {sorted(policy_versions)}"
|
||||
)
|
||||
# Rollout metrics over {all,effective} (eval batches are per-env, so no `agg` axis).
|
||||
# Episode metrics over {all,effective} (eval batches are per-env, so no `agg` axis).
|
||||
# ``effective`` = non-errored; pass@k / pass^k only over the effective set.
|
||||
rollouts = batch.rollouts
|
||||
effective = rollouts.effective
|
||||
episodes = batch.episodes
|
||||
effective = episodes.effective
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", rollouts), ("effective", effective)):
|
||||
for subset, pool in (("all", episodes), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(policy_version)
|
||||
metrics["step"] = float(batch.step)
|
||||
@@ -853,7 +866,7 @@ class Orchestrator:
|
||||
|
||||
# Success line — quality metrics over the effective set, error rate over the full returned
|
||||
# cohort. ``Stat.mean()`` is 0.0 for an empty set.
|
||||
eff, full = effective.metrics, rollouts.metrics
|
||||
eff, full = effective.metrics, episodes.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(
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -1,52 +1,62 @@
|
||||
"""TrainSink: three-level rollout sink for the training side.
|
||||
|
||||
1. ``process_rollout`` — eager per-rollout tokenization (overlaps with
|
||||
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
|
||||
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``.
|
||||
|
||||
``add()`` takes one episode (``list[Rollout]``) and returns
|
||||
``TrainBatch | None``; group accounting counts episodes, never loose traces.
|
||||
I/O concerns (ship to trainer, monitors.log) live on the
|
||||
orchestrator.
|
||||
"""
|
||||
"""Training-side episode, group, and batch assembly."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.algo.base import iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import stamp_loss_routing
|
||||
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.metrics import TrainEpisodes
|
||||
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.orchestrator.types import TrainBatch
|
||||
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id
|
||||
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
|
||||
``process_rollout``. This is what actually ships: forked traces can drop
|
||||
branches with no trainable tokens, so ``Trace.num_total_tokens`` (which sums
|
||||
over all branches) may overcount. For linear traces the two agree.
|
||||
|
||||
Zero-payload rollouts (no trainable samples at all) fall back to the trace
|
||||
total so they still advance token batching — a degenerate all-zero-payload
|
||||
stream then ships empty batches and trips the orchestrator's
|
||||
consecutive-empty-batch abort instead of stalling the readiness check."""
|
||||
return sum(len(sample.token_ids) for sample in rollout.samples) or rollout.num_total_tokens
|
||||
def payload_tokens(samples: list[TrainingSample], trace: vf.Trace | None = None) -> int:
|
||||
"""Token cost of one trainer-bound trace."""
|
||||
return sum(len(sample.token_ids) for sample in samples) or (trace.num_total_tokens if trace is not None else 0)
|
||||
|
||||
|
||||
def _prune_zero_advantages(sample: TrainingSample) -> bool:
|
||||
"""Remove zero-advantage tokens from the RL component."""
|
||||
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)``."""
|
||||
"""Score native episodes, admit groups, then compile trainer payloads."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -57,8 +67,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[vf.Episode]], 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,215 +78,203 @@ 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).
|
||||
# In-progress groups stay out until they finalize.
|
||||
self.pending_rollouts: TrainRollouts = TrainRollouts()
|
||||
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
|
||||
# isn't unique — the same task can be re-sampled while an
|
||||
# earlier group is still in flight
|
||||
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
|
||||
# Episodes arrived per group — the finalization count (an episode may
|
||||
# add several traces to ``pending_groups`` but counts once here).
|
||||
self.pending_group_episodes: dict[uuid.UUID, int] = defaultdict(int)
|
||||
self.pending_batch: list[Rollout] = []
|
||||
# Running payload-token total of ``pending_batch`` (token-batched
|
||||
# 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] = {}
|
||||
self.pending_episodes = TrainEpisodes()
|
||||
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
|
||||
self.pending_batch: dict[str, list[TrainingSample]] = {}
|
||||
self.episode_by_trace: dict[str, vf.Episode] = {}
|
||||
self.pending_tokens = 0
|
||||
self.zero_output_units = 0
|
||||
self.reported_zero_output_windows = 0
|
||||
|
||||
def group_size_for(self, env_name: str) -> int:
|
||||
return self.train_envs.get(env_name).config.group_size
|
||||
|
||||
def batch_progress(self) -> tuple[int, int, str]:
|
||||
"""``(current, target, unit)`` for the train batch — counts only
|
||||
``pending_batch`` (survivors of finalized groups, queued for the
|
||||
trainer), so it's an honest 0→target fill. Partial-group arrivals are
|
||||
reported separately by ``buffered_count()``."""
|
||||
if self.batch_size is not None:
|
||||
return len(self.pending_batch), self.batch_size, "rollouts"
|
||||
return len(self.pending_batch), self.batch_size, "traces"
|
||||
assert self.token_batch_size is not None
|
||||
return self.pending_tokens, self.token_batch_size, "tokens"
|
||||
|
||||
def buffered_count(self) -> int:
|
||||
"""Episodes that have arrived but sit in not-yet-complete groups —
|
||||
buffered in the sink ahead of the batch."""
|
||||
return sum(self.pending_group_episodes.values())
|
||||
return sum(len(group) for group in self.pending_groups.values())
|
||||
|
||||
def pending_batch_by_env(self) -> dict[str, int]:
|
||||
"""Per-env breakdown of ``batch_progress()`` (``pending_batch`` only);
|
||||
values sum to the aggregate."""
|
||||
counts: dict[str, int] = defaultdict(int)
|
||||
for r in self.pending_batch:
|
||||
counts[r.env_name] += 1
|
||||
for trace_id in self.pending_batch:
|
||||
episode = self.episode_by_trace[trace_id]
|
||||
counts[episode_env_name(episode)] += 1
|
||||
return dict(counts)
|
||||
|
||||
async def add(self, episode: list[Rollout]) -> TrainBatch | None:
|
||||
"""Process one episode arrival; finalize the group on the
|
||||
``group_size``-th episode; return a ``TrainBatch`` if the finalization
|
||||
pushed (or left) the batch over its threshold. Arrivals into
|
||||
still-incomplete groups never ship a batch."""
|
||||
group_id = episode[0].group_id
|
||||
env_name = episode[0].env_name
|
||||
for rollout in episode:
|
||||
await self.process_rollout(rollout)
|
||||
self.pending_groups[group_id].extend(episode)
|
||||
self.pending_group_episodes[group_id] += 1
|
||||
if self.pending_group_episodes[group_id] < self.group_size_for(env_name):
|
||||
async def add(self, episode: vf.Episode) -> TrainBatch | None:
|
||||
"""Process one completed episode and return a batch when ready."""
|
||||
await self.process_episode(episode)
|
||||
group_id = episode_group_id(episode)
|
||||
env_name = episode_env_name(episode)
|
||||
group = self.pending_groups[group_id]
|
||||
group.append(episode)
|
||||
if len(group) < self.group_size_for(env_name):
|
||||
return None
|
||||
|
||||
await self.process_group(group_id)
|
||||
# ``pending_batch`` only grows on group finalization, so readiness is
|
||||
# only re-checked here — the window of a shipped batch then always
|
||||
# contains at least the group that finalized it.
|
||||
ready = (
|
||||
len(self.pending_batch) >= self.batch_size
|
||||
if self.batch_size is not None
|
||||
else self.pending_tokens >= (self.token_batch_size or 0)
|
||||
)
|
||||
if ready:
|
||||
return self.process_batch()
|
||||
return None
|
||||
return self.process_batch() if ready else None
|
||||
|
||||
async def process_rollout(self, rollout: Rollout) -> None:
|
||||
"""Build training samples from the rollout's Trace (one per branch), walking the
|
||||
message graph. Training is renderer-only across all modes (RL/OPD student, SFT teacher),
|
||||
so every node already carries its tokens. Errored rollouts are dropped at the group
|
||||
level, so skip them here; untrainable traces never become training data."""
|
||||
if rollout.has_error or not rollout.agent.trainable:
|
||||
return
|
||||
samples = await asyncio.to_thread(
|
||||
trace_to_samples,
|
||||
rollout,
|
||||
env_name=rollout.env_name,
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
)
|
||||
rollout.samples = samples or []
|
||||
# Arrival phase: rollout-local scoring (raw reward, echo observation
|
||||
# weighting, opd/opsd reference logprobs) runs as soon as the rollout is
|
||||
# tokenized — before its group is complete.
|
||||
await self.train_envs.get(rollout.env_name).algorithm.finalize_rollout(rollout)
|
||||
async def process_episode(self, episode: vf.Episode) -> None:
|
||||
"""Run rollout-local algorithm work on one native episode."""
|
||||
env_name = episode_env_name(episode)
|
||||
await self.train_envs.get(env_name).algorithm.finalize_episode(episode)
|
||||
|
||||
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``."""
|
||||
async def process_group(self, group_id: str) -> None:
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
self.pending_group_episodes.pop(group_id, None)
|
||||
if not group:
|
||||
return
|
||||
# Window membership follows group finalization, not arrival: a rollout
|
||||
# only becomes observable (metrics / persistence) once its whole group
|
||||
# is finalized, so a batch's window never claims rollouts of a group
|
||||
# that ships later. Dropped groups still land here — they were observed.
|
||||
for r in group:
|
||||
self.pending_rollouts.append(r)
|
||||
env_name = group[0].env_name
|
||||
task_idx = group[0].task.data.idx
|
||||
survivors = [r for r in group if not r.has_error]
|
||||
num_errored = len(group) - len(survivors)
|
||||
|
||||
env_name = episode_env_name(group[0])
|
||||
env = self.train_envs.get(env_name)
|
||||
# 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:
|
||||
traces = [trace for episode in group for trace in episode.traces]
|
||||
survivors = [trace for _, trace in iter_trainable_traces(group)]
|
||||
task_idx = next((trace.task.data.idx for trace in traces), None)
|
||||
num_errored = sum(trace.has_error for trace in traces) + sum(
|
||||
not episode.ok for episode in group if not episode.traces
|
||||
)
|
||||
|
||||
if survivors:
|
||||
await env.algorithm.finalize_group(group)
|
||||
admitted = self._admit(group)
|
||||
if not survivors or not admitted:
|
||||
self.pending_episodes.extend(group, admitted=admitted)
|
||||
self._record_zero_output(group, survivors)
|
||||
reason = "no trainable survivors" if not survivors else "rejected by curriculum"
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
f"rollouts={len(group)} (errored={num_errored}) | dropped: no trainable survivors"
|
||||
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | dropped: {reason}"
|
||||
)
|
||||
return
|
||||
|
||||
# Advantages + per-sample wire stamping (advantage stream, loss
|
||||
# routing) are the algorithm's job (finalize_group); the sink only
|
||||
# owns the grouping mechanics.
|
||||
await env.algorithm.finalize_group(survivors)
|
||||
|
||||
# The env has a single sampling temperature; fan it out per token
|
||||
# (context tokens are masked out, so their temperature is don't-care).
|
||||
samples_by_trace: dict[str, list[TrainingSample]] = {}
|
||||
temperature = env.sampling_args["temperature"]
|
||||
for r in survivors:
|
||||
for sample in r.samples:
|
||||
for trace in survivors:
|
||||
samples = await asyncio.to_thread(
|
||||
trace_to_samples,
|
||||
trace,
|
||||
env_name=env_name,
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
)
|
||||
for sample in samples:
|
||||
sample.temperatures = [temperature] * len(sample.token_ids)
|
||||
stamp_loss_routing(sample, env.algorithm.action_loss_type)
|
||||
if samples:
|
||||
samples_by_trace[trace.id] = samples
|
||||
|
||||
if self.pre_filters:
|
||||
apply_filters(self.pre_filters, survivors)
|
||||
filtered_by_name: dict[str, int] = {}
|
||||
num_filtered = 0
|
||||
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.pending_episodes.extend(group, sampled_trace_ids=set(samples_by_trace), admitted=True)
|
||||
if not samples_by_trace:
|
||||
self._record_zero_output(group, survivors)
|
||||
return
|
||||
|
||||
# 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 "—"
|
||||
self.pending_batch.update(samples_by_trace)
|
||||
for episode in group:
|
||||
for trace in episode.traces:
|
||||
if trace.id in samples_by_trace:
|
||||
self.episode_by_trace[trace.id] = episode
|
||||
if self.token_batch_size is not None:
|
||||
self.pending_tokens += sum(
|
||||
payload_tokens(samples, self._trace(trace_id)) for trace_id, samples in samples_by_trace.items()
|
||||
)
|
||||
self.zero_output_units = 0
|
||||
self.reported_zero_output_windows = 0
|
||||
|
||||
rewards = [trace.reward for trace in survivors if trace.id in samples_by_trace]
|
||||
avg_reward = sum(rewards) / len(rewards)
|
||||
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"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reward={avg_reward:.4f}"
|
||||
)
|
||||
|
||||
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."""
|
||||
def _trace(self, trace_id: str) -> vf.Trace:
|
||||
episode = self.episode_by_trace[trace_id]
|
||||
return next(trace for trace in episode.traces if trace.id == trace_id)
|
||||
|
||||
def _admit(self, group: list[vf.Episode]) -> bool:
|
||||
return self.on_result(group) if self.on_result is not None else True
|
||||
|
||||
def _record_zero_output(self, group: list[vf.Episode], survivors: list[vf.Trace]) -> None:
|
||||
if self.batch_size is not None:
|
||||
cohort = self.pending_batch[: self.batch_size]
|
||||
self.pending_batch = self.pending_batch[self.batch_size :]
|
||||
returned_traces = sum(len(episode.traces) for episode in group)
|
||||
self.zero_output_units += len(survivors) or returned_traces or len(group)
|
||||
else:
|
||||
survivor_tokens = sum(trace.num_total_tokens for trace in survivors)
|
||||
episode_tokens = sum(episode.num_total_tokens for episode in group)
|
||||
self.zero_output_units += survivor_tokens or episode_tokens 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:
|
||||
items = list(self.pending_batch.items())
|
||||
if self.batch_size is not None:
|
||||
selected = items[: self.batch_size]
|
||||
else:
|
||||
assert self.token_batch_size is not None
|
||||
cut = 0
|
||||
running = 0
|
||||
for i, r in enumerate(self.pending_batch):
|
||||
running += payload_tokens(r)
|
||||
cut = i + 1
|
||||
for index, (trace_id, samples) in enumerate(items):
|
||||
running += payload_tokens(samples, self._trace(trace_id))
|
||||
cut = index + 1
|
||||
if running >= self.token_batch_size:
|
||||
break
|
||||
cohort = self.pending_batch[:cut]
|
||||
self.pending_batch = self.pending_batch[cut:]
|
||||
selected = items[:cut]
|
||||
self.pending_tokens -= running
|
||||
|
||||
if self.post_filters:
|
||||
apply_filters(self.post_filters, cohort)
|
||||
selected_by_trace = dict(selected)
|
||||
selected_ids = set(selected_by_trace)
|
||||
for trace_id in selected_ids:
|
||||
del self.pending_batch[trace_id]
|
||||
|
||||
# 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:
|
||||
selected_by_trace = {
|
||||
trace_id: [sample for sample in samples if _prune_zero_advantages(sample)]
|
||||
for trace_id, samples in selected
|
||||
}
|
||||
selected_by_trace = {trace_id: samples for trace_id, samples in selected_by_trace.items() if samples}
|
||||
samples = [sample for trace_samples in selected_by_trace.values() for sample in trace_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
|
||||
# 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
|
||||
# finalized groups (and any overflow) into the next shipped batch's window.
|
||||
rollouts = self.pending_rollouts
|
||||
shipped_ids = set(selected_by_trace)
|
||||
traces_by_episode: dict[int, list[vf.Trace]] = defaultdict(list)
|
||||
selected_episodes: dict[int, vf.Episode] = {}
|
||||
for trace_id in selected_ids:
|
||||
episode = self.episode_by_trace.pop(trace_id)
|
||||
if trace_id in shipped_ids:
|
||||
selected_episodes[id(episode)] = episode
|
||||
traces_by_episode[id(episode)].extend(trace for trace in episode.traces if trace.id == trace_id)
|
||||
cohort_episodes = [
|
||||
episode.model_copy(update={"traces": traces_by_episode[id(episode)]})
|
||||
for episode in selected_episodes.values()
|
||||
]
|
||||
cohort = TrainEpisodes(cohort_episodes, sampled_trace_ids=shipped_ids)
|
||||
|
||||
episodes = self.pending_episodes
|
||||
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()
|
||||
self.pending_episodes = TrainEpisodes()
|
||||
return TrainBatch(episodes=episodes, cohort=cohort, samples=samples)
|
||||
|
||||
@@ -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
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.curriculum import Curriculum
|
||||
from prime_rl.orchestrator.envs import TrainEnvs
|
||||
from prime_rl.orchestrator.utils import episode_env_name
|
||||
|
||||
|
||||
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,66 @@ 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[vf.Episode]) -> bool:
|
||||
"""Report a finalized group and return whether it should train."""
|
||||
if not group:
|
||||
raise ValueError("Cannot report an empty rollout group")
|
||||
env_name = episode_env_name(group[0])
|
||||
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:
|
||||
expected_fields = {"rng", "envs"}
|
||||
if set(state_dict) != expected_fields:
|
||||
raise ValueError(f"Train-source checkpoint fields must be {sorted(expected_fields)}")
|
||||
env_states = state_dict["envs"]
|
||||
if set(env_states) != set(self.curricula):
|
||||
raise ValueError(
|
||||
f"Train-source checkpoint envs {sorted(env_states)} do not match configured envs "
|
||||
f"{sorted(self.curricula)}"
|
||||
)
|
||||
self.rng.setstate(state_dict["rng"])
|
||||
for name, curriculum in self.curricula.items():
|
||||
curriculum.load_state_dict(env_states[name])
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -89,6 +89,25 @@ def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[b
|
||||
yield branch, mask
|
||||
|
||||
|
||||
def _loss_weights(branch: vf.Branch, name: str, trained_nodes: set[int]) -> list[float] | None:
|
||||
"""Flatten one graph-native loss stream, training each shared node once."""
|
||||
weights: list[float] = []
|
||||
for node in branch.nodes:
|
||||
node_weights = (node.loss_weights or {}).get(name)
|
||||
if node_weights is None or id(node) in trained_nodes:
|
||||
weights.extend([0.0] * len(node.token_ids))
|
||||
continue
|
||||
if len(node_weights) != len(node.token_ids):
|
||||
raise ValueError(
|
||||
f"loss weight stream {name!r} must align with node token_ids: "
|
||||
f"got {len(node_weights)}, expected {len(node.token_ids)}"
|
||||
)
|
||||
weights.extend(node_weights)
|
||||
if any(node_weights):
|
||||
trained_nodes.add(id(node))
|
||||
return weights if any(weights) else None
|
||||
|
||||
|
||||
def trace_to_samples(
|
||||
trace: vf.Trace,
|
||||
*,
|
||||
@@ -100,13 +119,14 @@ def trace_to_samples(
|
||||
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
|
||||
`branch.sampled_mask` / `branch.logprobs`), so a sample carries it directly: `mask` marks
|
||||
the trainable (model-sampled) tokens, the context tokens between completions stay masked
|
||||
out. Errored rollouts are dropped upstream (`TrainSink.process_rollout`), so no error
|
||||
out. Errored traces are dropped upstream (`TrainSink.process_episode`), so no error
|
||||
handling happens here. A branch carrying images also gets `mm_kwargs` (the concatenated
|
||||
pixel tensors) and `mm_token_type_ids` (the renderer's `mm_token_type_id_map` applied to
|
||||
the branch tokens). Branches with no sampled tokens (e.g. an openai client carrying none)
|
||||
yield nothing.
|
||||
"""
|
||||
samples: list[TrainingSample] = []
|
||||
trained_loss_nodes: dict[str, set[int]] = {"rl": set(), "ce": set(), "ref_kl": set()}
|
||||
for branch, mask in iter_trainable_branches(trace):
|
||||
token_ids = branch.token_ids
|
||||
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||
@@ -123,9 +143,14 @@ def trace_to_samples(
|
||||
logprobs=branch.logprobs,
|
||||
temperatures=[], # filled by TrainSink.process_group
|
||||
env_name=env_name,
|
||||
ref_logprobs=branch.reference_logprobs,
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
routed_experts=_encode_routed_experts(branch.routed_experts, len(token_ids)),
|
||||
rl_weights=_loss_weights(branch, "rl", trained_loss_nodes["rl"]),
|
||||
ce_weights=_loss_weights(branch, "ce", trained_loss_nodes["ce"]),
|
||||
ref_kl_weights=_loss_weights(branch, "ref_kl", trained_loss_nodes["ref_kl"]),
|
||||
advantages=branch.advantages,
|
||||
)
|
||||
)
|
||||
if not samples:
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user